69271048da24ddaea1556e1b0780410fe9d77977
[binutils-gdb.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3 Copyright (C) 1988-2023 Free Software Foundation, Inc.
4
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
9 the Free Software Foundation; either version 3 of the License, or
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
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20 /* See the GDB User Guide for details of the GDB remote protocol. */
21
22 #include "defs.h"
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "bfd.h"
28 #include "symfile.h"
29 #include "target.h"
30 #include "process-stratum-target.h"
31 #include "gdbcmd.h"
32 #include "objfiles.h"
33 #include "gdbthread.h"
34 #include "remote.h"
35 #include "remote-notif.h"
36 #include "regcache.h"
37 #include "value.h"
38 #include "observable.h"
39 #include "solib.h"
40 #include "cli/cli-decode.h"
41 #include "cli/cli-setshow.h"
42 #include "target-descriptions.h"
43 #include "gdb_bfd.h"
44 #include "gdbsupport/filestuff.h"
45 #include "gdbsupport/rsp-low.h"
46 #include "disasm.h"
47 #include "location.h"
48
49 #include "gdbsupport/gdb_sys_time.h"
50
51 #include "gdbsupport/event-loop.h"
52 #include "event-top.h"
53 #include "inf-loop.h"
54
55 #include <signal.h>
56 #include "serial.h"
57
58 #include "gdbcore.h"
59
60 #include "remote-fileio.h"
61 #include "gdbsupport/fileio.h"
62 #include <sys/stat.h>
63 #include "xml-support.h"
64
65 #include "memory-map.h"
66
67 #include "tracepoint.h"
68 #include "ax.h"
69 #include "ax-gdb.h"
70 #include "gdbsupport/agent.h"
71 #include "btrace.h"
72 #include "record-btrace.h"
73 #include "gdbsupport/scoped_restore.h"
74 #include "gdbsupport/environ.h"
75 #include "gdbsupport/byte-vector.h"
76 #include "gdbsupport/search.h"
77 #include <algorithm>
78 #include <iterator>
79 #include <unordered_map>
80 #include "async-event.h"
81 #include "gdbsupport/selftest.h"
82
83 /* The remote target. */
84
85 static const char remote_doc[] = N_("\
86 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
87 Specify the serial device it is connected to\n\
88 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
89
90 /* See remote.h */
91
92 bool remote_debug = false;
93
94 #define OPAQUETHREADBYTES 8
95
96 /* a 64 bit opaque identifier */
97 typedef unsigned char threadref[OPAQUETHREADBYTES];
98
99 struct gdb_ext_thread_info;
100 struct threads_listing_context;
101 typedef int (*rmt_thread_action) (threadref *ref, void *context);
102 struct protocol_feature;
103 struct packet_reg;
104
105 struct stop_reply;
106 typedef std::unique_ptr<stop_reply> stop_reply_up;
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
112 enum packet_support
113 {
114 PACKET_SUPPORT_UNKNOWN = 0,
115 PACKET_ENABLE,
116 PACKET_DISABLE
117 };
118
119 /* Convert the packet support auto_boolean to a name used for gdb printing. */
120
121 static const char *
122 get_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
140 static const char *
141 get_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
149 /* Analyze a packet's return value and update the packet config
150 accordingly. */
151
152 enum packet_result
153 {
154 PACKET_ERROR,
155 PACKET_OK,
156 PACKET_UNKNOWN
157 };
158
159 /* Enumeration of packets for a remote target. */
160
161 enum {
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
308 struct threads_listing_context;
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
315 struct 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
330 /* About this many threadids fit in a packet. */
331
332 #define MAXTHREADLISTRESULTS 32
333
334 /* Data for the vFile:pread readahead cache. */
335
336 struct 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_vector buf;
358
359 /* Cache hit and miss counters. */
360 ULONGEST hit_count = 0;
361 ULONGEST miss_count = 0;
362 };
363
364 /* Description of the remote protocol for a given architecture. */
365
366 struct packet_reg
367 {
368 long offset; /* Offset into G packet. */
369 long regnum; /* GDB's internal register number. */
370 LONGEST pnum; /* Remote protocol register number. */
371 int in_g_packet; /* Always part of G packet. */
372 /* long size in bytes; == register_size (arch, regnum);
373 at present. */
374 /* char *name; == gdbarch_register_name (arch, regnum);
375 at present. */
376 };
377
378 struct remote_arch_state
379 {
380 explicit remote_arch_state (struct gdbarch *gdbarch);
381
382 /* Description of the remote protocol registers. */
383 long sizeof_g_packet;
384
385 /* Description of the remote protocol registers indexed by REGNUM
386 (making an array gdbarch_num_regs in size). */
387 std::unique_ptr<packet_reg[]> regs;
388
389 /* This is the size (in chars) of the first response to the ``g''
390 packet. It is used as a heuristic when determining the maximum
391 size of memory-read and memory-write packets. A target will
392 typically only reserve a buffer large enough to hold the ``g''
393 packet. The size does not include packet overhead (headers and
394 trailers). */
395 long actual_register_packet_size;
396
397 /* This is the maximum size (in chars) of a non read/write packet.
398 It is also used as a cap on the size of read/write packets. */
399 long remote_packet_size;
400 };
401
402 /* Description of the remote protocol state for the currently
403 connected target. This is per-target state, and independent of the
404 selected architecture. */
405
406 class remote_state
407 {
408 public:
409
410 remote_state ();
411 ~remote_state ();
412
413 /* Get the remote arch state for GDBARCH. */
414 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
415
416 void create_async_event_handler ()
417 {
418 gdb_assert (m_async_event_handler_token == nullptr);
419 m_async_event_handler_token
420 = ::create_async_event_handler ([] (gdb_client_data data)
421 {
422 inferior_event_handler (INF_REG_EVENT);
423 },
424 nullptr, "remote");
425 }
426
427 void mark_async_event_handler ()
428 {
429 gdb_assert (this->is_async_p ());
430 ::mark_async_event_handler (m_async_event_handler_token);
431 }
432
433 void clear_async_event_handler ()
434 { ::clear_async_event_handler (m_async_event_handler_token); }
435
436 bool async_event_handler_marked () const
437 { return ::async_event_handler_marked (m_async_event_handler_token); }
438
439 void delete_async_event_handler ()
440 {
441 if (m_async_event_handler_token != nullptr)
442 ::delete_async_event_handler (&m_async_event_handler_token);
443 }
444
445 bool is_async_p () const
446 {
447 /* We're async whenever the serial device is. */
448 gdb_assert (this->remote_desc != nullptr);
449 return serial_is_async_p (this->remote_desc);
450 }
451
452 bool can_async_p () const
453 {
454 /* We can async whenever the serial device can. */
455 gdb_assert (this->remote_desc != nullptr);
456 return serial_can_async_p (this->remote_desc);
457 }
458
459 public: /* data */
460
461 /* A buffer to use for incoming packets, and its current size. The
462 buffer is grown dynamically for larger incoming packets.
463 Outgoing packets may also be constructed in this buffer.
464 The size of the buffer is always at least REMOTE_PACKET_SIZE;
465 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
466 packets. */
467 gdb::char_vector buf;
468
469 /* True if we're going through initial connection setup (finding out
470 about the remote side's threads, relocating symbols, etc.). */
471 bool starting_up = false;
472
473 /* If we negotiated packet size explicitly (and thus can bypass
474 heuristics for the largest packet size that will not overflow
475 a buffer in the stub), this will be set to that packet size.
476 Otherwise zero, meaning to use the guessed size. */
477 long explicit_packet_size = 0;
478
479 /* True, if in no ack mode. That is, neither GDB nor the stub will
480 expect acks from each other. The connection is assumed to be
481 reliable. */
482 bool noack_mode = false;
483
484 /* True if we're connected in extended remote mode. */
485 bool extended = false;
486
487 /* True if we resumed the target and we're waiting for the target to
488 stop. In the mean time, we can't start another command/query.
489 The remote server wouldn't be ready to process it, so we'd
490 timeout waiting for a reply that would never come and eventually
491 we'd close the connection. This can happen in asynchronous mode
492 because we allow GDB commands while the target is running. */
493 bool waiting_for_stop_reply = false;
494
495 /* The status of the stub support for the various vCont actions. */
496 vCont_action_support supports_vCont;
497
498 /* True if the user has pressed Ctrl-C, but the target hasn't
499 responded to that. */
500 bool ctrlc_pending_p = false;
501
502 /* True if we saw a Ctrl-C while reading or writing from/to the
503 remote descriptor. At that point it is not safe to send a remote
504 interrupt packet, so we instead remember we saw the Ctrl-C and
505 process it once we're done with sending/receiving the current
506 packet, which should be shortly. If however that takes too long,
507 and the user presses Ctrl-C again, we offer to disconnect. */
508 bool got_ctrlc_during_io = false;
509
510 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
511 remote_open knows that we don't have a file open when the program
512 starts. */
513 struct serial *remote_desc = nullptr;
514
515 /* These are the threads which we last sent to the remote system. The
516 TID member will be -1 for all or -2 for not sent yet. */
517 ptid_t general_thread = null_ptid;
518 ptid_t continue_thread = null_ptid;
519
520 /* This is the traceframe which we last selected on the remote system.
521 It will be -1 if no traceframe is selected. */
522 int remote_traceframe_number = -1;
523
524 char *last_pass_packet = nullptr;
525
526 /* The last QProgramSignals packet sent to the target. We bypass
527 sending a new program signals list down to the target if the new
528 packet is exactly the same as the last we sent. IOW, we only let
529 the target know about program signals list changes. */
530 char *last_program_signals_packet = nullptr;
531
532 gdb_signal last_sent_signal = GDB_SIGNAL_0;
533
534 bool last_sent_step = false;
535
536 /* The execution direction of the last resume we got. */
537 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
538
539 char *finished_object = nullptr;
540 char *finished_annex = nullptr;
541 ULONGEST finished_offset = 0;
542
543 /* Should we try the 'ThreadInfo' query packet?
544
545 This variable (NOT available to the user: auto-detect only!)
546 determines whether GDB will use the new, simpler "ThreadInfo"
547 query or the older, more complex syntax for thread queries.
548 This is an auto-detect variable (set to true at each connect,
549 and set to false when the target fails to recognize it). */
550 bool use_threadinfo_query = false;
551 bool use_threadextra_query = false;
552
553 threadref echo_nextthread {};
554 threadref nextthread {};
555 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
556
557 /* The state of remote notification. */
558 struct remote_notif_state *notif_state = nullptr;
559
560 /* The branch trace configuration. */
561 struct btrace_config btrace_config {};
562
563 /* The argument to the last "vFile:setfs:" packet we sent, used
564 to avoid sending repeated unnecessary "vFile:setfs:" packets.
565 Initialized to -1 to indicate that no "vFile:setfs:" packet
566 has yet been sent. */
567 int fs_pid = -1;
568
569 /* A readahead cache for vFile:pread. Often, reading a binary
570 involves a sequence of small reads. E.g., when parsing an ELF
571 file. A readahead cache helps mostly the case of remote
572 debugging on a connection with higher latency, due to the
573 request/reply nature of the RSP. We only cache data for a single
574 file descriptor at a time. */
575 struct readahead_cache readahead_cache;
576
577 /* The list of already fetched and acknowledged stop events. This
578 queue is used for notification Stop, and other notifications
579 don't need queue for their events, because the notification
580 events of Stop can't be consumed immediately, so that events
581 should be queued first, and be consumed by remote_wait_{ns,as}
582 one per time. Other notifications can consume their events
583 immediately, so queue is not needed for them. */
584 std::vector<stop_reply_up> stop_reply_queue;
585
586 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
587 ``forever'' still use the normal timeout mechanism. This is
588 currently used by the ASYNC code to guarentee that target reads
589 during the initial connect always time-out. Once getpkt has been
590 modified to return a timeout indication and, in turn
591 remote_wait()/wait_for_inferior() have gained a timeout parameter
592 this can go away. */
593 bool wait_forever_enabled_p = true;
594
595 private:
596 /* Asynchronous signal handle registered as event loop source for
597 when we have pending events ready to be passed to the core. */
598 async_event_handler *m_async_event_handler_token = nullptr;
599
600 /* Mapping of remote protocol data for each gdbarch. Usually there
601 is only one entry here, though we may see more with stubs that
602 support multi-process. */
603 std::unordered_map<struct gdbarch *, remote_arch_state>
604 m_arch_states;
605 };
606
607 static const target_info remote_target_info = {
608 "remote",
609 N_("Remote target using gdb-specific protocol"),
610 remote_doc
611 };
612
613 /* Description of a remote packet. */
614
615 struct packet_description
616 {
617 /* Name of the packet used for gdb output. */
618 const char *name;
619
620 /* Title of the packet, used by the set/show remote name-packet
621 commands to identify the individual packages and gdb output. */
622 const char *title;
623 };
624
625 /* Configuration of a remote packet. */
626
627 struct packet_config
628 {
629 /* If auto, GDB auto-detects support for this packet or feature,
630 either through qSupported, or by trying the packet and looking
631 at the response. If true, GDB assumes the target supports this
632 packet. If false, the packet is disabled. Configs that don't
633 have an associated command always have this set to auto. */
634 enum auto_boolean detect;
635
636 /* Does the target support this packet? */
637 enum packet_support support;
638 };
639
640 /* User configurable variables for the number of characters in a
641 memory read/write packet. MIN (rsa->remote_packet_size,
642 rsa->sizeof_g_packet) is the default. Some targets need smaller
643 values (fifo overruns, et.al.) and some users need larger values
644 (speed up transfers). The variables ``preferred_*'' (the user
645 request), ``current_*'' (what was actually set) and ``forced_*''
646 (Positive - a soft limit, negative - a hard limit). */
647
648 struct memory_packet_config
649 {
650 const char *name;
651 long size;
652 int fixed_p;
653 };
654
655 /* These global variables contain the default configuration for every new
656 remote_feature object. */
657 static memory_packet_config memory_read_packet_config =
658 {
659 "memory-read-packet-size",
660 };
661 static memory_packet_config memory_write_packet_config =
662 {
663 "memory-write-packet-size",
664 };
665
666 /* This global array contains packet descriptions (name and title). */
667 static packet_description packets_descriptions[PACKET_MAX];
668 /* This global array contains the default configuration for every new
669 per-remote target array. */
670 static packet_config remote_protocol_packets[PACKET_MAX];
671
672 /* Description of a remote target's features. It stores the configuration
673 and provides functions to determine supported features of the target. */
674
675 struct remote_features
676 {
677 remote_features ()
678 {
679 m_memory_read_packet_config = memory_read_packet_config;
680 m_memory_write_packet_config = memory_write_packet_config;
681
682 std::copy (std::begin (remote_protocol_packets),
683 std::end (remote_protocol_packets),
684 std::begin (m_protocol_packets));
685 }
686 ~remote_features () = default;
687
688 DISABLE_COPY_AND_ASSIGN (remote_features);
689
690 /* Returns whether a given packet defined by its enum value is supported. */
691 enum packet_support packet_support (int) const;
692
693 /* Returns the packet's corresponding "set remote foo-packet" command
694 state. See struct packet_config for more details. */
695 enum auto_boolean packet_set_cmd_state (int packet) const
696 { return m_protocol_packets[packet].detect; }
697
698 /* Returns true if the multi-process extensions are in effect. */
699 int remote_multi_process_p () const
700 { return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE; }
701
702 /* Returns true if fork events are supported. */
703 int remote_fork_event_p () const
704 { return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE; }
705
706 /* Returns true if vfork events are supported. */
707 int remote_vfork_event_p () const
708 { return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE; }
709
710 /* Returns true if exec events are supported. */
711 int remote_exec_event_p () const
712 { return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE; }
713
714 /* Returns true if memory tagging is supported, false otherwise. */
715 bool remote_memory_tagging_p () const
716 { return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE; }
717
718 /* Reset all packets back to "unknown support". Called when opening a
719 new connection to a remote target. */
720 void reset_all_packet_configs_support ();
721
722 /* Check result value in BUF for packet WHICH_PACKET and update the packet's
723 support configuration accordingly. */
724 packet_result packet_ok (const char *buf, const int which_packet);
725 packet_result packet_ok (const gdb::char_vector &buf, const int which_packet);
726
727 /* Configuration of a remote target's memory read packet. */
728 memory_packet_config m_memory_read_packet_config;
729 /* Configuration of a remote target's memory write packet. */
730 memory_packet_config m_memory_write_packet_config;
731
732 /* The per-remote target array which stores a remote's packet
733 configurations. */
734 packet_config m_protocol_packets[PACKET_MAX];
735 };
736
737 class remote_target : public process_stratum_target
738 {
739 public:
740 remote_target () = default;
741 ~remote_target () override;
742
743 const target_info &info () const override
744 { return remote_target_info; }
745
746 const char *connection_string () override;
747
748 thread_control_capabilities get_thread_control_capabilities () override
749 { return tc_schedlock; }
750
751 /* Open a remote connection. */
752 static void open (const char *, int);
753
754 void close () override;
755
756 void detach (inferior *, int) override;
757 void disconnect (const char *, int) override;
758
759 void commit_resumed () override;
760 void resume (ptid_t, int, enum gdb_signal) override;
761 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
762 bool has_pending_events () override;
763
764 void fetch_registers (struct regcache *, int) override;
765 void store_registers (struct regcache *, int) override;
766 void prepare_to_store (struct regcache *) override;
767
768 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
769
770 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
771 enum remove_bp_reason) override;
772
773
774 bool stopped_by_sw_breakpoint () override;
775 bool supports_stopped_by_sw_breakpoint () override;
776
777 bool stopped_by_hw_breakpoint () override;
778
779 bool supports_stopped_by_hw_breakpoint () override;
780
781 bool stopped_by_watchpoint () override;
782
783 bool stopped_data_address (CORE_ADDR *) override;
784
785 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
786
787 int can_use_hw_breakpoint (enum bptype, int, int) override;
788
789 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
790
791 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
792
793 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
794
795 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
796 struct expression *) override;
797
798 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
799 struct expression *) override;
800
801 void kill () override;
802
803 void load (const char *, int) override;
804
805 void mourn_inferior () override;
806
807 void pass_signals (gdb::array_view<const unsigned char>) override;
808
809 int set_syscall_catchpoint (int, bool, int,
810 gdb::array_view<const int>) override;
811
812 void program_signals (gdb::array_view<const unsigned char>) override;
813
814 bool thread_alive (ptid_t ptid) override;
815
816 const char *thread_name (struct thread_info *) override;
817
818 void update_thread_list () override;
819
820 std::string pid_to_str (ptid_t) override;
821
822 const char *extra_thread_info (struct thread_info *) override;
823
824 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
825
826 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
827 int handle_len,
828 inferior *inf) override;
829
830 gdb::array_view<const gdb_byte> thread_info_to_thread_handle (struct thread_info *tp)
831 override;
832
833 void stop (ptid_t) override;
834
835 void interrupt () override;
836
837 void pass_ctrlc () override;
838
839 enum target_xfer_status xfer_partial (enum target_object object,
840 const char *annex,
841 gdb_byte *readbuf,
842 const gdb_byte *writebuf,
843 ULONGEST offset, ULONGEST len,
844 ULONGEST *xfered_len) override;
845
846 ULONGEST get_memory_xfer_limit () override;
847
848 void rcmd (const char *command, struct ui_file *output) override;
849
850 const char *pid_to_exec_file (int pid) override;
851
852 void log_command (const char *cmd) override
853 {
854 serial_log_command (this, cmd);
855 }
856
857 CORE_ADDR get_thread_local_address (ptid_t ptid,
858 CORE_ADDR load_module_addr,
859 CORE_ADDR offset) override;
860
861 bool can_execute_reverse () override;
862
863 std::vector<mem_region> memory_map () override;
864
865 void flash_erase (ULONGEST address, LONGEST length) override;
866
867 void flash_done () override;
868
869 const struct target_desc *read_description () override;
870
871 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
872 const gdb_byte *pattern, ULONGEST pattern_len,
873 CORE_ADDR *found_addrp) override;
874
875 bool can_async_p () override;
876
877 bool is_async_p () override;
878
879 void async (bool) override;
880
881 int async_wait_fd () override;
882
883 void thread_events (int) override;
884
885 int can_do_single_step () override;
886
887 void terminal_inferior () override;
888
889 void terminal_ours () override;
890
891 bool supports_non_stop () override;
892
893 bool supports_multi_process () override;
894
895 bool supports_disable_randomization () override;
896
897 bool filesystem_is_local () override;
898
899
900 int fileio_open (struct inferior *inf, const char *filename,
901 int flags, int mode, int warn_if_slow,
902 fileio_error *target_errno) override;
903
904 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
905 ULONGEST offset, fileio_error *target_errno) override;
906
907 int fileio_pread (int fd, gdb_byte *read_buf, int len,
908 ULONGEST offset, fileio_error *target_errno) override;
909
910 int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
911
912 int fileio_close (int fd, fileio_error *target_errno) override;
913
914 int fileio_unlink (struct inferior *inf,
915 const char *filename,
916 fileio_error *target_errno) override;
917
918 gdb::optional<std::string>
919 fileio_readlink (struct inferior *inf,
920 const char *filename,
921 fileio_error *target_errno) override;
922
923 bool supports_enable_disable_tracepoint () override;
924
925 bool supports_string_tracing () override;
926
927 int remote_supports_cond_tracepoints ();
928
929 bool supports_evaluation_of_breakpoint_conditions () override;
930
931 int remote_supports_fast_tracepoints ();
932
933 int remote_supports_static_tracepoints ();
934
935 int remote_supports_install_in_trace ();
936
937 bool can_run_breakpoint_commands () override;
938
939 void trace_init () override;
940
941 void download_tracepoint (struct bp_location *location) override;
942
943 bool can_download_tracepoint () override;
944
945 void download_trace_state_variable (const trace_state_variable &tsv) override;
946
947 void enable_tracepoint (struct bp_location *location) override;
948
949 void disable_tracepoint (struct bp_location *location) override;
950
951 void trace_set_readonly_regions () override;
952
953 void trace_start () override;
954
955 int get_trace_status (struct trace_status *ts) override;
956
957 void get_tracepoint_status (tracepoint *tp, struct uploaded_tp *utp)
958 override;
959
960 void trace_stop () override;
961
962 int trace_find (enum trace_find_type type, int num,
963 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
964
965 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
966
967 int save_trace_data (const char *filename) override;
968
969 int upload_tracepoints (struct uploaded_tp **utpp) override;
970
971 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
972
973 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
974
975 int get_min_fast_tracepoint_insn_len () override;
976
977 void set_disconnected_tracing (int val) override;
978
979 void set_circular_trace_buffer (int val) override;
980
981 void set_trace_buffer_size (LONGEST val) override;
982
983 bool set_trace_notes (const char *user, const char *notes,
984 const char *stopnotes) override;
985
986 int core_of_thread (ptid_t ptid) override;
987
988 int verify_memory (const gdb_byte *data,
989 CORE_ADDR memaddr, ULONGEST size) override;
990
991
992 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
993
994 void set_permissions () override;
995
996 bool static_tracepoint_marker_at (CORE_ADDR,
997 struct static_tracepoint_marker *marker)
998 override;
999
1000 std::vector<static_tracepoint_marker>
1001 static_tracepoint_markers_by_strid (const char *id) override;
1002
1003 traceframe_info_up traceframe_info () override;
1004
1005 bool use_agent (bool use) override;
1006 bool can_use_agent () override;
1007
1008 struct btrace_target_info *
1009 enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
1010
1011 void disable_btrace (struct btrace_target_info *tinfo) override;
1012
1013 void teardown_btrace (struct btrace_target_info *tinfo) override;
1014
1015 enum btrace_error read_btrace (struct btrace_data *data,
1016 struct btrace_target_info *btinfo,
1017 enum btrace_read_type type) override;
1018
1019 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
1020 bool augmented_libraries_svr4_read () override;
1021 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
1022 void follow_exec (inferior *, ptid_t, const char *) override;
1023 int insert_fork_catchpoint (int) override;
1024 int remove_fork_catchpoint (int) override;
1025 int insert_vfork_catchpoint (int) override;
1026 int remove_vfork_catchpoint (int) override;
1027 int insert_exec_catchpoint (int) override;
1028 int remove_exec_catchpoint (int) override;
1029 enum exec_direction_kind execution_direction () override;
1030
1031 bool supports_memory_tagging () override;
1032
1033 bool fetch_memtags (CORE_ADDR address, size_t len,
1034 gdb::byte_vector &tags, int type) override;
1035
1036 bool store_memtags (CORE_ADDR address, size_t len,
1037 const gdb::byte_vector &tags, int type) override;
1038
1039 public: /* Remote specific methods. */
1040
1041 void remote_download_command_source (int num, ULONGEST addr,
1042 struct command_line *cmds);
1043
1044 void remote_file_put (const char *local_file, const char *remote_file,
1045 int from_tty);
1046 void remote_file_get (const char *remote_file, const char *local_file,
1047 int from_tty);
1048 void remote_file_delete (const char *remote_file, int from_tty);
1049
1050 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
1051 ULONGEST offset, fileio_error *remote_errno);
1052 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
1053 ULONGEST offset, fileio_error *remote_errno);
1054 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
1055 ULONGEST offset, fileio_error *remote_errno);
1056
1057 int remote_hostio_send_command (int command_bytes, int which_packet,
1058 fileio_error *remote_errno, const char **attachment,
1059 int *attachment_len);
1060 int remote_hostio_set_filesystem (struct inferior *inf,
1061 fileio_error *remote_errno);
1062 /* We should get rid of this and use fileio_open directly. */
1063 int remote_hostio_open (struct inferior *inf, const char *filename,
1064 int flags, int mode, int warn_if_slow,
1065 fileio_error *remote_errno);
1066 int remote_hostio_close (int fd, fileio_error *remote_errno);
1067
1068 int remote_hostio_unlink (inferior *inf, const char *filename,
1069 fileio_error *remote_errno);
1070
1071 struct remote_state *get_remote_state ();
1072
1073 long get_remote_packet_size (void);
1074 long get_memory_packet_size (struct memory_packet_config *config);
1075
1076 long get_memory_write_packet_size ();
1077 long get_memory_read_packet_size ();
1078
1079 char *append_pending_thread_resumptions (char *p, char *endp,
1080 ptid_t ptid);
1081 static void open_1 (const char *name, int from_tty, int extended_p);
1082 void start_remote (int from_tty, int extended_p);
1083 void remote_detach_1 (struct inferior *inf, int from_tty);
1084
1085 char *append_resumption (char *p, char *endp,
1086 ptid_t ptid, int step, gdb_signal siggnal);
1087 int remote_resume_with_vcont (ptid_t scope_ptid, int step,
1088 gdb_signal siggnal);
1089
1090 thread_info *add_current_inferior_and_thread (const char *wait_status);
1091
1092 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
1093 target_wait_flags options);
1094 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
1095 target_wait_flags options);
1096
1097 ptid_t process_stop_reply (struct stop_reply *stop_reply,
1098 target_waitstatus *status);
1099
1100 ptid_t select_thread_for_ambiguous_stop_reply
1101 (const struct target_waitstatus &status);
1102
1103 void remote_notice_new_inferior (ptid_t currthread, bool executing);
1104
1105 void print_one_stopped_thread (thread_info *thread);
1106 void process_initial_stop_replies (int from_tty);
1107
1108 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
1109 bool silent_p);
1110
1111 void btrace_sync_conf (const btrace_config *conf);
1112
1113 void remote_btrace_maybe_reopen ();
1114
1115 void remove_new_fork_children (threads_listing_context *context);
1116 void kill_new_fork_children (inferior *inf);
1117 void discard_pending_stop_replies (struct inferior *inf);
1118 int stop_reply_queue_length ();
1119
1120 void check_pending_events_prevent_wildcard_vcont
1121 (bool *may_global_wildcard_vcont);
1122
1123 void discard_pending_stop_replies_in_queue ();
1124 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
1125 struct stop_reply *queued_stop_reply (ptid_t ptid);
1126 int peek_stop_reply (ptid_t ptid);
1127 void remote_parse_stop_reply (const char *buf, stop_reply *event);
1128
1129 void remote_stop_ns (ptid_t ptid);
1130 void remote_interrupt_as ();
1131 void remote_interrupt_ns ();
1132
1133 char *remote_get_noisy_reply ();
1134 int remote_query_attached (int pid);
1135 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
1136 int try_open_exec);
1137
1138 ptid_t remote_current_thread (ptid_t oldpid);
1139 ptid_t get_current_thread (const char *wait_status);
1140
1141 void set_thread (ptid_t ptid, int gen);
1142 void set_general_thread (ptid_t ptid);
1143 void set_continue_thread (ptid_t ptid);
1144 void set_general_process ();
1145
1146 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
1147
1148 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
1149 gdb_ext_thread_info *info);
1150 int remote_get_threadinfo (threadref *threadid, int fieldset,
1151 gdb_ext_thread_info *info);
1152
1153 int parse_threadlist_response (const char *pkt, int result_limit,
1154 threadref *original_echo,
1155 threadref *resultlist,
1156 int *doneflag);
1157 int remote_get_threadlist (int startflag, threadref *nextthread,
1158 int result_limit, int *done, int *result_count,
1159 threadref *threadlist);
1160
1161 int remote_threadlist_iterator (rmt_thread_action stepfunction,
1162 void *context, int looplimit);
1163
1164 int remote_get_threads_with_ql (threads_listing_context *context);
1165 int remote_get_threads_with_qxfer (threads_listing_context *context);
1166 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
1167
1168 void extended_remote_restart ();
1169
1170 void get_offsets ();
1171
1172 void remote_check_symbols ();
1173
1174 void remote_supported_packet (const struct protocol_feature *feature,
1175 enum packet_support support,
1176 const char *argument);
1177
1178 void remote_query_supported ();
1179
1180 void remote_packet_size (const protocol_feature *feature,
1181 packet_support support, const char *value);
1182
1183 void remote_serial_quit_handler ();
1184
1185 void remote_detach_pid (int pid);
1186
1187 void remote_vcont_probe ();
1188
1189 void remote_resume_with_hc (ptid_t ptid, int step,
1190 gdb_signal siggnal);
1191
1192 void send_interrupt_sequence ();
1193 void interrupt_query ();
1194
1195 void remote_notif_get_pending_events (const notif_client *nc);
1196
1197 int fetch_register_using_p (struct regcache *regcache,
1198 packet_reg *reg);
1199 int send_g_packet ();
1200 void process_g_packet (struct regcache *regcache);
1201 void fetch_registers_using_g (struct regcache *regcache);
1202 int store_register_using_P (const struct regcache *regcache,
1203 packet_reg *reg);
1204 void store_registers_using_G (const struct regcache *regcache);
1205
1206 void set_remote_traceframe ();
1207
1208 void check_binary_download (CORE_ADDR addr);
1209
1210 target_xfer_status remote_write_bytes_aux (const char *header,
1211 CORE_ADDR memaddr,
1212 const gdb_byte *myaddr,
1213 ULONGEST len_units,
1214 int unit_size,
1215 ULONGEST *xfered_len_units,
1216 char packet_format,
1217 int use_length);
1218
1219 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
1220 const gdb_byte *myaddr, ULONGEST len,
1221 int unit_size, ULONGEST *xfered_len);
1222
1223 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
1224 ULONGEST len_units,
1225 int unit_size, ULONGEST *xfered_len_units);
1226
1227 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
1228 ULONGEST memaddr,
1229 ULONGEST len,
1230 int unit_size,
1231 ULONGEST *xfered_len);
1232
1233 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
1234 gdb_byte *myaddr, ULONGEST len,
1235 int unit_size,
1236 ULONGEST *xfered_len);
1237
1238 packet_result remote_send_printf (const char *format, ...)
1239 ATTRIBUTE_PRINTF (2, 3);
1240
1241 target_xfer_status remote_flash_write (ULONGEST address,
1242 ULONGEST length, ULONGEST *xfered_len,
1243 const gdb_byte *data);
1244
1245 int readchar (int timeout);
1246
1247 void remote_serial_write (const char *str, int len);
1248
1249 int putpkt (const char *buf);
1250 int putpkt_binary (const char *buf, int cnt);
1251
1252 int putpkt (const gdb::char_vector &buf)
1253 {
1254 return putpkt (buf.data ());
1255 }
1256
1257 void skip_frame ();
1258 long read_frame (gdb::char_vector *buf_p);
1259 int getpkt (gdb::char_vector *buf, bool forever = false,
1260 bool *is_notif = nullptr);
1261 int remote_vkill (int pid);
1262 void remote_kill_k ();
1263
1264 void extended_remote_disable_randomization (int val);
1265 int extended_remote_run (const std::string &args);
1266
1267 void send_environment_packet (const char *action,
1268 const char *packet,
1269 const char *value);
1270
1271 void extended_remote_environment_support ();
1272 void extended_remote_set_inferior_cwd ();
1273
1274 target_xfer_status remote_write_qxfer (const char *object_name,
1275 const char *annex,
1276 const gdb_byte *writebuf,
1277 ULONGEST offset, LONGEST len,
1278 ULONGEST *xfered_len,
1279 const unsigned int which_packet);
1280
1281 target_xfer_status remote_read_qxfer (const char *object_name,
1282 const char *annex,
1283 gdb_byte *readbuf, ULONGEST offset,
1284 LONGEST len,
1285 ULONGEST *xfered_len,
1286 const unsigned int which_packet);
1287
1288 void push_stop_reply (struct stop_reply *new_event);
1289
1290 bool vcont_r_supported ();
1291
1292 remote_features m_features;
1293
1294 private:
1295
1296 bool start_remote_1 (int from_tty, int extended_p);
1297
1298 /* The remote state. Don't reference this directly. Use the
1299 get_remote_state method instead. */
1300 remote_state m_remote_state;
1301 };
1302
1303 static const target_info extended_remote_target_info = {
1304 "extended-remote",
1305 N_("Extended remote target using gdb-specific protocol"),
1306 remote_doc
1307 };
1308
1309 /* Set up the extended remote target by extending the standard remote
1310 target and adding to it. */
1311
1312 class extended_remote_target final : public remote_target
1313 {
1314 public:
1315 const target_info &info () const override
1316 { return extended_remote_target_info; }
1317
1318 /* Open an extended-remote connection. */
1319 static void open (const char *, int);
1320
1321 bool can_create_inferior () override { return true; }
1322 void create_inferior (const char *, const std::string &,
1323 char **, int) override;
1324
1325 void detach (inferior *, int) override;
1326
1327 bool can_attach () override { return true; }
1328 void attach (const char *, int) override;
1329
1330 void post_attach (int) override;
1331 bool supports_disable_randomization () override;
1332 };
1333
1334 struct stop_reply : public notif_event
1335 {
1336 ~stop_reply ();
1337
1338 /* The identifier of the thread about this event */
1339 ptid_t ptid;
1340
1341 /* The remote state this event is associated with. When the remote
1342 connection, represented by a remote_state object, is closed,
1343 all the associated stop_reply events should be released. */
1344 struct remote_state *rs;
1345
1346 struct target_waitstatus ws;
1347
1348 /* The architecture associated with the expedited registers. */
1349 gdbarch *arch;
1350
1351 /* Expedited registers. This makes remote debugging a bit more
1352 efficient for those targets that provide critical registers as
1353 part of their normal status mechanism (as another roundtrip to
1354 fetch them is avoided). */
1355 std::vector<cached_reg_t> regcache;
1356
1357 enum target_stop_reason stop_reason;
1358
1359 CORE_ADDR watch_data_address;
1360
1361 int core;
1362 };
1363
1364 /* Return TARGET as a remote_target if it is one, else nullptr. */
1365
1366 static remote_target *
1367 as_remote_target (process_stratum_target *target)
1368 {
1369 return dynamic_cast<remote_target *> (target);
1370 }
1371
1372 /* See remote.h. */
1373
1374 bool
1375 is_remote_target (process_stratum_target *target)
1376 {
1377 return as_remote_target (target) != nullptr;
1378 }
1379
1380 /* Per-program-space data key. */
1381 static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
1382 remote_pspace_data;
1383
1384 /* The variable registered as the control variable used by the
1385 remote exec-file commands. While the remote exec-file setting is
1386 per-program-space, the set/show machinery uses this as the
1387 location of the remote exec-file value. */
1388 static std::string remote_exec_file_var;
1389
1390 /* The size to align memory write packets, when practical. The protocol
1391 does not guarantee any alignment, and gdb will generate short
1392 writes and unaligned writes, but even as a best-effort attempt this
1393 can improve bulk transfers. For instance, if a write is misaligned
1394 relative to the target's data bus, the stub may need to make an extra
1395 round trip fetching data from the target. This doesn't make a
1396 huge difference, but it's easy to do, so we try to be helpful.
1397
1398 The alignment chosen is arbitrary; usually data bus width is
1399 important here, not the possibly larger cache line size. */
1400 enum { REMOTE_ALIGN_WRITES = 16 };
1401
1402 /* Prototypes for local functions. */
1403
1404 static int hexnumlen (ULONGEST num);
1405
1406 static int stubhex (int ch);
1407
1408 static int hexnumstr (char *, ULONGEST);
1409
1410 static int hexnumnstr (char *, ULONGEST, int);
1411
1412 static CORE_ADDR remote_address_masked (CORE_ADDR);
1413
1414 static int stub_unpack_int (const char *buff, int fieldlength);
1415
1416 static void set_remote_protocol_packet_cmd (const char *args, int from_tty,
1417 cmd_list_element *c);
1418
1419 static void show_packet_config_cmd (ui_file *file,
1420 const unsigned int which_packet,
1421 remote_target *remote);
1422
1423 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1424 int from_tty,
1425 struct cmd_list_element *c,
1426 const char *value);
1427
1428 static ptid_t read_ptid (const char *buf, const char **obuf);
1429
1430 static bool remote_read_description_p (struct target_ops *target);
1431
1432 static void remote_console_output (const char *msg);
1433
1434 static void remote_btrace_reset (remote_state *rs);
1435
1436 static void remote_unpush_and_throw (remote_target *target);
1437
1438 /* For "remote". */
1439
1440 static struct cmd_list_element *remote_cmdlist;
1441
1442 /* For "set remote" and "show remote". */
1443
1444 static struct cmd_list_element *remote_set_cmdlist;
1445 static struct cmd_list_element *remote_show_cmdlist;
1446
1447 /* Controls whether GDB is willing to use range stepping. */
1448
1449 static bool use_range_stepping = true;
1450
1451 /* From the remote target's point of view, each thread is in one of these three
1452 states. */
1453 enum class resume_state
1454 {
1455 /* Not resumed - we haven't been asked to resume this thread. */
1456 NOT_RESUMED,
1457
1458 /* We have been asked to resume this thread, but haven't sent a vCont action
1459 for it yet. We'll need to consider it next time commit_resume is
1460 called. */
1461 RESUMED_PENDING_VCONT,
1462
1463 /* We have been asked to resume this thread, and we have sent a vCont action
1464 for it. */
1465 RESUMED,
1466 };
1467
1468 /* Information about a thread's pending vCont-resume. Used when a thread is in
1469 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1470 stores this information which is then picked up by
1471 remote_target::commit_resume to know which is the proper action for this
1472 thread to include in the vCont packet. */
1473 struct resumed_pending_vcont_info
1474 {
1475 /* True if the last resume call for this thread was a step request, false
1476 if a continue request. */
1477 bool step;
1478
1479 /* The signal specified in the last resume call for this thread. */
1480 gdb_signal sig;
1481 };
1482
1483 /* Private data that we'll store in (struct thread_info)->priv. */
1484 struct remote_thread_info : public private_thread_info
1485 {
1486 std::string extra;
1487 std::string name;
1488 int core = -1;
1489
1490 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1491 sequence of bytes. */
1492 gdb::byte_vector thread_handle;
1493
1494 /* Whether the target stopped for a breakpoint/watchpoint. */
1495 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1496
1497 /* This is set to the data address of the access causing the target
1498 to stop for a watchpoint. */
1499 CORE_ADDR watch_data_address = 0;
1500
1501 /* Get the thread's resume state. */
1502 enum resume_state get_resume_state () const
1503 {
1504 return m_resume_state;
1505 }
1506
1507 /* Put the thread in the NOT_RESUMED state. */
1508 void set_not_resumed ()
1509 {
1510 m_resume_state = resume_state::NOT_RESUMED;
1511 }
1512
1513 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1514 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1515 {
1516 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1517 m_resumed_pending_vcont_info.step = step;
1518 m_resumed_pending_vcont_info.sig = sig;
1519 }
1520
1521 /* Get the information this thread's pending vCont-resumption.
1522
1523 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1524 state. */
1525 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1526 {
1527 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1528
1529 return m_resumed_pending_vcont_info;
1530 }
1531
1532 /* Put the thread in the VCONT_RESUMED state. */
1533 void set_resumed ()
1534 {
1535 m_resume_state = resume_state::RESUMED;
1536 }
1537
1538 private:
1539 /* Resume state for this thread. This is used to implement vCont action
1540 coalescing (only when the target operates in non-stop mode).
1541
1542 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1543 which notes that this thread must be considered in the next commit_resume
1544 call.
1545
1546 remote_target::commit_resume sends a vCont packet with actions for the
1547 threads in the RESUMED_PENDING_VCONT state and moves them to the
1548 VCONT_RESUMED state.
1549
1550 When reporting a stop to the core for a thread, that thread is moved back
1551 to the NOT_RESUMED state. */
1552 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1553
1554 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1555 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1556 };
1557
1558 remote_state::remote_state ()
1559 : buf (400)
1560 {
1561 }
1562
1563 remote_state::~remote_state ()
1564 {
1565 xfree (this->last_pass_packet);
1566 xfree (this->last_program_signals_packet);
1567 xfree (this->finished_object);
1568 xfree (this->finished_annex);
1569 }
1570
1571 /* Utility: generate error from an incoming stub packet. */
1572 static void
1573 trace_error (char *buf)
1574 {
1575 if (*buf++ != 'E')
1576 return; /* not an error msg */
1577 switch (*buf)
1578 {
1579 case '1': /* malformed packet error */
1580 if (*++buf == '0') /* general case: */
1581 error (_("remote.c: error in outgoing packet."));
1582 else
1583 error (_("remote.c: error in outgoing packet at field #%ld."),
1584 strtol (buf, NULL, 16));
1585 default:
1586 error (_("Target returns error code '%s'."), buf);
1587 }
1588 }
1589
1590 /* Utility: wait for reply from stub, while accepting "O" packets. */
1591
1592 char *
1593 remote_target::remote_get_noisy_reply ()
1594 {
1595 struct remote_state *rs = get_remote_state ();
1596
1597 do /* Loop on reply from remote stub. */
1598 {
1599 char *buf;
1600
1601 QUIT; /* Allow user to bail out with ^C. */
1602 getpkt (&rs->buf);
1603 buf = rs->buf.data ();
1604 if (buf[0] == 'E')
1605 trace_error (buf);
1606 else if (startswith (buf, "qRelocInsn:"))
1607 {
1608 ULONGEST ul;
1609 CORE_ADDR from, to, org_to;
1610 const char *p, *pp;
1611 int adjusted_size = 0;
1612 int relocated = 0;
1613
1614 p = buf + strlen ("qRelocInsn:");
1615 pp = unpack_varlen_hex (p, &ul);
1616 if (*pp != ';')
1617 error (_("invalid qRelocInsn packet: %s"), buf);
1618 from = ul;
1619
1620 p = pp + 1;
1621 unpack_varlen_hex (p, &ul);
1622 to = ul;
1623
1624 org_to = to;
1625
1626 try
1627 {
1628 gdbarch_relocate_instruction (current_inferior ()->arch (),
1629 &to, from);
1630 relocated = 1;
1631 }
1632 catch (const gdb_exception &ex)
1633 {
1634 if (ex.error == MEMORY_ERROR)
1635 {
1636 /* Propagate memory errors silently back to the
1637 target. The stub may have limited the range of
1638 addresses we can write to, for example. */
1639 }
1640 else
1641 {
1642 /* Something unexpectedly bad happened. Be verbose
1643 so we can tell what, and propagate the error back
1644 to the stub, so it doesn't get stuck waiting for
1645 a response. */
1646 exception_fprintf (gdb_stderr, ex,
1647 _("warning: relocating instruction: "));
1648 }
1649 putpkt ("E01");
1650 }
1651
1652 if (relocated)
1653 {
1654 adjusted_size = to - org_to;
1655
1656 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1657 putpkt (buf);
1658 }
1659 }
1660 else if (buf[0] == 'O' && buf[1] != 'K')
1661 remote_console_output (buf + 1); /* 'O' message from stub */
1662 else
1663 return buf; /* Here's the actual reply. */
1664 }
1665 while (1);
1666 }
1667
1668 struct remote_arch_state *
1669 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1670 {
1671 remote_arch_state *rsa;
1672
1673 auto it = this->m_arch_states.find (gdbarch);
1674 if (it == this->m_arch_states.end ())
1675 {
1676 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1677 std::forward_as_tuple (gdbarch),
1678 std::forward_as_tuple (gdbarch));
1679 rsa = &p.first->second;
1680
1681 /* Make sure that the packet buffer is plenty big enough for
1682 this architecture. */
1683 if (this->buf.size () < rsa->remote_packet_size)
1684 this->buf.resize (2 * rsa->remote_packet_size);
1685 }
1686 else
1687 rsa = &it->second;
1688
1689 return rsa;
1690 }
1691
1692 /* Fetch the global remote target state. */
1693
1694 remote_state *
1695 remote_target::get_remote_state ()
1696 {
1697 /* Make sure that the remote architecture state has been
1698 initialized, because doing so might reallocate rs->buf. Any
1699 function which calls getpkt also needs to be mindful of changes
1700 to rs->buf, but this call limits the number of places which run
1701 into trouble. */
1702 m_remote_state.get_remote_arch_state (current_inferior ()->arch ());
1703
1704 return &m_remote_state;
1705 }
1706
1707 /* Fetch the remote exec-file from the current program space. */
1708
1709 static const char *
1710 get_remote_exec_file (void)
1711 {
1712 char *remote_exec_file;
1713
1714 remote_exec_file = remote_pspace_data.get (current_program_space);
1715 if (remote_exec_file == NULL)
1716 return "";
1717
1718 return remote_exec_file;
1719 }
1720
1721 /* Set the remote exec file for PSPACE. */
1722
1723 static void
1724 set_pspace_remote_exec_file (struct program_space *pspace,
1725 const char *remote_exec_file)
1726 {
1727 char *old_file = remote_pspace_data.get (pspace);
1728
1729 xfree (old_file);
1730 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1731 }
1732
1733 /* The "set/show remote exec-file" set command hook. */
1734
1735 static void
1736 set_remote_exec_file (const char *ignored, int from_tty,
1737 struct cmd_list_element *c)
1738 {
1739 set_pspace_remote_exec_file (current_program_space,
1740 remote_exec_file_var.c_str ());
1741 }
1742
1743 /* The "set/show remote exec-file" show command hook. */
1744
1745 static void
1746 show_remote_exec_file (struct ui_file *file, int from_tty,
1747 struct cmd_list_element *cmd, const char *value)
1748 {
1749 gdb_printf (file, "%s\n", get_remote_exec_file ());
1750 }
1751
1752 static int
1753 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1754 {
1755 int regnum, num_remote_regs, offset;
1756 struct packet_reg **remote_regs;
1757
1758 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1759 {
1760 struct packet_reg *r = &regs[regnum];
1761
1762 if (register_size (gdbarch, regnum) == 0)
1763 /* Do not try to fetch zero-sized (placeholder) registers. */
1764 r->pnum = -1;
1765 else
1766 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1767
1768 r->regnum = regnum;
1769 }
1770
1771 /* Define the g/G packet format as the contents of each register
1772 with a remote protocol number, in order of ascending protocol
1773 number. */
1774
1775 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1776 for (num_remote_regs = 0, regnum = 0;
1777 regnum < gdbarch_num_regs (gdbarch);
1778 regnum++)
1779 if (regs[regnum].pnum != -1)
1780 remote_regs[num_remote_regs++] = &regs[regnum];
1781
1782 std::sort (remote_regs, remote_regs + num_remote_regs,
1783 [] (const packet_reg *a, const packet_reg *b)
1784 { return a->pnum < b->pnum; });
1785
1786 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1787 {
1788 remote_regs[regnum]->in_g_packet = 1;
1789 remote_regs[regnum]->offset = offset;
1790 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1791 }
1792
1793 return offset;
1794 }
1795
1796 /* Given the architecture described by GDBARCH, return the remote
1797 protocol register's number and the register's offset in the g/G
1798 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1799 If the target does not have a mapping for REGNUM, return false,
1800 otherwise, return true. */
1801
1802 int
1803 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1804 int *pnum, int *poffset)
1805 {
1806 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1807
1808 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1809
1810 map_regcache_remote_table (gdbarch, regs.data ());
1811
1812 *pnum = regs[regnum].pnum;
1813 *poffset = regs[regnum].offset;
1814
1815 return *pnum != -1;
1816 }
1817
1818 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1819 {
1820 /* Use the architecture to build a regnum<->pnum table, which will be
1821 1:1 unless a feature set specifies otherwise. */
1822 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1823
1824 /* Record the maximum possible size of the g packet - it may turn out
1825 to be smaller. */
1826 this->sizeof_g_packet
1827 = map_regcache_remote_table (gdbarch, this->regs.get ());
1828
1829 /* Default maximum number of characters in a packet body. Many
1830 remote stubs have a hardwired buffer size of 400 bytes
1831 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1832 as the maximum packet-size to ensure that the packet and an extra
1833 NUL character can always fit in the buffer. This stops GDB
1834 trashing stubs that try to squeeze an extra NUL into what is
1835 already a full buffer (As of 1999-12-04 that was most stubs). */
1836 this->remote_packet_size = 400 - 1;
1837
1838 /* This one is filled in when a ``g'' packet is received. */
1839 this->actual_register_packet_size = 0;
1840
1841 /* Should rsa->sizeof_g_packet needs more space than the
1842 default, adjust the size accordingly. Remember that each byte is
1843 encoded as two characters. 32 is the overhead for the packet
1844 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1845 (``$NN:G...#NN'') is a better guess, the below has been padded a
1846 little. */
1847 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1848 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1849 }
1850
1851 /* Get a pointer to the current remote target. If not connected to a
1852 remote target, return NULL. */
1853
1854 static remote_target *
1855 get_current_remote_target ()
1856 {
1857 target_ops *proc_target = current_inferior ()->process_target ();
1858 return dynamic_cast<remote_target *> (proc_target);
1859 }
1860
1861 /* Return the current allowed size of a remote packet. This is
1862 inferred from the current architecture, and should be used to
1863 limit the length of outgoing packets. */
1864 long
1865 remote_target::get_remote_packet_size ()
1866 {
1867 struct remote_state *rs = get_remote_state ();
1868 remote_arch_state *rsa
1869 = rs->get_remote_arch_state (current_inferior ()->arch ());
1870
1871 if (rs->explicit_packet_size)
1872 return rs->explicit_packet_size;
1873
1874 return rsa->remote_packet_size;
1875 }
1876
1877 static struct packet_reg *
1878 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1879 long regnum)
1880 {
1881 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1882 return NULL;
1883 else
1884 {
1885 struct packet_reg *r = &rsa->regs[regnum];
1886
1887 gdb_assert (r->regnum == regnum);
1888 return r;
1889 }
1890 }
1891
1892 static struct packet_reg *
1893 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1894 LONGEST pnum)
1895 {
1896 int i;
1897
1898 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1899 {
1900 struct packet_reg *r = &rsa->regs[i];
1901
1902 if (r->pnum == pnum)
1903 return r;
1904 }
1905 return NULL;
1906 }
1907
1908 /* Allow the user to specify what sequence to send to the remote
1909 when he requests a program interruption: Although ^C is usually
1910 what remote systems expect (this is the default, here), it is
1911 sometimes preferable to send a break. On other systems such
1912 as the Linux kernel, a break followed by g, which is Magic SysRq g
1913 is required in order to interrupt the execution. */
1914 const char interrupt_sequence_control_c[] = "Ctrl-C";
1915 const char interrupt_sequence_break[] = "BREAK";
1916 const char interrupt_sequence_break_g[] = "BREAK-g";
1917 static const char *const interrupt_sequence_modes[] =
1918 {
1919 interrupt_sequence_control_c,
1920 interrupt_sequence_break,
1921 interrupt_sequence_break_g,
1922 NULL
1923 };
1924 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1925
1926 static void
1927 show_interrupt_sequence (struct ui_file *file, int from_tty,
1928 struct cmd_list_element *c,
1929 const char *value)
1930 {
1931 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1932 gdb_printf (file,
1933 _("Send the ASCII ETX character (Ctrl-c) "
1934 "to the remote target to interrupt the "
1935 "execution of the program.\n"));
1936 else if (interrupt_sequence_mode == interrupt_sequence_break)
1937 gdb_printf (file,
1938 _("send a break signal to the remote target "
1939 "to interrupt the execution of the program.\n"));
1940 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1941 gdb_printf (file,
1942 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1943 "the remote target to interrupt the execution "
1944 "of Linux kernel.\n"));
1945 else
1946 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
1947 interrupt_sequence_mode);
1948 }
1949
1950 /* This boolean variable specifies whether interrupt_sequence is sent
1951 to the remote target when gdb connects to it.
1952 This is mostly needed when you debug the Linux kernel: The Linux kernel
1953 expects BREAK g which is Magic SysRq g for connecting gdb. */
1954 static bool interrupt_on_connect = false;
1955
1956 /* This variable is used to implement the "set/show remotebreak" commands.
1957 Since these commands are now deprecated in favor of "set/show remote
1958 interrupt-sequence", it no longer has any effect on the code. */
1959 static bool remote_break;
1960
1961 static void
1962 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1963 {
1964 if (remote_break)
1965 interrupt_sequence_mode = interrupt_sequence_break;
1966 else
1967 interrupt_sequence_mode = interrupt_sequence_control_c;
1968 }
1969
1970 static void
1971 show_remotebreak (struct ui_file *file, int from_tty,
1972 struct cmd_list_element *c,
1973 const char *value)
1974 {
1975 }
1976
1977 /* This variable sets the number of bits in an address that are to be
1978 sent in a memory ("M" or "m") packet. Normally, after stripping
1979 leading zeros, the entire address would be sent. This variable
1980 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1981 initial implementation of remote.c restricted the address sent in
1982 memory packets to ``host::sizeof long'' bytes - (typically 32
1983 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1984 address was never sent. Since fixing this bug may cause a break in
1985 some remote targets this variable is principally provided to
1986 facilitate backward compatibility. */
1987
1988 static unsigned int remote_address_size;
1989
1990 \f
1991 /* The default max memory-write-packet-size, when the setting is
1992 "fixed". The 16k is historical. (It came from older GDB's using
1993 alloca for buffers and the knowledge (folklore?) that some hosts
1994 don't cope very well with large alloca calls.) */
1995 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1996
1997 /* The minimum remote packet size for memory transfers. Ensures we
1998 can write at least one byte. */
1999 #define MIN_MEMORY_PACKET_SIZE 20
2000
2001 /* Get the memory packet size, assuming it is fixed. */
2002
2003 static long
2004 get_fixed_memory_packet_size (struct memory_packet_config *config)
2005 {
2006 gdb_assert (config->fixed_p);
2007
2008 if (config->size <= 0)
2009 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
2010 else
2011 return config->size;
2012 }
2013
2014 /* Compute the current size of a read/write packet. Since this makes
2015 use of ``actual_register_packet_size'' the computation is dynamic. */
2016
2017 long
2018 remote_target::get_memory_packet_size (struct memory_packet_config *config)
2019 {
2020 struct remote_state *rs = get_remote_state ();
2021 remote_arch_state *rsa
2022 = rs->get_remote_arch_state (current_inferior ()->arch ());
2023
2024 long what_they_get;
2025 if (config->fixed_p)
2026 what_they_get = get_fixed_memory_packet_size (config);
2027 else
2028 {
2029 what_they_get = get_remote_packet_size ();
2030 /* Limit the packet to the size specified by the user. */
2031 if (config->size > 0
2032 && what_they_get > config->size)
2033 what_they_get = config->size;
2034
2035 /* Limit it to the size of the targets ``g'' response unless we have
2036 permission from the stub to use a larger packet size. */
2037 if (rs->explicit_packet_size == 0
2038 && rsa->actual_register_packet_size > 0
2039 && what_they_get > rsa->actual_register_packet_size)
2040 what_they_get = rsa->actual_register_packet_size;
2041 }
2042 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
2043 what_they_get = MIN_MEMORY_PACKET_SIZE;
2044
2045 /* Make sure there is room in the global buffer for this packet
2046 (including its trailing NUL byte). */
2047 if (rs->buf.size () < what_they_get + 1)
2048 rs->buf.resize (2 * what_they_get);
2049
2050 return what_they_get;
2051 }
2052
2053 /* Update the size of a read/write packet. If they user wants
2054 something really big then do a sanity check. */
2055
2056 static void
2057 set_memory_packet_size (const char *args, struct memory_packet_config *config,
2058 bool target_connected)
2059 {
2060 int fixed_p = config->fixed_p;
2061 long size = config->size;
2062
2063 if (args == NULL)
2064 error (_("Argument required (integer, \"fixed\" or \"limit\")."));
2065 else if (strcmp (args, "hard") == 0
2066 || strcmp (args, "fixed") == 0)
2067 fixed_p = 1;
2068 else if (strcmp (args, "soft") == 0
2069 || strcmp (args, "limit") == 0)
2070 fixed_p = 0;
2071 else
2072 {
2073 char *end;
2074
2075 size = strtoul (args, &end, 0);
2076 if (args == end)
2077 error (_("Invalid %s (bad syntax)."), config->name);
2078
2079 /* Instead of explicitly capping the size of a packet to or
2080 disallowing it, the user is allowed to set the size to
2081 something arbitrarily large. */
2082 }
2083
2084 /* Extra checks? */
2085 if (fixed_p && !config->fixed_p)
2086 {
2087 /* So that the query shows the correct value. */
2088 long query_size = (size <= 0
2089 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
2090 : size);
2091
2092 if (target_connected
2093 && !query (_("The target may not be able to correctly handle a %s\n"
2094 "of %ld bytes. Change the packet size? "),
2095 config->name, query_size))
2096 error (_("Packet size not changed."));
2097 else if (!target_connected
2098 && !query (_("Future remote targets may not be able to "
2099 "correctly handle a %s\nof %ld bytes. Change the "
2100 "packet size for future remote targets? "),
2101 config->name, query_size))
2102 error (_("Packet size not changed."));
2103 }
2104 /* Update the config. */
2105 config->fixed_p = fixed_p;
2106 config->size = size;
2107
2108 const char *target_type = get_target_type_name (target_connected);
2109 gdb_printf (_("The %s %s is set to \"%s\".\n"), config->name, target_type,
2110 args);
2111
2112 }
2113
2114 /* Show the memory-read or write-packet size configuration CONFIG of the
2115 target REMOTE. If REMOTE is nullptr, the default configuration for future
2116 remote targets should be passed in CONFIG. */
2117
2118 static void
2119 show_memory_packet_size (memory_packet_config *config, remote_target *remote)
2120 {
2121 const char *target_type = get_target_type_name (remote != nullptr);
2122
2123 if (config->size == 0)
2124 gdb_printf (_("The %s %s is 0 (default). "), config->name, target_type);
2125 else
2126 gdb_printf (_("The %s %s is %ld. "), config->name, target_type,
2127 config->size);
2128
2129 if (config->fixed_p)
2130 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
2131 get_fixed_memory_packet_size (config));
2132 else
2133 {
2134 if (remote != nullptr)
2135 gdb_printf (_("Packets are limited to %ld bytes.\n"),
2136 remote->get_memory_packet_size (config));
2137 else
2138 gdb_puts ("The actual limit will be further reduced "
2139 "dependent on the target.\n");
2140 }
2141 }
2142
2143 /* Configure the memory-write-packet size of the currently selected target. If
2144 no target is available, the default configuration for future remote targets
2145 is configured. */
2146
2147 static void
2148 set_memory_write_packet_size (const char *args, int from_tty)
2149 {
2150 remote_target *remote = get_current_remote_target ();
2151 if (remote != nullptr)
2152 {
2153 set_memory_packet_size
2154 (args, &remote->m_features.m_memory_write_packet_config, true);
2155 }
2156 else
2157 {
2158 memory_packet_config* config = &memory_write_packet_config;
2159 set_memory_packet_size (args, config, false);
2160 }
2161 }
2162
2163 /* Display the memory-write-packet size of the currently selected target. If
2164 no target is available, the default configuration for future remote targets
2165 is shown. */
2166
2167 static void
2168 show_memory_write_packet_size (const char *args, int from_tty)
2169 {
2170 remote_target *remote = get_current_remote_target ();
2171 if (remote != nullptr)
2172 show_memory_packet_size (&remote->m_features.m_memory_write_packet_config,
2173 remote);
2174 else
2175 show_memory_packet_size (&memory_write_packet_config, nullptr);
2176 }
2177
2178 /* Show the number of hardware watchpoints that can be used. */
2179
2180 static void
2181 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
2182 struct cmd_list_element *c,
2183 const char *value)
2184 {
2185 gdb_printf (file, _("The maximum number of target hardware "
2186 "watchpoints is %s.\n"), value);
2187 }
2188
2189 /* Show the length limit (in bytes) for hardware watchpoints. */
2190
2191 static void
2192 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
2193 struct cmd_list_element *c,
2194 const char *value)
2195 {
2196 gdb_printf (file, _("The maximum length (in bytes) of a target "
2197 "hardware watchpoint is %s.\n"), value);
2198 }
2199
2200 /* Show the number of hardware breakpoints that can be used. */
2201
2202 static void
2203 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
2204 struct cmd_list_element *c,
2205 const char *value)
2206 {
2207 gdb_printf (file, _("The maximum number of target hardware "
2208 "breakpoints is %s.\n"), value);
2209 }
2210
2211 /* Controls the maximum number of characters to display in the debug output
2212 for each remote packet. The remaining characters are omitted. */
2213
2214 static int remote_packet_max_chars = 512;
2215
2216 /* Show the maximum number of characters to display for each remote packet
2217 when remote debugging is enabled. */
2218
2219 static void
2220 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
2221 struct cmd_list_element *c,
2222 const char *value)
2223 {
2224 gdb_printf (file, _("Number of remote packet characters to "
2225 "display is %s.\n"), value);
2226 }
2227
2228 long
2229 remote_target::get_memory_write_packet_size ()
2230 {
2231 return get_memory_packet_size (&m_features.m_memory_write_packet_config);
2232 }
2233
2234 /* Configure the memory-read-packet size of the currently selected target. If
2235 no target is available, the default configuration for future remote targets
2236 is adapted. */
2237
2238 static void
2239 set_memory_read_packet_size (const char *args, int from_tty)
2240 {
2241 remote_target *remote = get_current_remote_target ();
2242 if (remote != nullptr)
2243 set_memory_packet_size
2244 (args, &remote->m_features.m_memory_read_packet_config, true);
2245 else
2246 {
2247 memory_packet_config* config = &memory_read_packet_config;
2248 set_memory_packet_size (args, config, false);
2249 }
2250
2251 }
2252
2253 /* Display the memory-read-packet size of the currently selected target. If
2254 no target is available, the default configuration for future remote targets
2255 is shown. */
2256
2257 static void
2258 show_memory_read_packet_size (const char *args, int from_tty)
2259 {
2260 remote_target *remote = get_current_remote_target ();
2261 if (remote != nullptr)
2262 show_memory_packet_size (&remote->m_features.m_memory_read_packet_config,
2263 remote);
2264 else
2265 show_memory_packet_size (&memory_read_packet_config, nullptr);
2266 }
2267
2268 long
2269 remote_target::get_memory_read_packet_size ()
2270 {
2271 long size = get_memory_packet_size (&m_features.m_memory_read_packet_config);
2272
2273 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
2274 extra buffer size argument before the memory read size can be
2275 increased beyond this. */
2276 if (size > get_remote_packet_size ())
2277 size = get_remote_packet_size ();
2278 return size;
2279 }
2280
2281 static enum packet_support packet_config_support (const packet_config *config);
2282
2283
2284 static void
2285 set_remote_protocol_packet_cmd (const char *args, int from_tty,
2286 cmd_list_element *c)
2287 {
2288 remote_target *remote = get_current_remote_target ();
2289 gdb_assert (c->var.has_value ());
2290
2291 auto *default_config = static_cast<packet_config *> (c->context ());
2292 const int packet_idx = std::distance (remote_protocol_packets,
2293 default_config);
2294
2295 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2296 {
2297 const char *name = packets_descriptions[packet_idx].name;
2298 const auto_boolean value = c->var->get<auto_boolean> ();
2299 const char *support = get_packet_support_name (value);
2300 const char *target_type = get_target_type_name (remote != nullptr);
2301
2302 if (remote != nullptr)
2303 remote->m_features.m_protocol_packets[packet_idx].detect = value;
2304 else
2305 remote_protocol_packets[packet_idx].detect = value;
2306
2307 gdb_printf (_("Support for the '%s' packet %s is set to \"%s\".\n"), name,
2308 target_type, support);
2309 return;
2310 }
2311
2312 internal_error (_("Could not find config for %s"), c->name);
2313 }
2314
2315 static void
2316 show_packet_config_cmd (ui_file *file, const unsigned int which_packet,
2317 remote_target *remote)
2318 {
2319 const char *support = "internal-error";
2320 const char *target_type = get_target_type_name (remote != nullptr);
2321
2322 packet_config *config;
2323 if (remote != nullptr)
2324 config = &remote->m_features.m_protocol_packets[which_packet];
2325 else
2326 config = &remote_protocol_packets[which_packet];
2327
2328 switch (packet_config_support (config))
2329 {
2330 case PACKET_ENABLE:
2331 support = "enabled";
2332 break;
2333 case PACKET_DISABLE:
2334 support = "disabled";
2335 break;
2336 case PACKET_SUPPORT_UNKNOWN:
2337 support = "unknown";
2338 break;
2339 }
2340 switch (config->detect)
2341 {
2342 case AUTO_BOOLEAN_AUTO:
2343 gdb_printf (file,
2344 _("Support for the '%s' packet %s is \"auto\", "
2345 "currently %s.\n"),
2346 packets_descriptions[which_packet].name, target_type,
2347 support);
2348 break;
2349 case AUTO_BOOLEAN_TRUE:
2350 case AUTO_BOOLEAN_FALSE:
2351 gdb_printf (file,
2352 _("Support for the '%s' packet %s is \"%s\".\n"),
2353 packets_descriptions[which_packet].name, target_type,
2354 get_packet_support_name (config->detect));
2355 break;
2356 }
2357 }
2358
2359 static void
2360 add_packet_config_cmd (const unsigned int which_packet, const char *name,
2361 const char *title, int legacy)
2362 {
2363 packets_descriptions[which_packet].name = name;
2364 packets_descriptions[which_packet].title = title;
2365
2366 packet_config *config = &remote_protocol_packets[which_packet];
2367
2368 gdb::unique_xmalloc_ptr<char> set_doc
2369 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
2370 name, title);
2371 gdb::unique_xmalloc_ptr<char> show_doc
2372 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
2373 name, title);
2374 /* set/show TITLE-packet {auto,on,off} */
2375 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
2376 set_show_commands cmds
2377 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
2378 &config->detect, set_doc.get (),
2379 show_doc.get (), NULL, /* help_doc */
2380 set_remote_protocol_packet_cmd,
2381 show_remote_protocol_packet_cmd,
2382 &remote_set_cmdlist, &remote_show_cmdlist);
2383 cmds.show->set_context (config);
2384 cmds.set->set_context (config);
2385
2386 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
2387 if (legacy)
2388 {
2389 /* It's not clear who should take ownership of the LEGACY_NAME string
2390 created below, so, for now, place the string into a static vector
2391 which ensures the strings is released when GDB exits. */
2392 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
2393 gdb::unique_xmalloc_ptr<char> legacy_name
2394 = xstrprintf ("%s-packet", name);
2395 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
2396 &remote_set_cmdlist);
2397 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
2398 &remote_show_cmdlist);
2399 legacy_names.emplace_back (std::move (legacy_name));
2400 }
2401 }
2402
2403 static enum packet_result
2404 packet_check_result (const char *buf)
2405 {
2406 if (buf[0] != '\0')
2407 {
2408 /* The stub recognized the packet request. Check that the
2409 operation succeeded. */
2410 if (buf[0] == 'E'
2411 && isxdigit (buf[1]) && isxdigit (buf[2])
2412 && buf[3] == '\0')
2413 /* "Enn" - definitely an error. */
2414 return PACKET_ERROR;
2415
2416 /* Always treat "E." as an error. This will be used for
2417 more verbose error messages, such as E.memtypes. */
2418 if (buf[0] == 'E' && buf[1] == '.')
2419 return PACKET_ERROR;
2420
2421 /* The packet may or may not be OK. Just assume it is. */
2422 return PACKET_OK;
2423 }
2424 else
2425 /* The stub does not support the packet. */
2426 return PACKET_UNKNOWN;
2427 }
2428
2429 static enum packet_result
2430 packet_check_result (const gdb::char_vector &buf)
2431 {
2432 return packet_check_result (buf.data ());
2433 }
2434
2435 packet_result
2436 remote_features::packet_ok (const char *buf, const int which_packet)
2437 {
2438 packet_config *config = &m_protocol_packets[which_packet];
2439 packet_description *descr = &packets_descriptions[which_packet];
2440
2441 enum packet_result result;
2442
2443 if (config->detect != AUTO_BOOLEAN_TRUE
2444 && config->support == PACKET_DISABLE)
2445 internal_error (_("packet_ok: attempt to use a disabled packet"));
2446
2447 result = packet_check_result (buf);
2448 switch (result)
2449 {
2450 case PACKET_OK:
2451 case PACKET_ERROR:
2452 /* The stub recognized the packet request. */
2453 if (config->support == PACKET_SUPPORT_UNKNOWN)
2454 {
2455 remote_debug_printf ("Packet %s (%s) is supported",
2456 descr->name, descr->title);
2457 config->support = PACKET_ENABLE;
2458 }
2459 break;
2460 case PACKET_UNKNOWN:
2461 /* The stub does not support the packet. */
2462 if (config->detect == AUTO_BOOLEAN_AUTO
2463 && config->support == PACKET_ENABLE)
2464 {
2465 /* If the stub previously indicated that the packet was
2466 supported then there is a protocol error. */
2467 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2468 descr->name, descr->title);
2469 }
2470 else if (config->detect == AUTO_BOOLEAN_TRUE)
2471 {
2472 /* The user set it wrong. */
2473 error (_("Enabled packet %s (%s) not recognized by stub"),
2474 descr->name, descr->title);
2475 }
2476
2477 remote_debug_printf ("Packet %s (%s) is NOT supported", descr->name,
2478 descr->title);
2479 config->support = PACKET_DISABLE;
2480 break;
2481 }
2482
2483 return result;
2484 }
2485
2486 packet_result
2487 remote_features::packet_ok (const gdb::char_vector &buf, const int which_packet)
2488 {
2489 return packet_ok (buf.data (), which_packet);
2490 }
2491
2492 /* Returns whether a given packet or feature is supported. This takes
2493 into account the state of the corresponding "set remote foo-packet"
2494 command, which may be used to bypass auto-detection. */
2495
2496 static enum packet_support
2497 packet_config_support (const packet_config *config)
2498 {
2499 switch (config->detect)
2500 {
2501 case AUTO_BOOLEAN_TRUE:
2502 return PACKET_ENABLE;
2503 case AUTO_BOOLEAN_FALSE:
2504 return PACKET_DISABLE;
2505 case AUTO_BOOLEAN_AUTO:
2506 return config->support;
2507 default:
2508 gdb_assert_not_reached ("bad switch");
2509 }
2510 }
2511
2512 packet_support
2513 remote_features::packet_support (int packet) const
2514 {
2515 const packet_config *config = &m_protocol_packets[packet];
2516 return packet_config_support (config);
2517 }
2518
2519 static void
2520 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2521 struct cmd_list_element *c,
2522 const char *value)
2523 {
2524 remote_target *remote = get_current_remote_target ();
2525 gdb_assert (c->var.has_value ());
2526
2527 auto *default_config = static_cast<packet_config *> (c->context ());
2528 const int packet_idx = std::distance (remote_protocol_packets,
2529 default_config);
2530
2531 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2532 {
2533 show_packet_config_cmd (file, packet_idx, remote);
2534 return;
2535 }
2536 internal_error (_("Could not find config for %s"), c->name);
2537 }
2538
2539 /* Should we try one of the 'Z' requests? */
2540
2541 enum Z_packet_type
2542 {
2543 Z_PACKET_SOFTWARE_BP,
2544 Z_PACKET_HARDWARE_BP,
2545 Z_PACKET_WRITE_WP,
2546 Z_PACKET_READ_WP,
2547 Z_PACKET_ACCESS_WP,
2548 NR_Z_PACKET_TYPES
2549 };
2550
2551 /* For compatibility with older distributions. Provide a ``set remote
2552 Z-packet ...'' command that updates all the Z packet types. */
2553
2554 static enum auto_boolean remote_Z_packet_detect;
2555
2556 static void
2557 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2558 struct cmd_list_element *c)
2559 {
2560 remote_target *remote = get_current_remote_target ();
2561 int i;
2562
2563 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2564 {
2565 if (remote != nullptr)
2566 remote->m_features.m_protocol_packets[PACKET_Z0 + i].detect
2567 = remote_Z_packet_detect;
2568 else
2569 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2570 }
2571
2572 const char *support = get_packet_support_name (remote_Z_packet_detect);
2573 const char *target_type = get_target_type_name (remote != nullptr);
2574 gdb_printf (_("Use of Z packets %s is set to \"%s\".\n"), target_type,
2575 support);
2576
2577 }
2578
2579 static void
2580 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2581 struct cmd_list_element *c,
2582 const char *value)
2583 {
2584 remote_target *remote = get_current_remote_target ();
2585 int i;
2586
2587 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2588 show_packet_config_cmd (file, PACKET_Z0 + i, remote);
2589 }
2590
2591 /* Insert fork catchpoint target routine. If fork events are enabled
2592 then return success, nothing more to do. */
2593
2594 int
2595 remote_target::insert_fork_catchpoint (int pid)
2596 {
2597 return !m_features.remote_fork_event_p ();
2598 }
2599
2600 /* Remove fork catchpoint target routine. Nothing to do, just
2601 return success. */
2602
2603 int
2604 remote_target::remove_fork_catchpoint (int pid)
2605 {
2606 return 0;
2607 }
2608
2609 /* Insert vfork catchpoint target routine. If vfork events are enabled
2610 then return success, nothing more to do. */
2611
2612 int
2613 remote_target::insert_vfork_catchpoint (int pid)
2614 {
2615 return !m_features.remote_vfork_event_p ();
2616 }
2617
2618 /* Remove vfork catchpoint target routine. Nothing to do, just
2619 return success. */
2620
2621 int
2622 remote_target::remove_vfork_catchpoint (int pid)
2623 {
2624 return 0;
2625 }
2626
2627 /* Insert exec catchpoint target routine. If exec events are
2628 enabled, just return success. */
2629
2630 int
2631 remote_target::insert_exec_catchpoint (int pid)
2632 {
2633 return !m_features.remote_exec_event_p ();
2634 }
2635
2636 /* Remove exec catchpoint target routine. Nothing to do, just
2637 return success. */
2638
2639 int
2640 remote_target::remove_exec_catchpoint (int pid)
2641 {
2642 return 0;
2643 }
2644
2645 \f
2646
2647 /* Take advantage of the fact that the TID field is not used, to tag
2648 special ptids with it set to != 0. */
2649 static const ptid_t magic_null_ptid (42000, -1, 1);
2650 static const ptid_t not_sent_ptid (42000, -2, 1);
2651 static const ptid_t any_thread_ptid (42000, 0, 1);
2652
2653 /* Find out if the stub attached to PID (and hence GDB should offer to
2654 detach instead of killing it when bailing out). */
2655
2656 int
2657 remote_target::remote_query_attached (int pid)
2658 {
2659 struct remote_state *rs = get_remote_state ();
2660 size_t size = get_remote_packet_size ();
2661
2662 if (m_features.packet_support (PACKET_qAttached) == PACKET_DISABLE)
2663 return 0;
2664
2665 if (m_features.remote_multi_process_p ())
2666 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2667 else
2668 xsnprintf (rs->buf.data (), size, "qAttached");
2669
2670 putpkt (rs->buf);
2671 getpkt (&rs->buf);
2672
2673 switch (m_features.packet_ok (rs->buf, PACKET_qAttached))
2674 {
2675 case PACKET_OK:
2676 if (strcmp (rs->buf.data (), "1") == 0)
2677 return 1;
2678 break;
2679 case PACKET_ERROR:
2680 warning (_("Remote failure reply: %s"), rs->buf.data ());
2681 break;
2682 case PACKET_UNKNOWN:
2683 break;
2684 }
2685
2686 return 0;
2687 }
2688
2689 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2690 has been invented by GDB, instead of reported by the target. Since
2691 we can be connected to a remote system before before knowing about
2692 any inferior, mark the target with execution when we find the first
2693 inferior. If ATTACHED is 1, then we had just attached to this
2694 inferior. If it is 0, then we just created this inferior. If it
2695 is -1, then try querying the remote stub to find out if it had
2696 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2697 attempt to open this inferior's executable as the main executable
2698 if no main executable is open already. */
2699
2700 inferior *
2701 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2702 int try_open_exec)
2703 {
2704 struct inferior *inf;
2705
2706 /* Check whether this process we're learning about is to be
2707 considered attached, or if is to be considered to have been
2708 spawned by the stub. */
2709 if (attached == -1)
2710 attached = remote_query_attached (pid);
2711
2712 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
2713 {
2714 /* If the target shares code across all inferiors, then every
2715 attach adds a new inferior. */
2716 inf = add_inferior (pid);
2717
2718 /* ... and every inferior is bound to the same program space.
2719 However, each inferior may still have its own address
2720 space. */
2721 inf->aspace = maybe_new_address_space ();
2722 inf->pspace = current_program_space;
2723 }
2724 else
2725 {
2726 /* In the traditional debugging scenario, there's a 1-1 match
2727 between program/address spaces. We simply bind the inferior
2728 to the program space's address space. */
2729 inf = current_inferior ();
2730
2731 /* However, if the current inferior is already bound to a
2732 process, find some other empty inferior. */
2733 if (inf->pid != 0)
2734 {
2735 inf = nullptr;
2736 for (inferior *it : all_inferiors ())
2737 if (it->pid == 0)
2738 {
2739 inf = it;
2740 break;
2741 }
2742 }
2743 if (inf == nullptr)
2744 {
2745 /* Since all inferiors were already bound to a process, add
2746 a new inferior. */
2747 inf = add_inferior_with_spaces ();
2748 }
2749 switch_to_inferior_no_thread (inf);
2750 inf->push_target (this);
2751 inferior_appeared (inf, pid);
2752 }
2753
2754 inf->attach_flag = attached;
2755 inf->fake_pid_p = fake_pid_p;
2756
2757 /* If no main executable is currently open then attempt to
2758 open the file that was executed to create this inferior. */
2759 if (try_open_exec && get_exec_file (0) == NULL)
2760 exec_file_locate_attach (pid, 0, 1);
2761
2762 /* Check for exec file mismatch, and let the user solve it. */
2763 validate_exec_file (1);
2764
2765 return inf;
2766 }
2767
2768 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2769 static remote_thread_info *get_remote_thread_info (remote_target *target,
2770 ptid_t ptid);
2771
2772 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2773 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2774 remote_state::starting_up flag) is true then the new thread is added
2775 silently, otherwise the new thread will be announced to the user. */
2776
2777 thread_info *
2778 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2779 bool silent_p)
2780 {
2781 struct remote_state *rs = get_remote_state ();
2782 struct thread_info *thread;
2783
2784 /* GDB historically didn't pull threads in the initial connection
2785 setup. If the remote target doesn't even have a concept of
2786 threads (e.g., a bare-metal target), even if internally we
2787 consider that a single-threaded target, mentioning a new thread
2788 might be confusing to the user. Be silent then, preserving the
2789 age old behavior. */
2790 if (rs->starting_up || silent_p)
2791 thread = add_thread_silent (this, ptid);
2792 else
2793 thread = add_thread (this, ptid);
2794
2795 /* We start by assuming threads are resumed. That state then gets updated
2796 when we process a matching stop reply. */
2797 get_remote_thread_info (thread)->set_resumed ();
2798
2799 set_executing (this, ptid, executing);
2800 set_running (this, ptid, running);
2801
2802 return thread;
2803 }
2804
2805 /* Come here when we learn about a thread id from the remote target.
2806 It may be the first time we hear about such thread, so take the
2807 opportunity to add it to GDB's thread list. In case this is the
2808 first time we're noticing its corresponding inferior, add it to
2809 GDB's inferior list as well. EXECUTING indicates whether the
2810 thread is (internally) executing or stopped. */
2811
2812 void
2813 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2814 {
2815 /* In non-stop mode, we assume new found threads are (externally)
2816 running until proven otherwise with a stop reply. In all-stop,
2817 we can only get here if all threads are stopped. */
2818 bool running = target_is_non_stop_p ();
2819
2820 /* If this is a new thread, add it to GDB's thread list.
2821 If we leave it up to WFI to do this, bad things will happen. */
2822
2823 thread_info *tp = this->find_thread (currthread);
2824 if (tp != NULL && tp->state == THREAD_EXITED)
2825 {
2826 /* We're seeing an event on a thread id we knew had exited.
2827 This has to be a new thread reusing the old id. Add it. */
2828 remote_add_thread (currthread, running, executing, false);
2829 return;
2830 }
2831
2832 if (!in_thread_list (this, currthread))
2833 {
2834 struct inferior *inf = NULL;
2835 int pid = currthread.pid ();
2836
2837 if (inferior_ptid.is_pid ()
2838 && pid == inferior_ptid.pid ())
2839 {
2840 /* inferior_ptid has no thread member yet. This can happen
2841 with the vAttach -> remote_wait,"TAAthread:" path if the
2842 stub doesn't support qC. This is the first stop reported
2843 after an attach, so this is the main thread. Update the
2844 ptid in the thread list. */
2845 if (in_thread_list (this, ptid_t (pid)))
2846 thread_change_ptid (this, inferior_ptid, currthread);
2847 else
2848 {
2849 thread_info *thr
2850 = remote_add_thread (currthread, running, executing, false);
2851 switch_to_thread (thr);
2852 }
2853 return;
2854 }
2855
2856 if (magic_null_ptid == inferior_ptid)
2857 {
2858 /* inferior_ptid is not set yet. This can happen with the
2859 vRun -> remote_wait,"TAAthread:" path if the stub
2860 doesn't support qC. This is the first stop reported
2861 after an attach, so this is the main thread. Update the
2862 ptid in the thread list. */
2863 thread_change_ptid (this, inferior_ptid, currthread);
2864 return;
2865 }
2866
2867 /* When connecting to a target remote, or to a target
2868 extended-remote which already was debugging an inferior, we
2869 may not know about it yet. Add it before adding its child
2870 thread, so notifications are emitted in a sensible order. */
2871 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2872 {
2873 bool fake_pid_p = !m_features.remote_multi_process_p ();
2874
2875 inf = remote_add_inferior (fake_pid_p,
2876 currthread.pid (), -1, 1);
2877 }
2878
2879 /* This is really a new thread. Add it. */
2880 thread_info *new_thr
2881 = remote_add_thread (currthread, running, executing, false);
2882
2883 /* If we found a new inferior, let the common code do whatever
2884 it needs to with it (e.g., read shared libraries, insert
2885 breakpoints), unless we're just setting up an all-stop
2886 connection. */
2887 if (inf != NULL)
2888 {
2889 struct remote_state *rs = get_remote_state ();
2890
2891 if (!rs->starting_up)
2892 notice_new_inferior (new_thr, executing, 0);
2893 }
2894 }
2895 }
2896
2897 /* Return THREAD's private thread data, creating it if necessary. */
2898
2899 static remote_thread_info *
2900 get_remote_thread_info (thread_info *thread)
2901 {
2902 gdb_assert (thread != NULL);
2903
2904 if (thread->priv == NULL)
2905 thread->priv.reset (new remote_thread_info);
2906
2907 return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
2908 }
2909
2910 /* Return PTID's private thread data, creating it if necessary. */
2911
2912 static remote_thread_info *
2913 get_remote_thread_info (remote_target *target, ptid_t ptid)
2914 {
2915 thread_info *thr = target->find_thread (ptid);
2916 return get_remote_thread_info (thr);
2917 }
2918
2919 /* Call this function as a result of
2920 1) A halt indication (T packet) containing a thread id
2921 2) A direct query of currthread
2922 3) Successful execution of set thread */
2923
2924 static void
2925 record_currthread (struct remote_state *rs, ptid_t currthread)
2926 {
2927 rs->general_thread = currthread;
2928 }
2929
2930 /* If 'QPassSignals' is supported, tell the remote stub what signals
2931 it can simply pass through to the inferior without reporting. */
2932
2933 void
2934 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2935 {
2936 if (m_features.packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2937 {
2938 char *pass_packet, *p;
2939 int count = 0;
2940 struct remote_state *rs = get_remote_state ();
2941
2942 gdb_assert (pass_signals.size () < 256);
2943 for (size_t i = 0; i < pass_signals.size (); i++)
2944 {
2945 if (pass_signals[i])
2946 count++;
2947 }
2948 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2949 strcpy (pass_packet, "QPassSignals:");
2950 p = pass_packet + strlen (pass_packet);
2951 for (size_t i = 0; i < pass_signals.size (); i++)
2952 {
2953 if (pass_signals[i])
2954 {
2955 if (i >= 16)
2956 *p++ = tohex (i >> 4);
2957 *p++ = tohex (i & 15);
2958 if (count)
2959 *p++ = ';';
2960 else
2961 break;
2962 count--;
2963 }
2964 }
2965 *p = 0;
2966 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2967 {
2968 putpkt (pass_packet);
2969 getpkt (&rs->buf);
2970 m_features.packet_ok (rs->buf, PACKET_QPassSignals);
2971 xfree (rs->last_pass_packet);
2972 rs->last_pass_packet = pass_packet;
2973 }
2974 else
2975 xfree (pass_packet);
2976 }
2977 }
2978
2979 /* If 'QCatchSyscalls' is supported, tell the remote stub
2980 to report syscalls to GDB. */
2981
2982 int
2983 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2984 gdb::array_view<const int> syscall_counts)
2985 {
2986 const char *catch_packet;
2987 enum packet_result result;
2988 int n_sysno = 0;
2989
2990 if (m_features.packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2991 {
2992 /* Not supported. */
2993 return 1;
2994 }
2995
2996 if (needed && any_count == 0)
2997 {
2998 /* Count how many syscalls are to be caught. */
2999 for (size_t i = 0; i < syscall_counts.size (); i++)
3000 {
3001 if (syscall_counts[i] != 0)
3002 n_sysno++;
3003 }
3004 }
3005
3006 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
3007 pid, needed, any_count, n_sysno);
3008
3009 std::string built_packet;
3010 if (needed)
3011 {
3012 /* Prepare a packet with the sysno list, assuming max 8+1
3013 characters for a sysno. If the resulting packet size is too
3014 big, fallback on the non-selective packet. */
3015 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
3016 built_packet.reserve (maxpktsz);
3017 built_packet = "QCatchSyscalls:1";
3018 if (any_count == 0)
3019 {
3020 /* Add in each syscall to be caught. */
3021 for (size_t i = 0; i < syscall_counts.size (); i++)
3022 {
3023 if (syscall_counts[i] != 0)
3024 string_appendf (built_packet, ";%zx", i);
3025 }
3026 }
3027 if (built_packet.size () > get_remote_packet_size ())
3028 {
3029 /* catch_packet too big. Fallback to less efficient
3030 non selective mode, with GDB doing the filtering. */
3031 catch_packet = "QCatchSyscalls:1";
3032 }
3033 else
3034 catch_packet = built_packet.c_str ();
3035 }
3036 else
3037 catch_packet = "QCatchSyscalls:0";
3038
3039 struct remote_state *rs = get_remote_state ();
3040
3041 putpkt (catch_packet);
3042 getpkt (&rs->buf);
3043 result = m_features.packet_ok (rs->buf, PACKET_QCatchSyscalls);
3044 if (result == PACKET_OK)
3045 return 0;
3046 else
3047 return -1;
3048 }
3049
3050 /* If 'QProgramSignals' is supported, tell the remote stub what
3051 signals it should pass through to the inferior when detaching. */
3052
3053 void
3054 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
3055 {
3056 if (m_features.packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
3057 {
3058 char *packet, *p;
3059 int count = 0;
3060 struct remote_state *rs = get_remote_state ();
3061
3062 gdb_assert (signals.size () < 256);
3063 for (size_t i = 0; i < signals.size (); i++)
3064 {
3065 if (signals[i])
3066 count++;
3067 }
3068 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
3069 strcpy (packet, "QProgramSignals:");
3070 p = packet + strlen (packet);
3071 for (size_t i = 0; i < signals.size (); i++)
3072 {
3073 if (signal_pass_state (i))
3074 {
3075 if (i >= 16)
3076 *p++ = tohex (i >> 4);
3077 *p++ = tohex (i & 15);
3078 if (count)
3079 *p++ = ';';
3080 else
3081 break;
3082 count--;
3083 }
3084 }
3085 *p = 0;
3086 if (!rs->last_program_signals_packet
3087 || strcmp (rs->last_program_signals_packet, packet) != 0)
3088 {
3089 putpkt (packet);
3090 getpkt (&rs->buf);
3091 m_features.packet_ok (rs->buf, PACKET_QProgramSignals);
3092 xfree (rs->last_program_signals_packet);
3093 rs->last_program_signals_packet = packet;
3094 }
3095 else
3096 xfree (packet);
3097 }
3098 }
3099
3100 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
3101 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
3102 thread. If GEN is set, set the general thread, if not, then set
3103 the step/continue thread. */
3104 void
3105 remote_target::set_thread (ptid_t ptid, int gen)
3106 {
3107 struct remote_state *rs = get_remote_state ();
3108 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
3109 char *buf = rs->buf.data ();
3110 char *endbuf = buf + get_remote_packet_size ();
3111
3112 if (state == ptid)
3113 return;
3114
3115 *buf++ = 'H';
3116 *buf++ = gen ? 'g' : 'c';
3117 if (ptid == magic_null_ptid)
3118 xsnprintf (buf, endbuf - buf, "0");
3119 else if (ptid == any_thread_ptid)
3120 xsnprintf (buf, endbuf - buf, "0");
3121 else if (ptid == minus_one_ptid)
3122 xsnprintf (buf, endbuf - buf, "-1");
3123 else
3124 write_ptid (buf, endbuf, ptid);
3125 putpkt (rs->buf);
3126 getpkt (&rs->buf);
3127 if (gen)
3128 rs->general_thread = ptid;
3129 else
3130 rs->continue_thread = ptid;
3131 }
3132
3133 void
3134 remote_target::set_general_thread (ptid_t ptid)
3135 {
3136 set_thread (ptid, 1);
3137 }
3138
3139 void
3140 remote_target::set_continue_thread (ptid_t ptid)
3141 {
3142 set_thread (ptid, 0);
3143 }
3144
3145 /* Change the remote current process. Which thread within the process
3146 ends up selected isn't important, as long as it is the same process
3147 as what INFERIOR_PTID points to.
3148
3149 This comes from that fact that there is no explicit notion of
3150 "selected process" in the protocol. The selected process for
3151 general operations is the process the selected general thread
3152 belongs to. */
3153
3154 void
3155 remote_target::set_general_process ()
3156 {
3157 /* If the remote can't handle multiple processes, don't bother. */
3158 if (!m_features.remote_multi_process_p ())
3159 return;
3160
3161 remote_state *rs = get_remote_state ();
3162
3163 /* We only need to change the remote current thread if it's pointing
3164 at some other process. */
3165 if (rs->general_thread.pid () != inferior_ptid.pid ())
3166 set_general_thread (inferior_ptid);
3167 }
3168
3169 \f
3170 /* Return nonzero if this is the main thread that we made up ourselves
3171 to model non-threaded targets as single-threaded. */
3172
3173 static int
3174 remote_thread_always_alive (ptid_t ptid)
3175 {
3176 if (ptid == magic_null_ptid)
3177 /* The main thread is always alive. */
3178 return 1;
3179
3180 if (ptid.pid () != 0 && ptid.lwp () == 0)
3181 /* The main thread is always alive. This can happen after a
3182 vAttach, if the remote side doesn't support
3183 multi-threading. */
3184 return 1;
3185
3186 return 0;
3187 }
3188
3189 /* Return nonzero if the thread PTID is still alive on the remote
3190 system. */
3191
3192 bool
3193 remote_target::thread_alive (ptid_t ptid)
3194 {
3195 struct remote_state *rs = get_remote_state ();
3196 char *p, *endp;
3197
3198 /* Check if this is a thread that we made up ourselves to model
3199 non-threaded targets as single-threaded. */
3200 if (remote_thread_always_alive (ptid))
3201 return 1;
3202
3203 p = rs->buf.data ();
3204 endp = p + get_remote_packet_size ();
3205
3206 *p++ = 'T';
3207 write_ptid (p, endp, ptid);
3208
3209 putpkt (rs->buf);
3210 getpkt (&rs->buf);
3211 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
3212 }
3213
3214 /* Return a pointer to a thread name if we know it and NULL otherwise.
3215 The thread_info object owns the memory for the name. */
3216
3217 const char *
3218 remote_target::thread_name (struct thread_info *info)
3219 {
3220 if (info->priv != NULL)
3221 {
3222 const std::string &name = get_remote_thread_info (info)->name;
3223 return !name.empty () ? name.c_str () : NULL;
3224 }
3225
3226 return NULL;
3227 }
3228
3229 /* About these extended threadlist and threadinfo packets. They are
3230 variable length packets but, the fields within them are often fixed
3231 length. They are redundant enough to send over UDP as is the
3232 remote protocol in general. There is a matching unit test module
3233 in libstub. */
3234
3235 /* WARNING: This threadref data structure comes from the remote O.S.,
3236 libstub protocol encoding, and remote.c. It is not particularly
3237 changeable. */
3238
3239 /* Right now, the internal structure is int. We want it to be bigger.
3240 Plan to fix this. */
3241
3242 typedef int gdb_threadref; /* Internal GDB thread reference. */
3243
3244 /* gdb_ext_thread_info is an internal GDB data structure which is
3245 equivalent to the reply of the remote threadinfo packet. */
3246
3247 struct gdb_ext_thread_info
3248 {
3249 threadref threadid; /* External form of thread reference. */
3250 int active; /* Has state interesting to GDB?
3251 regs, stack. */
3252 char display[256]; /* Brief state display, name,
3253 blocked/suspended. */
3254 char shortname[32]; /* To be used to name threads. */
3255 char more_display[256]; /* Long info, statistics, queue depth,
3256 whatever. */
3257 };
3258
3259 /* The volume of remote transfers can be limited by submitting
3260 a mask containing bits specifying the desired information.
3261 Use a union of these values as the 'selection' parameter to
3262 get_thread_info. FIXME: Make these TAG names more thread specific. */
3263
3264 #define TAG_THREADID 1
3265 #define TAG_EXISTS 2
3266 #define TAG_DISPLAY 4
3267 #define TAG_THREADNAME 8
3268 #define TAG_MOREDISPLAY 16
3269
3270 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3271
3272 static const char *unpack_nibble (const char *buf, int *val);
3273
3274 static const char *unpack_byte (const char *buf, int *value);
3275
3276 static char *pack_int (char *buf, int value);
3277
3278 static const char *unpack_int (const char *buf, int *value);
3279
3280 static const char *unpack_string (const char *src, char *dest, int length);
3281
3282 static char *pack_threadid (char *pkt, threadref *id);
3283
3284 static const char *unpack_threadid (const char *inbuf, threadref *id);
3285
3286 void int_to_threadref (threadref *id, int value);
3287
3288 static int threadref_to_int (threadref *ref);
3289
3290 static void copy_threadref (threadref *dest, threadref *src);
3291
3292 static int threadmatch (threadref *dest, threadref *src);
3293
3294 static char *pack_threadinfo_request (char *pkt, int mode,
3295 threadref *id);
3296
3297 static char *pack_threadlist_request (char *pkt, int startflag,
3298 int threadcount,
3299 threadref *nextthread);
3300
3301 static int remote_newthread_step (threadref *ref, void *context);
3302
3303
3304 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3305 buffer we're allowed to write to. Returns
3306 BUF+CHARACTERS_WRITTEN. */
3307
3308 char *
3309 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3310 {
3311 int pid, tid;
3312
3313 if (m_features.remote_multi_process_p ())
3314 {
3315 pid = ptid.pid ();
3316 if (pid < 0)
3317 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3318 else
3319 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3320 }
3321 tid = ptid.lwp ();
3322 if (tid < 0)
3323 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3324 else
3325 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3326
3327 return buf;
3328 }
3329
3330 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3331 last parsed char. Returns null_ptid if no thread id is found, and
3332 throws an error if the thread id has an invalid format. */
3333
3334 static ptid_t
3335 read_ptid (const char *buf, const char **obuf)
3336 {
3337 const char *p = buf;
3338 const char *pp;
3339 ULONGEST pid = 0, tid = 0;
3340
3341 if (*p == 'p')
3342 {
3343 /* Multi-process ptid. */
3344 pp = unpack_varlen_hex (p + 1, &pid);
3345 if (*pp != '.')
3346 error (_("invalid remote ptid: %s"), p);
3347
3348 p = pp;
3349 pp = unpack_varlen_hex (p + 1, &tid);
3350 if (obuf)
3351 *obuf = pp;
3352 return ptid_t (pid, tid);
3353 }
3354
3355 /* No multi-process. Just a tid. */
3356 pp = unpack_varlen_hex (p, &tid);
3357
3358 /* Return null_ptid when no thread id is found. */
3359 if (p == pp)
3360 {
3361 if (obuf)
3362 *obuf = pp;
3363 return null_ptid;
3364 }
3365
3366 /* Since the stub is not sending a process id, default to what's
3367 current_inferior, unless it doesn't have a PID yet. If so,
3368 then since there's no way to know the pid of the reported
3369 threads, use the magic number. */
3370 inferior *inf = current_inferior ();
3371 if (inf->pid == 0)
3372 pid = magic_null_ptid.pid ();
3373 else
3374 pid = inf->pid;
3375
3376 if (obuf)
3377 *obuf = pp;
3378 return ptid_t (pid, tid);
3379 }
3380
3381 static int
3382 stubhex (int ch)
3383 {
3384 if (ch >= 'a' && ch <= 'f')
3385 return ch - 'a' + 10;
3386 if (ch >= '0' && ch <= '9')
3387 return ch - '0';
3388 if (ch >= 'A' && ch <= 'F')
3389 return ch - 'A' + 10;
3390 return -1;
3391 }
3392
3393 static int
3394 stub_unpack_int (const char *buff, int fieldlength)
3395 {
3396 int nibble;
3397 int retval = 0;
3398
3399 while (fieldlength)
3400 {
3401 nibble = stubhex (*buff++);
3402 retval |= nibble;
3403 fieldlength--;
3404 if (fieldlength)
3405 retval = retval << 4;
3406 }
3407 return retval;
3408 }
3409
3410 static const char *
3411 unpack_nibble (const char *buf, int *val)
3412 {
3413 *val = fromhex (*buf++);
3414 return buf;
3415 }
3416
3417 static const char *
3418 unpack_byte (const char *buf, int *value)
3419 {
3420 *value = stub_unpack_int (buf, 2);
3421 return buf + 2;
3422 }
3423
3424 static char *
3425 pack_int (char *buf, int value)
3426 {
3427 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3428 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3429 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3430 buf = pack_hex_byte (buf, (value & 0xff));
3431 return buf;
3432 }
3433
3434 static const char *
3435 unpack_int (const char *buf, int *value)
3436 {
3437 *value = stub_unpack_int (buf, 8);
3438 return buf + 8;
3439 }
3440
3441 #if 0 /* Currently unused, uncomment when needed. */
3442 static char *pack_string (char *pkt, char *string);
3443
3444 static char *
3445 pack_string (char *pkt, char *string)
3446 {
3447 char ch;
3448 int len;
3449
3450 len = strlen (string);
3451 if (len > 200)
3452 len = 200; /* Bigger than most GDB packets, junk??? */
3453 pkt = pack_hex_byte (pkt, len);
3454 while (len-- > 0)
3455 {
3456 ch = *string++;
3457 if ((ch == '\0') || (ch == '#'))
3458 ch = '*'; /* Protect encapsulation. */
3459 *pkt++ = ch;
3460 }
3461 return pkt;
3462 }
3463 #endif /* 0 (unused) */
3464
3465 static const char *
3466 unpack_string (const char *src, char *dest, int length)
3467 {
3468 while (length--)
3469 *dest++ = *src++;
3470 *dest = '\0';
3471 return src;
3472 }
3473
3474 static char *
3475 pack_threadid (char *pkt, threadref *id)
3476 {
3477 char *limit;
3478 unsigned char *altid;
3479
3480 altid = (unsigned char *) id;
3481 limit = pkt + BUF_THREAD_ID_SIZE;
3482 while (pkt < limit)
3483 pkt = pack_hex_byte (pkt, *altid++);
3484 return pkt;
3485 }
3486
3487
3488 static const char *
3489 unpack_threadid (const char *inbuf, threadref *id)
3490 {
3491 char *altref;
3492 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3493 int x, y;
3494
3495 altref = (char *) id;
3496
3497 while (inbuf < limit)
3498 {
3499 x = stubhex (*inbuf++);
3500 y = stubhex (*inbuf++);
3501 *altref++ = (x << 4) | y;
3502 }
3503 return inbuf;
3504 }
3505
3506 /* Externally, threadrefs are 64 bits but internally, they are still
3507 ints. This is due to a mismatch of specifications. We would like
3508 to use 64bit thread references internally. This is an adapter
3509 function. */
3510
3511 void
3512 int_to_threadref (threadref *id, int value)
3513 {
3514 unsigned char *scan;
3515
3516 scan = (unsigned char *) id;
3517 {
3518 int i = 4;
3519 while (i--)
3520 *scan++ = 0;
3521 }
3522 *scan++ = (value >> 24) & 0xff;
3523 *scan++ = (value >> 16) & 0xff;
3524 *scan++ = (value >> 8) & 0xff;
3525 *scan++ = (value & 0xff);
3526 }
3527
3528 static int
3529 threadref_to_int (threadref *ref)
3530 {
3531 int i, value = 0;
3532 unsigned char *scan;
3533
3534 scan = *ref;
3535 scan += 4;
3536 i = 4;
3537 while (i-- > 0)
3538 value = (value << 8) | ((*scan++) & 0xff);
3539 return value;
3540 }
3541
3542 static void
3543 copy_threadref (threadref *dest, threadref *src)
3544 {
3545 int i;
3546 unsigned char *csrc, *cdest;
3547
3548 csrc = (unsigned char *) src;
3549 cdest = (unsigned char *) dest;
3550 i = 8;
3551 while (i--)
3552 *cdest++ = *csrc++;
3553 }
3554
3555 static int
3556 threadmatch (threadref *dest, threadref *src)
3557 {
3558 /* Things are broken right now, so just assume we got a match. */
3559 #if 0
3560 unsigned char *srcp, *destp;
3561 int i, result;
3562 srcp = (char *) src;
3563 destp = (char *) dest;
3564
3565 result = 1;
3566 while (i-- > 0)
3567 result &= (*srcp++ == *destp++) ? 1 : 0;
3568 return result;
3569 #endif
3570 return 1;
3571 }
3572
3573 /*
3574 threadid:1, # always request threadid
3575 context_exists:2,
3576 display:4,
3577 unique_name:8,
3578 more_display:16
3579 */
3580
3581 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3582
3583 static char *
3584 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3585 {
3586 *pkt++ = 'q'; /* Info Query */
3587 *pkt++ = 'P'; /* process or thread info */
3588 pkt = pack_int (pkt, mode); /* mode */
3589 pkt = pack_threadid (pkt, id); /* threadid */
3590 *pkt = '\0'; /* terminate */
3591 return pkt;
3592 }
3593
3594 /* These values tag the fields in a thread info response packet. */
3595 /* Tagging the fields allows us to request specific fields and to
3596 add more fields as time goes by. */
3597
3598 #define TAG_THREADID 1 /* Echo the thread identifier. */
3599 #define TAG_EXISTS 2 /* Is this process defined enough to
3600 fetch registers and its stack? */
3601 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3602 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3603 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3604 the process. */
3605
3606 int
3607 remote_target::remote_unpack_thread_info_response (const char *pkt,
3608 threadref *expectedref,
3609 gdb_ext_thread_info *info)
3610 {
3611 struct remote_state *rs = get_remote_state ();
3612 int mask, length;
3613 int tag;
3614 threadref ref;
3615 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3616 int retval = 1;
3617
3618 /* info->threadid = 0; FIXME: implement zero_threadref. */
3619 info->active = 0;
3620 info->display[0] = '\0';
3621 info->shortname[0] = '\0';
3622 info->more_display[0] = '\0';
3623
3624 /* Assume the characters indicating the packet type have been
3625 stripped. */
3626 pkt = unpack_int (pkt, &mask); /* arg mask */
3627 pkt = unpack_threadid (pkt, &ref);
3628
3629 if (mask == 0)
3630 warning (_("Incomplete response to threadinfo request."));
3631 if (!threadmatch (&ref, expectedref))
3632 { /* This is an answer to a different request. */
3633 warning (_("ERROR RMT Thread info mismatch."));
3634 return 0;
3635 }
3636 copy_threadref (&info->threadid, &ref);
3637
3638 /* Loop on tagged fields , try to bail if something goes wrong. */
3639
3640 /* Packets are terminated with nulls. */
3641 while ((pkt < limit) && mask && *pkt)
3642 {
3643 pkt = unpack_int (pkt, &tag); /* tag */
3644 pkt = unpack_byte (pkt, &length); /* length */
3645 if (!(tag & mask)) /* Tags out of synch with mask. */
3646 {
3647 warning (_("ERROR RMT: threadinfo tag mismatch."));
3648 retval = 0;
3649 break;
3650 }
3651 if (tag == TAG_THREADID)
3652 {
3653 if (length != 16)
3654 {
3655 warning (_("ERROR RMT: length of threadid is not 16."));
3656 retval = 0;
3657 break;
3658 }
3659 pkt = unpack_threadid (pkt, &ref);
3660 mask = mask & ~TAG_THREADID;
3661 continue;
3662 }
3663 if (tag == TAG_EXISTS)
3664 {
3665 info->active = stub_unpack_int (pkt, length);
3666 pkt += length;
3667 mask = mask & ~(TAG_EXISTS);
3668 if (length > 8)
3669 {
3670 warning (_("ERROR RMT: 'exists' length too long."));
3671 retval = 0;
3672 break;
3673 }
3674 continue;
3675 }
3676 if (tag == TAG_THREADNAME)
3677 {
3678 pkt = unpack_string (pkt, &info->shortname[0], length);
3679 mask = mask & ~TAG_THREADNAME;
3680 continue;
3681 }
3682 if (tag == TAG_DISPLAY)
3683 {
3684 pkt = unpack_string (pkt, &info->display[0], length);
3685 mask = mask & ~TAG_DISPLAY;
3686 continue;
3687 }
3688 if (tag == TAG_MOREDISPLAY)
3689 {
3690 pkt = unpack_string (pkt, &info->more_display[0], length);
3691 mask = mask & ~TAG_MOREDISPLAY;
3692 continue;
3693 }
3694 warning (_("ERROR RMT: unknown thread info tag."));
3695 break; /* Not a tag we know about. */
3696 }
3697 return retval;
3698 }
3699
3700 int
3701 remote_target::remote_get_threadinfo (threadref *threadid,
3702 int fieldset,
3703 gdb_ext_thread_info *info)
3704 {
3705 struct remote_state *rs = get_remote_state ();
3706 int result;
3707
3708 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3709 putpkt (rs->buf);
3710 getpkt (&rs->buf);
3711
3712 if (rs->buf[0] == '\0')
3713 return 0;
3714
3715 result = remote_unpack_thread_info_response (&rs->buf[2],
3716 threadid, info);
3717 return result;
3718 }
3719
3720 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3721
3722 static char *
3723 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3724 threadref *nextthread)
3725 {
3726 *pkt++ = 'q'; /* info query packet */
3727 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3728 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3729 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3730 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3731 *pkt = '\0';
3732 return pkt;
3733 }
3734
3735 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3736
3737 int
3738 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3739 threadref *original_echo,
3740 threadref *resultlist,
3741 int *doneflag)
3742 {
3743 struct remote_state *rs = get_remote_state ();
3744 int count, resultcount, done;
3745
3746 resultcount = 0;
3747 /* Assume the 'q' and 'M chars have been stripped. */
3748 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3749 /* done parse past here */
3750 pkt = unpack_byte (pkt, &count); /* count field */
3751 pkt = unpack_nibble (pkt, &done);
3752 /* The first threadid is the argument threadid. */
3753 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3754 while ((count-- > 0) && (pkt < limit))
3755 {
3756 pkt = unpack_threadid (pkt, resultlist++);
3757 if (resultcount++ >= result_limit)
3758 break;
3759 }
3760 if (doneflag)
3761 *doneflag = done;
3762 return resultcount;
3763 }
3764
3765 /* Fetch the next batch of threads from the remote. Returns -1 if the
3766 qL packet is not supported, 0 on error and 1 on success. */
3767
3768 int
3769 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3770 int result_limit, int *done, int *result_count,
3771 threadref *threadlist)
3772 {
3773 struct remote_state *rs = get_remote_state ();
3774 int result = 1;
3775
3776 /* Truncate result limit to be smaller than the packet size. */
3777 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3778 >= get_remote_packet_size ())
3779 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3780
3781 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3782 nextthread);
3783 putpkt (rs->buf);
3784 getpkt (&rs->buf);
3785 if (rs->buf[0] == '\0')
3786 {
3787 /* Packet not supported. */
3788 return -1;
3789 }
3790
3791 *result_count =
3792 parse_threadlist_response (&rs->buf[2], result_limit,
3793 &rs->echo_nextthread, threadlist, done);
3794
3795 if (!threadmatch (&rs->echo_nextthread, nextthread))
3796 {
3797 /* FIXME: This is a good reason to drop the packet. */
3798 /* Possibly, there is a duplicate response. */
3799 /* Possibilities :
3800 retransmit immediatly - race conditions
3801 retransmit after timeout - yes
3802 exit
3803 wait for packet, then exit
3804 */
3805 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3806 return 0; /* I choose simply exiting. */
3807 }
3808 if (*result_count <= 0)
3809 {
3810 if (*done != 1)
3811 {
3812 warning (_("RMT ERROR : failed to get remote thread list."));
3813 result = 0;
3814 }
3815 return result; /* break; */
3816 }
3817 if (*result_count > result_limit)
3818 {
3819 *result_count = 0;
3820 warning (_("RMT ERROR: threadlist response longer than requested."));
3821 return 0;
3822 }
3823 return result;
3824 }
3825
3826 /* Fetch the list of remote threads, with the qL packet, and call
3827 STEPFUNCTION for each thread found. Stops iterating and returns 1
3828 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3829 STEPFUNCTION returns false. If the packet is not supported,
3830 returns -1. */
3831
3832 int
3833 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3834 void *context, int looplimit)
3835 {
3836 struct remote_state *rs = get_remote_state ();
3837 int done, i, result_count;
3838 int startflag = 1;
3839 int result = 1;
3840 int loopcount = 0;
3841
3842 done = 0;
3843 while (!done)
3844 {
3845 if (loopcount++ > looplimit)
3846 {
3847 result = 0;
3848 warning (_("Remote fetch threadlist -infinite loop-."));
3849 break;
3850 }
3851 result = remote_get_threadlist (startflag, &rs->nextthread,
3852 MAXTHREADLISTRESULTS,
3853 &done, &result_count,
3854 rs->resultthreadlist);
3855 if (result <= 0)
3856 break;
3857 /* Clear for later iterations. */
3858 startflag = 0;
3859 /* Setup to resume next batch of thread references, set nextthread. */
3860 if (result_count >= 1)
3861 copy_threadref (&rs->nextthread,
3862 &rs->resultthreadlist[result_count - 1]);
3863 i = 0;
3864 while (result_count--)
3865 {
3866 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3867 {
3868 result = 0;
3869 break;
3870 }
3871 }
3872 }
3873 return result;
3874 }
3875
3876 /* A thread found on the remote target. */
3877
3878 struct thread_item
3879 {
3880 explicit thread_item (ptid_t ptid_)
3881 : ptid (ptid_)
3882 {}
3883
3884 thread_item (thread_item &&other) = default;
3885 thread_item &operator= (thread_item &&other) = default;
3886
3887 DISABLE_COPY_AND_ASSIGN (thread_item);
3888
3889 /* The thread's PTID. */
3890 ptid_t ptid;
3891
3892 /* The thread's extra info. */
3893 std::string extra;
3894
3895 /* The thread's name. */
3896 std::string name;
3897
3898 /* The core the thread was running on. -1 if not known. */
3899 int core = -1;
3900
3901 /* The thread handle associated with the thread. */
3902 gdb::byte_vector thread_handle;
3903 };
3904
3905 /* Context passed around to the various methods listing remote
3906 threads. As new threads are found, they're added to the ITEMS
3907 vector. */
3908
3909 struct threads_listing_context
3910 {
3911 /* Return true if this object contains an entry for a thread with ptid
3912 PTID. */
3913
3914 bool contains_thread (ptid_t ptid) const
3915 {
3916 auto match_ptid = [&] (const thread_item &item)
3917 {
3918 return item.ptid == ptid;
3919 };
3920
3921 auto it = std::find_if (this->items.begin (),
3922 this->items.end (),
3923 match_ptid);
3924
3925 return it != this->items.end ();
3926 }
3927
3928 /* Remove the thread with ptid PTID. */
3929
3930 void remove_thread (ptid_t ptid)
3931 {
3932 auto match_ptid = [&] (const thread_item &item)
3933 {
3934 return item.ptid == ptid;
3935 };
3936
3937 auto it = std::remove_if (this->items.begin (),
3938 this->items.end (),
3939 match_ptid);
3940
3941 if (it != this->items.end ())
3942 this->items.erase (it);
3943 }
3944
3945 /* The threads found on the remote target. */
3946 std::vector<thread_item> items;
3947 };
3948
3949 static int
3950 remote_newthread_step (threadref *ref, void *data)
3951 {
3952 struct threads_listing_context *context
3953 = (struct threads_listing_context *) data;
3954 int pid = inferior_ptid.pid ();
3955 int lwp = threadref_to_int (ref);
3956 ptid_t ptid (pid, lwp);
3957
3958 context->items.emplace_back (ptid);
3959
3960 return 1; /* continue iterator */
3961 }
3962
3963 #define CRAZY_MAX_THREADS 1000
3964
3965 ptid_t
3966 remote_target::remote_current_thread (ptid_t oldpid)
3967 {
3968 struct remote_state *rs = get_remote_state ();
3969
3970 putpkt ("qC");
3971 getpkt (&rs->buf);
3972 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3973 {
3974 const char *obuf;
3975 ptid_t result;
3976
3977 result = read_ptid (&rs->buf[2], &obuf);
3978 if (*obuf != '\0')
3979 remote_debug_printf ("warning: garbage in qC reply");
3980
3981 return result;
3982 }
3983 else
3984 return oldpid;
3985 }
3986
3987 /* List remote threads using the deprecated qL packet. */
3988
3989 int
3990 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3991 {
3992 if (remote_threadlist_iterator (remote_newthread_step, context,
3993 CRAZY_MAX_THREADS) >= 0)
3994 return 1;
3995
3996 return 0;
3997 }
3998
3999 #if defined(HAVE_LIBEXPAT)
4000
4001 static void
4002 start_thread (struct gdb_xml_parser *parser,
4003 const struct gdb_xml_element *element,
4004 void *user_data,
4005 std::vector<gdb_xml_value> &attributes)
4006 {
4007 struct threads_listing_context *data
4008 = (struct threads_listing_context *) user_data;
4009 struct gdb_xml_value *attr;
4010
4011 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
4012 ptid_t ptid = read_ptid (id, NULL);
4013
4014 data->items.emplace_back (ptid);
4015 thread_item &item = data->items.back ();
4016
4017 attr = xml_find_attribute (attributes, "core");
4018 if (attr != NULL)
4019 item.core = *(ULONGEST *) attr->value.get ();
4020
4021 attr = xml_find_attribute (attributes, "name");
4022 if (attr != NULL)
4023 item.name = (const char *) attr->value.get ();
4024
4025 attr = xml_find_attribute (attributes, "handle");
4026 if (attr != NULL)
4027 item.thread_handle = hex2bin ((const char *) attr->value.get ());
4028 }
4029
4030 static void
4031 end_thread (struct gdb_xml_parser *parser,
4032 const struct gdb_xml_element *element,
4033 void *user_data, const char *body_text)
4034 {
4035 struct threads_listing_context *data
4036 = (struct threads_listing_context *) user_data;
4037
4038 if (body_text != NULL && *body_text != '\0')
4039 data->items.back ().extra = body_text;
4040 }
4041
4042 const struct gdb_xml_attribute thread_attributes[] = {
4043 { "id", GDB_XML_AF_NONE, NULL, NULL },
4044 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
4045 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
4046 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
4047 { NULL, GDB_XML_AF_NONE, NULL, NULL }
4048 };
4049
4050 const struct gdb_xml_element thread_children[] = {
4051 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4052 };
4053
4054 const struct gdb_xml_element threads_children[] = {
4055 { "thread", thread_attributes, thread_children,
4056 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
4057 start_thread, end_thread },
4058 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4059 };
4060
4061 const struct gdb_xml_element threads_elements[] = {
4062 { "threads", NULL, threads_children,
4063 GDB_XML_EF_NONE, NULL, NULL },
4064 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4065 };
4066
4067 #endif
4068
4069 /* List remote threads using qXfer:threads:read. */
4070
4071 int
4072 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
4073 {
4074 #if defined(HAVE_LIBEXPAT)
4075 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4076 {
4077 gdb::optional<gdb::char_vector> xml
4078 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
4079
4080 if (xml && (*xml)[0] != '\0')
4081 {
4082 gdb_xml_parse_quick (_("threads"), "threads.dtd",
4083 threads_elements, xml->data (), context);
4084 }
4085
4086 return 1;
4087 }
4088 #endif
4089
4090 return 0;
4091 }
4092
4093 /* List remote threads using qfThreadInfo/qsThreadInfo. */
4094
4095 int
4096 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
4097 {
4098 struct remote_state *rs = get_remote_state ();
4099
4100 if (rs->use_threadinfo_query)
4101 {
4102 const char *bufp;
4103
4104 putpkt ("qfThreadInfo");
4105 getpkt (&rs->buf);
4106 bufp = rs->buf.data ();
4107 if (bufp[0] != '\0') /* q packet recognized */
4108 {
4109 while (*bufp++ == 'm') /* reply contains one or more TID */
4110 {
4111 do
4112 {
4113 ptid_t ptid = read_ptid (bufp, &bufp);
4114 context->items.emplace_back (ptid);
4115 }
4116 while (*bufp++ == ','); /* comma-separated list */
4117 putpkt ("qsThreadInfo");
4118 getpkt (&rs->buf);
4119 bufp = rs->buf.data ();
4120 }
4121 return 1;
4122 }
4123 else
4124 {
4125 /* Packet not recognized. */
4126 rs->use_threadinfo_query = 0;
4127 }
4128 }
4129
4130 return 0;
4131 }
4132
4133 /* Return true if INF only has one non-exited thread. */
4134
4135 static bool
4136 has_single_non_exited_thread (inferior *inf)
4137 {
4138 int count = 0;
4139 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
4140 if (++count > 1)
4141 break;
4142 return count == 1;
4143 }
4144
4145 /* Implement the to_update_thread_list function for the remote
4146 targets. */
4147
4148 void
4149 remote_target::update_thread_list ()
4150 {
4151 struct threads_listing_context context;
4152 int got_list = 0;
4153
4154 /* We have a few different mechanisms to fetch the thread list. Try
4155 them all, starting with the most preferred one first, falling
4156 back to older methods. */
4157 if (remote_get_threads_with_qxfer (&context)
4158 || remote_get_threads_with_qthreadinfo (&context)
4159 || remote_get_threads_with_ql (&context))
4160 {
4161 got_list = 1;
4162
4163 if (context.items.empty ()
4164 && remote_thread_always_alive (inferior_ptid))
4165 {
4166 /* Some targets don't really support threads, but still
4167 reply an (empty) thread list in response to the thread
4168 listing packets, instead of replying "packet not
4169 supported". Exit early so we don't delete the main
4170 thread. */
4171 return;
4172 }
4173
4174 /* CONTEXT now holds the current thread list on the remote
4175 target end. Delete GDB-side threads no longer found on the
4176 target. */
4177 for (thread_info *tp : all_threads_safe ())
4178 {
4179 if (tp->inf->process_target () != this)
4180 continue;
4181
4182 if (!context.contains_thread (tp->ptid))
4183 {
4184 /* Do not remove the thread if it is the last thread in
4185 the inferior. This situation happens when we have a
4186 pending exit process status to process. Otherwise we
4187 may end up with a seemingly live inferior (i.e. pid
4188 != 0) that has no threads. */
4189 if (has_single_non_exited_thread (tp->inf))
4190 continue;
4191
4192 /* Not found. */
4193 delete_thread (tp);
4194 }
4195 }
4196
4197 /* Remove any unreported fork child threads from CONTEXT so
4198 that we don't interfere with follow fork, which is where
4199 creation of such threads is handled. */
4200 remove_new_fork_children (&context);
4201
4202 /* And now add threads we don't know about yet to our list. */
4203 for (thread_item &item : context.items)
4204 {
4205 if (item.ptid != null_ptid)
4206 {
4207 /* In non-stop mode, we assume new found threads are
4208 executing until proven otherwise with a stop reply.
4209 In all-stop, we can only get here if all threads are
4210 stopped. */
4211 bool executing = target_is_non_stop_p ();
4212
4213 remote_notice_new_inferior (item.ptid, executing);
4214
4215 thread_info *tp = this->find_thread (item.ptid);
4216 remote_thread_info *info = get_remote_thread_info (tp);
4217 info->core = item.core;
4218 info->extra = std::move (item.extra);
4219 info->name = std::move (item.name);
4220 info->thread_handle = std::move (item.thread_handle);
4221 }
4222 }
4223 }
4224
4225 if (!got_list)
4226 {
4227 /* If no thread listing method is supported, then query whether
4228 each known thread is alive, one by one, with the T packet.
4229 If the target doesn't support threads at all, then this is a
4230 no-op. See remote_thread_alive. */
4231 prune_threads ();
4232 }
4233 }
4234
4235 /*
4236 * Collect a descriptive string about the given thread.
4237 * The target may say anything it wants to about the thread
4238 * (typically info about its blocked / runnable state, name, etc.).
4239 * This string will appear in the info threads display.
4240 *
4241 * Optional: targets are not required to implement this function.
4242 */
4243
4244 const char *
4245 remote_target::extra_thread_info (thread_info *tp)
4246 {
4247 struct remote_state *rs = get_remote_state ();
4248 int set;
4249 threadref id;
4250 struct gdb_ext_thread_info threadinfo;
4251
4252 if (rs->remote_desc == 0) /* paranoia */
4253 internal_error (_("remote_threads_extra_info"));
4254
4255 if (tp->ptid == magic_null_ptid
4256 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4257 /* This is the main thread which was added by GDB. The remote
4258 server doesn't know about it. */
4259 return NULL;
4260
4261 std::string &extra = get_remote_thread_info (tp)->extra;
4262
4263 /* If already have cached info, use it. */
4264 if (!extra.empty ())
4265 return extra.c_str ();
4266
4267 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4268 {
4269 /* If we're using qXfer:threads:read, then the extra info is
4270 included in the XML. So if we didn't have anything cached,
4271 it's because there's really no extra info. */
4272 return NULL;
4273 }
4274
4275 if (rs->use_threadextra_query)
4276 {
4277 char *b = rs->buf.data ();
4278 char *endb = b + get_remote_packet_size ();
4279
4280 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4281 b += strlen (b);
4282 write_ptid (b, endb, tp->ptid);
4283
4284 putpkt (rs->buf);
4285 getpkt (&rs->buf);
4286 if (rs->buf[0] != 0)
4287 {
4288 extra.resize (strlen (rs->buf.data ()) / 2);
4289 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4290 return extra.c_str ();
4291 }
4292 }
4293
4294 /* If the above query fails, fall back to the old method. */
4295 rs->use_threadextra_query = 0;
4296 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4297 | TAG_MOREDISPLAY | TAG_DISPLAY;
4298 int_to_threadref (&id, tp->ptid.lwp ());
4299 if (remote_get_threadinfo (&id, set, &threadinfo))
4300 if (threadinfo.active)
4301 {
4302 if (*threadinfo.shortname)
4303 string_appendf (extra, " Name: %s", threadinfo.shortname);
4304 if (*threadinfo.display)
4305 {
4306 if (!extra.empty ())
4307 extra += ',';
4308 string_appendf (extra, " State: %s", threadinfo.display);
4309 }
4310 if (*threadinfo.more_display)
4311 {
4312 if (!extra.empty ())
4313 extra += ',';
4314 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4315 }
4316 return extra.c_str ();
4317 }
4318 return NULL;
4319 }
4320 \f
4321
4322 bool
4323 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4324 struct static_tracepoint_marker *marker)
4325 {
4326 struct remote_state *rs = get_remote_state ();
4327 char *p = rs->buf.data ();
4328
4329 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4330 p += strlen (p);
4331 p += hexnumstr (p, addr);
4332 putpkt (rs->buf);
4333 getpkt (&rs->buf);
4334 p = rs->buf.data ();
4335
4336 if (*p == 'E')
4337 error (_("Remote failure reply: %s"), p);
4338
4339 if (*p++ == 'm')
4340 {
4341 parse_static_tracepoint_marker_definition (p, NULL, marker);
4342 return true;
4343 }
4344
4345 return false;
4346 }
4347
4348 std::vector<static_tracepoint_marker>
4349 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4350 {
4351 struct remote_state *rs = get_remote_state ();
4352 std::vector<static_tracepoint_marker> markers;
4353 const char *p;
4354 static_tracepoint_marker marker;
4355
4356 /* Ask for a first packet of static tracepoint marker
4357 definition. */
4358 putpkt ("qTfSTM");
4359 getpkt (&rs->buf);
4360 p = rs->buf.data ();
4361 if (*p == 'E')
4362 error (_("Remote failure reply: %s"), p);
4363
4364 while (*p++ == 'm')
4365 {
4366 do
4367 {
4368 parse_static_tracepoint_marker_definition (p, &p, &marker);
4369
4370 if (strid == NULL || marker.str_id == strid)
4371 markers.push_back (std::move (marker));
4372 }
4373 while (*p++ == ','); /* comma-separated list */
4374 /* Ask for another packet of static tracepoint definition. */
4375 putpkt ("qTsSTM");
4376 getpkt (&rs->buf);
4377 p = rs->buf.data ();
4378 }
4379
4380 return markers;
4381 }
4382
4383 \f
4384 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4385
4386 ptid_t
4387 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4388 {
4389 return ptid_t (inferior_ptid.pid (), lwp);
4390 }
4391 \f
4392
4393 /* Restart the remote side; this is an extended protocol operation. */
4394
4395 void
4396 remote_target::extended_remote_restart ()
4397 {
4398 struct remote_state *rs = get_remote_state ();
4399
4400 /* Send the restart command; for reasons I don't understand the
4401 remote side really expects a number after the "R". */
4402 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4403 putpkt (rs->buf);
4404
4405 remote_fileio_reset ();
4406 }
4407 \f
4408 /* Clean up connection to a remote debugger. */
4409
4410 void
4411 remote_target::close ()
4412 {
4413 /* Make sure we leave stdin registered in the event loop. */
4414 terminal_ours ();
4415
4416 trace_reset_local_state ();
4417
4418 delete this;
4419 }
4420
4421 remote_target::~remote_target ()
4422 {
4423 struct remote_state *rs = get_remote_state ();
4424
4425 /* Check for NULL because we may get here with a partially
4426 constructed target/connection. */
4427 if (rs->remote_desc == nullptr)
4428 return;
4429
4430 serial_close (rs->remote_desc);
4431
4432 /* We are destroying the remote target, so we should discard
4433 everything of this target. */
4434 discard_pending_stop_replies_in_queue ();
4435
4436 rs->delete_async_event_handler ();
4437
4438 delete rs->notif_state;
4439 }
4440
4441 /* Query the remote side for the text, data and bss offsets. */
4442
4443 void
4444 remote_target::get_offsets ()
4445 {
4446 struct remote_state *rs = get_remote_state ();
4447 char *buf;
4448 char *ptr;
4449 int lose, num_segments = 0, do_sections, do_segments;
4450 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4451
4452 if (current_program_space->symfile_object_file == NULL)
4453 return;
4454
4455 putpkt ("qOffsets");
4456 getpkt (&rs->buf);
4457 buf = rs->buf.data ();
4458
4459 if (buf[0] == '\000')
4460 return; /* Return silently. Stub doesn't support
4461 this command. */
4462 if (buf[0] == 'E')
4463 {
4464 warning (_("Remote failure reply: %s"), buf);
4465 return;
4466 }
4467
4468 /* Pick up each field in turn. This used to be done with scanf, but
4469 scanf will make trouble if CORE_ADDR size doesn't match
4470 conversion directives correctly. The following code will work
4471 with any size of CORE_ADDR. */
4472 text_addr = data_addr = bss_addr = 0;
4473 ptr = buf;
4474 lose = 0;
4475
4476 if (startswith (ptr, "Text="))
4477 {
4478 ptr += 5;
4479 /* Don't use strtol, could lose on big values. */
4480 while (*ptr && *ptr != ';')
4481 text_addr = (text_addr << 4) + fromhex (*ptr++);
4482
4483 if (startswith (ptr, ";Data="))
4484 {
4485 ptr += 6;
4486 while (*ptr && *ptr != ';')
4487 data_addr = (data_addr << 4) + fromhex (*ptr++);
4488 }
4489 else
4490 lose = 1;
4491
4492 if (!lose && startswith (ptr, ";Bss="))
4493 {
4494 ptr += 5;
4495 while (*ptr && *ptr != ';')
4496 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4497
4498 if (bss_addr != data_addr)
4499 warning (_("Target reported unsupported offsets: %s"), buf);
4500 }
4501 else
4502 lose = 1;
4503 }
4504 else if (startswith (ptr, "TextSeg="))
4505 {
4506 ptr += 8;
4507 /* Don't use strtol, could lose on big values. */
4508 while (*ptr && *ptr != ';')
4509 text_addr = (text_addr << 4) + fromhex (*ptr++);
4510 num_segments = 1;
4511
4512 if (startswith (ptr, ";DataSeg="))
4513 {
4514 ptr += 9;
4515 while (*ptr && *ptr != ';')
4516 data_addr = (data_addr << 4) + fromhex (*ptr++);
4517 num_segments++;
4518 }
4519 }
4520 else
4521 lose = 1;
4522
4523 if (lose)
4524 error (_("Malformed response to offset query, %s"), buf);
4525 else if (*ptr != '\0')
4526 warning (_("Target reported unsupported offsets: %s"), buf);
4527
4528 objfile *objf = current_program_space->symfile_object_file;
4529 section_offsets offs = objf->section_offsets;
4530
4531 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
4532 do_segments = (data != NULL);
4533 do_sections = num_segments == 0;
4534
4535 if (num_segments > 0)
4536 {
4537 segments[0] = text_addr;
4538 segments[1] = data_addr;
4539 }
4540 /* If we have two segments, we can still try to relocate everything
4541 by assuming that the .text and .data offsets apply to the whole
4542 text and data segments. Convert the offsets given in the packet
4543 to base addresses for symfile_map_offsets_to_segments. */
4544 else if (data != nullptr && data->segments.size () == 2)
4545 {
4546 segments[0] = data->segments[0].base + text_addr;
4547 segments[1] = data->segments[1].base + data_addr;
4548 num_segments = 2;
4549 }
4550 /* If the object file has only one segment, assume that it is text
4551 rather than data; main programs with no writable data are rare,
4552 but programs with no code are useless. Of course the code might
4553 have ended up in the data segment... to detect that we would need
4554 the permissions here. */
4555 else if (data && data->segments.size () == 1)
4556 {
4557 segments[0] = data->segments[0].base + text_addr;
4558 num_segments = 1;
4559 }
4560 /* There's no way to relocate by segment. */
4561 else
4562 do_segments = 0;
4563
4564 if (do_segments)
4565 {
4566 int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
4567 data.get (), offs,
4568 num_segments, segments);
4569
4570 if (ret == 0 && !do_sections)
4571 error (_("Can not handle qOffsets TextSeg "
4572 "response with this symbol file"));
4573
4574 if (ret > 0)
4575 do_sections = 0;
4576 }
4577
4578 if (do_sections)
4579 {
4580 offs[SECT_OFF_TEXT (objf)] = text_addr;
4581
4582 /* This is a temporary kludge to force data and bss to use the
4583 same offsets because that's what nlmconv does now. The real
4584 solution requires changes to the stub and remote.c that I
4585 don't have time to do right now. */
4586
4587 offs[SECT_OFF_DATA (objf)] = data_addr;
4588 offs[SECT_OFF_BSS (objf)] = data_addr;
4589 }
4590
4591 objfile_relocate (objf, offs);
4592 }
4593
4594 /* Send interrupt_sequence to remote target. */
4595
4596 void
4597 remote_target::send_interrupt_sequence ()
4598 {
4599 struct remote_state *rs = get_remote_state ();
4600
4601 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4602 remote_serial_write ("\x03", 1);
4603 else if (interrupt_sequence_mode == interrupt_sequence_break)
4604 serial_send_break (rs->remote_desc);
4605 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4606 {
4607 serial_send_break (rs->remote_desc);
4608 remote_serial_write ("g", 1);
4609 }
4610 else
4611 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
4612 interrupt_sequence_mode);
4613 }
4614
4615
4616 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4617 and extract the PTID. Returns NULL_PTID if not found. */
4618
4619 static ptid_t
4620 stop_reply_extract_thread (const char *stop_reply)
4621 {
4622 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4623 {
4624 const char *p;
4625
4626 /* Txx r:val ; r:val (...) */
4627 p = &stop_reply[3];
4628
4629 /* Look for "register" named "thread". */
4630 while (*p != '\0')
4631 {
4632 const char *p1;
4633
4634 p1 = strchr (p, ':');
4635 if (p1 == NULL)
4636 return null_ptid;
4637
4638 if (strncmp (p, "thread", p1 - p) == 0)
4639 return read_ptid (++p1, &p);
4640
4641 p1 = strchr (p, ';');
4642 if (p1 == NULL)
4643 return null_ptid;
4644 p1++;
4645
4646 p = p1;
4647 }
4648 }
4649
4650 return null_ptid;
4651 }
4652
4653 /* Determine the remote side's current thread. If we have a stop
4654 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4655 "thread" register we can extract the current thread from. If not,
4656 ask the remote which is the current thread with qC. The former
4657 method avoids a roundtrip. */
4658
4659 ptid_t
4660 remote_target::get_current_thread (const char *wait_status)
4661 {
4662 ptid_t ptid = null_ptid;
4663
4664 /* Note we don't use remote_parse_stop_reply as that makes use of
4665 the target architecture, which we haven't yet fully determined at
4666 this point. */
4667 if (wait_status != NULL)
4668 ptid = stop_reply_extract_thread (wait_status);
4669 if (ptid == null_ptid)
4670 ptid = remote_current_thread (inferior_ptid);
4671
4672 return ptid;
4673 }
4674
4675 /* Query the remote target for which is the current thread/process,
4676 add it to our tables, and update INFERIOR_PTID. The caller is
4677 responsible for setting the state such that the remote end is ready
4678 to return the current thread.
4679
4680 This function is called after handling the '?' or 'vRun' packets,
4681 whose response is a stop reply from which we can also try
4682 extracting the thread. If the target doesn't support the explicit
4683 qC query, we infer the current thread from that stop reply, passed
4684 in in WAIT_STATUS, which may be NULL.
4685
4686 The function returns pointer to the main thread of the inferior. */
4687
4688 thread_info *
4689 remote_target::add_current_inferior_and_thread (const char *wait_status)
4690 {
4691 bool fake_pid_p = false;
4692
4693 switch_to_no_thread ();
4694
4695 /* Now, if we have thread information, update the current thread's
4696 ptid. */
4697 ptid_t curr_ptid = get_current_thread (wait_status);
4698
4699 if (curr_ptid != null_ptid)
4700 {
4701 if (!m_features.remote_multi_process_p ())
4702 fake_pid_p = true;
4703 }
4704 else
4705 {
4706 /* Without this, some commands which require an active target
4707 (such as kill) won't work. This variable serves (at least)
4708 double duty as both the pid of the target process (if it has
4709 such), and as a flag indicating that a target is active. */
4710 curr_ptid = magic_null_ptid;
4711 fake_pid_p = true;
4712 }
4713
4714 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4715
4716 /* Add the main thread and switch to it. Don't try reading
4717 registers yet, since we haven't fetched the target description
4718 yet. */
4719 thread_info *tp = add_thread_silent (this, curr_ptid);
4720 switch_to_thread_no_regs (tp);
4721
4722 return tp;
4723 }
4724
4725 /* Print info about a thread that was found already stopped on
4726 connection. */
4727
4728 void
4729 remote_target::print_one_stopped_thread (thread_info *thread)
4730 {
4731 target_waitstatus ws;
4732
4733 /* If there is a pending waitstatus, use it. If there isn't it's because
4734 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4735 and process_initial_stop_replies decided it wasn't interesting to save
4736 and report to the core. */
4737 if (thread->has_pending_waitstatus ())
4738 {
4739 ws = thread->pending_waitstatus ();
4740 thread->clear_pending_waitstatus ();
4741 }
4742 else
4743 {
4744 ws.set_stopped (GDB_SIGNAL_0);
4745 }
4746
4747 switch_to_thread (thread);
4748 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4749 set_current_sal_from_frame (get_current_frame ());
4750
4751 /* For "info program". */
4752 set_last_target_status (this, thread->ptid, ws);
4753
4754 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4755 {
4756 enum gdb_signal sig = ws.sig ();
4757
4758 if (signal_print_state (sig))
4759 notify_signal_received (sig);
4760 }
4761
4762 notify_normal_stop (nullptr, 1);
4763 }
4764
4765 /* Process all initial stop replies the remote side sent in response
4766 to the ? packet. These indicate threads that were already stopped
4767 on initial connection. We mark these threads as stopped and print
4768 their current frame before giving the user the prompt. */
4769
4770 void
4771 remote_target::process_initial_stop_replies (int from_tty)
4772 {
4773 int pending_stop_replies = stop_reply_queue_length ();
4774 struct thread_info *selected = NULL;
4775 struct thread_info *lowest_stopped = NULL;
4776 struct thread_info *first = NULL;
4777
4778 /* This is only used when the target is non-stop. */
4779 gdb_assert (target_is_non_stop_p ());
4780
4781 /* Consume the initial pending events. */
4782 while (pending_stop_replies-- > 0)
4783 {
4784 ptid_t waiton_ptid = minus_one_ptid;
4785 ptid_t event_ptid;
4786 struct target_waitstatus ws;
4787 int ignore_event = 0;
4788
4789 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4790 if (remote_debug)
4791 print_target_wait_results (waiton_ptid, event_ptid, ws);
4792
4793 switch (ws.kind ())
4794 {
4795 case TARGET_WAITKIND_IGNORE:
4796 case TARGET_WAITKIND_NO_RESUMED:
4797 case TARGET_WAITKIND_SIGNALLED:
4798 case TARGET_WAITKIND_EXITED:
4799 /* We shouldn't see these, but if we do, just ignore. */
4800 remote_debug_printf ("event ignored");
4801 ignore_event = 1;
4802 break;
4803
4804 default:
4805 break;
4806 }
4807
4808 if (ignore_event)
4809 continue;
4810
4811 thread_info *evthread = this->find_thread (event_ptid);
4812
4813 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4814 {
4815 enum gdb_signal sig = ws.sig ();
4816
4817 /* Stubs traditionally report SIGTRAP as initial signal,
4818 instead of signal 0. Suppress it. */
4819 if (sig == GDB_SIGNAL_TRAP)
4820 sig = GDB_SIGNAL_0;
4821 evthread->set_stop_signal (sig);
4822 ws.set_stopped (sig);
4823 }
4824
4825 if (ws.kind () != TARGET_WAITKIND_STOPPED
4826 || ws.sig () != GDB_SIGNAL_0)
4827 evthread->set_pending_waitstatus (ws);
4828
4829 set_executing (this, event_ptid, false);
4830 set_running (this, event_ptid, false);
4831 get_remote_thread_info (evthread)->set_not_resumed ();
4832 }
4833
4834 /* "Notice" the new inferiors before anything related to
4835 registers/memory. */
4836 for (inferior *inf : all_non_exited_inferiors (this))
4837 {
4838 inf->needs_setup = true;
4839
4840 if (non_stop)
4841 {
4842 thread_info *thread = any_live_thread_of_inferior (inf);
4843 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4844 from_tty);
4845 }
4846 }
4847
4848 /* If all-stop on top of non-stop, pause all threads. Note this
4849 records the threads' stop pc, so must be done after "noticing"
4850 the inferiors. */
4851 if (!non_stop)
4852 {
4853 {
4854 /* At this point, the remote target is not async. It needs to be for
4855 the poll in stop_all_threads to consider events from it, so enable
4856 it temporarily. */
4857 gdb_assert (!this->is_async_p ());
4858 SCOPE_EXIT { target_async (false); };
4859 target_async (true);
4860 stop_all_threads ("remote connect in all-stop");
4861 }
4862
4863 /* If all threads of an inferior were already stopped, we
4864 haven't setup the inferior yet. */
4865 for (inferior *inf : all_non_exited_inferiors (this))
4866 {
4867 if (inf->needs_setup)
4868 {
4869 thread_info *thread = any_live_thread_of_inferior (inf);
4870 switch_to_thread_no_regs (thread);
4871 setup_inferior (0);
4872 }
4873 }
4874 }
4875
4876 /* Now go over all threads that are stopped, and print their current
4877 frame. If all-stop, then if there's a signalled thread, pick
4878 that as current. */
4879 for (thread_info *thread : all_non_exited_threads (this))
4880 {
4881 if (first == NULL)
4882 first = thread;
4883
4884 if (!non_stop)
4885 thread->set_running (false);
4886 else if (thread->state != THREAD_STOPPED)
4887 continue;
4888
4889 if (selected == nullptr && thread->has_pending_waitstatus ())
4890 selected = thread;
4891
4892 if (lowest_stopped == NULL
4893 || thread->inf->num < lowest_stopped->inf->num
4894 || thread->per_inf_num < lowest_stopped->per_inf_num)
4895 lowest_stopped = thread;
4896
4897 if (non_stop)
4898 print_one_stopped_thread (thread);
4899 }
4900
4901 /* In all-stop, we only print the status of one thread, and leave
4902 others with their status pending. */
4903 if (!non_stop)
4904 {
4905 thread_info *thread = selected;
4906 if (thread == NULL)
4907 thread = lowest_stopped;
4908 if (thread == NULL)
4909 thread = first;
4910
4911 print_one_stopped_thread (thread);
4912 }
4913 }
4914
4915 /* Mark a remote_target as starting (by setting the starting_up flag within
4916 its remote_state) for the lifetime of this object. The reference count
4917 on the remote target is temporarily incremented, to prevent the target
4918 being deleted under our feet. */
4919
4920 struct scoped_mark_target_starting
4921 {
4922 /* Constructor, TARGET is the target to be marked as starting, its
4923 reference count will be incremented. */
4924 scoped_mark_target_starting (remote_target *target)
4925 : m_remote_target (remote_target_ref::new_reference (target)),
4926 m_restore_starting_up (set_starting_up_flag (target))
4927 { /* Nothing. */ }
4928
4929 private:
4930
4931 /* Helper function, set the starting_up flag on TARGET and return an
4932 object which, when it goes out of scope, will restore the previous
4933 value of the starting_up flag. */
4934 static scoped_restore_tmpl<bool>
4935 set_starting_up_flag (remote_target *target)
4936 {
4937 remote_state *rs = target->get_remote_state ();
4938 gdb_assert (!rs->starting_up);
4939 return make_scoped_restore (&rs->starting_up, true);
4940 }
4941
4942 /* A gdb::ref_ptr pointer to a remote_target. */
4943 using remote_target_ref = gdb::ref_ptr<remote_target, target_ops_ref_policy>;
4944
4945 /* A reference to the target on which we are operating. */
4946 remote_target_ref m_remote_target;
4947
4948 /* An object which restores the previous value of the starting_up flag
4949 when it goes out of scope. */
4950 scoped_restore_tmpl<bool> m_restore_starting_up;
4951 };
4952
4953 /* Helper for remote_target::start_remote, start the remote connection and
4954 sync state. Return true if everything goes OK, otherwise, return false.
4955 This function exists so that the scoped_restore created within it will
4956 expire before we return to remote_target::start_remote. */
4957
4958 bool
4959 remote_target::start_remote_1 (int from_tty, int extended_p)
4960 {
4961 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4962
4963 struct remote_state *rs = get_remote_state ();
4964
4965 /* Signal other parts that we're going through the initial setup,
4966 and so things may not be stable yet. E.g., we don't try to
4967 install tracepoints until we've relocated symbols. Also, a
4968 Ctrl-C before we're connected and synced up can't interrupt the
4969 target. Instead, it offers to drop the (potentially wedged)
4970 connection. */
4971 scoped_mark_target_starting target_is_starting (this);
4972
4973 QUIT;
4974
4975 if (interrupt_on_connect)
4976 send_interrupt_sequence ();
4977
4978 /* Ack any packet which the remote side has already sent. */
4979 remote_serial_write ("+", 1);
4980
4981 /* The first packet we send to the target is the optional "supported
4982 packets" request. If the target can answer this, it will tell us
4983 which later probes to skip. */
4984 remote_query_supported ();
4985
4986 /* Check vCont support and set the remote state's vCont_action_support
4987 attribute. */
4988 remote_vcont_probe ();
4989
4990 /* If the stub wants to get a QAllow, compose one and send it. */
4991 if (m_features.packet_support (PACKET_QAllow) != PACKET_DISABLE)
4992 set_permissions ();
4993
4994 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4995 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4996 as a reply to known packet. For packet "vFile:setfs:" it is an
4997 invalid reply and GDB would return error in
4998 remote_hostio_set_filesystem, making remote files access impossible.
4999 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
5000 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
5001 {
5002 const char v_mustreplyempty[] = "vMustReplyEmpty";
5003
5004 putpkt (v_mustreplyempty);
5005 getpkt (&rs->buf);
5006 if (strcmp (rs->buf.data (), "OK") == 0)
5007 {
5008 m_features.m_protocol_packets[PACKET_vFile_setfs].support
5009 = PACKET_DISABLE;
5010 }
5011 else if (strcmp (rs->buf.data (), "") != 0)
5012 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
5013 rs->buf.data ());
5014 }
5015
5016 /* Next, we possibly activate noack mode.
5017
5018 If the QStartNoAckMode packet configuration is set to AUTO,
5019 enable noack mode if the stub reported a wish for it with
5020 qSupported.
5021
5022 If set to TRUE, then enable noack mode even if the stub didn't
5023 report it in qSupported. If the stub doesn't reply OK, the
5024 session ends with an error.
5025
5026 If FALSE, then don't activate noack mode, regardless of what the
5027 stub claimed should be the default with qSupported. */
5028
5029 if (m_features.packet_support (PACKET_QStartNoAckMode) != PACKET_DISABLE)
5030 {
5031 putpkt ("QStartNoAckMode");
5032 getpkt (&rs->buf);
5033 if (m_features.packet_ok (rs->buf, PACKET_QStartNoAckMode) == PACKET_OK)
5034 rs->noack_mode = 1;
5035 }
5036
5037 if (extended_p)
5038 {
5039 /* Tell the remote that we are using the extended protocol. */
5040 putpkt ("!");
5041 getpkt (&rs->buf);
5042 }
5043
5044 /* Let the target know which signals it is allowed to pass down to
5045 the program. */
5046 update_signals_program_target ();
5047
5048 /* Next, if the target can specify a description, read it. We do
5049 this before anything involving memory or registers. */
5050 target_find_description ();
5051
5052 /* Next, now that we know something about the target, update the
5053 address spaces in the program spaces. */
5054 update_address_spaces ();
5055
5056 /* On OSs where the list of libraries is global to all
5057 processes, we fetch them early. */
5058 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
5059 solib_add (NULL, from_tty, auto_solib_add);
5060
5061 if (target_is_non_stop_p ())
5062 {
5063 if (m_features.packet_support (PACKET_QNonStop) != PACKET_ENABLE)
5064 error (_("Non-stop mode requested, but remote "
5065 "does not support non-stop"));
5066
5067 putpkt ("QNonStop:1");
5068 getpkt (&rs->buf);
5069
5070 if (strcmp (rs->buf.data (), "OK") != 0)
5071 error (_("Remote refused setting non-stop mode with: %s"),
5072 rs->buf.data ());
5073
5074 /* Find about threads and processes the stub is already
5075 controlling. We default to adding them in the running state.
5076 The '?' query below will then tell us about which threads are
5077 stopped. */
5078 this->update_thread_list ();
5079 }
5080 else if (m_features.packet_support (PACKET_QNonStop) == PACKET_ENABLE)
5081 {
5082 /* Don't assume that the stub can operate in all-stop mode.
5083 Request it explicitly. */
5084 putpkt ("QNonStop:0");
5085 getpkt (&rs->buf);
5086
5087 if (strcmp (rs->buf.data (), "OK") != 0)
5088 error (_("Remote refused setting all-stop mode with: %s"),
5089 rs->buf.data ());
5090 }
5091
5092 /* Upload TSVs regardless of whether the target is running or not. The
5093 remote stub, such as GDBserver, may have some predefined or builtin
5094 TSVs, even if the target is not running. */
5095 if (get_trace_status (current_trace_status ()) != -1)
5096 {
5097 struct uploaded_tsv *uploaded_tsvs = NULL;
5098
5099 upload_trace_state_variables (&uploaded_tsvs);
5100 merge_uploaded_trace_state_variables (&uploaded_tsvs);
5101 }
5102
5103 /* Check whether the target is running now. */
5104 putpkt ("?");
5105 getpkt (&rs->buf);
5106
5107 if (!target_is_non_stop_p ())
5108 {
5109 char *wait_status = NULL;
5110
5111 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
5112 {
5113 if (!extended_p)
5114 error (_("The target is not running (try extended-remote?)"));
5115 return false;
5116 }
5117 else
5118 {
5119 /* Save the reply for later. */
5120 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
5121 strcpy (wait_status, rs->buf.data ());
5122 }
5123
5124 /* Fetch thread list. */
5125 target_update_thread_list ();
5126
5127 /* Let the stub know that we want it to return the thread. */
5128 set_continue_thread (minus_one_ptid);
5129
5130 if (thread_count (this) == 0)
5131 {
5132 /* Target has no concept of threads at all. GDB treats
5133 non-threaded target as single-threaded; add a main
5134 thread. */
5135 thread_info *tp = add_current_inferior_and_thread (wait_status);
5136 get_remote_thread_info (tp)->set_resumed ();
5137 }
5138 else
5139 {
5140 /* We have thread information; select the thread the target
5141 says should be current. If we're reconnecting to a
5142 multi-threaded program, this will ideally be the thread
5143 that last reported an event before GDB disconnected. */
5144 ptid_t curr_thread = get_current_thread (wait_status);
5145 if (curr_thread == null_ptid)
5146 {
5147 /* Odd... The target was able to list threads, but not
5148 tell us which thread was current (no "thread"
5149 register in T stop reply?). Just pick the first
5150 thread in the thread list then. */
5151
5152 remote_debug_printf ("warning: couldn't determine remote "
5153 "current thread; picking first in list.");
5154
5155 for (thread_info *tp : all_non_exited_threads (this,
5156 minus_one_ptid))
5157 {
5158 switch_to_thread (tp);
5159 break;
5160 }
5161 }
5162 else
5163 switch_to_thread (this->find_thread (curr_thread));
5164 }
5165
5166 /* init_wait_for_inferior should be called before get_offsets in order
5167 to manage `inserted' flag in bp loc in a correct state.
5168 breakpoint_init_inferior, called from init_wait_for_inferior, set
5169 `inserted' flag to 0, while before breakpoint_re_set, called from
5170 start_remote, set `inserted' flag to 1. In the initialization of
5171 inferior, breakpoint_init_inferior should be called first, and then
5172 breakpoint_re_set can be called. If this order is broken, state of
5173 `inserted' flag is wrong, and cause some problems on breakpoint
5174 manipulation. */
5175 init_wait_for_inferior ();
5176
5177 get_offsets (); /* Get text, data & bss offsets. */
5178
5179 /* If we could not find a description using qXfer, and we know
5180 how to do it some other way, try again. This is not
5181 supported for non-stop; it could be, but it is tricky if
5182 there are no stopped threads when we connect. */
5183 if (remote_read_description_p (this)
5184 && gdbarch_target_desc (current_inferior ()->arch ()) == NULL)
5185 {
5186 target_clear_description ();
5187 target_find_description ();
5188 }
5189
5190 /* Use the previously fetched status. */
5191 gdb_assert (wait_status != NULL);
5192 struct notif_event *reply
5193 = remote_notif_parse (this, &notif_client_stop, wait_status);
5194 push_stop_reply ((struct stop_reply *) reply);
5195
5196 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
5197 }
5198 else
5199 {
5200 /* Clear WFI global state. Do this before finding about new
5201 threads and inferiors, and setting the current inferior.
5202 Otherwise we would clear the proceed status of the current
5203 inferior when we want its stop_soon state to be preserved
5204 (see notice_new_inferior). */
5205 init_wait_for_inferior ();
5206
5207 /* In non-stop, we will either get an "OK", meaning that there
5208 are no stopped threads at this time; or, a regular stop
5209 reply. In the latter case, there may be more than one thread
5210 stopped --- we pull them all out using the vStopped
5211 mechanism. */
5212 if (strcmp (rs->buf.data (), "OK") != 0)
5213 {
5214 const notif_client *notif = &notif_client_stop;
5215
5216 /* remote_notif_get_pending_replies acks this one, and gets
5217 the rest out. */
5218 rs->notif_state->pending_event[notif_client_stop.id]
5219 = remote_notif_parse (this, notif, rs->buf.data ());
5220 remote_notif_get_pending_events (notif);
5221 }
5222
5223 if (thread_count (this) == 0)
5224 {
5225 if (!extended_p)
5226 error (_("The target is not running (try extended-remote?)"));
5227 return false;
5228 }
5229
5230 /* Report all signals during attach/startup. */
5231 pass_signals ({});
5232
5233 /* If there are already stopped threads, mark them stopped and
5234 report their stops before giving the prompt to the user. */
5235 process_initial_stop_replies (from_tty);
5236
5237 if (target_can_async_p ())
5238 target_async (true);
5239 }
5240
5241 /* Give the target a chance to look up symbols. */
5242 for (inferior *inf : all_inferiors (this))
5243 {
5244 /* The inferiors that exist at this point were created from what
5245 was found already running on the remote side, so we know they
5246 have execution. */
5247 gdb_assert (this->has_execution (inf));
5248
5249 /* No use without a symbol-file. */
5250 if (inf->pspace->symfile_object_file == nullptr)
5251 continue;
5252
5253 /* Need to switch to a specific thread, because remote_check_symbols
5254 uses INFERIOR_PTID to set the general thread. */
5255 scoped_restore_current_thread restore_thread;
5256 thread_info *thread = any_thread_of_inferior (inf);
5257 switch_to_thread (thread);
5258 this->remote_check_symbols ();
5259 }
5260
5261 /* Possibly the target has been engaged in a trace run started
5262 previously; find out where things are at. */
5263 if (get_trace_status (current_trace_status ()) != -1)
5264 {
5265 struct uploaded_tp *uploaded_tps = NULL;
5266
5267 if (current_trace_status ()->running)
5268 gdb_printf (_("Trace is already running on the target.\n"));
5269
5270 upload_tracepoints (&uploaded_tps);
5271
5272 merge_uploaded_tracepoints (&uploaded_tps);
5273 }
5274
5275 /* Possibly the target has been engaged in a btrace record started
5276 previously; find out where things are at. */
5277 remote_btrace_maybe_reopen ();
5278
5279 return true;
5280 }
5281
5282 /* Start the remote connection and sync state. */
5283
5284 void
5285 remote_target::start_remote (int from_tty, int extended_p)
5286 {
5287 if (start_remote_1 (from_tty, extended_p)
5288 && breakpoints_should_be_inserted_now ())
5289 insert_breakpoints ();
5290 }
5291
5292 const char *
5293 remote_target::connection_string ()
5294 {
5295 remote_state *rs = get_remote_state ();
5296
5297 if (rs->remote_desc->name != NULL)
5298 return rs->remote_desc->name;
5299 else
5300 return NULL;
5301 }
5302
5303 /* Open a connection to a remote debugger.
5304 NAME is the filename used for communication. */
5305
5306 void
5307 remote_target::open (const char *name, int from_tty)
5308 {
5309 open_1 (name, from_tty, 0);
5310 }
5311
5312 /* Open a connection to a remote debugger using the extended
5313 remote gdb protocol. NAME is the filename used for communication. */
5314
5315 void
5316 extended_remote_target::open (const char *name, int from_tty)
5317 {
5318 open_1 (name, from_tty, 1 /*extended_p */);
5319 }
5320
5321 void
5322 remote_features::reset_all_packet_configs_support ()
5323 {
5324 int i;
5325
5326 for (i = 0; i < PACKET_MAX; i++)
5327 m_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5328 }
5329
5330 /* Initialize all packet configs. */
5331
5332 static void
5333 init_all_packet_configs (void)
5334 {
5335 int i;
5336
5337 for (i = 0; i < PACKET_MAX; i++)
5338 {
5339 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5340 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5341 }
5342 }
5343
5344 /* Symbol look-up. */
5345
5346 void
5347 remote_target::remote_check_symbols ()
5348 {
5349 char *tmp;
5350 int end;
5351
5352 /* It doesn't make sense to send a qSymbol packet for an inferior that
5353 doesn't have execution, because the remote side doesn't know about
5354 inferiors without execution. */
5355 gdb_assert (target_has_execution ());
5356
5357 if (m_features.packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5358 return;
5359
5360 /* Make sure the remote is pointing at the right process. Note
5361 there's no way to select "no process". */
5362 set_general_process ();
5363
5364 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5365 because we need both at the same time. */
5366 gdb::char_vector msg (get_remote_packet_size ());
5367 gdb::char_vector reply (get_remote_packet_size ());
5368
5369 /* Invite target to request symbol lookups. */
5370
5371 putpkt ("qSymbol::");
5372 getpkt (&reply);
5373 m_features.packet_ok (reply, PACKET_qSymbol);
5374
5375 while (startswith (reply.data (), "qSymbol:"))
5376 {
5377 struct bound_minimal_symbol sym;
5378
5379 tmp = &reply[8];
5380 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5381 strlen (tmp) / 2);
5382 msg[end] = '\0';
5383 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5384 if (sym.minsym == NULL)
5385 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5386 &reply[8]);
5387 else
5388 {
5389 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
5390 CORE_ADDR sym_addr = sym.value_address ();
5391
5392 /* If this is a function address, return the start of code
5393 instead of any data function descriptor. */
5394 sym_addr = gdbarch_convert_from_func_ptr_addr
5395 (current_inferior ()->arch (), sym_addr,
5396 current_inferior ()->top_target ());
5397
5398 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5399 phex_nz (sym_addr, addr_size), &reply[8]);
5400 }
5401
5402 putpkt (msg.data ());
5403 getpkt (&reply);
5404 }
5405 }
5406
5407 static struct serial *
5408 remote_serial_open (const char *name)
5409 {
5410 static int udp_warning = 0;
5411
5412 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5413 of in ser-tcp.c, because it is the remote protocol assuming that the
5414 serial connection is reliable and not the serial connection promising
5415 to be. */
5416 if (!udp_warning && startswith (name, "udp:"))
5417 {
5418 warning (_("The remote protocol may be unreliable over UDP.\n"
5419 "Some events may be lost, rendering further debugging "
5420 "impossible."));
5421 udp_warning = 1;
5422 }
5423
5424 return serial_open (name);
5425 }
5426
5427 /* Inform the target of our permission settings. The permission flags
5428 work without this, but if the target knows the settings, it can do
5429 a couple things. First, it can add its own check, to catch cases
5430 that somehow manage to get by the permissions checks in target
5431 methods. Second, if the target is wired to disallow particular
5432 settings (for instance, a system in the field that is not set up to
5433 be able to stop at a breakpoint), it can object to any unavailable
5434 permissions. */
5435
5436 void
5437 remote_target::set_permissions ()
5438 {
5439 struct remote_state *rs = get_remote_state ();
5440
5441 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5442 "WriteReg:%x;WriteMem:%x;"
5443 "InsertBreak:%x;InsertTrace:%x;"
5444 "InsertFastTrace:%x;Stop:%x",
5445 may_write_registers, may_write_memory,
5446 may_insert_breakpoints, may_insert_tracepoints,
5447 may_insert_fast_tracepoints, may_stop);
5448 putpkt (rs->buf);
5449 getpkt (&rs->buf);
5450
5451 /* If the target didn't like the packet, warn the user. Do not try
5452 to undo the user's settings, that would just be maddening. */
5453 if (strcmp (rs->buf.data (), "OK") != 0)
5454 warning (_("Remote refused setting permissions with: %s"),
5455 rs->buf.data ());
5456 }
5457
5458 /* This type describes each known response to the qSupported
5459 packet. */
5460 struct protocol_feature
5461 {
5462 /* The name of this protocol feature. */
5463 const char *name;
5464
5465 /* The default for this protocol feature. */
5466 enum packet_support default_support;
5467
5468 /* The function to call when this feature is reported, or after
5469 qSupported processing if the feature is not supported.
5470 The first argument points to this structure. The second
5471 argument indicates whether the packet requested support be
5472 enabled, disabled, or probed (or the default, if this function
5473 is being called at the end of processing and this feature was
5474 not reported). The third argument may be NULL; if not NULL, it
5475 is a NUL-terminated string taken from the packet following
5476 this feature's name and an equals sign. */
5477 void (*func) (remote_target *remote, const struct protocol_feature *,
5478 enum packet_support, const char *);
5479
5480 /* The corresponding packet for this feature. Only used if
5481 FUNC is remote_supported_packet. */
5482 int packet;
5483 };
5484
5485 static void
5486 remote_supported_packet (remote_target *remote,
5487 const struct protocol_feature *feature,
5488 enum packet_support support,
5489 const char *argument)
5490 {
5491 if (argument)
5492 {
5493 warning (_("Remote qSupported response supplied an unexpected value for"
5494 " \"%s\"."), feature->name);
5495 return;
5496 }
5497
5498 remote->m_features.m_protocol_packets[feature->packet].support = support;
5499 }
5500
5501 void
5502 remote_target::remote_packet_size (const protocol_feature *feature,
5503 enum packet_support support, const char *value)
5504 {
5505 struct remote_state *rs = get_remote_state ();
5506
5507 int packet_size;
5508 char *value_end;
5509
5510 if (support != PACKET_ENABLE)
5511 return;
5512
5513 if (value == NULL || *value == '\0')
5514 {
5515 warning (_("Remote target reported \"%s\" without a size."),
5516 feature->name);
5517 return;
5518 }
5519
5520 errno = 0;
5521 packet_size = strtol (value, &value_end, 16);
5522 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5523 {
5524 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5525 feature->name, value);
5526 return;
5527 }
5528
5529 /* Record the new maximum packet size. */
5530 rs->explicit_packet_size = packet_size;
5531 }
5532
5533 static void
5534 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5535 enum packet_support support, const char *value)
5536 {
5537 remote->remote_packet_size (feature, support, value);
5538 }
5539
5540 static const struct protocol_feature remote_protocol_features[] = {
5541 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5542 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5543 PACKET_qXfer_auxv },
5544 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5545 PACKET_qXfer_exec_file },
5546 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5547 PACKET_qXfer_features },
5548 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5549 PACKET_qXfer_libraries },
5550 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5551 PACKET_qXfer_libraries_svr4 },
5552 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5553 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5554 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5555 PACKET_qXfer_memory_map },
5556 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5557 PACKET_qXfer_osdata },
5558 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5559 PACKET_qXfer_threads },
5560 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5561 PACKET_qXfer_traceframe_info },
5562 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5563 PACKET_QPassSignals },
5564 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5565 PACKET_QCatchSyscalls },
5566 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5567 PACKET_QProgramSignals },
5568 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5569 PACKET_QSetWorkingDir },
5570 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5571 PACKET_QStartupWithShell },
5572 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5573 PACKET_QEnvironmentHexEncoded },
5574 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5575 PACKET_QEnvironmentReset },
5576 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5577 PACKET_QEnvironmentUnset },
5578 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5579 PACKET_QStartNoAckMode },
5580 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5581 PACKET_multiprocess_feature },
5582 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5583 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5584 PACKET_qXfer_siginfo_read },
5585 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5586 PACKET_qXfer_siginfo_write },
5587 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5588 PACKET_ConditionalTracepoints },
5589 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5590 PACKET_ConditionalBreakpoints },
5591 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5592 PACKET_BreakpointCommands },
5593 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5594 PACKET_FastTracepoints },
5595 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5596 PACKET_StaticTracepoints },
5597 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5598 PACKET_InstallInTrace},
5599 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5600 PACKET_DisconnectedTracing_feature },
5601 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5602 PACKET_bc },
5603 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5604 PACKET_bs },
5605 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5606 PACKET_TracepointSource },
5607 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5608 PACKET_QAllow },
5609 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5610 PACKET_EnableDisableTracepoints_feature },
5611 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5612 PACKET_qXfer_fdpic },
5613 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5614 PACKET_qXfer_uib },
5615 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5616 PACKET_QDisableRandomization },
5617 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5618 { "QTBuffer:size", PACKET_DISABLE,
5619 remote_supported_packet, PACKET_QTBuffer_size},
5620 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5621 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5622 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5623 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5624 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5625 PACKET_qXfer_btrace },
5626 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5627 PACKET_qXfer_btrace_conf },
5628 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5629 PACKET_Qbtrace_conf_bts_size },
5630 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5631 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5632 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5633 PACKET_fork_event_feature },
5634 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5635 PACKET_vfork_event_feature },
5636 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5637 PACKET_exec_event_feature },
5638 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5639 PACKET_Qbtrace_conf_pt_size },
5640 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5641 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5642 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5643 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5644 PACKET_memory_tagging_feature },
5645 };
5646
5647 static char *remote_support_xml;
5648
5649 /* Register string appended to "xmlRegisters=" in qSupported query. */
5650
5651 void
5652 register_remote_support_xml (const char *xml)
5653 {
5654 #if defined(HAVE_LIBEXPAT)
5655 if (remote_support_xml == NULL)
5656 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5657 else
5658 {
5659 char *copy = xstrdup (remote_support_xml + 13);
5660 char *saveptr;
5661 char *p = strtok_r (copy, ",", &saveptr);
5662
5663 do
5664 {
5665 if (strcmp (p, xml) == 0)
5666 {
5667 /* already there */
5668 xfree (copy);
5669 return;
5670 }
5671 }
5672 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5673 xfree (copy);
5674
5675 remote_support_xml = reconcat (remote_support_xml,
5676 remote_support_xml, ",", xml,
5677 (char *) NULL);
5678 }
5679 #endif
5680 }
5681
5682 static void
5683 remote_query_supported_append (std::string *msg, const char *append)
5684 {
5685 if (!msg->empty ())
5686 msg->append (";");
5687 msg->append (append);
5688 }
5689
5690 void
5691 remote_target::remote_query_supported ()
5692 {
5693 struct remote_state *rs = get_remote_state ();
5694 char *next;
5695 int i;
5696 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5697
5698 /* The packet support flags are handled differently for this packet
5699 than for most others. We treat an error, a disabled packet, and
5700 an empty response identically: any features which must be reported
5701 to be used will be automatically disabled. An empty buffer
5702 accomplishes this, since that is also the representation for a list
5703 containing no features. */
5704
5705 rs->buf[0] = 0;
5706 if (m_features.packet_support (PACKET_qSupported) != PACKET_DISABLE)
5707 {
5708 std::string q;
5709
5710 if (m_features.packet_set_cmd_state (PACKET_multiprocess_feature)
5711 != AUTO_BOOLEAN_FALSE)
5712 remote_query_supported_append (&q, "multiprocess+");
5713
5714 if (m_features.packet_set_cmd_state (PACKET_swbreak_feature)
5715 != AUTO_BOOLEAN_FALSE)
5716 remote_query_supported_append (&q, "swbreak+");
5717
5718 if (m_features.packet_set_cmd_state (PACKET_hwbreak_feature)
5719 != AUTO_BOOLEAN_FALSE)
5720 remote_query_supported_append (&q, "hwbreak+");
5721
5722 remote_query_supported_append (&q, "qRelocInsn+");
5723
5724 if (m_features.packet_set_cmd_state (PACKET_fork_event_feature)
5725 != AUTO_BOOLEAN_FALSE)
5726 remote_query_supported_append (&q, "fork-events+");
5727
5728 if (m_features.packet_set_cmd_state (PACKET_vfork_event_feature)
5729 != AUTO_BOOLEAN_FALSE)
5730 remote_query_supported_append (&q, "vfork-events+");
5731
5732 if (m_features.packet_set_cmd_state (PACKET_exec_event_feature)
5733 != AUTO_BOOLEAN_FALSE)
5734 remote_query_supported_append (&q, "exec-events+");
5735
5736 if (m_features.packet_set_cmd_state (PACKET_vContSupported)
5737 != AUTO_BOOLEAN_FALSE)
5738 remote_query_supported_append (&q, "vContSupported+");
5739
5740 if (m_features.packet_set_cmd_state (PACKET_QThreadEvents)
5741 != AUTO_BOOLEAN_FALSE)
5742 remote_query_supported_append (&q, "QThreadEvents+");
5743
5744 if (m_features.packet_set_cmd_state (PACKET_no_resumed)
5745 != AUTO_BOOLEAN_FALSE)
5746 remote_query_supported_append (&q, "no-resumed+");
5747
5748 if (m_features.packet_set_cmd_state (PACKET_memory_tagging_feature)
5749 != AUTO_BOOLEAN_FALSE)
5750 remote_query_supported_append (&q, "memory-tagging+");
5751
5752 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5753 the qSupported:xmlRegisters=i386 handling. */
5754 if (remote_support_xml != NULL
5755 && (m_features.packet_support (PACKET_qXfer_features)
5756 != PACKET_DISABLE))
5757 remote_query_supported_append (&q, remote_support_xml);
5758
5759 q = "qSupported:" + q;
5760 putpkt (q.c_str ());
5761
5762 getpkt (&rs->buf);
5763
5764 /* If an error occurred, warn, but do not return - just reset the
5765 buffer to empty and go on to disable features. */
5766 if (m_features.packet_ok (rs->buf, PACKET_qSupported) == PACKET_ERROR)
5767 {
5768 warning (_("Remote failure reply: %s"), rs->buf.data ());
5769 rs->buf[0] = 0;
5770 }
5771 }
5772
5773 memset (seen, 0, sizeof (seen));
5774
5775 next = rs->buf.data ();
5776 while (*next)
5777 {
5778 enum packet_support is_supported;
5779 char *p, *end, *name_end, *value;
5780
5781 /* First separate out this item from the rest of the packet. If
5782 there's another item after this, we overwrite the separator
5783 (terminated strings are much easier to work with). */
5784 p = next;
5785 end = strchr (p, ';');
5786 if (end == NULL)
5787 {
5788 end = p + strlen (p);
5789 next = end;
5790 }
5791 else
5792 {
5793 *end = '\0';
5794 next = end + 1;
5795
5796 if (end == p)
5797 {
5798 warning (_("empty item in \"qSupported\" response"));
5799 continue;
5800 }
5801 }
5802
5803 name_end = strchr (p, '=');
5804 if (name_end)
5805 {
5806 /* This is a name=value entry. */
5807 is_supported = PACKET_ENABLE;
5808 value = name_end + 1;
5809 *name_end = '\0';
5810 }
5811 else
5812 {
5813 value = NULL;
5814 switch (end[-1])
5815 {
5816 case '+':
5817 is_supported = PACKET_ENABLE;
5818 break;
5819
5820 case '-':
5821 is_supported = PACKET_DISABLE;
5822 break;
5823
5824 case '?':
5825 is_supported = PACKET_SUPPORT_UNKNOWN;
5826 break;
5827
5828 default:
5829 warning (_("unrecognized item \"%s\" "
5830 "in \"qSupported\" response"), p);
5831 continue;
5832 }
5833 end[-1] = '\0';
5834 }
5835
5836 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5837 if (strcmp (remote_protocol_features[i].name, p) == 0)
5838 {
5839 const struct protocol_feature *feature;
5840
5841 seen[i] = 1;
5842 feature = &remote_protocol_features[i];
5843 feature->func (this, feature, is_supported, value);
5844 break;
5845 }
5846 }
5847
5848 /* If we increased the packet size, make sure to increase the global
5849 buffer size also. We delay this until after parsing the entire
5850 qSupported packet, because this is the same buffer we were
5851 parsing. */
5852 if (rs->buf.size () < rs->explicit_packet_size)
5853 rs->buf.resize (rs->explicit_packet_size);
5854
5855 /* Handle the defaults for unmentioned features. */
5856 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5857 if (!seen[i])
5858 {
5859 const struct protocol_feature *feature;
5860
5861 feature = &remote_protocol_features[i];
5862 feature->func (this, feature, feature->default_support, NULL);
5863 }
5864 }
5865
5866 /* Serial QUIT handler for the remote serial descriptor.
5867
5868 Defers handling a Ctrl-C until we're done with the current
5869 command/response packet sequence, unless:
5870
5871 - We're setting up the connection. Don't send a remote interrupt
5872 request, as we're not fully synced yet. Quit immediately
5873 instead.
5874
5875 - The target has been resumed in the foreground
5876 (target_terminal::is_ours is false) with a synchronous resume
5877 packet, and we're blocked waiting for the stop reply, thus a
5878 Ctrl-C should be immediately sent to the target.
5879
5880 - We get a second Ctrl-C while still within the same serial read or
5881 write. In that case the serial is seemingly wedged --- offer to
5882 quit/disconnect.
5883
5884 - We see a second Ctrl-C without target response, after having
5885 previously interrupted the target. In that case the target/stub
5886 is probably wedged --- offer to quit/disconnect.
5887 */
5888
5889 void
5890 remote_target::remote_serial_quit_handler ()
5891 {
5892 struct remote_state *rs = get_remote_state ();
5893
5894 if (check_quit_flag ())
5895 {
5896 /* If we're starting up, we're not fully synced yet. Quit
5897 immediately. */
5898 if (rs->starting_up)
5899 quit ();
5900 else if (rs->got_ctrlc_during_io)
5901 {
5902 if (query (_("The target is not responding to GDB commands.\n"
5903 "Stop debugging it? ")))
5904 remote_unpush_and_throw (this);
5905 }
5906 /* If ^C has already been sent once, offer to disconnect. */
5907 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5908 interrupt_query ();
5909 /* All-stop protocol, and blocked waiting for stop reply. Send
5910 an interrupt request. */
5911 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5912 target_interrupt ();
5913 else
5914 rs->got_ctrlc_during_io = 1;
5915 }
5916 }
5917
5918 /* The remote_target that is current while the quit handler is
5919 overridden with remote_serial_quit_handler. */
5920 static remote_target *curr_quit_handler_target;
5921
5922 static void
5923 remote_serial_quit_handler ()
5924 {
5925 curr_quit_handler_target->remote_serial_quit_handler ();
5926 }
5927
5928 /* Remove the remote target from the target stack of each inferior
5929 that is using it. Upper targets depend on it so remove them
5930 first. */
5931
5932 static void
5933 remote_unpush_target (remote_target *target)
5934 {
5935 /* We have to unpush the target from all inferiors, even those that
5936 aren't running. */
5937 scoped_restore_current_inferior restore_current_inferior;
5938
5939 for (inferior *inf : all_inferiors (target))
5940 {
5941 switch_to_inferior_no_thread (inf);
5942 inf->pop_all_targets_at_and_above (process_stratum);
5943 generic_mourn_inferior ();
5944 }
5945
5946 /* Don't rely on target_close doing this when the target is popped
5947 from the last remote inferior above, because something may be
5948 holding a reference to the target higher up on the stack, meaning
5949 target_close won't be called yet. We lost the connection to the
5950 target, so clear these now, otherwise we may later throw
5951 TARGET_CLOSE_ERROR while trying to tell the remote target to
5952 close the file. */
5953 fileio_handles_invalidate_target (target);
5954 }
5955
5956 static void
5957 remote_unpush_and_throw (remote_target *target)
5958 {
5959 remote_unpush_target (target);
5960 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5961 }
5962
5963 void
5964 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5965 {
5966 remote_target *curr_remote = get_current_remote_target ();
5967
5968 if (name == 0)
5969 error (_("To open a remote debug connection, you need to specify what\n"
5970 "serial device is attached to the remote system\n"
5971 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5972
5973 /* If we're connected to a running target, target_preopen will kill it.
5974 Ask this question first, before target_preopen has a chance to kill
5975 anything. */
5976 if (curr_remote != NULL && !target_has_execution ())
5977 {
5978 if (from_tty
5979 && !query (_("Already connected to a remote target. Disconnect? ")))
5980 error (_("Still connected."));
5981 }
5982
5983 /* Here the possibly existing remote target gets unpushed. */
5984 target_preopen (from_tty);
5985
5986 remote_fileio_reset ();
5987 reopen_exec_file ();
5988 reread_symbols (from_tty);
5989
5990 remote_target *remote
5991 = (extended_p ? new extended_remote_target () : new remote_target ());
5992 target_ops_up target_holder (remote);
5993
5994 remote_state *rs = remote->get_remote_state ();
5995
5996 /* See FIXME above. */
5997 if (!target_async_permitted)
5998 rs->wait_forever_enabled_p = true;
5999
6000 rs->remote_desc = remote_serial_open (name);
6001 if (!rs->remote_desc)
6002 perror_with_name (name);
6003
6004 if (baud_rate != -1)
6005 {
6006 if (serial_setbaudrate (rs->remote_desc, baud_rate))
6007 {
6008 /* The requested speed could not be set. Error out to
6009 top level after closing remote_desc. Take care to
6010 set remote_desc to NULL to avoid closing remote_desc
6011 more than once. */
6012 serial_close (rs->remote_desc);
6013 rs->remote_desc = NULL;
6014 perror_with_name (name);
6015 }
6016 }
6017
6018 serial_setparity (rs->remote_desc, serial_parity);
6019 serial_raw (rs->remote_desc);
6020
6021 /* If there is something sitting in the buffer we might take it as a
6022 response to a command, which would be bad. */
6023 serial_flush_input (rs->remote_desc);
6024
6025 if (from_tty)
6026 {
6027 gdb_puts ("Remote debugging using ");
6028 gdb_puts (name);
6029 gdb_puts ("\n");
6030 }
6031
6032 /* Switch to using the remote target now. */
6033 current_inferior ()->push_target (std::move (target_holder));
6034
6035 /* Register extra event sources in the event loop. */
6036 rs->create_async_event_handler ();
6037
6038 rs->notif_state = remote_notif_state_allocate (remote);
6039
6040 /* Reset the target state; these things will be queried either by
6041 remote_query_supported or as they are needed. */
6042 remote->m_features.reset_all_packet_configs_support ();
6043 rs->explicit_packet_size = 0;
6044 rs->noack_mode = 0;
6045 rs->extended = extended_p;
6046 rs->waiting_for_stop_reply = 0;
6047 rs->ctrlc_pending_p = 0;
6048 rs->got_ctrlc_during_io = 0;
6049
6050 rs->general_thread = not_sent_ptid;
6051 rs->continue_thread = not_sent_ptid;
6052 rs->remote_traceframe_number = -1;
6053
6054 rs->last_resume_exec_dir = EXEC_FORWARD;
6055
6056 /* Probe for ability to use "ThreadInfo" query, as required. */
6057 rs->use_threadinfo_query = 1;
6058 rs->use_threadextra_query = 1;
6059
6060 rs->readahead_cache.invalidate ();
6061
6062 if (target_async_permitted)
6063 {
6064 /* FIXME: cagney/1999-09-23: During the initial connection it is
6065 assumed that the target is already ready and able to respond to
6066 requests. Unfortunately remote_start_remote() eventually calls
6067 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
6068 around this. Eventually a mechanism that allows
6069 wait_for_inferior() to expect/get timeouts will be
6070 implemented. */
6071 rs->wait_forever_enabled_p = false;
6072 }
6073
6074 /* First delete any symbols previously loaded from shared libraries. */
6075 no_shared_libraries (NULL, 0);
6076
6077 /* Start the remote connection. If error() or QUIT, discard this
6078 target (we'd otherwise be in an inconsistent state) and then
6079 propogate the error on up the exception chain. This ensures that
6080 the caller doesn't stumble along blindly assuming that the
6081 function succeeded. The CLI doesn't have this problem but other
6082 UI's, such as MI do.
6083
6084 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
6085 this function should return an error indication letting the
6086 caller restore the previous state. Unfortunately the command
6087 ``target remote'' is directly wired to this function making that
6088 impossible. On a positive note, the CLI side of this problem has
6089 been fixed - the function set_cmd_context() makes it possible for
6090 all the ``target ....'' commands to share a common callback
6091 function. See cli-dump.c. */
6092 {
6093
6094 try
6095 {
6096 remote->start_remote (from_tty, extended_p);
6097 }
6098 catch (const gdb_exception &ex)
6099 {
6100 /* Pop the partially set up target - unless something else did
6101 already before throwing the exception. */
6102 if (ex.error != TARGET_CLOSE_ERROR)
6103 remote_unpush_target (remote);
6104 throw;
6105 }
6106 }
6107
6108 remote_btrace_reset (rs);
6109
6110 if (target_async_permitted)
6111 rs->wait_forever_enabled_p = true;
6112 }
6113
6114 /* Determine if WS represents a fork status. */
6115
6116 static bool
6117 is_fork_status (target_waitkind kind)
6118 {
6119 return (kind == TARGET_WAITKIND_FORKED
6120 || kind == TARGET_WAITKIND_VFORKED);
6121 }
6122
6123 /* Return THREAD's pending status if it is a pending fork parent, else
6124 return nullptr. */
6125
6126 static const target_waitstatus *
6127 thread_pending_fork_status (struct thread_info *thread)
6128 {
6129 const target_waitstatus &ws
6130 = (thread->has_pending_waitstatus ()
6131 ? thread->pending_waitstatus ()
6132 : thread->pending_follow);
6133
6134 if (!is_fork_status (ws.kind ()))
6135 return nullptr;
6136
6137 return &ws;
6138 }
6139
6140 /* Detach the specified process. */
6141
6142 void
6143 remote_target::remote_detach_pid (int pid)
6144 {
6145 struct remote_state *rs = get_remote_state ();
6146
6147 /* This should not be necessary, but the handling for D;PID in
6148 GDBserver versions prior to 8.2 incorrectly assumes that the
6149 selected process points to the same process we're detaching,
6150 leading to misbehavior (and possibly GDBserver crashing) when it
6151 does not. Since it's easy and cheap, work around it by forcing
6152 GDBserver to select GDB's current process. */
6153 set_general_process ();
6154
6155 if (m_features.remote_multi_process_p ())
6156 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
6157 else
6158 strcpy (rs->buf.data (), "D");
6159
6160 putpkt (rs->buf);
6161 getpkt (&rs->buf);
6162
6163 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
6164 ;
6165 else if (rs->buf[0] == '\0')
6166 error (_("Remote doesn't know how to detach"));
6167 else
6168 {
6169 /* It is possible that we have an unprocessed exit event for this
6170 pid. If this is the case then we can ignore the failure to detach
6171 and just pretend that the detach worked, as far as the user is
6172 concerned, the process exited immediately after the detach. */
6173 bool process_has_already_exited = false;
6174 remote_notif_get_pending_events (&notif_client_stop);
6175 for (stop_reply_up &reply : rs->stop_reply_queue)
6176 {
6177 if (reply->ptid.pid () != pid)
6178 continue;
6179
6180 enum target_waitkind kind = reply->ws.kind ();
6181 if (kind == TARGET_WAITKIND_EXITED
6182 || kind == TARGET_WAITKIND_SIGNALLED)
6183 {
6184 process_has_already_exited = true;
6185 remote_debug_printf
6186 ("detach failed, but process already exited");
6187 break;
6188 }
6189 }
6190
6191 if (!process_has_already_exited)
6192 error (_("can't detach process: %s"), (char *) rs->buf.data ());
6193 }
6194 }
6195
6196 /* This detaches a program to which we previously attached, using
6197 inferior_ptid to identify the process. After this is done, GDB
6198 can be used to debug some other program. We better not have left
6199 any breakpoints in the target program or it'll die when it hits
6200 one. */
6201
6202 void
6203 remote_target::remote_detach_1 (inferior *inf, int from_tty)
6204 {
6205 int pid = inferior_ptid.pid ();
6206 struct remote_state *rs = get_remote_state ();
6207 int is_fork_parent;
6208
6209 if (!target_has_execution ())
6210 error (_("No process to detach from."));
6211
6212 target_announce_detach (from_tty);
6213
6214 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
6215 {
6216 /* If we're in breakpoints-always-inserted mode, or the inferior
6217 is running, we have to remove breakpoints before detaching.
6218 We don't do this in common code instead because not all
6219 targets support removing breakpoints while the target is
6220 running. The remote target / gdbserver does, though. */
6221 remove_breakpoints_inf (current_inferior ());
6222 }
6223
6224 /* Tell the remote target to detach. */
6225 remote_detach_pid (pid);
6226
6227 /* Exit only if this is the only active inferior. */
6228 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
6229 gdb_puts (_("Ending remote debugging.\n"));
6230
6231 /* See if any thread of the inferior we are detaching has a pending fork
6232 status. In that case, we must detach from the child resulting from
6233 that fork. */
6234 for (thread_info *thread : inf->non_exited_threads ())
6235 {
6236 const target_waitstatus *ws = thread_pending_fork_status (thread);
6237
6238 if (ws == nullptr)
6239 continue;
6240
6241 remote_detach_pid (ws->child_ptid ().pid ());
6242 }
6243
6244 /* Check also for any pending fork events in the stop reply queue. */
6245 remote_notif_get_pending_events (&notif_client_stop);
6246 for (stop_reply_up &reply : rs->stop_reply_queue)
6247 {
6248 if (reply->ptid.pid () != pid)
6249 continue;
6250
6251 if (!is_fork_status (reply->ws.kind ()))
6252 continue;
6253
6254 remote_detach_pid (reply->ws.child_ptid ().pid ());
6255 }
6256
6257 thread_info *tp = this->find_thread (inferior_ptid);
6258
6259 /* Check to see if we are detaching a fork parent. Note that if we
6260 are detaching a fork child, tp == NULL. */
6261 is_fork_parent = (tp != NULL
6262 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
6263
6264 /* If doing detach-on-fork, we don't mourn, because that will delete
6265 breakpoints that should be available for the followed inferior. */
6266 if (!is_fork_parent)
6267 {
6268 /* Save the pid as a string before mourning, since that will
6269 unpush the remote target, and we need the string after. */
6270 std::string infpid = target_pid_to_str (ptid_t (pid));
6271
6272 target_mourn_inferior (inferior_ptid);
6273 if (print_inferior_events)
6274 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6275 inf->num, infpid.c_str ());
6276 }
6277 else
6278 {
6279 switch_to_no_thread ();
6280 detach_inferior (current_inferior ());
6281 }
6282 }
6283
6284 void
6285 remote_target::detach (inferior *inf, int from_tty)
6286 {
6287 remote_detach_1 (inf, from_tty);
6288 }
6289
6290 void
6291 extended_remote_target::detach (inferior *inf, int from_tty)
6292 {
6293 remote_detach_1 (inf, from_tty);
6294 }
6295
6296 /* Target follow-fork function for remote targets. On entry, and
6297 at return, the current inferior is the fork parent.
6298
6299 Note that although this is currently only used for extended-remote,
6300 it is named remote_follow_fork in anticipation of using it for the
6301 remote target as well. */
6302
6303 void
6304 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6305 target_waitkind fork_kind, bool follow_child,
6306 bool detach_fork)
6307 {
6308 process_stratum_target::follow_fork (child_inf, child_ptid,
6309 fork_kind, follow_child, detach_fork);
6310
6311 if ((fork_kind == TARGET_WAITKIND_FORKED
6312 && m_features.remote_fork_event_p ())
6313 || (fork_kind == TARGET_WAITKIND_VFORKED
6314 && m_features.remote_vfork_event_p ()))
6315 {
6316 /* When following the parent and detaching the child, we detach
6317 the child here. For the case of following the child and
6318 detaching the parent, the detach is done in the target-
6319 independent follow fork code in infrun.c. We can't use
6320 target_detach when detaching an unfollowed child because
6321 the client side doesn't know anything about the child. */
6322 if (detach_fork && !follow_child)
6323 {
6324 /* Detach the fork child. */
6325 remote_detach_pid (child_ptid.pid ());
6326 }
6327 }
6328 }
6329
6330 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6331 in the program space of the new inferior. */
6332
6333 void
6334 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6335 const char *execd_pathname)
6336 {
6337 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6338
6339 /* We know that this is a target file name, so if it has the "target:"
6340 prefix we strip it off before saving it in the program space. */
6341 if (is_target_filename (execd_pathname))
6342 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6343
6344 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6345 }
6346
6347 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6348
6349 void
6350 remote_target::disconnect (const char *args, int from_tty)
6351 {
6352 if (args)
6353 error (_("Argument given to \"disconnect\" when remotely debugging."));
6354
6355 /* Make sure we unpush even the extended remote targets. Calling
6356 target_mourn_inferior won't unpush, and
6357 remote_target::mourn_inferior won't unpush if there is more than
6358 one inferior left. */
6359 remote_unpush_target (this);
6360
6361 if (from_tty)
6362 gdb_puts ("Ending remote debugging.\n");
6363 }
6364
6365 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6366 be chatty about it. */
6367
6368 void
6369 extended_remote_target::attach (const char *args, int from_tty)
6370 {
6371 struct remote_state *rs = get_remote_state ();
6372 int pid;
6373 char *wait_status = NULL;
6374
6375 pid = parse_pid_to_attach (args);
6376
6377 /* Remote PID can be freely equal to getpid, do not check it here the same
6378 way as in other targets. */
6379
6380 if (m_features.packet_support (PACKET_vAttach) == PACKET_DISABLE)
6381 error (_("This target does not support attaching to a process"));
6382
6383 target_announce_attach (from_tty, pid);
6384
6385 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6386 putpkt (rs->buf);
6387 getpkt (&rs->buf);
6388
6389 switch (m_features.packet_ok (rs->buf, PACKET_vAttach))
6390 {
6391 case PACKET_OK:
6392 if (!target_is_non_stop_p ())
6393 {
6394 /* Save the reply for later. */
6395 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6396 strcpy (wait_status, rs->buf.data ());
6397 }
6398 else if (strcmp (rs->buf.data (), "OK") != 0)
6399 error (_("Attaching to %s failed with: %s"),
6400 target_pid_to_str (ptid_t (pid)).c_str (),
6401 rs->buf.data ());
6402 break;
6403 case PACKET_UNKNOWN:
6404 error (_("This target does not support attaching to a process"));
6405 default:
6406 error (_("Attaching to %s failed"),
6407 target_pid_to_str (ptid_t (pid)).c_str ());
6408 }
6409
6410 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6411
6412 inferior_ptid = ptid_t (pid);
6413
6414 if (target_is_non_stop_p ())
6415 {
6416 /* Get list of threads. */
6417 update_thread_list ();
6418
6419 thread_info *thread = first_thread_of_inferior (current_inferior ());
6420 if (thread != nullptr)
6421 switch_to_thread (thread);
6422
6423 /* Invalidate our notion of the remote current thread. */
6424 record_currthread (rs, minus_one_ptid);
6425 }
6426 else
6427 {
6428 /* Now, if we have thread information, update the main thread's
6429 ptid. */
6430 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6431
6432 /* Add the main thread to the thread list. We add the thread
6433 silently in this case (the final true parameter). */
6434 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
6435
6436 switch_to_thread (thr);
6437 }
6438
6439 /* Next, if the target can specify a description, read it. We do
6440 this before anything involving memory or registers. */
6441 target_find_description ();
6442
6443 if (!target_is_non_stop_p ())
6444 {
6445 /* Use the previously fetched status. */
6446 gdb_assert (wait_status != NULL);
6447
6448 struct notif_event *reply
6449 = remote_notif_parse (this, &notif_client_stop, wait_status);
6450
6451 push_stop_reply ((struct stop_reply *) reply);
6452 }
6453 else
6454 {
6455 gdb_assert (wait_status == NULL);
6456
6457 gdb_assert (target_can_async_p ());
6458 }
6459 }
6460
6461 /* Implementation of the to_post_attach method. */
6462
6463 void
6464 extended_remote_target::post_attach (int pid)
6465 {
6466 /* Get text, data & bss offsets. */
6467 get_offsets ();
6468
6469 /* In certain cases GDB might not have had the chance to start
6470 symbol lookup up until now. This could happen if the debugged
6471 binary is not using shared libraries, the vsyscall page is not
6472 present (on Linux) and the binary itself hadn't changed since the
6473 debugging process was started. */
6474 if (current_program_space->symfile_object_file != NULL)
6475 remote_check_symbols();
6476 }
6477
6478 \f
6479 /* Check for the availability of vCont. This function should also check
6480 the response. */
6481
6482 void
6483 remote_target::remote_vcont_probe ()
6484 {
6485 remote_state *rs = get_remote_state ();
6486 char *buf;
6487
6488 strcpy (rs->buf.data (), "vCont?");
6489 putpkt (rs->buf);
6490 getpkt (&rs->buf);
6491 buf = rs->buf.data ();
6492
6493 /* Make sure that the features we assume are supported. */
6494 if (startswith (buf, "vCont"))
6495 {
6496 char *p = &buf[5];
6497 int support_c, support_C;
6498
6499 rs->supports_vCont.s = 0;
6500 rs->supports_vCont.S = 0;
6501 support_c = 0;
6502 support_C = 0;
6503 rs->supports_vCont.t = 0;
6504 rs->supports_vCont.r = 0;
6505 while (p && *p == ';')
6506 {
6507 p++;
6508 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6509 rs->supports_vCont.s = 1;
6510 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6511 rs->supports_vCont.S = 1;
6512 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6513 support_c = 1;
6514 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6515 support_C = 1;
6516 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6517 rs->supports_vCont.t = 1;
6518 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6519 rs->supports_vCont.r = 1;
6520
6521 p = strchr (p, ';');
6522 }
6523
6524 /* If c, and C are not all supported, we can't use vCont. Clearing
6525 BUF will make packet_ok disable the packet. */
6526 if (!support_c || !support_C)
6527 buf[0] = 0;
6528 }
6529
6530 m_features.packet_ok (rs->buf, PACKET_vCont);
6531 }
6532
6533 /* Helper function for building "vCont" resumptions. Write a
6534 resumption to P. ENDP points to one-passed-the-end of the buffer
6535 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6536 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6537 resumed thread should be single-stepped and/or signalled. If PTID
6538 equals minus_one_ptid, then all threads are resumed; if PTID
6539 represents a process, then all threads of the process are
6540 resumed. */
6541
6542 char *
6543 remote_target::append_resumption (char *p, char *endp,
6544 ptid_t ptid, int step, gdb_signal siggnal)
6545 {
6546 struct remote_state *rs = get_remote_state ();
6547
6548 if (step && siggnal != GDB_SIGNAL_0)
6549 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6550 else if (step
6551 /* GDB is willing to range step. */
6552 && use_range_stepping
6553 /* Target supports range stepping. */
6554 && rs->supports_vCont.r
6555 /* We don't currently support range stepping multiple
6556 threads with a wildcard (though the protocol allows it,
6557 so stubs shouldn't make an active effort to forbid
6558 it). */
6559 && !(m_features.remote_multi_process_p () && ptid.is_pid ()))
6560 {
6561 struct thread_info *tp;
6562
6563 if (ptid == minus_one_ptid)
6564 {
6565 /* If we don't know about the target thread's tid, then
6566 we're resuming magic_null_ptid (see caller). */
6567 tp = this->find_thread (magic_null_ptid);
6568 }
6569 else
6570 tp = this->find_thread (ptid);
6571 gdb_assert (tp != NULL);
6572
6573 if (tp->control.may_range_step)
6574 {
6575 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
6576
6577 p += xsnprintf (p, endp - p, ";r%s,%s",
6578 phex_nz (tp->control.step_range_start,
6579 addr_size),
6580 phex_nz (tp->control.step_range_end,
6581 addr_size));
6582 }
6583 else
6584 p += xsnprintf (p, endp - p, ";s");
6585 }
6586 else if (step)
6587 p += xsnprintf (p, endp - p, ";s");
6588 else if (siggnal != GDB_SIGNAL_0)
6589 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6590 else
6591 p += xsnprintf (p, endp - p, ";c");
6592
6593 if (m_features.remote_multi_process_p () && ptid.is_pid ())
6594 {
6595 ptid_t nptid;
6596
6597 /* All (-1) threads of process. */
6598 nptid = ptid_t (ptid.pid (), -1);
6599
6600 p += xsnprintf (p, endp - p, ":");
6601 p = write_ptid (p, endp, nptid);
6602 }
6603 else if (ptid != minus_one_ptid)
6604 {
6605 p += xsnprintf (p, endp - p, ":");
6606 p = write_ptid (p, endp, ptid);
6607 }
6608
6609 return p;
6610 }
6611
6612 /* Clear the thread's private info on resume. */
6613
6614 static void
6615 resume_clear_thread_private_info (struct thread_info *thread)
6616 {
6617 if (thread->priv != NULL)
6618 {
6619 remote_thread_info *priv = get_remote_thread_info (thread);
6620
6621 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6622 priv->watch_data_address = 0;
6623 }
6624 }
6625
6626 /* Append a vCont continue-with-signal action for threads that have a
6627 non-zero stop signal. */
6628
6629 char *
6630 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6631 ptid_t ptid)
6632 {
6633 for (thread_info *thread : all_non_exited_threads (this, ptid))
6634 if (inferior_ptid != thread->ptid
6635 && thread->stop_signal () != GDB_SIGNAL_0)
6636 {
6637 p = append_resumption (p, endp, thread->ptid,
6638 0, thread->stop_signal ());
6639 thread->set_stop_signal (GDB_SIGNAL_0);
6640 resume_clear_thread_private_info (thread);
6641 }
6642
6643 return p;
6644 }
6645
6646 /* Set the target running, using the packets that use Hc
6647 (c/s/C/S). */
6648
6649 void
6650 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6651 gdb_signal siggnal)
6652 {
6653 struct remote_state *rs = get_remote_state ();
6654 char *buf;
6655
6656 rs->last_sent_signal = siggnal;
6657 rs->last_sent_step = step;
6658
6659 /* The c/s/C/S resume packets use Hc, so set the continue
6660 thread. */
6661 if (ptid == minus_one_ptid)
6662 set_continue_thread (any_thread_ptid);
6663 else
6664 set_continue_thread (ptid);
6665
6666 for (thread_info *thread : all_non_exited_threads (this))
6667 resume_clear_thread_private_info (thread);
6668
6669 buf = rs->buf.data ();
6670 if (::execution_direction == EXEC_REVERSE)
6671 {
6672 /* We don't pass signals to the target in reverse exec mode. */
6673 if (info_verbose && siggnal != GDB_SIGNAL_0)
6674 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6675 siggnal);
6676
6677 if (step && m_features.packet_support (PACKET_bs) == PACKET_DISABLE)
6678 error (_("Remote reverse-step not supported."));
6679 if (!step && m_features.packet_support (PACKET_bc) == PACKET_DISABLE)
6680 error (_("Remote reverse-continue not supported."));
6681
6682 strcpy (buf, step ? "bs" : "bc");
6683 }
6684 else if (siggnal != GDB_SIGNAL_0)
6685 {
6686 buf[0] = step ? 'S' : 'C';
6687 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6688 buf[2] = tohex (((int) siggnal) & 0xf);
6689 buf[3] = '\0';
6690 }
6691 else
6692 strcpy (buf, step ? "s" : "c");
6693
6694 putpkt (buf);
6695 }
6696
6697 /* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6698 STEP, and SIGGNAL have the same meaning as in target_resume. This
6699 function returns non-zero iff it resumes the inferior.
6700
6701 This function issues a strict subset of all possible vCont commands
6702 at the moment. */
6703
6704 int
6705 remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6706 enum gdb_signal siggnal)
6707 {
6708 struct remote_state *rs = get_remote_state ();
6709 char *p;
6710 char *endp;
6711
6712 /* No reverse execution actions defined for vCont. */
6713 if (::execution_direction == EXEC_REVERSE)
6714 return 0;
6715
6716 if (m_features.packet_support (PACKET_vCont) == PACKET_DISABLE)
6717 return 0;
6718
6719 p = rs->buf.data ();
6720 endp = p + get_remote_packet_size ();
6721
6722 /* If we could generate a wider range of packets, we'd have to worry
6723 about overflowing BUF. Should there be a generic
6724 "multi-part-packet" packet? */
6725
6726 p += xsnprintf (p, endp - p, "vCont");
6727
6728 if (scope_ptid == magic_null_ptid)
6729 {
6730 /* MAGIC_NULL_PTID means that we don't have any active threads,
6731 so we don't have any TID numbers the inferior will
6732 understand. Make sure to only send forms that do not specify
6733 a TID. */
6734 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6735 }
6736 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
6737 {
6738 /* Resume all threads (of all processes, or of a single
6739 process), with preference for INFERIOR_PTID. This assumes
6740 inferior_ptid belongs to the set of all threads we are about
6741 to resume. */
6742 if (step || siggnal != GDB_SIGNAL_0)
6743 {
6744 /* Step inferior_ptid, with or without signal. */
6745 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6746 }
6747
6748 /* Also pass down any pending signaled resumption for other
6749 threads not the current. */
6750 p = append_pending_thread_resumptions (p, endp, scope_ptid);
6751
6752 /* And continue others without a signal. */
6753 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
6754 }
6755 else
6756 {
6757 /* Scheduler locking; resume only SCOPE_PTID. */
6758 append_resumption (p, endp, scope_ptid, step, siggnal);
6759 }
6760
6761 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6762 putpkt (rs->buf);
6763
6764 if (target_is_non_stop_p ())
6765 {
6766 /* In non-stop, the stub replies to vCont with "OK". The stop
6767 reply will be reported asynchronously by means of a `%Stop'
6768 notification. */
6769 getpkt (&rs->buf);
6770 if (strcmp (rs->buf.data (), "OK") != 0)
6771 error (_("Unexpected vCont reply in non-stop mode: %s"),
6772 rs->buf.data ());
6773 }
6774
6775 return 1;
6776 }
6777
6778 /* Tell the remote machine to resume. */
6779
6780 void
6781 remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
6782 {
6783 struct remote_state *rs = get_remote_state ();
6784
6785 /* When connected in non-stop mode, the core resumes threads
6786 individually. Resuming remote threads directly in target_resume
6787 would thus result in sending one packet per thread. Instead, to
6788 minimize roundtrip latency, here we just store the resume
6789 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6790 resumption will be done in remote_target::commit_resume, where we'll be
6791 able to do vCont action coalescing. */
6792 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6793 {
6794 remote_thread_info *remote_thr
6795 = get_remote_thread_info (inferior_thread ());
6796
6797 /* We don't expect the core to ask to resume an already resumed (from
6798 its point of view) thread. */
6799 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6800
6801 remote_thr->set_resumed_pending_vcont (step, siggnal);
6802
6803 /* There's actually nothing that says that the core can't
6804 request a wildcard resume in non-stop mode, though. It's
6805 just that we know it doesn't currently, so we don't bother
6806 with it. */
6807 gdb_assert (scope_ptid == inferior_ptid);
6808 return;
6809 }
6810
6811 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6812 (explained in remote-notif.c:handle_notification) so
6813 remote_notif_process is not called. We need find a place where
6814 it is safe to start a 'vNotif' sequence. It is good to do it
6815 before resuming inferior, because inferior was stopped and no RSP
6816 traffic at that moment. */
6817 if (!target_is_non_stop_p ())
6818 remote_notif_process (rs->notif_state, &notif_client_stop);
6819
6820 rs->last_resume_exec_dir = ::execution_direction;
6821
6822 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6823 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
6824 remote_resume_with_hc (scope_ptid, step, siggnal);
6825
6826 /* Update resumed state tracked by the remote target. */
6827 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
6828 get_remote_thread_info (tp)->set_resumed ();
6829
6830 /* We've just told the target to resume. The remote server will
6831 wait for the inferior to stop, and then send a stop reply. In
6832 the mean time, we can't start another command/query ourselves
6833 because the stub wouldn't be ready to process it. This applies
6834 only to the base all-stop protocol, however. In non-stop (which
6835 only supports vCont), the stub replies with an "OK", and is
6836 immediate able to process further serial input. */
6837 if (!target_is_non_stop_p ())
6838 rs->waiting_for_stop_reply = 1;
6839 }
6840
6841 /* Private per-inferior info for target remote processes. */
6842
6843 struct remote_inferior : public private_inferior
6844 {
6845 /* Whether we can send a wildcard vCont for this process. */
6846 bool may_wildcard_vcont = true;
6847 };
6848
6849 /* Get the remote private inferior data associated to INF. */
6850
6851 static remote_inferior *
6852 get_remote_inferior (inferior *inf)
6853 {
6854 if (inf->priv == NULL)
6855 inf->priv.reset (new remote_inferior);
6856
6857 return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
6858 }
6859
6860 /* Class used to track the construction of a vCont packet in the
6861 outgoing packet buffer. This is used to send multiple vCont
6862 packets if we have more actions than would fit a single packet. */
6863
6864 class vcont_builder
6865 {
6866 public:
6867 explicit vcont_builder (remote_target *remote)
6868 : m_remote (remote)
6869 {
6870 restart ();
6871 }
6872
6873 void flush ();
6874 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6875
6876 private:
6877 void restart ();
6878
6879 /* The remote target. */
6880 remote_target *m_remote;
6881
6882 /* Pointer to the first action. P points here if no action has been
6883 appended yet. */
6884 char *m_first_action;
6885
6886 /* Where the next action will be appended. */
6887 char *m_p;
6888
6889 /* The end of the buffer. Must never write past this. */
6890 char *m_endp;
6891 };
6892
6893 /* Prepare the outgoing buffer for a new vCont packet. */
6894
6895 void
6896 vcont_builder::restart ()
6897 {
6898 struct remote_state *rs = m_remote->get_remote_state ();
6899
6900 m_p = rs->buf.data ();
6901 m_endp = m_p + m_remote->get_remote_packet_size ();
6902 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6903 m_first_action = m_p;
6904 }
6905
6906 /* If the vCont packet being built has any action, send it to the
6907 remote end. */
6908
6909 void
6910 vcont_builder::flush ()
6911 {
6912 struct remote_state *rs;
6913
6914 if (m_p == m_first_action)
6915 return;
6916
6917 rs = m_remote->get_remote_state ();
6918 m_remote->putpkt (rs->buf);
6919 m_remote->getpkt (&rs->buf);
6920 if (strcmp (rs->buf.data (), "OK") != 0)
6921 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
6922 }
6923
6924 /* The largest action is range-stepping, with its two addresses. This
6925 is more than sufficient. If a new, bigger action is created, it'll
6926 quickly trigger a failed assertion in append_resumption (and we'll
6927 just bump this). */
6928 #define MAX_ACTION_SIZE 200
6929
6930 /* Append a new vCont action in the outgoing packet being built. If
6931 the action doesn't fit the packet along with previous actions, push
6932 what we've got so far to the remote end and start over a new vCont
6933 packet (with the new action). */
6934
6935 void
6936 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6937 {
6938 char buf[MAX_ACTION_SIZE + 1];
6939
6940 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6941 ptid, step, siggnal);
6942
6943 /* Check whether this new action would fit in the vCont packet along
6944 with previous actions. If not, send what we've got so far and
6945 start a new vCont packet. */
6946 size_t rsize = endp - buf;
6947 if (rsize > m_endp - m_p)
6948 {
6949 flush ();
6950 restart ();
6951
6952 /* Should now fit. */
6953 gdb_assert (rsize <= m_endp - m_p);
6954 }
6955
6956 memcpy (m_p, buf, rsize);
6957 m_p += rsize;
6958 *m_p = '\0';
6959 }
6960
6961 /* to_commit_resume implementation. */
6962
6963 void
6964 remote_target::commit_resumed ()
6965 {
6966 /* If connected in all-stop mode, we'd send the remote resume
6967 request directly from remote_resume. Likewise if
6968 reverse-debugging, as there are no defined vCont actions for
6969 reverse execution. */
6970 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6971 return;
6972
6973 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6974 instead of resuming all threads of each process individually.
6975 However, if any thread of a process must remain halted, we can't
6976 send wildcard resumes and must send one action per thread.
6977
6978 Care must be taken to not resume threads/processes the server
6979 side already told us are stopped, but the core doesn't know about
6980 yet, because the events are still in the vStopped notification
6981 queue. For example:
6982
6983 #1 => vCont s:p1.1;c
6984 #2 <= OK
6985 #3 <= %Stopped T05 p1.1
6986 #4 => vStopped
6987 #5 <= T05 p1.2
6988 #6 => vStopped
6989 #7 <= OK
6990 #8 (infrun handles the stop for p1.1 and continues stepping)
6991 #9 => vCont s:p1.1;c
6992
6993 The last vCont above would resume thread p1.2 by mistake, because
6994 the server has no idea that the event for p1.2 had not been
6995 handled yet.
6996
6997 The server side must similarly ignore resume actions for the
6998 thread that has a pending %Stopped notification (and any other
6999 threads with events pending), until GDB acks the notification
7000 with vStopped. Otherwise, e.g., the following case is
7001 mishandled:
7002
7003 #1 => g (or any other packet)
7004 #2 <= [registers]
7005 #3 <= %Stopped T05 p1.2
7006 #4 => vCont s:p1.1;c
7007 #5 <= OK
7008
7009 Above, the server must not resume thread p1.2. GDB can't know
7010 that p1.2 stopped until it acks the %Stopped notification, and
7011 since from GDB's perspective all threads should be running, it
7012 sends a "c" action.
7013
7014 Finally, special care must also be given to handling fork/vfork
7015 events. A (v)fork event actually tells us that two processes
7016 stopped -- the parent and the child. Until we follow the fork,
7017 we must not resume the child. Therefore, if we have a pending
7018 fork follow, we must not send a global wildcard resume action
7019 (vCont;c). We can still send process-wide wildcards though. */
7020
7021 /* Start by assuming a global wildcard (vCont;c) is possible. */
7022 bool may_global_wildcard_vcont = true;
7023
7024 /* And assume every process is individually wildcard-able too. */
7025 for (inferior *inf : all_non_exited_inferiors (this))
7026 {
7027 remote_inferior *priv = get_remote_inferior (inf);
7028
7029 priv->may_wildcard_vcont = true;
7030 }
7031
7032 /* Check for any pending events (not reported or processed yet) and
7033 disable process and global wildcard resumes appropriately. */
7034 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
7035
7036 bool any_pending_vcont_resume = false;
7037
7038 for (thread_info *tp : all_non_exited_threads (this))
7039 {
7040 remote_thread_info *priv = get_remote_thread_info (tp);
7041
7042 /* If a thread of a process is not meant to be resumed, then we
7043 can't wildcard that process. */
7044 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
7045 {
7046 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
7047
7048 /* And if we can't wildcard a process, we can't wildcard
7049 everything either. */
7050 may_global_wildcard_vcont = false;
7051 continue;
7052 }
7053
7054 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
7055 any_pending_vcont_resume = true;
7056
7057 /* If a thread is the parent of an unfollowed fork, then we
7058 can't do a global wildcard, as that would resume the fork
7059 child. */
7060 if (thread_pending_fork_status (tp) != nullptr)
7061 may_global_wildcard_vcont = false;
7062 }
7063
7064 /* We didn't have any resumed thread pending a vCont resume, so nothing to
7065 do. */
7066 if (!any_pending_vcont_resume)
7067 return;
7068
7069 /* Now let's build the vCont packet(s). Actions must be appended
7070 from narrower to wider scopes (thread -> process -> global). If
7071 we end up with too many actions for a single packet vcont_builder
7072 flushes the current vCont packet to the remote side and starts a
7073 new one. */
7074 struct vcont_builder vcont_builder (this);
7075
7076 /* Threads first. */
7077 for (thread_info *tp : all_non_exited_threads (this))
7078 {
7079 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7080
7081 /* If the thread was previously vCont-resumed, no need to send a specific
7082 action for it. If we didn't receive a resume request for it, don't
7083 send an action for it either. */
7084 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
7085 continue;
7086
7087 gdb_assert (!thread_is_in_step_over_chain (tp));
7088
7089 /* We should never be commit-resuming a thread that has a stop reply.
7090 Otherwise, we would end up reporting a stop event for a thread while
7091 it is running on the remote target. */
7092 remote_state *rs = get_remote_state ();
7093 for (const auto &stop_reply : rs->stop_reply_queue)
7094 gdb_assert (stop_reply->ptid != tp->ptid);
7095
7096 const resumed_pending_vcont_info &info
7097 = remote_thr->resumed_pending_vcont_info ();
7098
7099 /* Check if we need to send a specific action for this thread. If not,
7100 it will be included in a wildcard resume instead. */
7101 if (info.step || info.sig != GDB_SIGNAL_0
7102 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
7103 vcont_builder.push_action (tp->ptid, info.step, info.sig);
7104
7105 remote_thr->set_resumed ();
7106 }
7107
7108 /* Now check whether we can send any process-wide wildcard. This is
7109 to avoid sending a global wildcard in the case nothing is
7110 supposed to be resumed. */
7111 bool any_process_wildcard = false;
7112
7113 for (inferior *inf : all_non_exited_inferiors (this))
7114 {
7115 if (get_remote_inferior (inf)->may_wildcard_vcont)
7116 {
7117 any_process_wildcard = true;
7118 break;
7119 }
7120 }
7121
7122 if (any_process_wildcard)
7123 {
7124 /* If all processes are wildcard-able, then send a single "c"
7125 action, otherwise, send an "all (-1) threads of process"
7126 continue action for each running process, if any. */
7127 if (may_global_wildcard_vcont)
7128 {
7129 vcont_builder.push_action (minus_one_ptid,
7130 false, GDB_SIGNAL_0);
7131 }
7132 else
7133 {
7134 for (inferior *inf : all_non_exited_inferiors (this))
7135 {
7136 if (get_remote_inferior (inf)->may_wildcard_vcont)
7137 {
7138 vcont_builder.push_action (ptid_t (inf->pid),
7139 false, GDB_SIGNAL_0);
7140 }
7141 }
7142 }
7143 }
7144
7145 vcont_builder.flush ();
7146 }
7147
7148 /* Implementation of target_has_pending_events. */
7149
7150 bool
7151 remote_target::has_pending_events ()
7152 {
7153 if (target_can_async_p ())
7154 {
7155 remote_state *rs = get_remote_state ();
7156
7157 if (rs->async_event_handler_marked ())
7158 return true;
7159
7160 /* Note that BUFCNT can be negative, indicating sticky
7161 error. */
7162 if (rs->remote_desc->bufcnt != 0)
7163 return true;
7164 }
7165 return false;
7166 }
7167
7168 \f
7169
7170 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
7171 thread, all threads of a remote process, or all threads of all
7172 processes. */
7173
7174 void
7175 remote_target::remote_stop_ns (ptid_t ptid)
7176 {
7177 struct remote_state *rs = get_remote_state ();
7178 char *p = rs->buf.data ();
7179 char *endp = p + get_remote_packet_size ();
7180
7181 /* If any thread that needs to stop was resumed but pending a vCont
7182 resume, generate a phony stop_reply. However, first check
7183 whether the thread wasn't resumed with a signal. Generating a
7184 phony stop in that case would result in losing the signal. */
7185 bool needs_commit = false;
7186 for (thread_info *tp : all_non_exited_threads (this, ptid))
7187 {
7188 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7189
7190 if (remote_thr->get_resume_state ()
7191 == resume_state::RESUMED_PENDING_VCONT)
7192 {
7193 const resumed_pending_vcont_info &info
7194 = remote_thr->resumed_pending_vcont_info ();
7195 if (info.sig != GDB_SIGNAL_0)
7196 {
7197 /* This signal must be forwarded to the inferior. We
7198 could commit-resume just this thread, but its simpler
7199 to just commit-resume everything. */
7200 needs_commit = true;
7201 break;
7202 }
7203 }
7204 }
7205
7206 if (needs_commit)
7207 commit_resumed ();
7208 else
7209 for (thread_info *tp : all_non_exited_threads (this, ptid))
7210 {
7211 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7212
7213 if (remote_thr->get_resume_state ()
7214 == resume_state::RESUMED_PENDING_VCONT)
7215 {
7216 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
7217 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
7218 tp->ptid.lwp (),
7219 pulongest (tp->ptid.tid ()));
7220
7221 /* Check that the thread wasn't resumed with a signal.
7222 Generating a phony stop would result in losing the
7223 signal. */
7224 const resumed_pending_vcont_info &info
7225 = remote_thr->resumed_pending_vcont_info ();
7226 gdb_assert (info.sig == GDB_SIGNAL_0);
7227
7228 stop_reply *sr = new stop_reply ();
7229 sr->ptid = tp->ptid;
7230 sr->rs = rs;
7231 sr->ws.set_stopped (GDB_SIGNAL_0);
7232 sr->arch = tp->inf->arch ();
7233 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7234 sr->watch_data_address = 0;
7235 sr->core = 0;
7236 this->push_stop_reply (sr);
7237
7238 /* Pretend that this thread was actually resumed on the
7239 remote target, then stopped. If we leave it in the
7240 RESUMED_PENDING_VCONT state and the commit_resumed
7241 method is called while the stop reply is still in the
7242 queue, we'll end up reporting a stop event to the core
7243 for that thread while it is running on the remote
7244 target... that would be bad. */
7245 remote_thr->set_resumed ();
7246 }
7247 }
7248
7249 if (!rs->supports_vCont.t)
7250 error (_("Remote server does not support stopping threads"));
7251
7252 if (ptid == minus_one_ptid
7253 || (!m_features.remote_multi_process_p () && ptid.is_pid ()))
7254 p += xsnprintf (p, endp - p, "vCont;t");
7255 else
7256 {
7257 ptid_t nptid;
7258
7259 p += xsnprintf (p, endp - p, "vCont;t:");
7260
7261 if (ptid.is_pid ())
7262 /* All (-1) threads of process. */
7263 nptid = ptid_t (ptid.pid (), -1);
7264 else
7265 {
7266 /* Small optimization: if we already have a stop reply for
7267 this thread, no use in telling the stub we want this
7268 stopped. */
7269 if (peek_stop_reply (ptid))
7270 return;
7271
7272 nptid = ptid;
7273 }
7274
7275 write_ptid (p, endp, nptid);
7276 }
7277
7278 /* In non-stop, we get an immediate OK reply. The stop reply will
7279 come in asynchronously by notification. */
7280 putpkt (rs->buf);
7281 getpkt (&rs->buf);
7282 if (strcmp (rs->buf.data (), "OK") != 0)
7283 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7284 rs->buf.data ());
7285 }
7286
7287 /* All-stop version of target_interrupt. Sends a break or a ^C to
7288 interrupt the remote target. It is undefined which thread of which
7289 process reports the interrupt. */
7290
7291 void
7292 remote_target::remote_interrupt_as ()
7293 {
7294 struct remote_state *rs = get_remote_state ();
7295
7296 rs->ctrlc_pending_p = 1;
7297
7298 /* If the inferior is stopped already, but the core didn't know
7299 about it yet, just ignore the request. The pending stop events
7300 will be collected in remote_wait. */
7301 if (stop_reply_queue_length () > 0)
7302 return;
7303
7304 /* Send interrupt_sequence to remote target. */
7305 send_interrupt_sequence ();
7306 }
7307
7308 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7309 the remote target. It is undefined which thread of which process
7310 reports the interrupt. Throws an error if the packet is not
7311 supported by the server. */
7312
7313 void
7314 remote_target::remote_interrupt_ns ()
7315 {
7316 struct remote_state *rs = get_remote_state ();
7317 char *p = rs->buf.data ();
7318 char *endp = p + get_remote_packet_size ();
7319
7320 xsnprintf (p, endp - p, "vCtrlC");
7321
7322 /* In non-stop, we get an immediate OK reply. The stop reply will
7323 come in asynchronously by notification. */
7324 putpkt (rs->buf);
7325 getpkt (&rs->buf);
7326
7327 switch (m_features.packet_ok (rs->buf, PACKET_vCtrlC))
7328 {
7329 case PACKET_OK:
7330 break;
7331 case PACKET_UNKNOWN:
7332 error (_("No support for interrupting the remote target."));
7333 case PACKET_ERROR:
7334 error (_("Interrupting target failed: %s"), rs->buf.data ());
7335 }
7336 }
7337
7338 /* Implement the to_stop function for the remote targets. */
7339
7340 void
7341 remote_target::stop (ptid_t ptid)
7342 {
7343 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7344
7345 if (target_is_non_stop_p ())
7346 remote_stop_ns (ptid);
7347 else
7348 {
7349 /* We don't currently have a way to transparently pause the
7350 remote target in all-stop mode. Interrupt it instead. */
7351 remote_interrupt_as ();
7352 }
7353 }
7354
7355 /* Implement the to_interrupt function for the remote targets. */
7356
7357 void
7358 remote_target::interrupt ()
7359 {
7360 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7361
7362 if (target_is_non_stop_p ())
7363 remote_interrupt_ns ();
7364 else
7365 remote_interrupt_as ();
7366 }
7367
7368 /* Implement the to_pass_ctrlc function for the remote targets. */
7369
7370 void
7371 remote_target::pass_ctrlc ()
7372 {
7373 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7374
7375 struct remote_state *rs = get_remote_state ();
7376
7377 /* If we're starting up, we're not fully synced yet. Quit
7378 immediately. */
7379 if (rs->starting_up)
7380 quit ();
7381 /* If ^C has already been sent once, offer to disconnect. */
7382 else if (rs->ctrlc_pending_p)
7383 interrupt_query ();
7384 else
7385 target_interrupt ();
7386 }
7387
7388 /* Ask the user what to do when an interrupt is received. */
7389
7390 void
7391 remote_target::interrupt_query ()
7392 {
7393 struct remote_state *rs = get_remote_state ();
7394
7395 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7396 {
7397 if (query (_("The target is not responding to interrupt requests.\n"
7398 "Stop debugging it? ")))
7399 {
7400 remote_unpush_target (this);
7401 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7402 }
7403 }
7404 else
7405 {
7406 if (query (_("Interrupted while waiting for the program.\n"
7407 "Give up waiting? ")))
7408 quit ();
7409 }
7410 }
7411
7412 /* Enable/disable target terminal ownership. Most targets can use
7413 terminal groups to control terminal ownership. Remote targets are
7414 different in that explicit transfer of ownership to/from GDB/target
7415 is required. */
7416
7417 void
7418 remote_target::terminal_inferior ()
7419 {
7420 /* NOTE: At this point we could also register our selves as the
7421 recipient of all input. Any characters typed could then be
7422 passed on down to the target. */
7423 }
7424
7425 void
7426 remote_target::terminal_ours ()
7427 {
7428 }
7429
7430 static void
7431 remote_console_output (const char *msg)
7432 {
7433 const char *p;
7434
7435 for (p = msg; p[0] && p[1]; p += 2)
7436 {
7437 char tb[2];
7438 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7439
7440 tb[0] = c;
7441 tb[1] = 0;
7442 gdb_stdtarg->puts (tb);
7443 }
7444 gdb_stdtarg->flush ();
7445 }
7446
7447 /* Return the length of the stop reply queue. */
7448
7449 int
7450 remote_target::stop_reply_queue_length ()
7451 {
7452 remote_state *rs = get_remote_state ();
7453 return rs->stop_reply_queue.size ();
7454 }
7455
7456 static void
7457 remote_notif_stop_parse (remote_target *remote,
7458 const notif_client *self, const char *buf,
7459 struct notif_event *event)
7460 {
7461 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7462 }
7463
7464 static void
7465 remote_notif_stop_ack (remote_target *remote,
7466 const notif_client *self, const char *buf,
7467 struct notif_event *event)
7468 {
7469 struct stop_reply *stop_reply = (struct stop_reply *) event;
7470
7471 /* acknowledge */
7472 putpkt (remote, self->ack_command);
7473
7474 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7475 the notification. It was left in the queue because we need to
7476 acknowledge it and pull the rest of the notifications out. */
7477 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7478 remote->push_stop_reply (stop_reply);
7479 }
7480
7481 static int
7482 remote_notif_stop_can_get_pending_events (remote_target *remote,
7483 const notif_client *self)
7484 {
7485 /* We can't get pending events in remote_notif_process for
7486 notification stop, and we have to do this in remote_wait_ns
7487 instead. If we fetch all queued events from stub, remote stub
7488 may exit and we have no chance to process them back in
7489 remote_wait_ns. */
7490 remote_state *rs = remote->get_remote_state ();
7491 rs->mark_async_event_handler ();
7492 return 0;
7493 }
7494
7495 stop_reply::~stop_reply ()
7496 {
7497 for (cached_reg_t &reg : regcache)
7498 xfree (reg.data);
7499 }
7500
7501 static notif_event_up
7502 remote_notif_stop_alloc_reply ()
7503 {
7504 return notif_event_up (new struct stop_reply ());
7505 }
7506
7507 /* A client of notification Stop. */
7508
7509 const notif_client notif_client_stop =
7510 {
7511 "Stop",
7512 "vStopped",
7513 remote_notif_stop_parse,
7514 remote_notif_stop_ack,
7515 remote_notif_stop_can_get_pending_events,
7516 remote_notif_stop_alloc_reply,
7517 REMOTE_NOTIF_STOP,
7518 };
7519
7520 /* If CONTEXT contains any fork child threads that have not been
7521 reported yet, remove them from the CONTEXT list. If such a
7522 thread exists it is because we are stopped at a fork catchpoint
7523 and have not yet called follow_fork, which will set up the
7524 host-side data structures for the new process. */
7525
7526 void
7527 remote_target::remove_new_fork_children (threads_listing_context *context)
7528 {
7529 const notif_client *notif = &notif_client_stop;
7530
7531 /* For any threads stopped at a fork event, remove the corresponding
7532 fork child threads from the CONTEXT list. */
7533 for (thread_info *thread : all_non_exited_threads (this))
7534 {
7535 const target_waitstatus *ws = thread_pending_fork_status (thread);
7536
7537 if (ws == nullptr)
7538 continue;
7539
7540 context->remove_thread (ws->child_ptid ());
7541 }
7542
7543 /* Check for any pending fork events (not reported or processed yet)
7544 in process PID and remove those fork child threads from the
7545 CONTEXT list as well. */
7546 remote_notif_get_pending_events (notif);
7547 for (auto &event : get_remote_state ()->stop_reply_queue)
7548 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7549 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7550 context->remove_thread (event->ws.child_ptid ());
7551 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7552 context->remove_thread (event->ptid);
7553 }
7554
7555 /* Check whether any event pending in the vStopped queue would prevent a
7556 global or process wildcard vCont action. Set *may_global_wildcard to
7557 false if we can't do a global wildcard (vCont;c), and clear the event
7558 inferior's may_wildcard_vcont flag if we can't do a process-wide
7559 wildcard resume (vCont;c:pPID.-1). */
7560
7561 void
7562 remote_target::check_pending_events_prevent_wildcard_vcont
7563 (bool *may_global_wildcard)
7564 {
7565 const notif_client *notif = &notif_client_stop;
7566
7567 remote_notif_get_pending_events (notif);
7568 for (auto &event : get_remote_state ()->stop_reply_queue)
7569 {
7570 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7571 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7572 continue;
7573
7574 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7575 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7576 *may_global_wildcard = false;
7577
7578 /* This may be the first time we heard about this process.
7579 Regardless, we must not do a global wildcard resume, otherwise
7580 we'd resume this process too. */
7581 *may_global_wildcard = false;
7582 if (event->ptid != null_ptid)
7583 {
7584 inferior *inf = find_inferior_ptid (this, event->ptid);
7585 if (inf != NULL)
7586 get_remote_inferior (inf)->may_wildcard_vcont = false;
7587 }
7588 }
7589 }
7590
7591 /* Discard all pending stop replies of inferior INF. */
7592
7593 void
7594 remote_target::discard_pending_stop_replies (struct inferior *inf)
7595 {
7596 struct stop_reply *reply;
7597 struct remote_state *rs = get_remote_state ();
7598 struct remote_notif_state *rns = rs->notif_state;
7599
7600 /* This function can be notified when an inferior exists. When the
7601 target is not remote, the notification state is NULL. */
7602 if (rs->remote_desc == NULL)
7603 return;
7604
7605 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7606
7607 /* Discard the in-flight notification. */
7608 if (reply != NULL && reply->ptid.pid () == inf->pid)
7609 {
7610 /* Leave the notification pending, since the server expects that
7611 we acknowledge it with vStopped. But clear its contents, so
7612 that later on when we acknowledge it, we also discard it. */
7613 remote_debug_printf
7614 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7615 reply->ptid.to_string().c_str(),
7616 reply->ws.to_string ().c_str ());
7617 reply->ws.set_ignore ();
7618 }
7619
7620 /* Discard the stop replies we have already pulled with
7621 vStopped. */
7622 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7623 rs->stop_reply_queue.end (),
7624 [=] (const stop_reply_up &event)
7625 {
7626 return event->ptid.pid () == inf->pid;
7627 });
7628 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7629 remote_debug_printf
7630 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7631 (*it)->ptid.to_string().c_str(),
7632 (*it)->ws.to_string ().c_str ());
7633 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7634 }
7635
7636 /* Discard the stop replies for RS in stop_reply_queue. */
7637
7638 void
7639 remote_target::discard_pending_stop_replies_in_queue ()
7640 {
7641 remote_state *rs = get_remote_state ();
7642
7643 /* Discard the stop replies we have already pulled with
7644 vStopped. */
7645 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7646 rs->stop_reply_queue.end (),
7647 [=] (const stop_reply_up &event)
7648 {
7649 return event->rs == rs;
7650 });
7651 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7652 }
7653
7654 /* Remove the first reply in 'stop_reply_queue' which matches
7655 PTID. */
7656
7657 struct stop_reply *
7658 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7659 {
7660 remote_state *rs = get_remote_state ();
7661
7662 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7663 rs->stop_reply_queue.end (),
7664 [=] (const stop_reply_up &event)
7665 {
7666 return event->ptid.matches (ptid);
7667 });
7668 struct stop_reply *result;
7669 if (iter == rs->stop_reply_queue.end ())
7670 result = nullptr;
7671 else
7672 {
7673 result = iter->release ();
7674 rs->stop_reply_queue.erase (iter);
7675 }
7676
7677 if (notif_debug)
7678 gdb_printf (gdb_stdlog,
7679 "notif: discard queued event: 'Stop' in %s\n",
7680 ptid.to_string ().c_str ());
7681
7682 return result;
7683 }
7684
7685 /* Look for a queued stop reply belonging to PTID. If one is found,
7686 remove it from the queue, and return it. Returns NULL if none is
7687 found. If there are still queued events left to process, tell the
7688 event loop to get back to target_wait soon. */
7689
7690 struct stop_reply *
7691 remote_target::queued_stop_reply (ptid_t ptid)
7692 {
7693 remote_state *rs = get_remote_state ();
7694 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7695
7696 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7697 {
7698 /* There's still at least an event left. */
7699 rs->mark_async_event_handler ();
7700 }
7701
7702 return r;
7703 }
7704
7705 /* Push a fully parsed stop reply in the stop reply queue. Since we
7706 know that we now have at least one queued event left to pass to the
7707 core side, tell the event loop to get back to target_wait soon. */
7708
7709 void
7710 remote_target::push_stop_reply (struct stop_reply *new_event)
7711 {
7712 remote_state *rs = get_remote_state ();
7713 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7714
7715 if (notif_debug)
7716 gdb_printf (gdb_stdlog,
7717 "notif: push 'Stop' %s to queue %d\n",
7718 new_event->ptid.to_string ().c_str (),
7719 int (rs->stop_reply_queue.size ()));
7720
7721 /* Mark the pending event queue only if async mode is currently enabled.
7722 If async mode is not currently enabled, then, if it later becomes
7723 enabled, and there are events in this queue, we will mark the event
7724 token at that point, see remote_target::async. */
7725 if (target_is_async_p ())
7726 rs->mark_async_event_handler ();
7727 }
7728
7729 /* Returns true if we have a stop reply for PTID. */
7730
7731 int
7732 remote_target::peek_stop_reply (ptid_t ptid)
7733 {
7734 remote_state *rs = get_remote_state ();
7735 for (auto &event : rs->stop_reply_queue)
7736 if (ptid == event->ptid
7737 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7738 return 1;
7739 return 0;
7740 }
7741
7742 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7743 starting with P and ending with PEND matches PREFIX. */
7744
7745 static int
7746 strprefix (const char *p, const char *pend, const char *prefix)
7747 {
7748 for ( ; p < pend; p++, prefix++)
7749 if (*p != *prefix)
7750 return 0;
7751 return *prefix == '\0';
7752 }
7753
7754 /* Parse the stop reply in BUF. Either the function succeeds, and the
7755 result is stored in EVENT, or throws an error. */
7756
7757 void
7758 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7759 {
7760 remote_arch_state *rsa = NULL;
7761 ULONGEST addr;
7762 const char *p;
7763 int skipregs = 0;
7764
7765 event->ptid = null_ptid;
7766 event->rs = get_remote_state ();
7767 event->ws.set_ignore ();
7768 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7769 event->regcache.clear ();
7770 event->core = -1;
7771
7772 switch (buf[0])
7773 {
7774 case 'T': /* Status with PC, SP, FP, ... */
7775 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7776 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7777 ss = signal number
7778 n... = register number
7779 r... = register contents
7780 */
7781
7782 p = &buf[3]; /* after Txx */
7783 while (*p)
7784 {
7785 const char *p1;
7786 int fieldsize;
7787
7788 p1 = strchr (p, ':');
7789 if (p1 == NULL)
7790 error (_("Malformed packet(a) (missing colon): %s\n\
7791 Packet: '%s'\n"),
7792 p, buf);
7793 if (p == p1)
7794 error (_("Malformed packet(a) (missing register number): %s\n\
7795 Packet: '%s'\n"),
7796 p, buf);
7797
7798 /* Some "registers" are actually extended stop information.
7799 Note if you're adding a new entry here: GDB 7.9 and
7800 earlier assume that all register "numbers" that start
7801 with an hex digit are real register numbers. Make sure
7802 the server only sends such a packet if it knows the
7803 client understands it. */
7804
7805 if (strprefix (p, p1, "thread"))
7806 event->ptid = read_ptid (++p1, &p);
7807 else if (strprefix (p, p1, "syscall_entry"))
7808 {
7809 ULONGEST sysno;
7810
7811 p = unpack_varlen_hex (++p1, &sysno);
7812 event->ws.set_syscall_entry ((int) sysno);
7813 }
7814 else if (strprefix (p, p1, "syscall_return"))
7815 {
7816 ULONGEST sysno;
7817
7818 p = unpack_varlen_hex (++p1, &sysno);
7819 event->ws.set_syscall_return ((int) sysno);
7820 }
7821 else if (strprefix (p, p1, "watch")
7822 || strprefix (p, p1, "rwatch")
7823 || strprefix (p, p1, "awatch"))
7824 {
7825 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7826 p = unpack_varlen_hex (++p1, &addr);
7827 event->watch_data_address = (CORE_ADDR) addr;
7828 }
7829 else if (strprefix (p, p1, "swbreak"))
7830 {
7831 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7832
7833 /* Make sure the stub doesn't forget to indicate support
7834 with qSupported. */
7835 if (m_features.packet_support (PACKET_swbreak_feature)
7836 != PACKET_ENABLE)
7837 error (_("Unexpected swbreak stop reason"));
7838
7839 /* The value part is documented as "must be empty",
7840 though we ignore it, in case we ever decide to make
7841 use of it in a backward compatible way. */
7842 p = strchrnul (p1 + 1, ';');
7843 }
7844 else if (strprefix (p, p1, "hwbreak"))
7845 {
7846 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7847
7848 /* Make sure the stub doesn't forget to indicate support
7849 with qSupported. */
7850 if (m_features.packet_support (PACKET_hwbreak_feature)
7851 != PACKET_ENABLE)
7852 error (_("Unexpected hwbreak stop reason"));
7853
7854 /* See above. */
7855 p = strchrnul (p1 + 1, ';');
7856 }
7857 else if (strprefix (p, p1, "library"))
7858 {
7859 event->ws.set_loaded ();
7860 p = strchrnul (p1 + 1, ';');
7861 }
7862 else if (strprefix (p, p1, "replaylog"))
7863 {
7864 event->ws.set_no_history ();
7865 /* p1 will indicate "begin" or "end", but it makes
7866 no difference for now, so ignore it. */
7867 p = strchrnul (p1 + 1, ';');
7868 }
7869 else if (strprefix (p, p1, "core"))
7870 {
7871 ULONGEST c;
7872
7873 p = unpack_varlen_hex (++p1, &c);
7874 event->core = c;
7875 }
7876 else if (strprefix (p, p1, "fork"))
7877 event->ws.set_forked (read_ptid (++p1, &p));
7878 else if (strprefix (p, p1, "vfork"))
7879 event->ws.set_vforked (read_ptid (++p1, &p));
7880 else if (strprefix (p, p1, "vforkdone"))
7881 {
7882 event->ws.set_vfork_done ();
7883 p = strchrnul (p1 + 1, ';');
7884 }
7885 else if (strprefix (p, p1, "exec"))
7886 {
7887 ULONGEST ignored;
7888 int pathlen;
7889
7890 /* Determine the length of the execd pathname. */
7891 p = unpack_varlen_hex (++p1, &ignored);
7892 pathlen = (p - p1) / 2;
7893
7894 /* Save the pathname for event reporting and for
7895 the next run command. */
7896 gdb::unique_xmalloc_ptr<char> pathname
7897 ((char *) xmalloc (pathlen + 1));
7898 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
7899 pathname.get ()[pathlen] = '\0';
7900
7901 /* This is freed during event handling. */
7902 event->ws.set_execd (std::move (pathname));
7903
7904 /* Skip the registers included in this packet, since
7905 they may be for an architecture different from the
7906 one used by the original program. */
7907 skipregs = 1;
7908 }
7909 else if (strprefix (p, p1, "create"))
7910 {
7911 event->ws.set_thread_created ();
7912 p = strchrnul (p1 + 1, ';');
7913 }
7914 else
7915 {
7916 ULONGEST pnum;
7917 const char *p_temp;
7918
7919 if (skipregs)
7920 {
7921 p = strchrnul (p1 + 1, ';');
7922 p++;
7923 continue;
7924 }
7925
7926 /* Maybe a real ``P'' register number. */
7927 p_temp = unpack_varlen_hex (p, &pnum);
7928 /* If the first invalid character is the colon, we got a
7929 register number. Otherwise, it's an unknown stop
7930 reason. */
7931 if (p_temp == p1)
7932 {
7933 /* If we haven't parsed the event's thread yet, find
7934 it now, in order to find the architecture of the
7935 reported expedited registers. */
7936 if (event->ptid == null_ptid)
7937 {
7938 /* If there is no thread-id information then leave
7939 the event->ptid as null_ptid. Later in
7940 process_stop_reply we will pick a suitable
7941 thread. */
7942 const char *thr = strstr (p1 + 1, ";thread:");
7943 if (thr != NULL)
7944 event->ptid = read_ptid (thr + strlen (";thread:"),
7945 NULL);
7946 }
7947
7948 if (rsa == NULL)
7949 {
7950 inferior *inf
7951 = (event->ptid == null_ptid
7952 ? NULL
7953 : find_inferior_ptid (this, event->ptid));
7954 /* If this is the first time we learn anything
7955 about this process, skip the registers
7956 included in this packet, since we don't yet
7957 know which architecture to use to parse them.
7958 We'll determine the architecture later when
7959 we process the stop reply and retrieve the
7960 target description, via
7961 remote_notice_new_inferior ->
7962 post_create_inferior. */
7963 if (inf == NULL)
7964 {
7965 p = strchrnul (p1 + 1, ';');
7966 p++;
7967 continue;
7968 }
7969
7970 event->arch = inf->arch ();
7971 rsa = event->rs->get_remote_arch_state (event->arch);
7972 }
7973
7974 packet_reg *reg
7975 = packet_reg_from_pnum (event->arch, rsa, pnum);
7976 cached_reg_t cached_reg;
7977
7978 if (reg == NULL)
7979 error (_("Remote sent bad register number %s: %s\n\
7980 Packet: '%s'\n"),
7981 hex_string (pnum), p, buf);
7982
7983 cached_reg.num = reg->regnum;
7984 cached_reg.data = (gdb_byte *)
7985 xmalloc (register_size (event->arch, reg->regnum));
7986
7987 p = p1 + 1;
7988 fieldsize = hex2bin (p, cached_reg.data,
7989 register_size (event->arch, reg->regnum));
7990 p += 2 * fieldsize;
7991 if (fieldsize < register_size (event->arch, reg->regnum))
7992 warning (_("Remote reply is too short: %s"), buf);
7993
7994 event->regcache.push_back (cached_reg);
7995 }
7996 else
7997 {
7998 /* Not a number. Silently skip unknown optional
7999 info. */
8000 p = strchrnul (p1 + 1, ';');
8001 }
8002 }
8003
8004 if (*p != ';')
8005 error (_("Remote register badly formatted: %s\nhere: %s"),
8006 buf, p);
8007 ++p;
8008 }
8009
8010 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
8011 break;
8012
8013 /* fall through */
8014 case 'S': /* Old style status, just signal only. */
8015 {
8016 int sig;
8017
8018 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
8019 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
8020 event->ws.set_stopped ((enum gdb_signal) sig);
8021 else
8022 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
8023 }
8024 break;
8025 case 'w': /* Thread exited. */
8026 {
8027 ULONGEST value;
8028
8029 p = unpack_varlen_hex (&buf[1], &value);
8030 event->ws.set_thread_exited (value);
8031 if (*p != ';')
8032 error (_("stop reply packet badly formatted: %s"), buf);
8033 event->ptid = read_ptid (++p, NULL);
8034 break;
8035 }
8036 case 'W': /* Target exited. */
8037 case 'X':
8038 {
8039 ULONGEST value;
8040
8041 /* GDB used to accept only 2 hex chars here. Stubs should
8042 only send more if they detect GDB supports multi-process
8043 support. */
8044 p = unpack_varlen_hex (&buf[1], &value);
8045
8046 if (buf[0] == 'W')
8047 {
8048 /* The remote process exited. */
8049 event->ws.set_exited (value);
8050 }
8051 else
8052 {
8053 /* The remote process exited with a signal. */
8054 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
8055 event->ws.set_signalled ((enum gdb_signal) value);
8056 else
8057 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
8058 }
8059
8060 /* If no process is specified, return null_ptid, and let the
8061 caller figure out the right process to use. */
8062 int pid = 0;
8063 if (*p == '\0')
8064 ;
8065 else if (*p == ';')
8066 {
8067 p++;
8068
8069 if (*p == '\0')
8070 ;
8071 else if (startswith (p, "process:"))
8072 {
8073 ULONGEST upid;
8074
8075 p += sizeof ("process:") - 1;
8076 unpack_varlen_hex (p, &upid);
8077 pid = upid;
8078 }
8079 else
8080 error (_("unknown stop reply packet: %s"), buf);
8081 }
8082 else
8083 error (_("unknown stop reply packet: %s"), buf);
8084 event->ptid = ptid_t (pid);
8085 }
8086 break;
8087 case 'N':
8088 event->ws.set_no_resumed ();
8089 event->ptid = minus_one_ptid;
8090 break;
8091 }
8092 }
8093
8094 /* When the stub wants to tell GDB about a new notification reply, it
8095 sends a notification (%Stop, for example). Those can come it at
8096 any time, hence, we have to make sure that any pending
8097 putpkt/getpkt sequence we're making is finished, before querying
8098 the stub for more events with the corresponding ack command
8099 (vStopped, for example). E.g., if we started a vStopped sequence
8100 immediately upon receiving the notification, something like this
8101 could happen:
8102
8103 1.1) --> Hg 1
8104 1.2) <-- OK
8105 1.3) --> g
8106 1.4) <-- %Stop
8107 1.5) --> vStopped
8108 1.6) <-- (registers reply to step #1.3)
8109
8110 Obviously, the reply in step #1.6 would be unexpected to a vStopped
8111 query.
8112
8113 To solve this, whenever we parse a %Stop notification successfully,
8114 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
8115 doing whatever we were doing:
8116
8117 2.1) --> Hg 1
8118 2.2) <-- OK
8119 2.3) --> g
8120 2.4) <-- %Stop
8121 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
8122 2.5) <-- (registers reply to step #2.3)
8123
8124 Eventually after step #2.5, we return to the event loop, which
8125 notices there's an event on the
8126 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
8127 associated callback --- the function below. At this point, we're
8128 always safe to start a vStopped sequence. :
8129
8130 2.6) --> vStopped
8131 2.7) <-- T05 thread:2
8132 2.8) --> vStopped
8133 2.9) --> OK
8134 */
8135
8136 void
8137 remote_target::remote_notif_get_pending_events (const notif_client *nc)
8138 {
8139 struct remote_state *rs = get_remote_state ();
8140
8141 if (rs->notif_state->pending_event[nc->id] != NULL)
8142 {
8143 if (notif_debug)
8144 gdb_printf (gdb_stdlog,
8145 "notif: process: '%s' ack pending event\n",
8146 nc->name);
8147
8148 /* acknowledge */
8149 nc->ack (this, nc, rs->buf.data (),
8150 rs->notif_state->pending_event[nc->id]);
8151 rs->notif_state->pending_event[nc->id] = NULL;
8152
8153 while (1)
8154 {
8155 getpkt (&rs->buf);
8156 if (strcmp (rs->buf.data (), "OK") == 0)
8157 break;
8158 else
8159 remote_notif_ack (this, nc, rs->buf.data ());
8160 }
8161 }
8162 else
8163 {
8164 if (notif_debug)
8165 gdb_printf (gdb_stdlog,
8166 "notif: process: '%s' no pending reply\n",
8167 nc->name);
8168 }
8169 }
8170
8171 /* Wrapper around remote_target::remote_notif_get_pending_events to
8172 avoid having to export the whole remote_target class. */
8173
8174 void
8175 remote_notif_get_pending_events (remote_target *remote, const notif_client *nc)
8176 {
8177 remote->remote_notif_get_pending_events (nc);
8178 }
8179
8180 /* Called from process_stop_reply when the stop packet we are responding
8181 to didn't include a process-id or thread-id. STATUS is the stop event
8182 we are responding to.
8183
8184 It is the task of this function to select a suitable thread (or process)
8185 and return its ptid, this is the thread (or process) we will assume the
8186 stop event came from.
8187
8188 In some cases there isn't really any choice about which thread (or
8189 process) is selected, a basic remote with a single process containing a
8190 single thread might choose not to send any process-id or thread-id in
8191 its stop packets, this function will select and return the one and only
8192 thread.
8193
8194 However, if a target supports multiple threads (or processes) and still
8195 doesn't include a thread-id (or process-id) in its stop packet then
8196 first, this is a badly behaving target, and second, we're going to have
8197 to select a thread (or process) at random and use that. This function
8198 will print a warning to the user if it detects that there is the
8199 possibility that GDB is guessing which thread (or process) to
8200 report.
8201
8202 Note that this is called before GDB fetches the updated thread list from the
8203 target. So it's possible for the stop reply to be ambiguous and for GDB to
8204 not realize it. For example, if there's initially one thread, the target
8205 spawns a second thread, and then sends a stop reply without an id that
8206 concerns the first thread. GDB will assume the stop reply is about the
8207 first thread - the only thread it knows about - without printing a warning.
8208 Anyway, if the remote meant for the stop reply to be about the second thread,
8209 then it would be really broken, because GDB doesn't know about that thread
8210 yet. */
8211
8212 ptid_t
8213 remote_target::select_thread_for_ambiguous_stop_reply
8214 (const target_waitstatus &status)
8215 {
8216 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8217
8218 /* Some stop events apply to all threads in an inferior, while others
8219 only apply to a single thread. */
8220 bool process_wide_stop
8221 = (status.kind () == TARGET_WAITKIND_EXITED
8222 || status.kind () == TARGET_WAITKIND_SIGNALLED);
8223
8224 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
8225
8226 thread_info *first_resumed_thread = nullptr;
8227 bool ambiguous = false;
8228
8229 /* Consider all non-exited threads of the target, find the first resumed
8230 one. */
8231 for (thread_info *thr : all_non_exited_threads (this))
8232 {
8233 remote_thread_info *remote_thr = get_remote_thread_info (thr);
8234
8235 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8236 continue;
8237
8238 if (first_resumed_thread == nullptr)
8239 first_resumed_thread = thr;
8240 else if (!process_wide_stop
8241 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8242 ambiguous = true;
8243 }
8244
8245 gdb_assert (first_resumed_thread != nullptr);
8246
8247 remote_debug_printf ("first resumed thread is %s",
8248 pid_to_str (first_resumed_thread->ptid).c_str ());
8249 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8250
8251 /* Warn if the remote target is sending ambiguous stop replies. */
8252 if (ambiguous)
8253 {
8254 static bool warned = false;
8255
8256 if (!warned)
8257 {
8258 /* If you are seeing this warning then the remote target has
8259 stopped without specifying a thread-id, but the target
8260 does have multiple threads (or inferiors), and so GDB is
8261 having to guess which thread stopped.
8262
8263 Examples of what might cause this are the target sending
8264 and 'S' stop packet, or a 'T' stop packet and not
8265 including a thread-id.
8266
8267 Additionally, the target might send a 'W' or 'X packet
8268 without including a process-id, when the target has
8269 multiple running inferiors. */
8270 if (process_wide_stop)
8271 warning (_("multi-inferior target stopped without "
8272 "sending a process-id, using first "
8273 "non-exited inferior"));
8274 else
8275 warning (_("multi-threaded target stopped without "
8276 "sending a thread-id, using first "
8277 "non-exited thread"));
8278 warned = true;
8279 }
8280 }
8281
8282 /* If this is a stop for all threads then don't use a particular threads
8283 ptid, instead create a new ptid where only the pid field is set. */
8284 if (process_wide_stop)
8285 return ptid_t (first_resumed_thread->ptid.pid ());
8286 else
8287 return first_resumed_thread->ptid;
8288 }
8289
8290 /* Called when it is decided that STOP_REPLY holds the info of the
8291 event that is to be returned to the core. This function always
8292 destroys STOP_REPLY. */
8293
8294 ptid_t
8295 remote_target::process_stop_reply (struct stop_reply *stop_reply,
8296 struct target_waitstatus *status)
8297 {
8298 *status = stop_reply->ws;
8299 ptid_t ptid = stop_reply->ptid;
8300
8301 /* If no thread/process was reported by the stub then select a suitable
8302 thread/process. */
8303 if (ptid == null_ptid)
8304 ptid = select_thread_for_ambiguous_stop_reply (*status);
8305 gdb_assert (ptid != null_ptid);
8306
8307 if (status->kind () != TARGET_WAITKIND_EXITED
8308 && status->kind () != TARGET_WAITKIND_SIGNALLED
8309 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8310 {
8311 /* Expedited registers. */
8312 if (!stop_reply->regcache.empty ())
8313 {
8314 struct regcache *regcache
8315 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
8316
8317 for (cached_reg_t &reg : stop_reply->regcache)
8318 {
8319 regcache->raw_supply (reg.num, reg.data);
8320 xfree (reg.data);
8321 }
8322
8323 stop_reply->regcache.clear ();
8324 }
8325
8326 remote_notice_new_inferior (ptid, false);
8327 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8328 remote_thr->core = stop_reply->core;
8329 remote_thr->stop_reason = stop_reply->stop_reason;
8330 remote_thr->watch_data_address = stop_reply->watch_data_address;
8331
8332 if (target_is_non_stop_p ())
8333 {
8334 /* If the target works in non-stop mode, a stop-reply indicates that
8335 only this thread stopped. */
8336 remote_thr->set_not_resumed ();
8337 }
8338 else
8339 {
8340 /* If the target works in all-stop mode, a stop-reply indicates that
8341 all the target's threads stopped. */
8342 for (thread_info *tp : all_non_exited_threads (this))
8343 get_remote_thread_info (tp)->set_not_resumed ();
8344 }
8345 }
8346
8347 delete stop_reply;
8348 return ptid;
8349 }
8350
8351 /* The non-stop mode version of target_wait. */
8352
8353 ptid_t
8354 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8355 target_wait_flags options)
8356 {
8357 struct remote_state *rs = get_remote_state ();
8358 struct stop_reply *stop_reply;
8359 int ret;
8360 bool is_notif = false;
8361
8362 /* If in non-stop mode, get out of getpkt even if a
8363 notification is received. */
8364
8365 ret = getpkt (&rs->buf, false /* forever */, &is_notif);
8366 while (1)
8367 {
8368 if (ret != -1 && !is_notif)
8369 switch (rs->buf[0])
8370 {
8371 case 'E': /* Error of some sort. */
8372 /* We're out of sync with the target now. Did it continue
8373 or not? We can't tell which thread it was in non-stop,
8374 so just ignore this. */
8375 warning (_("Remote failure reply: %s"), rs->buf.data ());
8376 break;
8377 case 'O': /* Console output. */
8378 remote_console_output (&rs->buf[1]);
8379 break;
8380 default:
8381 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8382 break;
8383 }
8384
8385 /* Acknowledge a pending stop reply that may have arrived in the
8386 mean time. */
8387 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8388 remote_notif_get_pending_events (&notif_client_stop);
8389
8390 /* If indeed we noticed a stop reply, we're done. */
8391 stop_reply = queued_stop_reply (ptid);
8392 if (stop_reply != NULL)
8393 return process_stop_reply (stop_reply, status);
8394
8395 /* Still no event. If we're just polling for an event, then
8396 return to the event loop. */
8397 if (options & TARGET_WNOHANG)
8398 {
8399 status->set_ignore ();
8400 return minus_one_ptid;
8401 }
8402
8403 /* Otherwise do a blocking wait. */
8404 ret = getpkt (&rs->buf, true /* forever */, &is_notif);
8405 }
8406 }
8407
8408 /* Return the first resumed thread. */
8409
8410 static ptid_t
8411 first_remote_resumed_thread (remote_target *target)
8412 {
8413 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8414 if (tp->resumed ())
8415 return tp->ptid;
8416 return null_ptid;
8417 }
8418
8419 /* Wait until the remote machine stops, then return, storing status in
8420 STATUS just as `wait' would. */
8421
8422 ptid_t
8423 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8424 target_wait_flags options)
8425 {
8426 struct remote_state *rs = get_remote_state ();
8427 ptid_t event_ptid = null_ptid;
8428 char *buf;
8429 struct stop_reply *stop_reply;
8430
8431 again:
8432
8433 status->set_ignore ();
8434
8435 stop_reply = queued_stop_reply (ptid);
8436 if (stop_reply != NULL)
8437 {
8438 /* None of the paths that push a stop reply onto the queue should
8439 have set the waiting_for_stop_reply flag. */
8440 gdb_assert (!rs->waiting_for_stop_reply);
8441 event_ptid = process_stop_reply (stop_reply, status);
8442 }
8443 else
8444 {
8445 bool forever = ((options & TARGET_WNOHANG) == 0
8446 && rs->wait_forever_enabled_p);
8447
8448 if (!rs->waiting_for_stop_reply)
8449 {
8450 status->set_no_resumed ();
8451 return minus_one_ptid;
8452 }
8453
8454 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8455 _never_ wait for ever -> test on target_is_async_p().
8456 However, before we do that we need to ensure that the caller
8457 knows how to take the target into/out of async mode. */
8458 bool is_notif;
8459 int ret = getpkt (&rs->buf, forever, &is_notif);
8460
8461 /* GDB gets a notification. Return to core as this event is
8462 not interesting. */
8463 if (ret != -1 && is_notif)
8464 return minus_one_ptid;
8465
8466 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8467 return minus_one_ptid;
8468
8469 buf = rs->buf.data ();
8470
8471 /* Assume that the target has acknowledged Ctrl-C unless we receive
8472 an 'F' or 'O' packet. */
8473 if (buf[0] != 'F' && buf[0] != 'O')
8474 rs->ctrlc_pending_p = 0;
8475
8476 switch (buf[0])
8477 {
8478 case 'E': /* Error of some sort. */
8479 /* We're out of sync with the target now. Did it continue or
8480 not? Not is more likely, so report a stop. */
8481 rs->waiting_for_stop_reply = 0;
8482
8483 warning (_("Remote failure reply: %s"), buf);
8484 status->set_stopped (GDB_SIGNAL_0);
8485 break;
8486 case 'F': /* File-I/O request. */
8487 /* GDB may access the inferior memory while handling the File-I/O
8488 request, but we don't want GDB accessing memory while waiting
8489 for a stop reply. See the comments in putpkt_binary. Set
8490 waiting_for_stop_reply to 0 temporarily. */
8491 rs->waiting_for_stop_reply = 0;
8492 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8493 rs->ctrlc_pending_p = 0;
8494 /* GDB handled the File-I/O request, and the target is running
8495 again. Keep waiting for events. */
8496 rs->waiting_for_stop_reply = 1;
8497 break;
8498 case 'N': case 'T': case 'S': case 'X': case 'W':
8499 {
8500 /* There is a stop reply to handle. */
8501 rs->waiting_for_stop_reply = 0;
8502
8503 stop_reply
8504 = (struct stop_reply *) remote_notif_parse (this,
8505 &notif_client_stop,
8506 rs->buf.data ());
8507
8508 event_ptid = process_stop_reply (stop_reply, status);
8509 break;
8510 }
8511 case 'O': /* Console output. */
8512 remote_console_output (buf + 1);
8513 break;
8514 case '\0':
8515 if (rs->last_sent_signal != GDB_SIGNAL_0)
8516 {
8517 /* Zero length reply means that we tried 'S' or 'C' and the
8518 remote system doesn't support it. */
8519 target_terminal::ours_for_output ();
8520 gdb_printf
8521 ("Can't send signals to this remote system. %s not sent.\n",
8522 gdb_signal_to_name (rs->last_sent_signal));
8523 rs->last_sent_signal = GDB_SIGNAL_0;
8524 target_terminal::inferior ();
8525
8526 strcpy (buf, rs->last_sent_step ? "s" : "c");
8527 putpkt (buf);
8528 break;
8529 }
8530 /* fallthrough */
8531 default:
8532 warning (_("Invalid remote reply: %s"), buf);
8533 break;
8534 }
8535 }
8536
8537 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8538 return minus_one_ptid;
8539 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8540 {
8541 /* Nothing interesting happened. If we're doing a non-blocking
8542 poll, we're done. Otherwise, go back to waiting. */
8543 if (options & TARGET_WNOHANG)
8544 return minus_one_ptid;
8545 else
8546 goto again;
8547 }
8548 else if (status->kind () != TARGET_WAITKIND_EXITED
8549 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8550 {
8551 if (event_ptid != null_ptid)
8552 record_currthread (rs, event_ptid);
8553 else
8554 event_ptid = first_remote_resumed_thread (this);
8555 }
8556 else
8557 {
8558 /* A process exit. Invalidate our notion of current thread. */
8559 record_currthread (rs, minus_one_ptid);
8560 /* It's possible that the packet did not include a pid. */
8561 if (event_ptid == null_ptid)
8562 event_ptid = first_remote_resumed_thread (this);
8563 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8564 if (event_ptid == null_ptid)
8565 event_ptid = magic_null_ptid;
8566 }
8567
8568 return event_ptid;
8569 }
8570
8571 /* Wait until the remote machine stops, then return, storing status in
8572 STATUS just as `wait' would. */
8573
8574 ptid_t
8575 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8576 target_wait_flags options)
8577 {
8578 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8579
8580 remote_state *rs = get_remote_state ();
8581
8582 /* Start by clearing the flag that asks for our wait method to be called,
8583 we'll mark it again at the end if needed. If the target is not in
8584 async mode then the async token should not be marked. */
8585 if (target_is_async_p ())
8586 rs->clear_async_event_handler ();
8587 else
8588 gdb_assert (!rs->async_event_handler_marked ());
8589
8590 ptid_t event_ptid;
8591
8592 if (target_is_non_stop_p ())
8593 event_ptid = wait_ns (ptid, status, options);
8594 else
8595 event_ptid = wait_as (ptid, status, options);
8596
8597 if (target_is_async_p ())
8598 {
8599 /* If there are events left in the queue, or unacknowledged
8600 notifications, then tell the event loop to call us again. */
8601 if (!rs->stop_reply_queue.empty ()
8602 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8603 rs->mark_async_event_handler ();
8604 }
8605
8606 return event_ptid;
8607 }
8608
8609 /* Fetch a single register using a 'p' packet. */
8610
8611 int
8612 remote_target::fetch_register_using_p (struct regcache *regcache,
8613 packet_reg *reg)
8614 {
8615 struct gdbarch *gdbarch = regcache->arch ();
8616 struct remote_state *rs = get_remote_state ();
8617 char *buf, *p;
8618 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8619 int i;
8620
8621 if (m_features.packet_support (PACKET_p) == PACKET_DISABLE)
8622 return 0;
8623
8624 if (reg->pnum == -1)
8625 return 0;
8626
8627 p = rs->buf.data ();
8628 *p++ = 'p';
8629 p += hexnumstr (p, reg->pnum);
8630 *p++ = '\0';
8631 putpkt (rs->buf);
8632 getpkt (&rs->buf);
8633
8634 buf = rs->buf.data ();
8635
8636 switch (m_features.packet_ok (rs->buf, PACKET_p))
8637 {
8638 case PACKET_OK:
8639 break;
8640 case PACKET_UNKNOWN:
8641 return 0;
8642 case PACKET_ERROR:
8643 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8644 gdbarch_register_name (regcache->arch (), reg->regnum),
8645 buf);
8646 }
8647
8648 /* If this register is unfetchable, tell the regcache. */
8649 if (buf[0] == 'x')
8650 {
8651 regcache->raw_supply (reg->regnum, NULL);
8652 return 1;
8653 }
8654
8655 /* Otherwise, parse and supply the value. */
8656 p = buf;
8657 i = 0;
8658 while (p[0] != 0)
8659 {
8660 if (p[1] == 0)
8661 error (_("fetch_register_using_p: early buf termination"));
8662
8663 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8664 p += 2;
8665 }
8666 regcache->raw_supply (reg->regnum, regp);
8667 return 1;
8668 }
8669
8670 /* Fetch the registers included in the target's 'g' packet. */
8671
8672 int
8673 remote_target::send_g_packet ()
8674 {
8675 struct remote_state *rs = get_remote_state ();
8676 int buf_len;
8677
8678 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8679 putpkt (rs->buf);
8680 getpkt (&rs->buf);
8681 if (packet_check_result (rs->buf) == PACKET_ERROR)
8682 error (_("Could not read registers; remote failure reply '%s'"),
8683 rs->buf.data ());
8684
8685 /* We can get out of synch in various cases. If the first character
8686 in the buffer is not a hex character, assume that has happened
8687 and try to fetch another packet to read. */
8688 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8689 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8690 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8691 && rs->buf[0] != 'x') /* New: unavailable register value. */
8692 {
8693 remote_debug_printf ("Bad register packet; fetching a new packet");
8694 getpkt (&rs->buf);
8695 }
8696
8697 buf_len = strlen (rs->buf.data ());
8698
8699 /* Sanity check the received packet. */
8700 if (buf_len % 2 != 0)
8701 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8702
8703 return buf_len / 2;
8704 }
8705
8706 void
8707 remote_target::process_g_packet (struct regcache *regcache)
8708 {
8709 struct gdbarch *gdbarch = regcache->arch ();
8710 struct remote_state *rs = get_remote_state ();
8711 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8712 int i, buf_len;
8713 char *p;
8714 char *regs;
8715
8716 buf_len = strlen (rs->buf.data ());
8717
8718 /* Further sanity checks, with knowledge of the architecture. */
8719 if (buf_len > 2 * rsa->sizeof_g_packet)
8720 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8721 "bytes): %s"),
8722 rsa->sizeof_g_packet, buf_len / 2,
8723 rs->buf.data ());
8724
8725 /* Save the size of the packet sent to us by the target. It is used
8726 as a heuristic when determining the max size of packets that the
8727 target can safely receive. */
8728 if (rsa->actual_register_packet_size == 0)
8729 rsa->actual_register_packet_size = buf_len;
8730
8731 /* If this is smaller than we guessed the 'g' packet would be,
8732 update our records. A 'g' reply that doesn't include a register's
8733 value implies either that the register is not available, or that
8734 the 'p' packet must be used. */
8735 if (buf_len < 2 * rsa->sizeof_g_packet)
8736 {
8737 long sizeof_g_packet = buf_len / 2;
8738
8739 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8740 {
8741 long offset = rsa->regs[i].offset;
8742 long reg_size = register_size (gdbarch, i);
8743
8744 if (rsa->regs[i].pnum == -1)
8745 continue;
8746
8747 if (offset >= sizeof_g_packet)
8748 rsa->regs[i].in_g_packet = 0;
8749 else if (offset + reg_size > sizeof_g_packet)
8750 error (_("Truncated register %d in remote 'g' packet"), i);
8751 else
8752 rsa->regs[i].in_g_packet = 1;
8753 }
8754
8755 /* Looks valid enough, we can assume this is the correct length
8756 for a 'g' packet. It's important not to adjust
8757 rsa->sizeof_g_packet if we have truncated registers otherwise
8758 this "if" won't be run the next time the method is called
8759 with a packet of the same size and one of the internal errors
8760 below will trigger instead. */
8761 rsa->sizeof_g_packet = sizeof_g_packet;
8762 }
8763
8764 regs = (char *) alloca (rsa->sizeof_g_packet);
8765
8766 /* Unimplemented registers read as all bits zero. */
8767 memset (regs, 0, rsa->sizeof_g_packet);
8768
8769 /* Reply describes registers byte by byte, each byte encoded as two
8770 hex characters. Suck them all up, then supply them to the
8771 register cacheing/storage mechanism. */
8772
8773 p = rs->buf.data ();
8774 for (i = 0; i < rsa->sizeof_g_packet; i++)
8775 {
8776 if (p[0] == 0 || p[1] == 0)
8777 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8778 internal_error (_("unexpected end of 'g' packet reply"));
8779
8780 if (p[0] == 'x' && p[1] == 'x')
8781 regs[i] = 0; /* 'x' */
8782 else
8783 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8784 p += 2;
8785 }
8786
8787 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8788 {
8789 struct packet_reg *r = &rsa->regs[i];
8790 long reg_size = register_size (gdbarch, i);
8791
8792 if (r->in_g_packet)
8793 {
8794 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8795 /* This shouldn't happen - we adjusted in_g_packet above. */
8796 internal_error (_("unexpected end of 'g' packet reply"));
8797 else if (rs->buf[r->offset * 2] == 'x')
8798 {
8799 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8800 /* The register isn't available, mark it as such (at
8801 the same time setting the value to zero). */
8802 regcache->raw_supply (r->regnum, NULL);
8803 }
8804 else
8805 regcache->raw_supply (r->regnum, regs + r->offset);
8806 }
8807 }
8808 }
8809
8810 void
8811 remote_target::fetch_registers_using_g (struct regcache *regcache)
8812 {
8813 send_g_packet ();
8814 process_g_packet (regcache);
8815 }
8816
8817 /* Make the remote selected traceframe match GDB's selected
8818 traceframe. */
8819
8820 void
8821 remote_target::set_remote_traceframe ()
8822 {
8823 int newnum;
8824 struct remote_state *rs = get_remote_state ();
8825
8826 if (rs->remote_traceframe_number == get_traceframe_number ())
8827 return;
8828
8829 /* Avoid recursion, remote_trace_find calls us again. */
8830 rs->remote_traceframe_number = get_traceframe_number ();
8831
8832 newnum = target_trace_find (tfind_number,
8833 get_traceframe_number (), 0, 0, NULL);
8834
8835 /* Should not happen. If it does, all bets are off. */
8836 if (newnum != get_traceframe_number ())
8837 warning (_("could not set remote traceframe"));
8838 }
8839
8840 void
8841 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8842 {
8843 struct gdbarch *gdbarch = regcache->arch ();
8844 struct remote_state *rs = get_remote_state ();
8845 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8846 int i;
8847
8848 set_remote_traceframe ();
8849 set_general_thread (regcache->ptid ());
8850
8851 if (regnum >= 0)
8852 {
8853 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8854
8855 gdb_assert (reg != NULL);
8856
8857 /* If this register might be in the 'g' packet, try that first -
8858 we are likely to read more than one register. If this is the
8859 first 'g' packet, we might be overly optimistic about its
8860 contents, so fall back to 'p'. */
8861 if (reg->in_g_packet)
8862 {
8863 fetch_registers_using_g (regcache);
8864 if (reg->in_g_packet)
8865 return;
8866 }
8867
8868 if (fetch_register_using_p (regcache, reg))
8869 return;
8870
8871 /* This register is not available. */
8872 regcache->raw_supply (reg->regnum, NULL);
8873
8874 return;
8875 }
8876
8877 fetch_registers_using_g (regcache);
8878
8879 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8880 if (!rsa->regs[i].in_g_packet)
8881 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8882 {
8883 /* This register is not available. */
8884 regcache->raw_supply (i, NULL);
8885 }
8886 }
8887
8888 /* Prepare to store registers. Since we may send them all (using a
8889 'G' request), we have to read out the ones we don't want to change
8890 first. */
8891
8892 void
8893 remote_target::prepare_to_store (struct regcache *regcache)
8894 {
8895 struct remote_state *rs = get_remote_state ();
8896 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8897 int i;
8898
8899 /* Make sure the entire registers array is valid. */
8900 switch (m_features.packet_support (PACKET_P))
8901 {
8902 case PACKET_DISABLE:
8903 case PACKET_SUPPORT_UNKNOWN:
8904 /* Make sure all the necessary registers are cached. */
8905 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8906 if (rsa->regs[i].in_g_packet)
8907 regcache->raw_update (rsa->regs[i].regnum);
8908 break;
8909 case PACKET_ENABLE:
8910 break;
8911 }
8912 }
8913
8914 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8915 packet was not recognized. */
8916
8917 int
8918 remote_target::store_register_using_P (const struct regcache *regcache,
8919 packet_reg *reg)
8920 {
8921 struct gdbarch *gdbarch = regcache->arch ();
8922 struct remote_state *rs = get_remote_state ();
8923 /* Try storing a single register. */
8924 char *buf = rs->buf.data ();
8925 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8926 char *p;
8927
8928 if (m_features.packet_support (PACKET_P) == PACKET_DISABLE)
8929 return 0;
8930
8931 if (reg->pnum == -1)
8932 return 0;
8933
8934 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8935 p = buf + strlen (buf);
8936 regcache->raw_collect (reg->regnum, regp);
8937 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8938 putpkt (rs->buf);
8939 getpkt (&rs->buf);
8940
8941 switch (m_features.packet_ok (rs->buf, PACKET_P))
8942 {
8943 case PACKET_OK:
8944 return 1;
8945 case PACKET_ERROR:
8946 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8947 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
8948 case PACKET_UNKNOWN:
8949 return 0;
8950 default:
8951 internal_error (_("Bad result from packet_ok"));
8952 }
8953 }
8954
8955 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8956 contents of the register cache buffer. FIXME: ignores errors. */
8957
8958 void
8959 remote_target::store_registers_using_G (const struct regcache *regcache)
8960 {
8961 struct remote_state *rs = get_remote_state ();
8962 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8963 gdb_byte *regs;
8964 char *p;
8965
8966 /* Extract all the registers in the regcache copying them into a
8967 local buffer. */
8968 {
8969 int i;
8970
8971 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8972 memset (regs, 0, rsa->sizeof_g_packet);
8973 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8974 {
8975 struct packet_reg *r = &rsa->regs[i];
8976
8977 if (r->in_g_packet)
8978 regcache->raw_collect (r->regnum, regs + r->offset);
8979 }
8980 }
8981
8982 /* Command describes registers byte by byte,
8983 each byte encoded as two hex characters. */
8984 p = rs->buf.data ();
8985 *p++ = 'G';
8986 bin2hex (regs, p, rsa->sizeof_g_packet);
8987 putpkt (rs->buf);
8988 getpkt (&rs->buf);
8989 if (packet_check_result (rs->buf) == PACKET_ERROR)
8990 error (_("Could not write registers; remote failure reply '%s'"),
8991 rs->buf.data ());
8992 }
8993
8994 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8995 of the register cache buffer. FIXME: ignores errors. */
8996
8997 void
8998 remote_target::store_registers (struct regcache *regcache, int regnum)
8999 {
9000 struct gdbarch *gdbarch = regcache->arch ();
9001 struct remote_state *rs = get_remote_state ();
9002 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
9003 int i;
9004
9005 set_remote_traceframe ();
9006 set_general_thread (regcache->ptid ());
9007
9008 if (regnum >= 0)
9009 {
9010 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
9011
9012 gdb_assert (reg != NULL);
9013
9014 /* Always prefer to store registers using the 'P' packet if
9015 possible; we often change only a small number of registers.
9016 Sometimes we change a larger number; we'd need help from a
9017 higher layer to know to use 'G'. */
9018 if (store_register_using_P (regcache, reg))
9019 return;
9020
9021 /* For now, don't complain if we have no way to write the
9022 register. GDB loses track of unavailable registers too
9023 easily. Some day, this may be an error. We don't have
9024 any way to read the register, either... */
9025 if (!reg->in_g_packet)
9026 return;
9027
9028 store_registers_using_G (regcache);
9029 return;
9030 }
9031
9032 store_registers_using_G (regcache);
9033
9034 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
9035 if (!rsa->regs[i].in_g_packet)
9036 if (!store_register_using_P (regcache, &rsa->regs[i]))
9037 /* See above for why we do not issue an error here. */
9038 continue;
9039 }
9040 \f
9041
9042 /* Return the number of hex digits in num. */
9043
9044 static int
9045 hexnumlen (ULONGEST num)
9046 {
9047 int i;
9048
9049 for (i = 0; num != 0; i++)
9050 num >>= 4;
9051
9052 return std::max (i, 1);
9053 }
9054
9055 /* Set BUF to the minimum number of hex digits representing NUM. */
9056
9057 static int
9058 hexnumstr (char *buf, ULONGEST num)
9059 {
9060 int len = hexnumlen (num);
9061
9062 return hexnumnstr (buf, num, len);
9063 }
9064
9065
9066 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
9067
9068 static int
9069 hexnumnstr (char *buf, ULONGEST num, int width)
9070 {
9071 int i;
9072
9073 buf[width] = '\0';
9074
9075 for (i = width - 1; i >= 0; i--)
9076 {
9077 buf[i] = "0123456789abcdef"[(num & 0xf)];
9078 num >>= 4;
9079 }
9080
9081 return width;
9082 }
9083
9084 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
9085
9086 static CORE_ADDR
9087 remote_address_masked (CORE_ADDR addr)
9088 {
9089 unsigned int address_size = remote_address_size;
9090
9091 /* If "remoteaddresssize" was not set, default to target address size. */
9092 if (!address_size)
9093 address_size = gdbarch_addr_bit (current_inferior ()->arch ());
9094
9095 if (address_size > 0
9096 && address_size < (sizeof (ULONGEST) * 8))
9097 {
9098 /* Only create a mask when that mask can safely be constructed
9099 in a ULONGEST variable. */
9100 ULONGEST mask = 1;
9101
9102 mask = (mask << address_size) - 1;
9103 addr &= mask;
9104 }
9105 return addr;
9106 }
9107
9108 /* Determine whether the remote target supports binary downloading.
9109 This is accomplished by sending a no-op memory write of zero length
9110 to the target at the specified address. It does not suffice to send
9111 the whole packet, since many stubs strip the eighth bit and
9112 subsequently compute a wrong checksum, which causes real havoc with
9113 remote_write_bytes.
9114
9115 NOTE: This can still lose if the serial line is not eight-bit
9116 clean. In cases like this, the user should clear "remote
9117 X-packet". */
9118
9119 void
9120 remote_target::check_binary_download (CORE_ADDR addr)
9121 {
9122 struct remote_state *rs = get_remote_state ();
9123
9124 switch (m_features.packet_support (PACKET_X))
9125 {
9126 case PACKET_DISABLE:
9127 break;
9128 case PACKET_ENABLE:
9129 break;
9130 case PACKET_SUPPORT_UNKNOWN:
9131 {
9132 char *p;
9133
9134 p = rs->buf.data ();
9135 *p++ = 'X';
9136 p += hexnumstr (p, (ULONGEST) addr);
9137 *p++ = ',';
9138 p += hexnumstr (p, (ULONGEST) 0);
9139 *p++ = ':';
9140 *p = '\0';
9141
9142 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9143 getpkt (&rs->buf);
9144
9145 if (rs->buf[0] == '\0')
9146 {
9147 remote_debug_printf ("binary downloading NOT supported by target");
9148 m_features.m_protocol_packets[PACKET_X].support = PACKET_DISABLE;
9149 }
9150 else
9151 {
9152 remote_debug_printf ("binary downloading supported by target");
9153 m_features.m_protocol_packets[PACKET_X].support = PACKET_ENABLE;
9154 }
9155 break;
9156 }
9157 }
9158 }
9159
9160 /* Helper function to resize the payload in order to try to get a good
9161 alignment. We try to write an amount of data such that the next write will
9162 start on an address aligned on REMOTE_ALIGN_WRITES. */
9163
9164 static int
9165 align_for_efficient_write (int todo, CORE_ADDR memaddr)
9166 {
9167 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
9168 }
9169
9170 /* Write memory data directly to the remote machine.
9171 This does not inform the data cache; the data cache uses this.
9172 HEADER is the starting part of the packet.
9173 MEMADDR is the address in the remote memory space.
9174 MYADDR is the address of the buffer in our space.
9175 LEN_UNITS is the number of addressable units to write.
9176 UNIT_SIZE is the length in bytes of an addressable unit.
9177 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9178 should send data as binary ('X'), or hex-encoded ('M').
9179
9180 The function creates packet of the form
9181 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9182
9183 where encoding of <DATA> is terminated by PACKET_FORMAT.
9184
9185 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9186 are omitted.
9187
9188 Return the transferred status, error or OK (an
9189 'enum target_xfer_status' value). Save the number of addressable units
9190 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9191
9192 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9193 exchange between gdb and the stub could look like (?? in place of the
9194 checksum):
9195
9196 -> $m1000,4#??
9197 <- aaaabbbbccccdddd
9198
9199 -> $M1000,3:eeeeffffeeee#??
9200 <- OK
9201
9202 -> $m1000,4#??
9203 <- eeeeffffeeeedddd */
9204
9205 target_xfer_status
9206 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
9207 const gdb_byte *myaddr,
9208 ULONGEST len_units,
9209 int unit_size,
9210 ULONGEST *xfered_len_units,
9211 char packet_format, int use_length)
9212 {
9213 struct remote_state *rs = get_remote_state ();
9214 char *p;
9215 char *plen = NULL;
9216 int plenlen = 0;
9217 int todo_units;
9218 int units_written;
9219 int payload_capacity_bytes;
9220 int payload_length_bytes;
9221
9222 if (packet_format != 'X' && packet_format != 'M')
9223 internal_error (_("remote_write_bytes_aux: bad packet format"));
9224
9225 if (len_units == 0)
9226 return TARGET_XFER_EOF;
9227
9228 payload_capacity_bytes = get_memory_write_packet_size ();
9229
9230 /* The packet buffer will be large enough for the payload;
9231 get_memory_packet_size ensures this. */
9232 rs->buf[0] = '\0';
9233
9234 /* Compute the size of the actual payload by subtracting out the
9235 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9236
9237 payload_capacity_bytes -= strlen ("$,:#NN");
9238 if (!use_length)
9239 /* The comma won't be used. */
9240 payload_capacity_bytes += 1;
9241 payload_capacity_bytes -= strlen (header);
9242 payload_capacity_bytes -= hexnumlen (memaddr);
9243
9244 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9245
9246 strcat (rs->buf.data (), header);
9247 p = rs->buf.data () + strlen (header);
9248
9249 /* Compute a best guess of the number of bytes actually transfered. */
9250 if (packet_format == 'X')
9251 {
9252 /* Best guess at number of bytes that will fit. */
9253 todo_units = std::min (len_units,
9254 (ULONGEST) payload_capacity_bytes / unit_size);
9255 if (use_length)
9256 payload_capacity_bytes -= hexnumlen (todo_units);
9257 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9258 }
9259 else
9260 {
9261 /* Number of bytes that will fit. */
9262 todo_units
9263 = std::min (len_units,
9264 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9265 if (use_length)
9266 payload_capacity_bytes -= hexnumlen (todo_units);
9267 todo_units = std::min (todo_units,
9268 (payload_capacity_bytes / unit_size) / 2);
9269 }
9270
9271 if (todo_units <= 0)
9272 internal_error (_("minimum packet size too small to write data"));
9273
9274 /* If we already need another packet, then try to align the end
9275 of this packet to a useful boundary. */
9276 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9277 todo_units = align_for_efficient_write (todo_units, memaddr);
9278
9279 /* Append "<memaddr>". */
9280 memaddr = remote_address_masked (memaddr);
9281 p += hexnumstr (p, (ULONGEST) memaddr);
9282
9283 if (use_length)
9284 {
9285 /* Append ",". */
9286 *p++ = ',';
9287
9288 /* Append the length and retain its location and size. It may need to be
9289 adjusted once the packet body has been created. */
9290 plen = p;
9291 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9292 p += plenlen;
9293 }
9294
9295 /* Append ":". */
9296 *p++ = ':';
9297 *p = '\0';
9298
9299 /* Append the packet body. */
9300 if (packet_format == 'X')
9301 {
9302 /* Binary mode. Send target system values byte by byte, in
9303 increasing byte addresses. Only escape certain critical
9304 characters. */
9305 payload_length_bytes =
9306 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9307 &units_written, payload_capacity_bytes);
9308
9309 /* If not all TODO units fit, then we'll need another packet. Make
9310 a second try to keep the end of the packet aligned. Don't do
9311 this if the packet is tiny. */
9312 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9313 {
9314 int new_todo_units;
9315
9316 new_todo_units = align_for_efficient_write (units_written, memaddr);
9317
9318 if (new_todo_units != units_written)
9319 payload_length_bytes =
9320 remote_escape_output (myaddr, new_todo_units, unit_size,
9321 (gdb_byte *) p, &units_written,
9322 payload_capacity_bytes);
9323 }
9324
9325 p += payload_length_bytes;
9326 if (use_length && units_written < todo_units)
9327 {
9328 /* Escape chars have filled up the buffer prematurely,
9329 and we have actually sent fewer units than planned.
9330 Fix-up the length field of the packet. Use the same
9331 number of characters as before. */
9332 plen += hexnumnstr (plen, (ULONGEST) units_written,
9333 plenlen);
9334 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9335 }
9336 }
9337 else
9338 {
9339 /* Normal mode: Send target system values byte by byte, in
9340 increasing byte addresses. Each byte is encoded as a two hex
9341 value. */
9342 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9343 units_written = todo_units;
9344 }
9345
9346 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9347 getpkt (&rs->buf);
9348
9349 if (rs->buf[0] == 'E')
9350 return TARGET_XFER_E_IO;
9351
9352 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9353 send fewer units than we'd planned. */
9354 *xfered_len_units = (ULONGEST) units_written;
9355 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9356 }
9357
9358 /* Write memory data directly to the remote machine.
9359 This does not inform the data cache; the data cache uses this.
9360 MEMADDR is the address in the remote memory space.
9361 MYADDR is the address of the buffer in our space.
9362 LEN is the number of bytes.
9363
9364 Return the transferred status, error or OK (an
9365 'enum target_xfer_status' value). Save the number of bytes
9366 transferred in *XFERED_LEN. Only transfer a single packet. */
9367
9368 target_xfer_status
9369 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9370 ULONGEST len, int unit_size,
9371 ULONGEST *xfered_len)
9372 {
9373 const char *packet_format = NULL;
9374
9375 /* Check whether the target supports binary download. */
9376 check_binary_download (memaddr);
9377
9378 switch (m_features.packet_support (PACKET_X))
9379 {
9380 case PACKET_ENABLE:
9381 packet_format = "X";
9382 break;
9383 case PACKET_DISABLE:
9384 packet_format = "M";
9385 break;
9386 case PACKET_SUPPORT_UNKNOWN:
9387 internal_error (_("remote_write_bytes: bad internal state"));
9388 default:
9389 internal_error (_("bad switch"));
9390 }
9391
9392 return remote_write_bytes_aux (packet_format,
9393 memaddr, myaddr, len, unit_size, xfered_len,
9394 packet_format[0], 1);
9395 }
9396
9397 /* Read memory data directly from the remote machine.
9398 This does not use the data cache; the data cache uses this.
9399 MEMADDR is the address in the remote memory space.
9400 MYADDR is the address of the buffer in our space.
9401 LEN_UNITS is the number of addressable memory units to read..
9402 UNIT_SIZE is the length in bytes of an addressable unit.
9403
9404 Return the transferred status, error or OK (an
9405 'enum target_xfer_status' value). Save the number of bytes
9406 transferred in *XFERED_LEN_UNITS.
9407
9408 See the comment of remote_write_bytes_aux for an example of
9409 memory read/write exchange between gdb and the stub. */
9410
9411 target_xfer_status
9412 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9413 ULONGEST len_units,
9414 int unit_size, ULONGEST *xfered_len_units)
9415 {
9416 struct remote_state *rs = get_remote_state ();
9417 int buf_size_bytes; /* Max size of packet output buffer. */
9418 char *p;
9419 int todo_units;
9420 int decoded_bytes;
9421
9422 buf_size_bytes = get_memory_read_packet_size ();
9423 /* The packet buffer will be large enough for the payload;
9424 get_memory_packet_size ensures this. */
9425
9426 /* Number of units that will fit. */
9427 todo_units = std::min (len_units,
9428 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9429
9430 /* Construct "m"<memaddr>","<len>". */
9431 memaddr = remote_address_masked (memaddr);
9432 p = rs->buf.data ();
9433 *p++ = 'm';
9434 p += hexnumstr (p, (ULONGEST) memaddr);
9435 *p++ = ',';
9436 p += hexnumstr (p, (ULONGEST) todo_units);
9437 *p = '\0';
9438 putpkt (rs->buf);
9439 getpkt (&rs->buf);
9440 if (rs->buf[0] == 'E'
9441 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9442 && rs->buf[3] == '\0')
9443 return TARGET_XFER_E_IO;
9444 /* Reply describes memory byte by byte, each byte encoded as two hex
9445 characters. */
9446 p = rs->buf.data ();
9447 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9448 /* Return what we have. Let higher layers handle partial reads. */
9449 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9450 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9451 }
9452
9453 /* Using the set of read-only target sections of remote, read live
9454 read-only memory.
9455
9456 For interface/parameters/return description see target.h,
9457 to_xfer_partial. */
9458
9459 target_xfer_status
9460 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9461 ULONGEST memaddr,
9462 ULONGEST len,
9463 int unit_size,
9464 ULONGEST *xfered_len)
9465 {
9466 const struct target_section *secp;
9467
9468 secp = target_section_by_addr (this, memaddr);
9469 if (secp != NULL
9470 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9471 {
9472 ULONGEST memend = memaddr + len;
9473
9474 const std::vector<target_section> *table
9475 = target_get_section_table (this);
9476 for (const target_section &p : *table)
9477 {
9478 if (memaddr >= p.addr)
9479 {
9480 if (memend <= p.endaddr)
9481 {
9482 /* Entire transfer is within this section. */
9483 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9484 xfered_len);
9485 }
9486 else if (memaddr >= p.endaddr)
9487 {
9488 /* This section ends before the transfer starts. */
9489 continue;
9490 }
9491 else
9492 {
9493 /* This section overlaps the transfer. Just do half. */
9494 len = p.endaddr - memaddr;
9495 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9496 xfered_len);
9497 }
9498 }
9499 }
9500 }
9501
9502 return TARGET_XFER_EOF;
9503 }
9504
9505 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9506 first if the requested memory is unavailable in traceframe.
9507 Otherwise, fall back to remote_read_bytes_1. */
9508
9509 target_xfer_status
9510 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9511 gdb_byte *myaddr, ULONGEST len, int unit_size,
9512 ULONGEST *xfered_len)
9513 {
9514 if (len == 0)
9515 return TARGET_XFER_EOF;
9516
9517 if (get_traceframe_number () != -1)
9518 {
9519 std::vector<mem_range> available;
9520
9521 /* If we fail to get the set of available memory, then the
9522 target does not support querying traceframe info, and so we
9523 attempt reading from the traceframe anyway (assuming the
9524 target implements the old QTro packet then). */
9525 if (traceframe_available_memory (&available, memaddr, len))
9526 {
9527 if (available.empty () || available[0].start != memaddr)
9528 {
9529 enum target_xfer_status res;
9530
9531 /* Don't read into the traceframe's available
9532 memory. */
9533 if (!available.empty ())
9534 {
9535 LONGEST oldlen = len;
9536
9537 len = available[0].start - memaddr;
9538 gdb_assert (len <= oldlen);
9539 }
9540
9541 /* This goes through the topmost target again. */
9542 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9543 len, unit_size, xfered_len);
9544 if (res == TARGET_XFER_OK)
9545 return TARGET_XFER_OK;
9546 else
9547 {
9548 /* No use trying further, we know some memory starting
9549 at MEMADDR isn't available. */
9550 *xfered_len = len;
9551 return (*xfered_len != 0) ?
9552 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9553 }
9554 }
9555
9556 /* Don't try to read more than how much is available, in
9557 case the target implements the deprecated QTro packet to
9558 cater for older GDBs (the target's knowledge of read-only
9559 sections may be outdated by now). */
9560 len = available[0].length;
9561 }
9562 }
9563
9564 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9565 }
9566
9567 \f
9568
9569 /* Sends a packet with content determined by the printf format string
9570 FORMAT and the remaining arguments, then gets the reply. Returns
9571 whether the packet was a success, a failure, or unknown. */
9572
9573 packet_result
9574 remote_target::remote_send_printf (const char *format, ...)
9575 {
9576 struct remote_state *rs = get_remote_state ();
9577 int max_size = get_remote_packet_size ();
9578 va_list ap;
9579
9580 va_start (ap, format);
9581
9582 rs->buf[0] = '\0';
9583 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9584
9585 va_end (ap);
9586
9587 if (size >= max_size)
9588 internal_error (_("Too long remote packet."));
9589
9590 if (putpkt (rs->buf) < 0)
9591 error (_("Communication problem with target."));
9592
9593 rs->buf[0] = '\0';
9594 getpkt (&rs->buf);
9595
9596 return packet_check_result (rs->buf);
9597 }
9598
9599 /* Flash writing can take quite some time. We'll set
9600 effectively infinite timeout for flash operations.
9601 In future, we'll need to decide on a better approach. */
9602 static const int remote_flash_timeout = 1000;
9603
9604 void
9605 remote_target::flash_erase (ULONGEST address, LONGEST length)
9606 {
9607 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
9608 enum packet_result ret;
9609 scoped_restore restore_timeout
9610 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9611
9612 ret = remote_send_printf ("vFlashErase:%s,%s",
9613 phex (address, addr_size),
9614 phex (length, 4));
9615 switch (ret)
9616 {
9617 case PACKET_UNKNOWN:
9618 error (_("Remote target does not support flash erase"));
9619 case PACKET_ERROR:
9620 error (_("Error erasing flash with vFlashErase packet"));
9621 default:
9622 break;
9623 }
9624 }
9625
9626 target_xfer_status
9627 remote_target::remote_flash_write (ULONGEST address,
9628 ULONGEST length, ULONGEST *xfered_len,
9629 const gdb_byte *data)
9630 {
9631 scoped_restore restore_timeout
9632 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9633 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9634 xfered_len,'X', 0);
9635 }
9636
9637 void
9638 remote_target::flash_done ()
9639 {
9640 int ret;
9641
9642 scoped_restore restore_timeout
9643 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9644
9645 ret = remote_send_printf ("vFlashDone");
9646
9647 switch (ret)
9648 {
9649 case PACKET_UNKNOWN:
9650 error (_("Remote target does not support vFlashDone"));
9651 case PACKET_ERROR:
9652 error (_("Error finishing flash operation"));
9653 default:
9654 break;
9655 }
9656 }
9657
9658 \f
9659 /* Stuff for dealing with the packets which are part of this protocol.
9660 See comment at top of file for details. */
9661
9662 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9663 error to higher layers. Called when a serial error is detected.
9664 The exception message is STRING, followed by a colon and a blank,
9665 the system error message for errno at function entry and final dot
9666 for output compatibility with throw_perror_with_name. */
9667
9668 static void
9669 unpush_and_perror (remote_target *target, const char *string)
9670 {
9671 int saved_errno = errno;
9672
9673 remote_unpush_target (target);
9674 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9675 safe_strerror (saved_errno));
9676 }
9677
9678 /* Read a single character from the remote end. The current quit
9679 handler is overridden to avoid quitting in the middle of packet
9680 sequence, as that would break communication with the remote server.
9681 See remote_serial_quit_handler for more detail. */
9682
9683 int
9684 remote_target::readchar (int timeout)
9685 {
9686 int ch;
9687 struct remote_state *rs = get_remote_state ();
9688
9689 {
9690 scoped_restore restore_quit_target
9691 = make_scoped_restore (&curr_quit_handler_target, this);
9692 scoped_restore restore_quit
9693 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9694
9695 rs->got_ctrlc_during_io = 0;
9696
9697 ch = serial_readchar (rs->remote_desc, timeout);
9698
9699 if (rs->got_ctrlc_during_io)
9700 set_quit_flag ();
9701 }
9702
9703 if (ch >= 0)
9704 return ch;
9705
9706 switch ((enum serial_rc) ch)
9707 {
9708 case SERIAL_EOF:
9709 remote_unpush_target (this);
9710 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9711 /* no return */
9712 case SERIAL_ERROR:
9713 unpush_and_perror (this, _("Remote communication error. "
9714 "Target disconnected"));
9715 /* no return */
9716 case SERIAL_TIMEOUT:
9717 break;
9718 }
9719 return ch;
9720 }
9721
9722 /* Wrapper for serial_write that closes the target and throws if
9723 writing fails. The current quit handler is overridden to avoid
9724 quitting in the middle of packet sequence, as that would break
9725 communication with the remote server. See
9726 remote_serial_quit_handler for more detail. */
9727
9728 void
9729 remote_target::remote_serial_write (const char *str, int len)
9730 {
9731 struct remote_state *rs = get_remote_state ();
9732
9733 scoped_restore restore_quit_target
9734 = make_scoped_restore (&curr_quit_handler_target, this);
9735 scoped_restore restore_quit
9736 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9737
9738 rs->got_ctrlc_during_io = 0;
9739
9740 if (serial_write (rs->remote_desc, str, len))
9741 {
9742 unpush_and_perror (this, _("Remote communication error. "
9743 "Target disconnected"));
9744 }
9745
9746 if (rs->got_ctrlc_during_io)
9747 set_quit_flag ();
9748 }
9749
9750 /* Return a string representing an escaped version of BUF, of len N.
9751 E.g. \n is converted to \\n, \t to \\t, etc. */
9752
9753 static std::string
9754 escape_buffer (const char *buf, int n)
9755 {
9756 string_file stb;
9757
9758 stb.putstrn (buf, n, '\\');
9759 return stb.release ();
9760 }
9761
9762 int
9763 remote_target::putpkt (const char *buf)
9764 {
9765 return putpkt_binary (buf, strlen (buf));
9766 }
9767
9768 /* Wrapper around remote_target::putpkt to avoid exporting
9769 remote_target. */
9770
9771 int
9772 putpkt (remote_target *remote, const char *buf)
9773 {
9774 return remote->putpkt (buf);
9775 }
9776
9777 /* Send a packet to the remote machine, with error checking. The data
9778 of the packet is in BUF. The string in BUF can be at most
9779 get_remote_packet_size () - 5 to account for the $, # and checksum,
9780 and for a possible /0 if we are debugging (remote_debug) and want
9781 to print the sent packet as a string. */
9782
9783 int
9784 remote_target::putpkt_binary (const char *buf, int cnt)
9785 {
9786 struct remote_state *rs = get_remote_state ();
9787 int i;
9788 unsigned char csum = 0;
9789 gdb::def_vector<char> data (cnt + 6);
9790 char *buf2 = data.data ();
9791
9792 int ch;
9793 int tcount = 0;
9794 char *p;
9795
9796 /* Catch cases like trying to read memory or listing threads while
9797 we're waiting for a stop reply. The remote server wouldn't be
9798 ready to handle this request, so we'd hang and timeout. We don't
9799 have to worry about this in synchronous mode, because in that
9800 case it's not possible to issue a command while the target is
9801 running. This is not a problem in non-stop mode, because in that
9802 case, the stub is always ready to process serial input. */
9803 if (!target_is_non_stop_p ()
9804 && target_is_async_p ()
9805 && rs->waiting_for_stop_reply)
9806 {
9807 error (_("Cannot execute this command while the target is running.\n"
9808 "Use the \"interrupt\" command to stop the target\n"
9809 "and then try again."));
9810 }
9811
9812 /* Copy the packet into buffer BUF2, encapsulating it
9813 and giving it a checksum. */
9814
9815 p = buf2;
9816 *p++ = '$';
9817
9818 for (i = 0; i < cnt; i++)
9819 {
9820 csum += buf[i];
9821 *p++ = buf[i];
9822 }
9823 *p++ = '#';
9824 *p++ = tohex ((csum >> 4) & 0xf);
9825 *p++ = tohex (csum & 0xf);
9826
9827 /* Send it over and over until we get a positive ack. */
9828
9829 while (1)
9830 {
9831 if (remote_debug)
9832 {
9833 *p = '\0';
9834
9835 int len = (int) (p - buf2);
9836 int max_chars;
9837
9838 if (remote_packet_max_chars < 0)
9839 max_chars = len;
9840 else
9841 max_chars = remote_packet_max_chars;
9842
9843 std::string str
9844 = escape_buffer (buf2, std::min (len, max_chars));
9845
9846 if (len > max_chars)
9847 remote_debug_printf_nofunc
9848 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9849 len - max_chars);
9850 else
9851 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9852 }
9853 remote_serial_write (buf2, p - buf2);
9854
9855 /* If this is a no acks version of the remote protocol, send the
9856 packet and move on. */
9857 if (rs->noack_mode)
9858 break;
9859
9860 /* Read until either a timeout occurs (-2) or '+' is read.
9861 Handle any notification that arrives in the mean time. */
9862 while (1)
9863 {
9864 ch = readchar (remote_timeout);
9865
9866 switch (ch)
9867 {
9868 case '+':
9869 remote_debug_printf_nofunc ("Received Ack");
9870 return 1;
9871 case '-':
9872 remote_debug_printf_nofunc ("Received Nak");
9873 /* FALLTHROUGH */
9874 case SERIAL_TIMEOUT:
9875 tcount++;
9876 if (tcount > 3)
9877 return 0;
9878 break; /* Retransmit buffer. */
9879 case '$':
9880 {
9881 remote_debug_printf ("Packet instead of Ack, ignoring it");
9882 /* It's probably an old response sent because an ACK
9883 was lost. Gobble up the packet and ack it so it
9884 doesn't get retransmitted when we resend this
9885 packet. */
9886 skip_frame ();
9887 remote_serial_write ("+", 1);
9888 continue; /* Now, go look for +. */
9889 }
9890
9891 case '%':
9892 {
9893 int val;
9894
9895 /* If we got a notification, handle it, and go back to looking
9896 for an ack. */
9897 /* We've found the start of a notification. Now
9898 collect the data. */
9899 val = read_frame (&rs->buf);
9900 if (val >= 0)
9901 {
9902 remote_debug_printf_nofunc
9903 (" Notification received: %s",
9904 escape_buffer (rs->buf.data (), val).c_str ());
9905
9906 handle_notification (rs->notif_state, rs->buf.data ());
9907 /* We're in sync now, rewait for the ack. */
9908 tcount = 0;
9909 }
9910 else
9911 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9912 rs->buf.data ());
9913 continue;
9914 }
9915 /* fall-through */
9916 default:
9917 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9918 rs->buf.data ());
9919 continue;
9920 }
9921 break; /* Here to retransmit. */
9922 }
9923
9924 #if 0
9925 /* This is wrong. If doing a long backtrace, the user should be
9926 able to get out next time we call QUIT, without anything as
9927 violent as interrupt_query. If we want to provide a way out of
9928 here without getting to the next QUIT, it should be based on
9929 hitting ^C twice as in remote_wait. */
9930 if (quit_flag)
9931 {
9932 quit_flag = 0;
9933 interrupt_query ();
9934 }
9935 #endif
9936 }
9937
9938 return 0;
9939 }
9940
9941 /* Come here after finding the start of a frame when we expected an
9942 ack. Do our best to discard the rest of this packet. */
9943
9944 void
9945 remote_target::skip_frame ()
9946 {
9947 int c;
9948
9949 while (1)
9950 {
9951 c = readchar (remote_timeout);
9952 switch (c)
9953 {
9954 case SERIAL_TIMEOUT:
9955 /* Nothing we can do. */
9956 return;
9957 case '#':
9958 /* Discard the two bytes of checksum and stop. */
9959 c = readchar (remote_timeout);
9960 if (c >= 0)
9961 c = readchar (remote_timeout);
9962
9963 return;
9964 case '*': /* Run length encoding. */
9965 /* Discard the repeat count. */
9966 c = readchar (remote_timeout);
9967 if (c < 0)
9968 return;
9969 break;
9970 default:
9971 /* A regular character. */
9972 break;
9973 }
9974 }
9975 }
9976
9977 /* Come here after finding the start of the frame. Collect the rest
9978 into *BUF, verifying the checksum, length, and handling run-length
9979 compression. NUL terminate the buffer. If there is not enough room,
9980 expand *BUF.
9981
9982 Returns -1 on error, number of characters in buffer (ignoring the
9983 trailing NULL) on success. (could be extended to return one of the
9984 SERIAL status indications). */
9985
9986 long
9987 remote_target::read_frame (gdb::char_vector *buf_p)
9988 {
9989 unsigned char csum;
9990 long bc;
9991 int c;
9992 char *buf = buf_p->data ();
9993 struct remote_state *rs = get_remote_state ();
9994
9995 csum = 0;
9996 bc = 0;
9997
9998 while (1)
9999 {
10000 c = readchar (remote_timeout);
10001 switch (c)
10002 {
10003 case SERIAL_TIMEOUT:
10004 remote_debug_printf ("Timeout in mid-packet, retrying");
10005 return -1;
10006
10007 case '$':
10008 remote_debug_printf ("Saw new packet start in middle of old one");
10009 return -1; /* Start a new packet, count retries. */
10010
10011 case '#':
10012 {
10013 unsigned char pktcsum;
10014 int check_0 = 0;
10015 int check_1 = 0;
10016
10017 buf[bc] = '\0';
10018
10019 check_0 = readchar (remote_timeout);
10020 if (check_0 >= 0)
10021 check_1 = readchar (remote_timeout);
10022
10023 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
10024 {
10025 remote_debug_printf ("Timeout in checksum, retrying");
10026 return -1;
10027 }
10028 else if (check_0 < 0 || check_1 < 0)
10029 {
10030 remote_debug_printf ("Communication error in checksum");
10031 return -1;
10032 }
10033
10034 /* Don't recompute the checksum; with no ack packets we
10035 don't have any way to indicate a packet retransmission
10036 is necessary. */
10037 if (rs->noack_mode)
10038 return bc;
10039
10040 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
10041 if (csum == pktcsum)
10042 return bc;
10043
10044 remote_debug_printf
10045 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
10046 pktcsum, csum, escape_buffer (buf, bc).c_str ());
10047
10048 /* Number of characters in buffer ignoring trailing
10049 NULL. */
10050 return -1;
10051 }
10052 case '*': /* Run length encoding. */
10053 {
10054 int repeat;
10055
10056 csum += c;
10057 c = readchar (remote_timeout);
10058 csum += c;
10059 repeat = c - ' ' + 3; /* Compute repeat count. */
10060
10061 /* The character before ``*'' is repeated. */
10062
10063 if (repeat > 0 && repeat <= 255 && bc > 0)
10064 {
10065 if (bc + repeat - 1 >= buf_p->size () - 1)
10066 {
10067 /* Make some more room in the buffer. */
10068 buf_p->resize (buf_p->size () + repeat);
10069 buf = buf_p->data ();
10070 }
10071
10072 memset (&buf[bc], buf[bc - 1], repeat);
10073 bc += repeat;
10074 continue;
10075 }
10076
10077 buf[bc] = '\0';
10078 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
10079 return -1;
10080 }
10081 default:
10082 if (bc >= buf_p->size () - 1)
10083 {
10084 /* Make some more room in the buffer. */
10085 buf_p->resize (buf_p->size () * 2);
10086 buf = buf_p->data ();
10087 }
10088
10089 buf[bc++] = c;
10090 csum += c;
10091 continue;
10092 }
10093 }
10094 }
10095
10096 /* Set this to the maximum number of seconds to wait instead of waiting forever
10097 in target_wait(). If this timer times out, then it generates an error and
10098 the command is aborted. This replaces most of the need for timeouts in the
10099 GDB test suite, and makes it possible to distinguish between a hung target
10100 and one with slow communications. */
10101
10102 static int watchdog = 0;
10103 static void
10104 show_watchdog (struct ui_file *file, int from_tty,
10105 struct cmd_list_element *c, const char *value)
10106 {
10107 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
10108 }
10109
10110 /* Read a packet from the remote machine, with error checking, and
10111 store it in *BUF. Resize *BUF if necessary to hold the result. If
10112 FOREVER, wait forever rather than timing out; this is used (in
10113 synchronous mode) to wait for a target that is is executing user
10114 code to stop. If FOREVER == false, this function is allowed to time
10115 out gracefully and return an indication of this to the caller.
10116 Otherwise return the number of bytes read. If IS_NOTIF is not
10117 NULL, then consider receiving a notification enough reason to
10118 return to the caller. In this case, *IS_NOTIF is an output boolean
10119 that indicates whether *BUF holds a notification or not (a regular
10120 packet). */
10121
10122 int
10123 remote_target::getpkt (gdb::char_vector *buf, bool forever, bool *is_notif)
10124 {
10125 struct remote_state *rs = get_remote_state ();
10126 int c;
10127 int tries;
10128 int timeout;
10129 int val = -1;
10130
10131 strcpy (buf->data (), "timeout");
10132
10133 if (forever)
10134 timeout = watchdog > 0 ? watchdog : -1;
10135 else if (is_notif != nullptr)
10136 timeout = 0; /* There should already be a char in the buffer. If
10137 not, bail out. */
10138 else
10139 timeout = remote_timeout;
10140
10141 #define MAX_TRIES 3
10142
10143 /* Process any number of notifications, and then return when
10144 we get a packet. */
10145 for (;;)
10146 {
10147 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
10148 times. */
10149 for (tries = 1; tries <= MAX_TRIES; tries++)
10150 {
10151 /* This can loop forever if the remote side sends us
10152 characters continuously, but if it pauses, we'll get
10153 SERIAL_TIMEOUT from readchar because of timeout. Then
10154 we'll count that as a retry.
10155
10156 Note that even when forever is set, we will only wait
10157 forever prior to the start of a packet. After that, we
10158 expect characters to arrive at a brisk pace. They should
10159 show up within remote_timeout intervals. */
10160 do
10161 c = readchar (timeout);
10162 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
10163
10164 if (c == SERIAL_TIMEOUT)
10165 {
10166 if (is_notif != nullptr)
10167 return -1; /* Don't complain, it's normal to not get
10168 anything in this case. */
10169
10170 if (forever) /* Watchdog went off? Kill the target. */
10171 {
10172 remote_unpush_target (this);
10173 throw_error (TARGET_CLOSE_ERROR,
10174 _("Watchdog timeout has expired. "
10175 "Target detached."));
10176 }
10177
10178 remote_debug_printf ("Timed out.");
10179 }
10180 else
10181 {
10182 /* We've found the start of a packet or notification.
10183 Now collect the data. */
10184 val = read_frame (buf);
10185 if (val >= 0)
10186 break;
10187 }
10188
10189 remote_serial_write ("-", 1);
10190 }
10191
10192 if (tries > MAX_TRIES)
10193 {
10194 /* We have tried hard enough, and just can't receive the
10195 packet/notification. Give up. */
10196 gdb_printf (_("Ignoring packet error, continuing...\n"));
10197
10198 /* Skip the ack char if we're in no-ack mode. */
10199 if (!rs->noack_mode)
10200 remote_serial_write ("+", 1);
10201 return -1;
10202 }
10203
10204 /* If we got an ordinary packet, return that to our caller. */
10205 if (c == '$')
10206 {
10207 if (remote_debug)
10208 {
10209 int max_chars;
10210
10211 if (remote_packet_max_chars < 0)
10212 max_chars = val;
10213 else
10214 max_chars = remote_packet_max_chars;
10215
10216 std::string str
10217 = escape_buffer (buf->data (),
10218 std::min (val, max_chars));
10219
10220 if (val > max_chars)
10221 remote_debug_printf_nofunc
10222 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10223 val - max_chars);
10224 else
10225 remote_debug_printf_nofunc ("Packet received: %s",
10226 str.c_str ());
10227 }
10228
10229 /* Skip the ack char if we're in no-ack mode. */
10230 if (!rs->noack_mode)
10231 remote_serial_write ("+", 1);
10232 if (is_notif != NULL)
10233 *is_notif = false;
10234 return val;
10235 }
10236
10237 /* If we got a notification, handle it, and go back to looking
10238 for a packet. */
10239 else
10240 {
10241 gdb_assert (c == '%');
10242
10243 remote_debug_printf_nofunc
10244 (" Notification received: %s",
10245 escape_buffer (buf->data (), val).c_str ());
10246
10247 if (is_notif != NULL)
10248 *is_notif = true;
10249
10250 handle_notification (rs->notif_state, buf->data ());
10251
10252 /* Notifications require no acknowledgement. */
10253
10254 if (is_notif != nullptr)
10255 return val;
10256 }
10257 }
10258 }
10259
10260 /* Kill any new fork children of inferior INF that haven't been
10261 processed by follow_fork. */
10262
10263 void
10264 remote_target::kill_new_fork_children (inferior *inf)
10265 {
10266 remote_state *rs = get_remote_state ();
10267 const notif_client *notif = &notif_client_stop;
10268
10269 /* Kill the fork child threads of any threads in inferior INF that are stopped
10270 at a fork event. */
10271 for (thread_info *thread : inf->non_exited_threads ())
10272 {
10273 const target_waitstatus *ws = thread_pending_fork_status (thread);
10274
10275 if (ws == nullptr)
10276 continue;
10277
10278 int child_pid = ws->child_ptid ().pid ();
10279 int res = remote_vkill (child_pid);
10280
10281 if (res != 0)
10282 error (_("Can't kill fork child process %d"), child_pid);
10283 }
10284
10285 /* Check for any pending fork events (not reported or processed yet)
10286 in inferior INF and kill those fork child threads as well. */
10287 remote_notif_get_pending_events (notif);
10288 for (auto &event : rs->stop_reply_queue)
10289 {
10290 if (event->ptid.pid () != inf->pid)
10291 continue;
10292
10293 if (!is_fork_status (event->ws.kind ()))
10294 continue;
10295
10296 int child_pid = event->ws.child_ptid ().pid ();
10297 int res = remote_vkill (child_pid);
10298
10299 if (res != 0)
10300 error (_("Can't kill fork child process %d"), child_pid);
10301 }
10302 }
10303
10304 \f
10305 /* Target hook to kill the current inferior. */
10306
10307 void
10308 remote_target::kill ()
10309 {
10310 int res = -1;
10311 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10312
10313 gdb_assert (inf != nullptr);
10314
10315 if (m_features.packet_support (PACKET_vKill) != PACKET_DISABLE)
10316 {
10317 /* If we're stopped while forking and we haven't followed yet,
10318 kill the child task. We need to do this before killing the
10319 parent task because if this is a vfork then the parent will
10320 be sleeping. */
10321 kill_new_fork_children (inf);
10322
10323 res = remote_vkill (inf->pid);
10324 if (res == 0)
10325 {
10326 target_mourn_inferior (inferior_ptid);
10327 return;
10328 }
10329 }
10330
10331 /* If we are in 'target remote' mode and we are killing the only
10332 inferior, then we will tell gdbserver to exit and unpush the
10333 target. */
10334 if (res == -1 && !m_features.remote_multi_process_p ()
10335 && number_of_live_inferiors (this) == 1)
10336 {
10337 remote_kill_k ();
10338
10339 /* We've killed the remote end, we get to mourn it. If we are
10340 not in extended mode, mourning the inferior also unpushes
10341 remote_ops from the target stack, which closes the remote
10342 connection. */
10343 target_mourn_inferior (inferior_ptid);
10344
10345 return;
10346 }
10347
10348 error (_("Can't kill process"));
10349 }
10350
10351 /* Send a kill request to the target using the 'vKill' packet. */
10352
10353 int
10354 remote_target::remote_vkill (int pid)
10355 {
10356 if (m_features.packet_support (PACKET_vKill) == PACKET_DISABLE)
10357 return -1;
10358
10359 remote_state *rs = get_remote_state ();
10360
10361 /* Tell the remote target to detach. */
10362 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10363 putpkt (rs->buf);
10364 getpkt (&rs->buf);
10365
10366 switch (m_features.packet_ok (rs->buf, PACKET_vKill))
10367 {
10368 case PACKET_OK:
10369 return 0;
10370 case PACKET_ERROR:
10371 return 1;
10372 case PACKET_UNKNOWN:
10373 return -1;
10374 default:
10375 internal_error (_("Bad result from packet_ok"));
10376 }
10377 }
10378
10379 /* Send a kill request to the target using the 'k' packet. */
10380
10381 void
10382 remote_target::remote_kill_k ()
10383 {
10384 /* Catch errors so the user can quit from gdb even when we
10385 aren't on speaking terms with the remote system. */
10386 try
10387 {
10388 putpkt ("k");
10389 }
10390 catch (const gdb_exception_error &ex)
10391 {
10392 if (ex.error == TARGET_CLOSE_ERROR)
10393 {
10394 /* If we got an (EOF) error that caused the target
10395 to go away, then we're done, that's what we wanted.
10396 "k" is susceptible to cause a premature EOF, given
10397 that the remote server isn't actually required to
10398 reply to "k", and it can happen that it doesn't
10399 even get to reply ACK to the "k". */
10400 return;
10401 }
10402
10403 /* Otherwise, something went wrong. We didn't actually kill
10404 the target. Just propagate the exception, and let the
10405 user or higher layers decide what to do. */
10406 throw;
10407 }
10408 }
10409
10410 void
10411 remote_target::mourn_inferior ()
10412 {
10413 struct remote_state *rs = get_remote_state ();
10414
10415 /* We're no longer interested in notification events of an inferior
10416 that exited or was killed/detached. */
10417 discard_pending_stop_replies (current_inferior ());
10418
10419 /* In 'target remote' mode with one inferior, we close the connection. */
10420 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10421 {
10422 remote_unpush_target (this);
10423 return;
10424 }
10425
10426 /* In case we got here due to an error, but we're going to stay
10427 connected. */
10428 rs->waiting_for_stop_reply = 0;
10429
10430 /* If the current general thread belonged to the process we just
10431 detached from or has exited, the remote side current general
10432 thread becomes undefined. Considering a case like this:
10433
10434 - We just got here due to a detach.
10435 - The process that we're detaching from happens to immediately
10436 report a global breakpoint being hit in non-stop mode, in the
10437 same thread we had selected before.
10438 - GDB attaches to this process again.
10439 - This event happens to be the next event we handle.
10440
10441 GDB would consider that the current general thread didn't need to
10442 be set on the stub side (with Hg), since for all it knew,
10443 GENERAL_THREAD hadn't changed.
10444
10445 Notice that although in all-stop mode, the remote server always
10446 sets the current thread to the thread reporting the stop event,
10447 that doesn't happen in non-stop mode; in non-stop, the stub *must
10448 not* change the current thread when reporting a breakpoint hit,
10449 due to the decoupling of event reporting and event handling.
10450
10451 To keep things simple, we always invalidate our notion of the
10452 current thread. */
10453 record_currthread (rs, minus_one_ptid);
10454
10455 /* Call common code to mark the inferior as not running. */
10456 generic_mourn_inferior ();
10457 }
10458
10459 bool
10460 extended_remote_target::supports_disable_randomization ()
10461 {
10462 return (m_features.packet_support (PACKET_QDisableRandomization)
10463 == PACKET_ENABLE);
10464 }
10465
10466 void
10467 remote_target::extended_remote_disable_randomization (int val)
10468 {
10469 struct remote_state *rs = get_remote_state ();
10470 char *reply;
10471
10472 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10473 "QDisableRandomization:%x", val);
10474 putpkt (rs->buf);
10475 reply = remote_get_noisy_reply ();
10476 if (*reply == '\0')
10477 error (_("Target does not support QDisableRandomization."));
10478 if (strcmp (reply, "OK") != 0)
10479 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10480 }
10481
10482 int
10483 remote_target::extended_remote_run (const std::string &args)
10484 {
10485 struct remote_state *rs = get_remote_state ();
10486 int len;
10487 const char *remote_exec_file = get_remote_exec_file ();
10488
10489 /* If the user has disabled vRun support, or we have detected that
10490 support is not available, do not try it. */
10491 if (m_features.packet_support (PACKET_vRun) == PACKET_DISABLE)
10492 return -1;
10493
10494 strcpy (rs->buf.data (), "vRun;");
10495 len = strlen (rs->buf.data ());
10496
10497 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10498 error (_("Remote file name too long for run packet"));
10499 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10500 strlen (remote_exec_file));
10501
10502 if (!args.empty ())
10503 {
10504 int i;
10505
10506 gdb_argv argv (args.c_str ());
10507 for (i = 0; argv[i] != NULL; i++)
10508 {
10509 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10510 error (_("Argument list too long for run packet"));
10511 rs->buf[len++] = ';';
10512 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10513 strlen (argv[i]));
10514 }
10515 }
10516
10517 rs->buf[len++] = '\0';
10518
10519 putpkt (rs->buf);
10520 getpkt (&rs->buf);
10521
10522 switch (m_features.packet_ok (rs->buf, PACKET_vRun))
10523 {
10524 case PACKET_OK:
10525 /* We have a wait response. All is well. */
10526 return 0;
10527 case PACKET_UNKNOWN:
10528 return -1;
10529 case PACKET_ERROR:
10530 if (remote_exec_file[0] == '\0')
10531 error (_("Running the default executable on the remote target failed; "
10532 "try \"set remote exec-file\"?"));
10533 else
10534 error (_("Running \"%s\" on the remote target failed"),
10535 remote_exec_file);
10536 default:
10537 gdb_assert_not_reached ("bad switch");
10538 }
10539 }
10540
10541 /* Helper function to send set/unset environment packets. ACTION is
10542 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10543 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10544 sent. */
10545
10546 void
10547 remote_target::send_environment_packet (const char *action,
10548 const char *packet,
10549 const char *value)
10550 {
10551 remote_state *rs = get_remote_state ();
10552
10553 /* Convert the environment variable to an hex string, which
10554 is the best format to be transmitted over the wire. */
10555 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10556 strlen (value));
10557
10558 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10559 "%s:%s", packet, encoded_value.c_str ());
10560
10561 putpkt (rs->buf);
10562 getpkt (&rs->buf);
10563 if (strcmp (rs->buf.data (), "OK") != 0)
10564 warning (_("Unable to %s environment variable '%s' on remote."),
10565 action, value);
10566 }
10567
10568 /* Helper function to handle the QEnvironment* packets. */
10569
10570 void
10571 remote_target::extended_remote_environment_support ()
10572 {
10573 remote_state *rs = get_remote_state ();
10574
10575 if (m_features.packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10576 {
10577 putpkt ("QEnvironmentReset");
10578 getpkt (&rs->buf);
10579 if (strcmp (rs->buf.data (), "OK") != 0)
10580 warning (_("Unable to reset environment on remote."));
10581 }
10582
10583 gdb_environ *e = &current_inferior ()->environment;
10584
10585 if (m_features.packet_support (PACKET_QEnvironmentHexEncoded)
10586 != PACKET_DISABLE)
10587 {
10588 for (const std::string &el : e->user_set_env ())
10589 send_environment_packet ("set", "QEnvironmentHexEncoded",
10590 el.c_str ());
10591 }
10592
10593
10594 if (m_features.packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10595 for (const std::string &el : e->user_unset_env ())
10596 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10597 }
10598
10599 /* Helper function to set the current working directory for the
10600 inferior in the remote target. */
10601
10602 void
10603 remote_target::extended_remote_set_inferior_cwd ()
10604 {
10605 if (m_features.packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10606 {
10607 const std::string &inferior_cwd = current_inferior ()->cwd ();
10608 remote_state *rs = get_remote_state ();
10609
10610 if (!inferior_cwd.empty ())
10611 {
10612 std::string hexpath
10613 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10614 inferior_cwd.size ());
10615
10616 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10617 "QSetWorkingDir:%s", hexpath.c_str ());
10618 }
10619 else
10620 {
10621 /* An empty inferior_cwd means that the user wants us to
10622 reset the remote server's inferior's cwd. */
10623 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10624 "QSetWorkingDir:");
10625 }
10626
10627 putpkt (rs->buf);
10628 getpkt (&rs->buf);
10629 if (m_features.packet_ok (rs->buf, PACKET_QSetWorkingDir) != PACKET_OK)
10630 error (_("\
10631 Remote replied unexpectedly while setting the inferior's working\n\
10632 directory: %s"),
10633 rs->buf.data ());
10634
10635 }
10636 }
10637
10638 /* In the extended protocol we want to be able to do things like
10639 "run" and have them basically work as expected. So we need
10640 a special create_inferior function. We support changing the
10641 executable file and the command line arguments, but not the
10642 environment. */
10643
10644 void
10645 extended_remote_target::create_inferior (const char *exec_file,
10646 const std::string &args,
10647 char **env, int from_tty)
10648 {
10649 int run_worked;
10650 char *stop_reply;
10651 struct remote_state *rs = get_remote_state ();
10652 const char *remote_exec_file = get_remote_exec_file ();
10653
10654 /* If running asynchronously, register the target file descriptor
10655 with the event loop. */
10656 if (target_can_async_p ())
10657 target_async (true);
10658
10659 /* Disable address space randomization if requested (and supported). */
10660 if (supports_disable_randomization ())
10661 extended_remote_disable_randomization (disable_randomization);
10662
10663 /* If startup-with-shell is on, we inform gdbserver to start the
10664 remote inferior using a shell. */
10665 if (m_features.packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10666 {
10667 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10668 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10669 putpkt (rs->buf);
10670 getpkt (&rs->buf);
10671 if (strcmp (rs->buf.data (), "OK") != 0)
10672 error (_("\
10673 Remote replied unexpectedly while setting startup-with-shell: %s"),
10674 rs->buf.data ());
10675 }
10676
10677 extended_remote_environment_support ();
10678
10679 extended_remote_set_inferior_cwd ();
10680
10681 /* Now restart the remote server. */
10682 run_worked = extended_remote_run (args) != -1;
10683 if (!run_worked)
10684 {
10685 /* vRun was not supported. Fail if we need it to do what the
10686 user requested. */
10687 if (remote_exec_file[0])
10688 error (_("Remote target does not support \"set remote exec-file\""));
10689 if (!args.empty ())
10690 error (_("Remote target does not support \"set args\" or run ARGS"));
10691
10692 /* Fall back to "R". */
10693 extended_remote_restart ();
10694 }
10695
10696 /* vRun's success return is a stop reply. */
10697 stop_reply = run_worked ? rs->buf.data () : NULL;
10698 add_current_inferior_and_thread (stop_reply);
10699
10700 /* Get updated offsets, if the stub uses qOffsets. */
10701 get_offsets ();
10702 }
10703 \f
10704
10705 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10706 the list of conditions (in agent expression bytecode format), if any, the
10707 target needs to evaluate. The output is placed into the packet buffer
10708 started from BUF and ended at BUF_END. */
10709
10710 static int
10711 remote_add_target_side_condition (struct gdbarch *gdbarch,
10712 struct bp_target_info *bp_tgt, char *buf,
10713 char *buf_end)
10714 {
10715 if (bp_tgt->conditions.empty ())
10716 return 0;
10717
10718 buf += strlen (buf);
10719 xsnprintf (buf, buf_end - buf, "%s", ";");
10720 buf++;
10721
10722 /* Send conditions to the target. */
10723 for (agent_expr *aexpr : bp_tgt->conditions)
10724 {
10725 xsnprintf (buf, buf_end - buf, "X%x,", (int) aexpr->buf.size ());
10726 buf += strlen (buf);
10727 for (int i = 0; i < aexpr->buf.size (); ++i)
10728 buf = pack_hex_byte (buf, aexpr->buf[i]);
10729 *buf = '\0';
10730 }
10731 return 0;
10732 }
10733
10734 static void
10735 remote_add_target_side_commands (struct gdbarch *gdbarch,
10736 struct bp_target_info *bp_tgt, char *buf)
10737 {
10738 if (bp_tgt->tcommands.empty ())
10739 return;
10740
10741 buf += strlen (buf);
10742
10743 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10744 buf += strlen (buf);
10745
10746 /* Concatenate all the agent expressions that are commands into the
10747 cmds parameter. */
10748 for (agent_expr *aexpr : bp_tgt->tcommands)
10749 {
10750 sprintf (buf, "X%x,", (int) aexpr->buf.size ());
10751 buf += strlen (buf);
10752 for (int i = 0; i < aexpr->buf.size (); ++i)
10753 buf = pack_hex_byte (buf, aexpr->buf[i]);
10754 *buf = '\0';
10755 }
10756 }
10757
10758 /* Insert a breakpoint. On targets that have software breakpoint
10759 support, we ask the remote target to do the work; on targets
10760 which don't, we insert a traditional memory breakpoint. */
10761
10762 int
10763 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10764 struct bp_target_info *bp_tgt)
10765 {
10766 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10767 If it succeeds, then set the support to PACKET_ENABLE. If it
10768 fails, and the user has explicitly requested the Z support then
10769 report an error, otherwise, mark it disabled and go on. */
10770
10771 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
10772 {
10773 CORE_ADDR addr = bp_tgt->reqstd_address;
10774 struct remote_state *rs;
10775 char *p, *endbuf;
10776
10777 /* Make sure the remote is pointing at the right process, if
10778 necessary. */
10779 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10780 set_general_process ();
10781
10782 rs = get_remote_state ();
10783 p = rs->buf.data ();
10784 endbuf = p + get_remote_packet_size ();
10785
10786 *(p++) = 'Z';
10787 *(p++) = '0';
10788 *(p++) = ',';
10789 addr = (ULONGEST) remote_address_masked (addr);
10790 p += hexnumstr (p, addr);
10791 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10792
10793 if (supports_evaluation_of_breakpoint_conditions ())
10794 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10795
10796 if (can_run_breakpoint_commands ())
10797 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10798
10799 putpkt (rs->buf);
10800 getpkt (&rs->buf);
10801
10802 switch (m_features.packet_ok (rs->buf, PACKET_Z0))
10803 {
10804 case PACKET_ERROR:
10805 return -1;
10806 case PACKET_OK:
10807 return 0;
10808 case PACKET_UNKNOWN:
10809 break;
10810 }
10811 }
10812
10813 /* If this breakpoint has target-side commands but this stub doesn't
10814 support Z0 packets, throw error. */
10815 if (!bp_tgt->tcommands.empty ())
10816 throw_error (NOT_SUPPORTED_ERROR, _("\
10817 Target doesn't support breakpoints that have target side commands."));
10818
10819 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10820 }
10821
10822 int
10823 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10824 struct bp_target_info *bp_tgt,
10825 enum remove_bp_reason reason)
10826 {
10827 CORE_ADDR addr = bp_tgt->placed_address;
10828 struct remote_state *rs = get_remote_state ();
10829
10830 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
10831 {
10832 char *p = rs->buf.data ();
10833 char *endbuf = p + get_remote_packet_size ();
10834
10835 /* Make sure the remote is pointing at the right process, if
10836 necessary. */
10837 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10838 set_general_process ();
10839
10840 *(p++) = 'z';
10841 *(p++) = '0';
10842 *(p++) = ',';
10843
10844 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10845 p += hexnumstr (p, addr);
10846 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10847
10848 putpkt (rs->buf);
10849 getpkt (&rs->buf);
10850
10851 return (rs->buf[0] == 'E');
10852 }
10853
10854 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10855 }
10856
10857 static enum Z_packet_type
10858 watchpoint_to_Z_packet (int type)
10859 {
10860 switch (type)
10861 {
10862 case hw_write:
10863 return Z_PACKET_WRITE_WP;
10864 break;
10865 case hw_read:
10866 return Z_PACKET_READ_WP;
10867 break;
10868 case hw_access:
10869 return Z_PACKET_ACCESS_WP;
10870 break;
10871 default:
10872 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
10873 }
10874 }
10875
10876 int
10877 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10878 enum target_hw_bp_type type, struct expression *cond)
10879 {
10880 struct remote_state *rs = get_remote_state ();
10881 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10882 char *p;
10883 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10884
10885 if (m_features.packet_support ((to_underlying (PACKET_Z0)
10886 + to_underlying (packet))) == PACKET_DISABLE)
10887 return 1;
10888
10889 /* Make sure the remote is pointing at the right process, if
10890 necessary. */
10891 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10892 set_general_process ();
10893
10894 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10895 p = strchr (rs->buf.data (), '\0');
10896 addr = remote_address_masked (addr);
10897 p += hexnumstr (p, (ULONGEST) addr);
10898 xsnprintf (p, endbuf - p, ",%x", len);
10899
10900 putpkt (rs->buf);
10901 getpkt (&rs->buf);
10902
10903 switch (m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
10904 + to_underlying (packet))))
10905 {
10906 case PACKET_ERROR:
10907 return -1;
10908 case PACKET_UNKNOWN:
10909 return 1;
10910 case PACKET_OK:
10911 return 0;
10912 }
10913 internal_error (_("remote_insert_watchpoint: reached end of function"));
10914 }
10915
10916 bool
10917 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10918 CORE_ADDR start, int length)
10919 {
10920 CORE_ADDR diff = remote_address_masked (addr - start);
10921
10922 return diff < length;
10923 }
10924
10925
10926 int
10927 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10928 enum target_hw_bp_type type, struct expression *cond)
10929 {
10930 struct remote_state *rs = get_remote_state ();
10931 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10932 char *p;
10933 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10934
10935 if (m_features.packet_support ((to_underlying (PACKET_Z0)
10936 + to_underlying (packet))) == PACKET_DISABLE)
10937 return -1;
10938
10939 /* Make sure the remote is pointing at the right process, if
10940 necessary. */
10941 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10942 set_general_process ();
10943
10944 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10945 p = strchr (rs->buf.data (), '\0');
10946 addr = remote_address_masked (addr);
10947 p += hexnumstr (p, (ULONGEST) addr);
10948 xsnprintf (p, endbuf - p, ",%x", len);
10949 putpkt (rs->buf);
10950 getpkt (&rs->buf);
10951
10952 switch (m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
10953 + to_underlying (packet))))
10954 {
10955 case PACKET_ERROR:
10956 case PACKET_UNKNOWN:
10957 return -1;
10958 case PACKET_OK:
10959 return 0;
10960 }
10961 internal_error (_("remote_remove_watchpoint: reached end of function"));
10962 }
10963
10964
10965 static int remote_hw_watchpoint_limit = -1;
10966 static int remote_hw_watchpoint_length_limit = -1;
10967 static int remote_hw_breakpoint_limit = -1;
10968
10969 int
10970 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10971 {
10972 if (remote_hw_watchpoint_length_limit == 0)
10973 return 0;
10974 else if (remote_hw_watchpoint_length_limit < 0)
10975 return 1;
10976 else if (len <= remote_hw_watchpoint_length_limit)
10977 return 1;
10978 else
10979 return 0;
10980 }
10981
10982 int
10983 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10984 {
10985 if (type == bp_hardware_breakpoint)
10986 {
10987 if (remote_hw_breakpoint_limit == 0)
10988 return 0;
10989 else if (remote_hw_breakpoint_limit < 0)
10990 return 1;
10991 else if (cnt <= remote_hw_breakpoint_limit)
10992 return 1;
10993 }
10994 else
10995 {
10996 if (remote_hw_watchpoint_limit == 0)
10997 return 0;
10998 else if (remote_hw_watchpoint_limit < 0)
10999 return 1;
11000 else if (ot)
11001 return -1;
11002 else if (cnt <= remote_hw_watchpoint_limit)
11003 return 1;
11004 }
11005 return -1;
11006 }
11007
11008 /* The to_stopped_by_sw_breakpoint method of target remote. */
11009
11010 bool
11011 remote_target::stopped_by_sw_breakpoint ()
11012 {
11013 struct thread_info *thread = inferior_thread ();
11014
11015 return (thread->priv != NULL
11016 && (get_remote_thread_info (thread)->stop_reason
11017 == TARGET_STOPPED_BY_SW_BREAKPOINT));
11018 }
11019
11020 /* The to_supports_stopped_by_sw_breakpoint method of target
11021 remote. */
11022
11023 bool
11024 remote_target::supports_stopped_by_sw_breakpoint ()
11025 {
11026 return (m_features.packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
11027 }
11028
11029 /* The to_stopped_by_hw_breakpoint method of target remote. */
11030
11031 bool
11032 remote_target::stopped_by_hw_breakpoint ()
11033 {
11034 struct thread_info *thread = inferior_thread ();
11035
11036 return (thread->priv != NULL
11037 && (get_remote_thread_info (thread)->stop_reason
11038 == TARGET_STOPPED_BY_HW_BREAKPOINT));
11039 }
11040
11041 /* The to_supports_stopped_by_hw_breakpoint method of target
11042 remote. */
11043
11044 bool
11045 remote_target::supports_stopped_by_hw_breakpoint ()
11046 {
11047 return (m_features.packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
11048 }
11049
11050 bool
11051 remote_target::stopped_by_watchpoint ()
11052 {
11053 struct thread_info *thread = inferior_thread ();
11054
11055 return (thread->priv != NULL
11056 && (get_remote_thread_info (thread)->stop_reason
11057 == TARGET_STOPPED_BY_WATCHPOINT));
11058 }
11059
11060 bool
11061 remote_target::stopped_data_address (CORE_ADDR *addr_p)
11062 {
11063 struct thread_info *thread = inferior_thread ();
11064
11065 if (thread->priv != NULL
11066 && (get_remote_thread_info (thread)->stop_reason
11067 == TARGET_STOPPED_BY_WATCHPOINT))
11068 {
11069 *addr_p = get_remote_thread_info (thread)->watch_data_address;
11070 return true;
11071 }
11072
11073 return false;
11074 }
11075
11076
11077 int
11078 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
11079 struct bp_target_info *bp_tgt)
11080 {
11081 CORE_ADDR addr = bp_tgt->reqstd_address;
11082 struct remote_state *rs;
11083 char *p, *endbuf;
11084 char *message;
11085
11086 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11087 return -1;
11088
11089 /* Make sure the remote is pointing at the right process, if
11090 necessary. */
11091 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11092 set_general_process ();
11093
11094 rs = get_remote_state ();
11095 p = rs->buf.data ();
11096 endbuf = p + get_remote_packet_size ();
11097
11098 *(p++) = 'Z';
11099 *(p++) = '1';
11100 *(p++) = ',';
11101
11102 addr = remote_address_masked (addr);
11103 p += hexnumstr (p, (ULONGEST) addr);
11104 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11105
11106 if (supports_evaluation_of_breakpoint_conditions ())
11107 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
11108
11109 if (can_run_breakpoint_commands ())
11110 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11111
11112 putpkt (rs->buf);
11113 getpkt (&rs->buf);
11114
11115 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
11116 {
11117 case PACKET_ERROR:
11118 if (rs->buf[1] == '.')
11119 {
11120 message = strchr (&rs->buf[2], '.');
11121 if (message)
11122 error (_("Remote failure reply: %s"), message + 1);
11123 }
11124 return -1;
11125 case PACKET_UNKNOWN:
11126 return -1;
11127 case PACKET_OK:
11128 return 0;
11129 }
11130 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
11131 }
11132
11133
11134 int
11135 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
11136 struct bp_target_info *bp_tgt)
11137 {
11138 CORE_ADDR addr;
11139 struct remote_state *rs = get_remote_state ();
11140 char *p = rs->buf.data ();
11141 char *endbuf = p + get_remote_packet_size ();
11142
11143 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11144 return -1;
11145
11146 /* Make sure the remote is pointing at the right process, if
11147 necessary. */
11148 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11149 set_general_process ();
11150
11151 *(p++) = 'z';
11152 *(p++) = '1';
11153 *(p++) = ',';
11154
11155 addr = remote_address_masked (bp_tgt->placed_address);
11156 p += hexnumstr (p, (ULONGEST) addr);
11157 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11158
11159 putpkt (rs->buf);
11160 getpkt (&rs->buf);
11161
11162 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
11163 {
11164 case PACKET_ERROR:
11165 case PACKET_UNKNOWN:
11166 return -1;
11167 case PACKET_OK:
11168 return 0;
11169 }
11170 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
11171 }
11172
11173 /* Verify memory using the "qCRC:" request. */
11174
11175 int
11176 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
11177 {
11178 struct remote_state *rs = get_remote_state ();
11179 unsigned long host_crc, target_crc;
11180 char *tmp;
11181
11182 /* It doesn't make sense to use qCRC if the remote target is
11183 connected but not running. */
11184 if (target_has_execution ()
11185 && m_features.packet_support (PACKET_qCRC) != PACKET_DISABLE)
11186 {
11187 enum packet_result result;
11188
11189 /* Make sure the remote is pointing at the right process. */
11190 set_general_process ();
11191
11192 /* FIXME: assumes lma can fit into long. */
11193 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
11194 (long) lma, (long) size);
11195 putpkt (rs->buf);
11196
11197 /* Be clever; compute the host_crc before waiting for target
11198 reply. */
11199 host_crc = xcrc32 (data, size, 0xffffffff);
11200
11201 getpkt (&rs->buf);
11202
11203 result = m_features.packet_ok (rs->buf, PACKET_qCRC);
11204 if (result == PACKET_ERROR)
11205 return -1;
11206 else if (result == PACKET_OK)
11207 {
11208 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11209 target_crc = target_crc * 16 + fromhex (*tmp);
11210
11211 return (host_crc == target_crc);
11212 }
11213 }
11214
11215 return simple_verify_memory (this, data, lma, size);
11216 }
11217
11218 /* compare-sections command
11219
11220 With no arguments, compares each loadable section in the exec bfd
11221 with the same memory range on the target, and reports mismatches.
11222 Useful for verifying the image on the target against the exec file. */
11223
11224 static void
11225 compare_sections_command (const char *args, int from_tty)
11226 {
11227 asection *s;
11228 const char *sectname;
11229 bfd_size_type size;
11230 bfd_vma lma;
11231 int matched = 0;
11232 int mismatched = 0;
11233 int res;
11234 int read_only = 0;
11235
11236 if (!current_program_space->exec_bfd ())
11237 error (_("command cannot be used without an exec file"));
11238
11239 if (args != NULL && strcmp (args, "-r") == 0)
11240 {
11241 read_only = 1;
11242 args = NULL;
11243 }
11244
11245 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11246 {
11247 if (!(s->flags & SEC_LOAD))
11248 continue; /* Skip non-loadable section. */
11249
11250 if (read_only && (s->flags & SEC_READONLY) == 0)
11251 continue; /* Skip writeable sections */
11252
11253 size = bfd_section_size (s);
11254 if (size == 0)
11255 continue; /* Skip zero-length section. */
11256
11257 sectname = bfd_section_name (s);
11258 if (args && strcmp (args, sectname) != 0)
11259 continue; /* Not the section selected by user. */
11260
11261 matched = 1; /* Do this section. */
11262 lma = s->lma;
11263
11264 gdb::byte_vector sectdata (size);
11265 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11266 sectdata.data (), 0, size);
11267
11268 res = target_verify_memory (sectdata.data (), lma, size);
11269
11270 if (res == -1)
11271 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11272 paddress (current_inferior ()->arch (), lma),
11273 paddress (current_inferior ()->arch (), lma + size));
11274
11275 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11276 paddress (current_inferior ()->arch (), lma),
11277 paddress (current_inferior ()->arch (), lma + size));
11278 if (res)
11279 gdb_printf ("matched.\n");
11280 else
11281 {
11282 gdb_printf ("MIS-MATCHED!\n");
11283 mismatched++;
11284 }
11285 }
11286 if (mismatched > 0)
11287 warning (_("One or more sections of the target image does "
11288 "not match the loaded file"));
11289 if (args && !matched)
11290 gdb_printf (_("No loaded section named '%s'.\n"), args);
11291 }
11292
11293 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11294 into remote target. The number of bytes written to the remote
11295 target is returned, or -1 for error. */
11296
11297 target_xfer_status
11298 remote_target::remote_write_qxfer (const char *object_name,
11299 const char *annex, const gdb_byte *writebuf,
11300 ULONGEST offset, LONGEST len,
11301 ULONGEST *xfered_len,
11302 const unsigned int which_packet)
11303 {
11304 int i, buf_len;
11305 ULONGEST n;
11306 struct remote_state *rs = get_remote_state ();
11307 int max_size = get_memory_write_packet_size ();
11308
11309 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11310 return TARGET_XFER_E_IO;
11311
11312 /* Insert header. */
11313 i = snprintf (rs->buf.data (), max_size,
11314 "qXfer:%s:write:%s:%s:",
11315 object_name, annex ? annex : "",
11316 phex_nz (offset, sizeof offset));
11317 max_size -= (i + 1);
11318
11319 /* Escape as much data as fits into rs->buf. */
11320 buf_len = remote_escape_output
11321 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11322
11323 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11324 || getpkt (&rs->buf) < 0
11325 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
11326 return TARGET_XFER_E_IO;
11327
11328 unpack_varlen_hex (rs->buf.data (), &n);
11329
11330 *xfered_len = n;
11331 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11332 }
11333
11334 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11335 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11336 number of bytes read is returned, or 0 for EOF, or -1 for error.
11337 The number of bytes read may be less than LEN without indicating an
11338 EOF. PACKET is checked and updated to indicate whether the remote
11339 target supports this object. */
11340
11341 target_xfer_status
11342 remote_target::remote_read_qxfer (const char *object_name,
11343 const char *annex,
11344 gdb_byte *readbuf, ULONGEST offset,
11345 LONGEST len,
11346 ULONGEST *xfered_len,
11347 const unsigned int which_packet)
11348 {
11349 struct remote_state *rs = get_remote_state ();
11350 LONGEST i, n, packet_len;
11351
11352 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11353 return TARGET_XFER_E_IO;
11354
11355 /* Check whether we've cached an end-of-object packet that matches
11356 this request. */
11357 if (rs->finished_object)
11358 {
11359 if (strcmp (object_name, rs->finished_object) == 0
11360 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11361 && offset == rs->finished_offset)
11362 return TARGET_XFER_EOF;
11363
11364
11365 /* Otherwise, we're now reading something different. Discard
11366 the cache. */
11367 xfree (rs->finished_object);
11368 xfree (rs->finished_annex);
11369 rs->finished_object = NULL;
11370 rs->finished_annex = NULL;
11371 }
11372
11373 /* Request only enough to fit in a single packet. The actual data
11374 may not, since we don't know how much of it will need to be escaped;
11375 the target is free to respond with slightly less data. We subtract
11376 five to account for the response type and the protocol frame. */
11377 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11378 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11379 "qXfer:%s:read:%s:%s,%s",
11380 object_name, annex ? annex : "",
11381 phex_nz (offset, sizeof offset),
11382 phex_nz (n, sizeof n));
11383 i = putpkt (rs->buf);
11384 if (i < 0)
11385 return TARGET_XFER_E_IO;
11386
11387 rs->buf[0] = '\0';
11388 packet_len = getpkt (&rs->buf);
11389 if (packet_len < 0
11390 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
11391 return TARGET_XFER_E_IO;
11392
11393 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11394 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11395
11396 /* 'm' means there is (or at least might be) more data after this
11397 batch. That does not make sense unless there's at least one byte
11398 of data in this reply. */
11399 if (rs->buf[0] == 'm' && packet_len == 1)
11400 error (_("Remote qXfer reply contained no data."));
11401
11402 /* Got some data. */
11403 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11404 packet_len - 1, readbuf, n);
11405
11406 /* 'l' is an EOF marker, possibly including a final block of data,
11407 or possibly empty. If we have the final block of a non-empty
11408 object, record this fact to bypass a subsequent partial read. */
11409 if (rs->buf[0] == 'l' && offset + i > 0)
11410 {
11411 rs->finished_object = xstrdup (object_name);
11412 rs->finished_annex = xstrdup (annex ? annex : "");
11413 rs->finished_offset = offset + i;
11414 }
11415
11416 if (i == 0)
11417 return TARGET_XFER_EOF;
11418 else
11419 {
11420 *xfered_len = i;
11421 return TARGET_XFER_OK;
11422 }
11423 }
11424
11425 enum target_xfer_status
11426 remote_target::xfer_partial (enum target_object object,
11427 const char *annex, gdb_byte *readbuf,
11428 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11429 ULONGEST *xfered_len)
11430 {
11431 struct remote_state *rs;
11432 int i;
11433 char *p2;
11434 char query_type;
11435 int unit_size
11436 = gdbarch_addressable_memory_unit_size (current_inferior ()->arch ());
11437
11438 set_remote_traceframe ();
11439 set_general_thread (inferior_ptid);
11440
11441 rs = get_remote_state ();
11442
11443 /* Handle memory using the standard memory routines. */
11444 if (object == TARGET_OBJECT_MEMORY)
11445 {
11446 /* If the remote target is connected but not running, we should
11447 pass this request down to a lower stratum (e.g. the executable
11448 file). */
11449 if (!target_has_execution ())
11450 return TARGET_XFER_EOF;
11451
11452 if (writebuf != NULL)
11453 return remote_write_bytes (offset, writebuf, len, unit_size,
11454 xfered_len);
11455 else
11456 return remote_read_bytes (offset, readbuf, len, unit_size,
11457 xfered_len);
11458 }
11459
11460 /* Handle extra signal info using qxfer packets. */
11461 if (object == TARGET_OBJECT_SIGNAL_INFO)
11462 {
11463 if (readbuf)
11464 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11465 xfered_len, PACKET_qXfer_siginfo_read);
11466 else
11467 return remote_write_qxfer ("siginfo", annex, writebuf, offset, len,
11468 xfered_len, PACKET_qXfer_siginfo_write);
11469 }
11470
11471 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11472 {
11473 if (readbuf)
11474 return remote_read_qxfer ("statictrace", annex,
11475 readbuf, offset, len, xfered_len,
11476 PACKET_qXfer_statictrace_read);
11477 else
11478 return TARGET_XFER_E_IO;
11479 }
11480
11481 /* Only handle flash writes. */
11482 if (writebuf != NULL)
11483 {
11484 switch (object)
11485 {
11486 case TARGET_OBJECT_FLASH:
11487 return remote_flash_write (offset, len, xfered_len,
11488 writebuf);
11489
11490 default:
11491 return TARGET_XFER_E_IO;
11492 }
11493 }
11494
11495 /* Map pre-existing objects onto letters. DO NOT do this for new
11496 objects!!! Instead specify new query packets. */
11497 switch (object)
11498 {
11499 case TARGET_OBJECT_AVR:
11500 query_type = 'R';
11501 break;
11502
11503 case TARGET_OBJECT_AUXV:
11504 gdb_assert (annex == NULL);
11505 return remote_read_qxfer
11506 ("auxv", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_auxv);
11507
11508 case TARGET_OBJECT_AVAILABLE_FEATURES:
11509 return remote_read_qxfer
11510 ("features", annex, readbuf, offset, len, xfered_len,
11511 PACKET_qXfer_features);
11512
11513 case TARGET_OBJECT_LIBRARIES:
11514 return remote_read_qxfer
11515 ("libraries", annex, readbuf, offset, len, xfered_len,
11516 PACKET_qXfer_libraries);
11517
11518 case TARGET_OBJECT_LIBRARIES_SVR4:
11519 return remote_read_qxfer
11520 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11521 PACKET_qXfer_libraries_svr4);
11522
11523 case TARGET_OBJECT_MEMORY_MAP:
11524 gdb_assert (annex == NULL);
11525 return remote_read_qxfer
11526 ("memory-map", annex, readbuf, offset, len, xfered_len,
11527 PACKET_qXfer_memory_map);
11528
11529 case TARGET_OBJECT_OSDATA:
11530 /* Should only get here if we're connected. */
11531 gdb_assert (rs->remote_desc);
11532 return remote_read_qxfer
11533 ("osdata", annex, readbuf, offset, len, xfered_len,
11534 PACKET_qXfer_osdata);
11535
11536 case TARGET_OBJECT_THREADS:
11537 gdb_assert (annex == NULL);
11538 return remote_read_qxfer
11539 ("threads", annex, readbuf, offset, len, xfered_len,
11540 PACKET_qXfer_threads);
11541
11542 case TARGET_OBJECT_TRACEFRAME_INFO:
11543 gdb_assert (annex == NULL);
11544 return remote_read_qxfer
11545 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11546 PACKET_qXfer_traceframe_info);
11547
11548 case TARGET_OBJECT_FDPIC:
11549 return remote_read_qxfer
11550 ("fdpic", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_fdpic);
11551
11552 case TARGET_OBJECT_OPENVMS_UIB:
11553 return remote_read_qxfer
11554 ("uib", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_uib);
11555
11556 case TARGET_OBJECT_BTRACE:
11557 return remote_read_qxfer
11558 ("btrace", annex, readbuf, offset, len, xfered_len,
11559 PACKET_qXfer_btrace);
11560
11561 case TARGET_OBJECT_BTRACE_CONF:
11562 return remote_read_qxfer
11563 ("btrace-conf", annex, readbuf, offset, len, xfered_len,
11564 PACKET_qXfer_btrace_conf);
11565
11566 case TARGET_OBJECT_EXEC_FILE:
11567 return remote_read_qxfer
11568 ("exec-file", annex, readbuf, offset, len, xfered_len,
11569 PACKET_qXfer_exec_file);
11570
11571 default:
11572 return TARGET_XFER_E_IO;
11573 }
11574
11575 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11576 large enough let the caller deal with it. */
11577 if (len < get_remote_packet_size ())
11578 return TARGET_XFER_E_IO;
11579 len = get_remote_packet_size ();
11580
11581 /* Except for querying the minimum buffer size, target must be open. */
11582 if (!rs->remote_desc)
11583 error (_("remote query is only available after target open"));
11584
11585 gdb_assert (annex != NULL);
11586 gdb_assert (readbuf != NULL);
11587
11588 p2 = rs->buf.data ();
11589 *p2++ = 'q';
11590 *p2++ = query_type;
11591
11592 /* We used one buffer char for the remote protocol q command and
11593 another for the query type. As the remote protocol encapsulation
11594 uses 4 chars plus one extra in case we are debugging
11595 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11596 string. */
11597 i = 0;
11598 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11599 {
11600 /* Bad caller may have sent forbidden characters. */
11601 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11602 *p2++ = annex[i];
11603 i++;
11604 }
11605 *p2 = '\0';
11606 gdb_assert (annex[i] == '\0');
11607
11608 i = putpkt (rs->buf);
11609 if (i < 0)
11610 return TARGET_XFER_E_IO;
11611
11612 getpkt (&rs->buf);
11613 strcpy ((char *) readbuf, rs->buf.data ());
11614
11615 *xfered_len = strlen ((char *) readbuf);
11616 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11617 }
11618
11619 /* Implementation of to_get_memory_xfer_limit. */
11620
11621 ULONGEST
11622 remote_target::get_memory_xfer_limit ()
11623 {
11624 return get_memory_write_packet_size ();
11625 }
11626
11627 int
11628 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11629 const gdb_byte *pattern, ULONGEST pattern_len,
11630 CORE_ADDR *found_addrp)
11631 {
11632 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
11633 struct remote_state *rs = get_remote_state ();
11634 int max_size = get_memory_write_packet_size ();
11635
11636 /* Number of packet bytes used to encode the pattern;
11637 this could be more than PATTERN_LEN due to escape characters. */
11638 int escaped_pattern_len;
11639 /* Amount of pattern that was encodable in the packet. */
11640 int used_pattern_len;
11641 int i;
11642 int found;
11643 ULONGEST found_addr;
11644
11645 auto read_memory = [this] (CORE_ADDR addr, gdb_byte *result, size_t len)
11646 {
11647 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11648 == len);
11649 };
11650
11651 /* Don't go to the target if we don't have to. This is done before
11652 checking packet_support to avoid the possibility that a success for this
11653 edge case means the facility works in general. */
11654 if (pattern_len > search_space_len)
11655 return 0;
11656 if (pattern_len == 0)
11657 {
11658 *found_addrp = start_addr;
11659 return 1;
11660 }
11661
11662 /* If we already know the packet isn't supported, fall back to the simple
11663 way of searching memory. */
11664
11665 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11666 {
11667 /* Target doesn't provided special support, fall back and use the
11668 standard support (copy memory and do the search here). */
11669 return simple_search_memory (read_memory, start_addr, search_space_len,
11670 pattern, pattern_len, found_addrp);
11671 }
11672
11673 /* Make sure the remote is pointing at the right process. */
11674 set_general_process ();
11675
11676 /* Insert header. */
11677 i = snprintf (rs->buf.data (), max_size,
11678 "qSearch:memory:%s;%s;",
11679 phex_nz (start_addr, addr_size),
11680 phex_nz (search_space_len, sizeof (search_space_len)));
11681 max_size -= (i + 1);
11682
11683 /* Escape as much data as fits into rs->buf. */
11684 escaped_pattern_len =
11685 remote_escape_output (pattern, pattern_len, 1,
11686 (gdb_byte *) rs->buf.data () + i,
11687 &used_pattern_len, max_size);
11688
11689 /* Bail if the pattern is too large. */
11690 if (used_pattern_len != pattern_len)
11691 error (_("Pattern is too large to transmit to remote target."));
11692
11693 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11694 || getpkt (&rs->buf) < 0
11695 || m_features.packet_ok (rs->buf, PACKET_qSearch_memory) != PACKET_OK)
11696 {
11697 /* The request may not have worked because the command is not
11698 supported. If so, fall back to the simple way. */
11699 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11700 {
11701 return simple_search_memory (read_memory, start_addr, search_space_len,
11702 pattern, pattern_len, found_addrp);
11703 }
11704 return -1;
11705 }
11706
11707 if (rs->buf[0] == '0')
11708 found = 0;
11709 else if (rs->buf[0] == '1')
11710 {
11711 found = 1;
11712 if (rs->buf[1] != ',')
11713 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11714 unpack_varlen_hex (&rs->buf[2], &found_addr);
11715 *found_addrp = found_addr;
11716 }
11717 else
11718 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11719
11720 return found;
11721 }
11722
11723 void
11724 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11725 {
11726 struct remote_state *rs = get_remote_state ();
11727 char *p = rs->buf.data ();
11728
11729 if (!rs->remote_desc)
11730 error (_("remote rcmd is only available after target open"));
11731
11732 /* Send a NULL command across as an empty command. */
11733 if (command == NULL)
11734 command = "";
11735
11736 /* The query prefix. */
11737 strcpy (rs->buf.data (), "qRcmd,");
11738 p = strchr (rs->buf.data (), '\0');
11739
11740 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11741 > get_remote_packet_size ())
11742 error (_("\"monitor\" command ``%s'' is too long."), command);
11743
11744 /* Encode the actual command. */
11745 bin2hex ((const gdb_byte *) command, p, strlen (command));
11746
11747 if (putpkt (rs->buf) < 0)
11748 error (_("Communication problem with target."));
11749
11750 /* get/display the response */
11751 while (1)
11752 {
11753 char *buf;
11754
11755 /* XXX - see also remote_get_noisy_reply(). */
11756 QUIT; /* Allow user to bail out with ^C. */
11757 rs->buf[0] = '\0';
11758 if (getpkt (&rs->buf) == -1)
11759 {
11760 /* Timeout. Continue to (try to) read responses.
11761 This is better than stopping with an error, assuming the stub
11762 is still executing the (long) monitor command.
11763 If needed, the user can interrupt gdb using C-c, obtaining
11764 an effect similar to stop on timeout. */
11765 continue;
11766 }
11767 buf = rs->buf.data ();
11768 if (buf[0] == '\0')
11769 error (_("Target does not support this command."));
11770 if (buf[0] == 'O' && buf[1] != 'K')
11771 {
11772 remote_console_output (buf + 1); /* 'O' message from stub. */
11773 continue;
11774 }
11775 if (strcmp (buf, "OK") == 0)
11776 break;
11777 if (strlen (buf) == 3 && buf[0] == 'E'
11778 && isxdigit (buf[1]) && isxdigit (buf[2]))
11779 {
11780 error (_("Protocol error with Rcmd"));
11781 }
11782 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11783 {
11784 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11785
11786 gdb_putc (c, outbuf);
11787 }
11788 break;
11789 }
11790 }
11791
11792 std::vector<mem_region>
11793 remote_target::memory_map ()
11794 {
11795 std::vector<mem_region> result;
11796 gdb::optional<gdb::char_vector> text
11797 = target_read_stralloc (current_inferior ()->top_target (),
11798 TARGET_OBJECT_MEMORY_MAP, NULL);
11799
11800 if (text)
11801 result = parse_memory_map (text->data ());
11802
11803 return result;
11804 }
11805
11806 /* Set of callbacks used to implement the 'maint packet' command. */
11807
11808 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
11809 {
11810 /* Called before the packet is sent. BUF is the packet content before
11811 the protocol specific prefix, suffix, and escaping is added. */
11812
11813 void sending (gdb::array_view<const char> &buf) override
11814 {
11815 gdb_puts ("sending: ");
11816 print_packet (buf);
11817 gdb_puts ("\n");
11818 }
11819
11820 /* Called with BUF, the reply from the remote target. */
11821
11822 void received (gdb::array_view<const char> &buf) override
11823 {
11824 gdb_puts ("received: \"");
11825 print_packet (buf);
11826 gdb_puts ("\"\n");
11827 }
11828
11829 private:
11830
11831 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11832 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11833
11834 static void
11835 print_packet (gdb::array_view<const char> &buf)
11836 {
11837 string_file stb;
11838
11839 for (int i = 0; i < buf.size (); ++i)
11840 {
11841 gdb_byte c = buf[i];
11842 if (isprint (c))
11843 gdb_putc (c, &stb);
11844 else
11845 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
11846 }
11847
11848 gdb_puts (stb.string ().c_str ());
11849 }
11850 };
11851
11852 /* See remote.h. */
11853
11854 void
11855 send_remote_packet (gdb::array_view<const char> &buf,
11856 send_remote_packet_callbacks *callbacks)
11857 {
11858 if (buf.size () == 0 || buf.data ()[0] == '\0')
11859 error (_("a remote packet must not be empty"));
11860
11861 remote_target *remote = get_current_remote_target ();
11862 if (remote == nullptr)
11863 error (_("packets can only be sent to a remote target"));
11864
11865 callbacks->sending (buf);
11866
11867 remote->putpkt_binary (buf.data (), buf.size ());
11868 remote_state *rs = remote->get_remote_state ();
11869 int bytes = remote->getpkt (&rs->buf);
11870
11871 if (bytes < 0)
11872 error (_("error while fetching packet from remote target"));
11873
11874 gdb::array_view<const char> view (&rs->buf[0], bytes);
11875 callbacks->received (view);
11876 }
11877
11878 /* Entry point for the 'maint packet' command. */
11879
11880 static void
11881 cli_packet_command (const char *args, int from_tty)
11882 {
11883 cli_packet_command_callbacks cb;
11884 gdb::array_view<const char> view
11885 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11886 send_remote_packet (view, &cb);
11887 }
11888
11889 #if 0
11890 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11891
11892 static void display_thread_info (struct gdb_ext_thread_info *info);
11893
11894 static void threadset_test_cmd (char *cmd, int tty);
11895
11896 static void threadalive_test (char *cmd, int tty);
11897
11898 static void threadlist_test_cmd (char *cmd, int tty);
11899
11900 int get_and_display_threadinfo (threadref *ref);
11901
11902 static void threadinfo_test_cmd (char *cmd, int tty);
11903
11904 static int thread_display_step (threadref *ref, void *context);
11905
11906 static void threadlist_update_test_cmd (char *cmd, int tty);
11907
11908 static void init_remote_threadtests (void);
11909
11910 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11911
11912 static void
11913 threadset_test_cmd (const char *cmd, int tty)
11914 {
11915 int sample_thread = SAMPLE_THREAD;
11916
11917 gdb_printf (_("Remote threadset test\n"));
11918 set_general_thread (sample_thread);
11919 }
11920
11921
11922 static void
11923 threadalive_test (const char *cmd, int tty)
11924 {
11925 int sample_thread = SAMPLE_THREAD;
11926 int pid = inferior_ptid.pid ();
11927 ptid_t ptid = ptid_t (pid, sample_thread, 0);
11928
11929 if (remote_thread_alive (ptid))
11930 gdb_printf ("PASS: Thread alive test\n");
11931 else
11932 gdb_printf ("FAIL: Thread alive test\n");
11933 }
11934
11935 void output_threadid (char *title, threadref *ref);
11936
11937 void
11938 output_threadid (char *title, threadref *ref)
11939 {
11940 char hexid[20];
11941
11942 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
11943 hexid[16] = 0;
11944 gdb_printf ("%s %s\n", title, (&hexid[0]));
11945 }
11946
11947 static void
11948 threadlist_test_cmd (const char *cmd, int tty)
11949 {
11950 int startflag = 1;
11951 threadref nextthread;
11952 int done, result_count;
11953 threadref threadlist[3];
11954
11955 gdb_printf ("Remote Threadlist test\n");
11956 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11957 &result_count, &threadlist[0]))
11958 gdb_printf ("FAIL: threadlist test\n");
11959 else
11960 {
11961 threadref *scan = threadlist;
11962 threadref *limit = scan + result_count;
11963
11964 while (scan < limit)
11965 output_threadid (" thread ", scan++);
11966 }
11967 }
11968
11969 void
11970 display_thread_info (struct gdb_ext_thread_info *info)
11971 {
11972 output_threadid ("Threadid: ", &info->threadid);
11973 gdb_printf ("Name: %s\n ", info->shortname);
11974 gdb_printf ("State: %s\n", info->display);
11975 gdb_printf ("other: %s\n\n", info->more_display);
11976 }
11977
11978 int
11979 get_and_display_threadinfo (threadref *ref)
11980 {
11981 int result;
11982 int set;
11983 struct gdb_ext_thread_info threadinfo;
11984
11985 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11986 | TAG_MOREDISPLAY | TAG_DISPLAY;
11987 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11988 display_thread_info (&threadinfo);
11989 return result;
11990 }
11991
11992 static void
11993 threadinfo_test_cmd (const char *cmd, int tty)
11994 {
11995 int athread = SAMPLE_THREAD;
11996 threadref thread;
11997 int set;
11998
11999 int_to_threadref (&thread, athread);
12000 gdb_printf ("Remote Threadinfo test\n");
12001 if (!get_and_display_threadinfo (&thread))
12002 gdb_printf ("FAIL cannot get thread info\n");
12003 }
12004
12005 static int
12006 thread_display_step (threadref *ref, void *context)
12007 {
12008 /* output_threadid(" threadstep ",ref); *//* simple test */
12009 return get_and_display_threadinfo (ref);
12010 }
12011
12012 static void
12013 threadlist_update_test_cmd (const char *cmd, int tty)
12014 {
12015 gdb_printf ("Remote Threadlist update test\n");
12016 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
12017 }
12018
12019 static void
12020 init_remote_threadtests (void)
12021 {
12022 add_com ("tlist", class_obscure, threadlist_test_cmd,
12023 _("Fetch and print the remote list of "
12024 "thread identifiers, one pkt only."));
12025 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
12026 _("Fetch and display info about one thread."));
12027 add_com ("tset", class_obscure, threadset_test_cmd,
12028 _("Test setting to a different thread."));
12029 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
12030 _("Iterate through updating all remote thread info."));
12031 add_com ("talive", class_obscure, threadalive_test,
12032 _("Remote thread alive test."));
12033 }
12034
12035 #endif /* 0 */
12036
12037 /* Convert a thread ID to a string. */
12038
12039 std::string
12040 remote_target::pid_to_str (ptid_t ptid)
12041 {
12042 if (ptid == null_ptid)
12043 return normal_pid_to_str (ptid);
12044 else if (ptid.is_pid ())
12045 {
12046 /* Printing an inferior target id. */
12047
12048 /* When multi-process extensions are off, there's no way in the
12049 remote protocol to know the remote process id, if there's any
12050 at all. There's one exception --- when we're connected with
12051 target extended-remote, and we manually attached to a process
12052 with "attach PID". We don't record anywhere a flag that
12053 allows us to distinguish that case from the case of
12054 connecting with extended-remote and the stub already being
12055 attached to a process, and reporting yes to qAttached, hence
12056 no smart special casing here. */
12057 if (!m_features.remote_multi_process_p ())
12058 return "Remote target";
12059
12060 return normal_pid_to_str (ptid);
12061 }
12062 else
12063 {
12064 if (magic_null_ptid == ptid)
12065 return "Thread <main>";
12066 else if (m_features.remote_multi_process_p ())
12067 if (ptid.lwp () == 0)
12068 return normal_pid_to_str (ptid);
12069 else
12070 return string_printf ("Thread %d.%ld",
12071 ptid.pid (), ptid.lwp ());
12072 else
12073 return string_printf ("Thread %ld", ptid.lwp ());
12074 }
12075 }
12076
12077 /* Get the address of the thread local variable in OBJFILE which is
12078 stored at OFFSET within the thread local storage for thread PTID. */
12079
12080 CORE_ADDR
12081 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
12082 CORE_ADDR offset)
12083 {
12084 if (m_features.packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
12085 {
12086 struct remote_state *rs = get_remote_state ();
12087 char *p = rs->buf.data ();
12088 char *endp = p + get_remote_packet_size ();
12089 enum packet_result result;
12090
12091 strcpy (p, "qGetTLSAddr:");
12092 p += strlen (p);
12093 p = write_ptid (p, endp, ptid);
12094 *p++ = ',';
12095 p += hexnumstr (p, offset);
12096 *p++ = ',';
12097 p += hexnumstr (p, lm);
12098 *p++ = '\0';
12099
12100 putpkt (rs->buf);
12101 getpkt (&rs->buf);
12102 result = m_features.packet_ok (rs->buf, PACKET_qGetTLSAddr);
12103 if (result == PACKET_OK)
12104 {
12105 ULONGEST addr;
12106
12107 unpack_varlen_hex (rs->buf.data (), &addr);
12108 return addr;
12109 }
12110 else if (result == PACKET_UNKNOWN)
12111 throw_error (TLS_GENERIC_ERROR,
12112 _("Remote target doesn't support qGetTLSAddr packet"));
12113 else
12114 throw_error (TLS_GENERIC_ERROR,
12115 _("Remote target failed to process qGetTLSAddr request"));
12116 }
12117 else
12118 throw_error (TLS_GENERIC_ERROR,
12119 _("TLS not supported or disabled on this target"));
12120 /* Not reached. */
12121 return 0;
12122 }
12123
12124 /* Provide thread local base, i.e. Thread Information Block address.
12125 Returns 1 if ptid is found and thread_local_base is non zero. */
12126
12127 bool
12128 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
12129 {
12130 if (m_features.packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
12131 {
12132 struct remote_state *rs = get_remote_state ();
12133 char *p = rs->buf.data ();
12134 char *endp = p + get_remote_packet_size ();
12135 enum packet_result result;
12136
12137 strcpy (p, "qGetTIBAddr:");
12138 p += strlen (p);
12139 p = write_ptid (p, endp, ptid);
12140 *p++ = '\0';
12141
12142 putpkt (rs->buf);
12143 getpkt (&rs->buf);
12144 result = m_features.packet_ok (rs->buf, PACKET_qGetTIBAddr);
12145 if (result == PACKET_OK)
12146 {
12147 ULONGEST val;
12148 unpack_varlen_hex (rs->buf.data (), &val);
12149 if (addr)
12150 *addr = (CORE_ADDR) val;
12151 return true;
12152 }
12153 else if (result == PACKET_UNKNOWN)
12154 error (_("Remote target doesn't support qGetTIBAddr packet"));
12155 else
12156 error (_("Remote target failed to process qGetTIBAddr request"));
12157 }
12158 else
12159 error (_("qGetTIBAddr not supported or disabled on this target"));
12160 /* Not reached. */
12161 return false;
12162 }
12163
12164 /* Support for inferring a target description based on the current
12165 architecture and the size of a 'g' packet. While the 'g' packet
12166 can have any size (since optional registers can be left off the
12167 end), some sizes are easily recognizable given knowledge of the
12168 approximate architecture. */
12169
12170 struct remote_g_packet_guess
12171 {
12172 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
12173 : bytes (bytes_),
12174 tdesc (tdesc_)
12175 {
12176 }
12177
12178 int bytes;
12179 const struct target_desc *tdesc;
12180 };
12181
12182 struct remote_g_packet_data
12183 {
12184 std::vector<remote_g_packet_guess> guesses;
12185 };
12186
12187 static const registry<gdbarch>::key<struct remote_g_packet_data>
12188 remote_g_packet_data_handle;
12189
12190 static struct remote_g_packet_data *
12191 get_g_packet_data (struct gdbarch *gdbarch)
12192 {
12193 struct remote_g_packet_data *data
12194 = remote_g_packet_data_handle.get (gdbarch);
12195 if (data == nullptr)
12196 data = remote_g_packet_data_handle.emplace (gdbarch);
12197 return data;
12198 }
12199
12200 void
12201 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12202 const struct target_desc *tdesc)
12203 {
12204 struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
12205
12206 gdb_assert (tdesc != NULL);
12207
12208 for (const remote_g_packet_guess &guess : data->guesses)
12209 if (guess.bytes == bytes)
12210 internal_error (_("Duplicate g packet description added for size %d"),
12211 bytes);
12212
12213 data->guesses.emplace_back (bytes, tdesc);
12214 }
12215
12216 /* Return true if remote_read_description would do anything on this target
12217 and architecture, false otherwise. */
12218
12219 static bool
12220 remote_read_description_p (struct target_ops *target)
12221 {
12222 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
12223
12224 return !data->guesses.empty ();
12225 }
12226
12227 const struct target_desc *
12228 remote_target::read_description ()
12229 {
12230 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
12231
12232 /* Do not try this during initial connection, when we do not know
12233 whether there is a running but stopped thread. */
12234 if (!target_has_execution () || inferior_ptid == null_ptid)
12235 return beneath ()->read_description ();
12236
12237 if (!data->guesses.empty ())
12238 {
12239 int bytes = send_g_packet ();
12240
12241 for (const remote_g_packet_guess &guess : data->guesses)
12242 if (guess.bytes == bytes)
12243 return guess.tdesc;
12244
12245 /* We discard the g packet. A minor optimization would be to
12246 hold on to it, and fill the register cache once we have selected
12247 an architecture, but it's too tricky to do safely. */
12248 }
12249
12250 return beneath ()->read_description ();
12251 }
12252
12253 /* Remote file transfer support. This is host-initiated I/O, not
12254 target-initiated; for target-initiated, see remote-fileio.c. */
12255
12256 /* If *LEFT is at least the length of STRING, copy STRING to
12257 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12258 decrease *LEFT. Otherwise raise an error. */
12259
12260 static void
12261 remote_buffer_add_string (char **buffer, int *left, const char *string)
12262 {
12263 int len = strlen (string);
12264
12265 if (len > *left)
12266 error (_("Packet too long for target."));
12267
12268 memcpy (*buffer, string, len);
12269 *buffer += len;
12270 *left -= len;
12271
12272 /* NUL-terminate the buffer as a convenience, if there is
12273 room. */
12274 if (*left)
12275 **buffer = '\0';
12276 }
12277
12278 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12279 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12280 decrease *LEFT. Otherwise raise an error. */
12281
12282 static void
12283 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12284 int len)
12285 {
12286 if (2 * len > *left)
12287 error (_("Packet too long for target."));
12288
12289 bin2hex (bytes, *buffer, len);
12290 *buffer += 2 * len;
12291 *left -= 2 * len;
12292
12293 /* NUL-terminate the buffer as a convenience, if there is
12294 room. */
12295 if (*left)
12296 **buffer = '\0';
12297 }
12298
12299 /* If *LEFT is large enough, convert VALUE to hex and add it to
12300 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12301 decrease *LEFT. Otherwise raise an error. */
12302
12303 static void
12304 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12305 {
12306 int len = hexnumlen (value);
12307
12308 if (len > *left)
12309 error (_("Packet too long for target."));
12310
12311 hexnumstr (*buffer, value);
12312 *buffer += len;
12313 *left -= len;
12314
12315 /* NUL-terminate the buffer as a convenience, if there is
12316 room. */
12317 if (*left)
12318 **buffer = '\0';
12319 }
12320
12321 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12322 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
12323 was included, and *ATTACHMENT to point to the start of the annex
12324 if any. The length of the packet isn't needed here; there may
12325 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12326
12327 Return 0 if the packet could be parsed, -1 if it could not. If
12328 -1 is returned, the other variables may not be initialized. */
12329
12330 static int
12331 remote_hostio_parse_result (const char *buffer, int *retcode,
12332 fileio_error *remote_errno, const char **attachment)
12333 {
12334 char *p, *p2;
12335
12336 *remote_errno = FILEIO_SUCCESS;
12337 *attachment = NULL;
12338
12339 if (buffer[0] != 'F')
12340 return -1;
12341
12342 errno = 0;
12343 *retcode = strtol (&buffer[1], &p, 16);
12344 if (errno != 0 || p == &buffer[1])
12345 return -1;
12346
12347 /* Check for ",errno". */
12348 if (*p == ',')
12349 {
12350 errno = 0;
12351 *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
12352 if (errno != 0 || p + 1 == p2)
12353 return -1;
12354 p = p2;
12355 }
12356
12357 /* Check for ";attachment". If there is no attachment, the
12358 packet should end here. */
12359 if (*p == ';')
12360 {
12361 *attachment = p + 1;
12362 return 0;
12363 }
12364 else if (*p == '\0')
12365 return 0;
12366 else
12367 return -1;
12368 }
12369
12370 /* Send a prepared I/O packet to the target and read its response.
12371 The prepared packet is in the global RS->BUF before this function
12372 is called, and the answer is there when we return.
12373
12374 COMMAND_BYTES is the length of the request to send, which may include
12375 binary data. WHICH_PACKET is the packet configuration to check
12376 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12377 is set to the error number and -1 is returned. Otherwise the value
12378 returned by the function is returned.
12379
12380 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12381 attachment is expected; an error will be reported if there's a
12382 mismatch. If one is found, *ATTACHMENT will be set to point into
12383 the packet buffer and *ATTACHMENT_LEN will be set to the
12384 attachment's length. */
12385
12386 int
12387 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12388 fileio_error *remote_errno, const char **attachment,
12389 int *attachment_len)
12390 {
12391 struct remote_state *rs = get_remote_state ();
12392 int ret, bytes_read;
12393 const char *attachment_tmp;
12394
12395 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
12396 {
12397 *remote_errno = FILEIO_ENOSYS;
12398 return -1;
12399 }
12400
12401 putpkt_binary (rs->buf.data (), command_bytes);
12402 bytes_read = getpkt (&rs->buf);
12403
12404 /* If it timed out, something is wrong. Don't try to parse the
12405 buffer. */
12406 if (bytes_read < 0)
12407 {
12408 *remote_errno = FILEIO_EINVAL;
12409 return -1;
12410 }
12411
12412 switch (m_features.packet_ok (rs->buf, which_packet))
12413 {
12414 case PACKET_ERROR:
12415 *remote_errno = FILEIO_EINVAL;
12416 return -1;
12417 case PACKET_UNKNOWN:
12418 *remote_errno = FILEIO_ENOSYS;
12419 return -1;
12420 case PACKET_OK:
12421 break;
12422 }
12423
12424 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12425 &attachment_tmp))
12426 {
12427 *remote_errno = FILEIO_EINVAL;
12428 return -1;
12429 }
12430
12431 /* Make sure we saw an attachment if and only if we expected one. */
12432 if ((attachment_tmp == NULL && attachment != NULL)
12433 || (attachment_tmp != NULL && attachment == NULL))
12434 {
12435 *remote_errno = FILEIO_EINVAL;
12436 return -1;
12437 }
12438
12439 /* If an attachment was found, it must point into the packet buffer;
12440 work out how many bytes there were. */
12441 if (attachment_tmp != NULL)
12442 {
12443 *attachment = attachment_tmp;
12444 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12445 }
12446
12447 return ret;
12448 }
12449
12450 /* See declaration.h. */
12451
12452 void
12453 readahead_cache::invalidate ()
12454 {
12455 this->fd = -1;
12456 }
12457
12458 /* See declaration.h. */
12459
12460 void
12461 readahead_cache::invalidate_fd (int fd)
12462 {
12463 if (this->fd == fd)
12464 this->fd = -1;
12465 }
12466
12467 /* Set the filesystem remote_hostio functions that take FILENAME
12468 arguments will use. Return 0 on success, or -1 if an error
12469 occurs (and set *REMOTE_ERRNO). */
12470
12471 int
12472 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12473 fileio_error *remote_errno)
12474 {
12475 struct remote_state *rs = get_remote_state ();
12476 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12477 char *p = rs->buf.data ();
12478 int left = get_remote_packet_size () - 1;
12479 char arg[9];
12480 int ret;
12481
12482 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12483 return 0;
12484
12485 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12486 return 0;
12487
12488 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12489
12490 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12491 remote_buffer_add_string (&p, &left, arg);
12492
12493 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12494 remote_errno, NULL, NULL);
12495
12496 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12497 return 0;
12498
12499 if (ret == 0)
12500 rs->fs_pid = required_pid;
12501
12502 return ret;
12503 }
12504
12505 /* Implementation of to_fileio_open. */
12506
12507 int
12508 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12509 int flags, int mode, int warn_if_slow,
12510 fileio_error *remote_errno)
12511 {
12512 struct remote_state *rs = get_remote_state ();
12513 char *p = rs->buf.data ();
12514 int left = get_remote_packet_size () - 1;
12515
12516 if (warn_if_slow)
12517 {
12518 static int warning_issued = 0;
12519
12520 gdb_printf (_("Reading %s from remote target...\n"),
12521 filename);
12522
12523 if (!warning_issued)
12524 {
12525 warning (_("File transfers from remote targets can be slow."
12526 " Use \"set sysroot\" to access files locally"
12527 " instead."));
12528 warning_issued = 1;
12529 }
12530 }
12531
12532 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12533 return -1;
12534
12535 remote_buffer_add_string (&p, &left, "vFile:open:");
12536
12537 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12538 strlen (filename));
12539 remote_buffer_add_string (&p, &left, ",");
12540
12541 remote_buffer_add_int (&p, &left, flags);
12542 remote_buffer_add_string (&p, &left, ",");
12543
12544 remote_buffer_add_int (&p, &left, mode);
12545
12546 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12547 remote_errno, NULL, NULL);
12548 }
12549
12550 int
12551 remote_target::fileio_open (struct inferior *inf, const char *filename,
12552 int flags, int mode, int warn_if_slow,
12553 fileio_error *remote_errno)
12554 {
12555 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12556 remote_errno);
12557 }
12558
12559 /* Implementation of to_fileio_pwrite. */
12560
12561 int
12562 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12563 ULONGEST offset, fileio_error *remote_errno)
12564 {
12565 struct remote_state *rs = get_remote_state ();
12566 char *p = rs->buf.data ();
12567 int left = get_remote_packet_size ();
12568 int out_len;
12569
12570 rs->readahead_cache.invalidate_fd (fd);
12571
12572 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12573
12574 remote_buffer_add_int (&p, &left, fd);
12575 remote_buffer_add_string (&p, &left, ",");
12576
12577 remote_buffer_add_int (&p, &left, offset);
12578 remote_buffer_add_string (&p, &left, ",");
12579
12580 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12581 (get_remote_packet_size ()
12582 - (p - rs->buf.data ())));
12583
12584 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12585 remote_errno, NULL, NULL);
12586 }
12587
12588 int
12589 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12590 ULONGEST offset, fileio_error *remote_errno)
12591 {
12592 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12593 }
12594
12595 /* Helper for the implementation of to_fileio_pread. Read the file
12596 from the remote side with vFile:pread. */
12597
12598 int
12599 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12600 ULONGEST offset, fileio_error *remote_errno)
12601 {
12602 struct remote_state *rs = get_remote_state ();
12603 char *p = rs->buf.data ();
12604 const char *attachment;
12605 int left = get_remote_packet_size ();
12606 int ret, attachment_len;
12607 int read_len;
12608
12609 remote_buffer_add_string (&p, &left, "vFile:pread:");
12610
12611 remote_buffer_add_int (&p, &left, fd);
12612 remote_buffer_add_string (&p, &left, ",");
12613
12614 remote_buffer_add_int (&p, &left, len);
12615 remote_buffer_add_string (&p, &left, ",");
12616
12617 remote_buffer_add_int (&p, &left, offset);
12618
12619 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12620 remote_errno, &attachment,
12621 &attachment_len);
12622
12623 if (ret < 0)
12624 return ret;
12625
12626 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12627 read_buf, len);
12628 if (read_len != ret)
12629 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12630
12631 return ret;
12632 }
12633
12634 /* See declaration.h. */
12635
12636 int
12637 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12638 ULONGEST offset)
12639 {
12640 if (this->fd == fd
12641 && this->offset <= offset
12642 && offset < this->offset + this->buf.size ())
12643 {
12644 ULONGEST max = this->offset + this->buf.size ();
12645
12646 if (offset + len > max)
12647 len = max - offset;
12648
12649 memcpy (read_buf, &this->buf[offset - this->offset], len);
12650 return len;
12651 }
12652
12653 return 0;
12654 }
12655
12656 /* Implementation of to_fileio_pread. */
12657
12658 int
12659 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12660 ULONGEST offset, fileio_error *remote_errno)
12661 {
12662 int ret;
12663 struct remote_state *rs = get_remote_state ();
12664 readahead_cache *cache = &rs->readahead_cache;
12665
12666 ret = cache->pread (fd, read_buf, len, offset);
12667 if (ret > 0)
12668 {
12669 cache->hit_count++;
12670
12671 remote_debug_printf ("readahead cache hit %s",
12672 pulongest (cache->hit_count));
12673 return ret;
12674 }
12675
12676 cache->miss_count++;
12677
12678 remote_debug_printf ("readahead cache miss %s",
12679 pulongest (cache->miss_count));
12680
12681 cache->fd = fd;
12682 cache->offset = offset;
12683 cache->buf.resize (get_remote_packet_size ());
12684
12685 ret = remote_hostio_pread_vFile (cache->fd, &cache->buf[0],
12686 cache->buf.size (),
12687 cache->offset, remote_errno);
12688 if (ret <= 0)
12689 {
12690 cache->invalidate_fd (fd);
12691 return ret;
12692 }
12693
12694 cache->buf.resize (ret);
12695 return cache->pread (fd, read_buf, len, offset);
12696 }
12697
12698 int
12699 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12700 ULONGEST offset, fileio_error *remote_errno)
12701 {
12702 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12703 }
12704
12705 /* Implementation of to_fileio_close. */
12706
12707 int
12708 remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
12709 {
12710 struct remote_state *rs = get_remote_state ();
12711 char *p = rs->buf.data ();
12712 int left = get_remote_packet_size () - 1;
12713
12714 rs->readahead_cache.invalidate_fd (fd);
12715
12716 remote_buffer_add_string (&p, &left, "vFile:close:");
12717
12718 remote_buffer_add_int (&p, &left, fd);
12719
12720 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12721 remote_errno, NULL, NULL);
12722 }
12723
12724 int
12725 remote_target::fileio_close (int fd, fileio_error *remote_errno)
12726 {
12727 return remote_hostio_close (fd, remote_errno);
12728 }
12729
12730 /* Implementation of to_fileio_unlink. */
12731
12732 int
12733 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12734 fileio_error *remote_errno)
12735 {
12736 struct remote_state *rs = get_remote_state ();
12737 char *p = rs->buf.data ();
12738 int left = get_remote_packet_size () - 1;
12739
12740 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12741 return -1;
12742
12743 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12744
12745 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12746 strlen (filename));
12747
12748 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12749 remote_errno, NULL, NULL);
12750 }
12751
12752 int
12753 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12754 fileio_error *remote_errno)
12755 {
12756 return remote_hostio_unlink (inf, filename, remote_errno);
12757 }
12758
12759 /* Implementation of to_fileio_readlink. */
12760
12761 gdb::optional<std::string>
12762 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12763 fileio_error *remote_errno)
12764 {
12765 struct remote_state *rs = get_remote_state ();
12766 char *p = rs->buf.data ();
12767 const char *attachment;
12768 int left = get_remote_packet_size ();
12769 int len, attachment_len;
12770 int read_len;
12771
12772 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12773 return {};
12774
12775 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12776
12777 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12778 strlen (filename));
12779
12780 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12781 remote_errno, &attachment,
12782 &attachment_len);
12783
12784 if (len < 0)
12785 return {};
12786
12787 std::string ret (len, '\0');
12788
12789 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12790 (gdb_byte *) &ret[0], len);
12791 if (read_len != len)
12792 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12793
12794 return ret;
12795 }
12796
12797 /* Implementation of to_fileio_fstat. */
12798
12799 int
12800 remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
12801 {
12802 struct remote_state *rs = get_remote_state ();
12803 char *p = rs->buf.data ();
12804 int left = get_remote_packet_size ();
12805 int attachment_len, ret;
12806 const char *attachment;
12807 struct fio_stat fst;
12808 int read_len;
12809
12810 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12811
12812 remote_buffer_add_int (&p, &left, fd);
12813
12814 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12815 remote_errno, &attachment,
12816 &attachment_len);
12817 if (ret < 0)
12818 {
12819 if (*remote_errno != FILEIO_ENOSYS)
12820 return ret;
12821
12822 /* Strictly we should return -1, ENOSYS here, but when
12823 "set sysroot remote:" was implemented in August 2008
12824 BFD's need for a stat function was sidestepped with
12825 this hack. This was not remedied until March 2015
12826 so we retain the previous behavior to avoid breaking
12827 compatibility.
12828
12829 Note that the memset is a March 2015 addition; older
12830 GDBs set st_size *and nothing else* so the structure
12831 would have garbage in all other fields. This might
12832 break something but retaining the previous behavior
12833 here would be just too wrong. */
12834
12835 memset (st, 0, sizeof (struct stat));
12836 st->st_size = INT_MAX;
12837 return 0;
12838 }
12839
12840 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12841 (gdb_byte *) &fst, sizeof (fst));
12842
12843 if (read_len != ret)
12844 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12845
12846 if (read_len != sizeof (fst))
12847 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12848 read_len, (int) sizeof (fst));
12849
12850 remote_fileio_to_host_stat (&fst, st);
12851
12852 return 0;
12853 }
12854
12855 /* Implementation of to_filesystem_is_local. */
12856
12857 bool
12858 remote_target::filesystem_is_local ()
12859 {
12860 /* Valgrind GDB presents itself as a remote target but works
12861 on the local filesystem: it does not implement remote get
12862 and users are not expected to set a sysroot. To handle
12863 this case we treat the remote filesystem as local if the
12864 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12865 does not support vFile:open. */
12866 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
12867 {
12868 packet_support ps = m_features.packet_support (PACKET_vFile_open);
12869
12870 if (ps == PACKET_SUPPORT_UNKNOWN)
12871 {
12872 int fd;
12873 fileio_error remote_errno;
12874
12875 /* Try opening a file to probe support. The supplied
12876 filename is irrelevant, we only care about whether
12877 the stub recognizes the packet or not. */
12878 fd = remote_hostio_open (NULL, "just probing",
12879 FILEIO_O_RDONLY, 0700, 0,
12880 &remote_errno);
12881
12882 if (fd >= 0)
12883 remote_hostio_close (fd, &remote_errno);
12884
12885 ps = m_features.packet_support (PACKET_vFile_open);
12886 }
12887
12888 if (ps == PACKET_DISABLE)
12889 {
12890 static int warning_issued = 0;
12891
12892 if (!warning_issued)
12893 {
12894 warning (_("remote target does not support file"
12895 " transfer, attempting to access files"
12896 " from local filesystem."));
12897 warning_issued = 1;
12898 }
12899
12900 return true;
12901 }
12902 }
12903
12904 return false;
12905 }
12906
12907 static char *
12908 remote_hostio_error (fileio_error errnum)
12909 {
12910 int host_error = fileio_error_to_host (errnum);
12911
12912 if (host_error == -1)
12913 error (_("Unknown remote I/O error %d"), errnum);
12914 else
12915 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12916 }
12917
12918 /* A RAII wrapper around a remote file descriptor. */
12919
12920 class scoped_remote_fd
12921 {
12922 public:
12923 scoped_remote_fd (remote_target *remote, int fd)
12924 : m_remote (remote), m_fd (fd)
12925 {
12926 }
12927
12928 ~scoped_remote_fd ()
12929 {
12930 if (m_fd != -1)
12931 {
12932 try
12933 {
12934 fileio_error remote_errno;
12935 m_remote->remote_hostio_close (m_fd, &remote_errno);
12936 }
12937 catch (...)
12938 {
12939 /* Swallow exception before it escapes the dtor. If
12940 something goes wrong, likely the connection is gone,
12941 and there's nothing else that can be done. */
12942 }
12943 }
12944 }
12945
12946 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12947
12948 /* Release ownership of the file descriptor, and return it. */
12949 ATTRIBUTE_UNUSED_RESULT int release () noexcept
12950 {
12951 int fd = m_fd;
12952 m_fd = -1;
12953 return fd;
12954 }
12955
12956 /* Return the owned file descriptor. */
12957 int get () const noexcept
12958 {
12959 return m_fd;
12960 }
12961
12962 private:
12963 /* The remote target. */
12964 remote_target *m_remote;
12965
12966 /* The owned remote I/O file descriptor. */
12967 int m_fd;
12968 };
12969
12970 void
12971 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12972 {
12973 remote_target *remote = get_current_remote_target ();
12974
12975 if (remote == nullptr)
12976 error (_("command can only be used with remote target"));
12977
12978 remote->remote_file_put (local_file, remote_file, from_tty);
12979 }
12980
12981 void
12982 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12983 int from_tty)
12984 {
12985 int retcode, bytes, io_size;
12986 fileio_error remote_errno;
12987 int bytes_in_buffer;
12988 int saw_eof;
12989 ULONGEST offset;
12990
12991 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12992 if (file == NULL)
12993 perror_with_name (local_file);
12994
12995 scoped_remote_fd fd
12996 (this, remote_hostio_open (NULL,
12997 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12998 | FILEIO_O_TRUNC),
12999 0700, 0, &remote_errno));
13000 if (fd.get () == -1)
13001 remote_hostio_error (remote_errno);
13002
13003 /* Send up to this many bytes at once. They won't all fit in the
13004 remote packet limit, so we'll transfer slightly fewer. */
13005 io_size = get_remote_packet_size ();
13006 gdb::byte_vector buffer (io_size);
13007
13008 bytes_in_buffer = 0;
13009 saw_eof = 0;
13010 offset = 0;
13011 while (bytes_in_buffer || !saw_eof)
13012 {
13013 if (!saw_eof)
13014 {
13015 bytes = fread (buffer.data () + bytes_in_buffer, 1,
13016 io_size - bytes_in_buffer,
13017 file.get ());
13018 if (bytes == 0)
13019 {
13020 if (ferror (file.get ()))
13021 error (_("Error reading %s."), local_file);
13022 else
13023 {
13024 /* EOF. Unless there is something still in the
13025 buffer from the last iteration, we are done. */
13026 saw_eof = 1;
13027 if (bytes_in_buffer == 0)
13028 break;
13029 }
13030 }
13031 }
13032 else
13033 bytes = 0;
13034
13035 bytes += bytes_in_buffer;
13036 bytes_in_buffer = 0;
13037
13038 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
13039 offset, &remote_errno);
13040
13041 if (retcode < 0)
13042 remote_hostio_error (remote_errno);
13043 else if (retcode == 0)
13044 error (_("Remote write of %d bytes returned 0!"), bytes);
13045 else if (retcode < bytes)
13046 {
13047 /* Short write. Save the rest of the read data for the next
13048 write. */
13049 bytes_in_buffer = bytes - retcode;
13050 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
13051 }
13052
13053 offset += retcode;
13054 }
13055
13056 if (remote_hostio_close (fd.release (), &remote_errno))
13057 remote_hostio_error (remote_errno);
13058
13059 if (from_tty)
13060 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
13061 }
13062
13063 void
13064 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
13065 {
13066 remote_target *remote = get_current_remote_target ();
13067
13068 if (remote == nullptr)
13069 error (_("command can only be used with remote target"));
13070
13071 remote->remote_file_get (remote_file, local_file, from_tty);
13072 }
13073
13074 void
13075 remote_target::remote_file_get (const char *remote_file, const char *local_file,
13076 int from_tty)
13077 {
13078 fileio_error remote_errno;
13079 int bytes, io_size;
13080 ULONGEST offset;
13081
13082 scoped_remote_fd fd
13083 (this, remote_hostio_open (NULL,
13084 remote_file, FILEIO_O_RDONLY, 0, 0,
13085 &remote_errno));
13086 if (fd.get () == -1)
13087 remote_hostio_error (remote_errno);
13088
13089 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
13090 if (file == NULL)
13091 perror_with_name (local_file);
13092
13093 /* Send up to this many bytes at once. They won't all fit in the
13094 remote packet limit, so we'll transfer slightly fewer. */
13095 io_size = get_remote_packet_size ();
13096 gdb::byte_vector buffer (io_size);
13097
13098 offset = 0;
13099 while (1)
13100 {
13101 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
13102 &remote_errno);
13103 if (bytes == 0)
13104 /* Success, but no bytes, means end-of-file. */
13105 break;
13106 if (bytes == -1)
13107 remote_hostio_error (remote_errno);
13108
13109 offset += bytes;
13110
13111 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
13112 if (bytes == 0)
13113 perror_with_name (local_file);
13114 }
13115
13116 if (remote_hostio_close (fd.release (), &remote_errno))
13117 remote_hostio_error (remote_errno);
13118
13119 if (from_tty)
13120 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
13121 }
13122
13123 void
13124 remote_file_delete (const char *remote_file, int from_tty)
13125 {
13126 remote_target *remote = get_current_remote_target ();
13127
13128 if (remote == nullptr)
13129 error (_("command can only be used with remote target"));
13130
13131 remote->remote_file_delete (remote_file, from_tty);
13132 }
13133
13134 void
13135 remote_target::remote_file_delete (const char *remote_file, int from_tty)
13136 {
13137 int retcode;
13138 fileio_error remote_errno;
13139
13140 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
13141 if (retcode == -1)
13142 remote_hostio_error (remote_errno);
13143
13144 if (from_tty)
13145 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
13146 }
13147
13148 static void
13149 remote_put_command (const char *args, int from_tty)
13150 {
13151 if (args == NULL)
13152 error_no_arg (_("file to put"));
13153
13154 gdb_argv argv (args);
13155 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13156 error (_("Invalid parameters to remote put"));
13157
13158 remote_file_put (argv[0], argv[1], from_tty);
13159 }
13160
13161 static void
13162 remote_get_command (const char *args, int from_tty)
13163 {
13164 if (args == NULL)
13165 error_no_arg (_("file to get"));
13166
13167 gdb_argv argv (args);
13168 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13169 error (_("Invalid parameters to remote get"));
13170
13171 remote_file_get (argv[0], argv[1], from_tty);
13172 }
13173
13174 static void
13175 remote_delete_command (const char *args, int from_tty)
13176 {
13177 if (args == NULL)
13178 error_no_arg (_("file to delete"));
13179
13180 gdb_argv argv (args);
13181 if (argv[0] == NULL || argv[1] != NULL)
13182 error (_("Invalid parameters to remote delete"));
13183
13184 remote_file_delete (argv[0], from_tty);
13185 }
13186
13187 bool
13188 remote_target::can_execute_reverse ()
13189 {
13190 if (m_features.packet_support (PACKET_bs) == PACKET_ENABLE
13191 || m_features.packet_support (PACKET_bc) == PACKET_ENABLE)
13192 return true;
13193 else
13194 return false;
13195 }
13196
13197 bool
13198 remote_target::supports_non_stop ()
13199 {
13200 return true;
13201 }
13202
13203 bool
13204 remote_target::supports_disable_randomization ()
13205 {
13206 /* Only supported in extended mode. */
13207 return false;
13208 }
13209
13210 bool
13211 remote_target::supports_multi_process ()
13212 {
13213 return m_features.remote_multi_process_p ();
13214 }
13215
13216 int
13217 remote_target::remote_supports_cond_tracepoints ()
13218 {
13219 return (m_features.packet_support (PACKET_ConditionalTracepoints)
13220 == PACKET_ENABLE);
13221 }
13222
13223 bool
13224 remote_target::supports_evaluation_of_breakpoint_conditions ()
13225 {
13226 return (m_features.packet_support (PACKET_ConditionalBreakpoints)
13227 == PACKET_ENABLE);
13228 }
13229
13230 int
13231 remote_target::remote_supports_fast_tracepoints ()
13232 {
13233 return m_features.packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13234 }
13235
13236 int
13237 remote_target::remote_supports_static_tracepoints ()
13238 {
13239 return m_features.packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13240 }
13241
13242 int
13243 remote_target::remote_supports_install_in_trace ()
13244 {
13245 return m_features.packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13246 }
13247
13248 bool
13249 remote_target::supports_enable_disable_tracepoint ()
13250 {
13251 return (m_features.packet_support (PACKET_EnableDisableTracepoints_feature)
13252 == PACKET_ENABLE);
13253 }
13254
13255 bool
13256 remote_target::supports_string_tracing ()
13257 {
13258 return m_features.packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13259 }
13260
13261 bool
13262 remote_target::can_run_breakpoint_commands ()
13263 {
13264 return m_features.packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13265 }
13266
13267 void
13268 remote_target::trace_init ()
13269 {
13270 struct remote_state *rs = get_remote_state ();
13271
13272 putpkt ("QTinit");
13273 remote_get_noisy_reply ();
13274 if (strcmp (rs->buf.data (), "OK") != 0)
13275 error (_("Target does not support this command."));
13276 }
13277
13278 /* Recursive routine to walk through command list including loops, and
13279 download packets for each command. */
13280
13281 void
13282 remote_target::remote_download_command_source (int num, ULONGEST addr,
13283 struct command_line *cmds)
13284 {
13285 struct remote_state *rs = get_remote_state ();
13286 struct command_line *cmd;
13287
13288 for (cmd = cmds; cmd; cmd = cmd->next)
13289 {
13290 QUIT; /* Allow user to bail out with ^C. */
13291 strcpy (rs->buf.data (), "QTDPsrc:");
13292 encode_source_string (num, addr, "cmd", cmd->line,
13293 rs->buf.data () + strlen (rs->buf.data ()),
13294 rs->buf.size () - strlen (rs->buf.data ()));
13295 putpkt (rs->buf);
13296 remote_get_noisy_reply ();
13297 if (strcmp (rs->buf.data (), "OK"))
13298 warning (_("Target does not support source download."));
13299
13300 if (cmd->control_type == while_control
13301 || cmd->control_type == while_stepping_control)
13302 {
13303 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13304
13305 QUIT; /* Allow user to bail out with ^C. */
13306 strcpy (rs->buf.data (), "QTDPsrc:");
13307 encode_source_string (num, addr, "cmd", "end",
13308 rs->buf.data () + strlen (rs->buf.data ()),
13309 rs->buf.size () - strlen (rs->buf.data ()));
13310 putpkt (rs->buf);
13311 remote_get_noisy_reply ();
13312 if (strcmp (rs->buf.data (), "OK"))
13313 warning (_("Target does not support source download."));
13314 }
13315 }
13316 }
13317
13318 void
13319 remote_target::download_tracepoint (struct bp_location *loc)
13320 {
13321 CORE_ADDR tpaddr;
13322 char addrbuf[40];
13323 std::vector<std::string> tdp_actions;
13324 std::vector<std::string> stepping_actions;
13325 char *pkt;
13326 struct breakpoint *b = loc->owner;
13327 tracepoint *t = gdb::checked_static_cast<tracepoint *> (b);
13328 struct remote_state *rs = get_remote_state ();
13329 int ret;
13330 const char *err_msg = _("Tracepoint packet too large for target.");
13331 size_t size_left;
13332
13333 /* We use a buffer other than rs->buf because we'll build strings
13334 across multiple statements, and other statements in between could
13335 modify rs->buf. */
13336 gdb::char_vector buf (get_remote_packet_size ());
13337
13338 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13339
13340 tpaddr = loc->address;
13341 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13342 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13343 b->number, addrbuf, /* address */
13344 (b->enable_state == bp_enabled ? 'E' : 'D'),
13345 t->step_count, t->pass_count);
13346
13347 if (ret < 0 || ret >= buf.size ())
13348 error ("%s", err_msg);
13349
13350 /* Fast tracepoints are mostly handled by the target, but we can
13351 tell the target how big of an instruction block should be moved
13352 around. */
13353 if (b->type == bp_fast_tracepoint)
13354 {
13355 /* Only test for support at download time; we may not know
13356 target capabilities at definition time. */
13357 if (remote_supports_fast_tracepoints ())
13358 {
13359 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13360 NULL))
13361 {
13362 size_left = buf.size () - strlen (buf.data ());
13363 ret = snprintf (buf.data () + strlen (buf.data ()),
13364 size_left, ":F%x",
13365 gdb_insn_length (loc->gdbarch, tpaddr));
13366
13367 if (ret < 0 || ret >= size_left)
13368 error ("%s", err_msg);
13369 }
13370 else
13371 /* If it passed validation at definition but fails now,
13372 something is very wrong. */
13373 internal_error (_("Fast tracepoint not valid during download"));
13374 }
13375 else
13376 /* Fast tracepoints are functionally identical to regular
13377 tracepoints, so don't take lack of support as a reason to
13378 give up on the trace run. */
13379 warning (_("Target does not support fast tracepoints, "
13380 "downloading %d as regular tracepoint"), b->number);
13381 }
13382 else if (b->type == bp_static_tracepoint
13383 || b->type == bp_static_marker_tracepoint)
13384 {
13385 /* Only test for support at download time; we may not know
13386 target capabilities at definition time. */
13387 if (remote_supports_static_tracepoints ())
13388 {
13389 struct static_tracepoint_marker marker;
13390
13391 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13392 {
13393 size_left = buf.size () - strlen (buf.data ());
13394 ret = snprintf (buf.data () + strlen (buf.data ()),
13395 size_left, ":S");
13396
13397 if (ret < 0 || ret >= size_left)
13398 error ("%s", err_msg);
13399 }
13400 else
13401 error (_("Static tracepoint not valid during download"));
13402 }
13403 else
13404 /* Fast tracepoints are functionally identical to regular
13405 tracepoints, so don't take lack of support as a reason
13406 to give up on the trace run. */
13407 error (_("Target does not support static tracepoints"));
13408 }
13409 /* If the tracepoint has a conditional, make it into an agent
13410 expression and append to the definition. */
13411 if (loc->cond)
13412 {
13413 /* Only test support at download time, we may not know target
13414 capabilities at definition time. */
13415 if (remote_supports_cond_tracepoints ())
13416 {
13417 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13418 loc->cond.get ());
13419
13420 size_left = buf.size () - strlen (buf.data ());
13421
13422 ret = snprintf (buf.data () + strlen (buf.data ()),
13423 size_left, ":X%x,", (int) aexpr->buf.size ());
13424
13425 if (ret < 0 || ret >= size_left)
13426 error ("%s", err_msg);
13427
13428 size_left = buf.size () - strlen (buf.data ());
13429
13430 /* Two bytes to encode each aexpr byte, plus the terminating
13431 null byte. */
13432 if (aexpr->buf.size () * 2 + 1 > size_left)
13433 error ("%s", err_msg);
13434
13435 pkt = buf.data () + strlen (buf.data ());
13436
13437 for (int ndx = 0; ndx < aexpr->buf.size (); ++ndx)
13438 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13439 *pkt = '\0';
13440 }
13441 else
13442 warning (_("Target does not support conditional tracepoints, "
13443 "ignoring tp %d cond"), b->number);
13444 }
13445
13446 if (b->commands || !default_collect.empty ())
13447 {
13448 size_left = buf.size () - strlen (buf.data ());
13449
13450 ret = snprintf (buf.data () + strlen (buf.data ()),
13451 size_left, "-");
13452
13453 if (ret < 0 || ret >= size_left)
13454 error ("%s", err_msg);
13455 }
13456
13457 putpkt (buf.data ());
13458 remote_get_noisy_reply ();
13459 if (strcmp (rs->buf.data (), "OK"))
13460 error (_("Target does not support tracepoints."));
13461
13462 /* do_single_steps (t); */
13463 for (auto action_it = tdp_actions.begin ();
13464 action_it != tdp_actions.end (); action_it++)
13465 {
13466 QUIT; /* Allow user to bail out with ^C. */
13467
13468 bool has_more = ((action_it + 1) != tdp_actions.end ()
13469 || !stepping_actions.empty ());
13470
13471 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13472 b->number, addrbuf, /* address */
13473 action_it->c_str (),
13474 has_more ? '-' : 0);
13475
13476 if (ret < 0 || ret >= buf.size ())
13477 error ("%s", err_msg);
13478
13479 putpkt (buf.data ());
13480 remote_get_noisy_reply ();
13481 if (strcmp (rs->buf.data (), "OK"))
13482 error (_("Error on target while setting tracepoints."));
13483 }
13484
13485 for (auto action_it = stepping_actions.begin ();
13486 action_it != stepping_actions.end (); action_it++)
13487 {
13488 QUIT; /* Allow user to bail out with ^C. */
13489
13490 bool is_first = action_it == stepping_actions.begin ();
13491 bool has_more = (action_it + 1) != stepping_actions.end ();
13492
13493 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13494 b->number, addrbuf, /* address */
13495 is_first ? "S" : "",
13496 action_it->c_str (),
13497 has_more ? "-" : "");
13498
13499 if (ret < 0 || ret >= buf.size ())
13500 error ("%s", err_msg);
13501
13502 putpkt (buf.data ());
13503 remote_get_noisy_reply ();
13504 if (strcmp (rs->buf.data (), "OK"))
13505 error (_("Error on target while setting tracepoints."));
13506 }
13507
13508 if (m_features.packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13509 {
13510 if (b->locspec != nullptr)
13511 {
13512 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13513
13514 if (ret < 0 || ret >= buf.size ())
13515 error ("%s", err_msg);
13516
13517 const char *str = b->locspec->to_string ();
13518 encode_source_string (b->number, loc->address, "at", str,
13519 buf.data () + strlen (buf.data ()),
13520 buf.size () - strlen (buf.data ()));
13521 putpkt (buf.data ());
13522 remote_get_noisy_reply ();
13523 if (strcmp (rs->buf.data (), "OK"))
13524 warning (_("Target does not support source download."));
13525 }
13526 if (b->cond_string)
13527 {
13528 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13529
13530 if (ret < 0 || ret >= buf.size ())
13531 error ("%s", err_msg);
13532
13533 encode_source_string (b->number, loc->address,
13534 "cond", b->cond_string.get (),
13535 buf.data () + strlen (buf.data ()),
13536 buf.size () - strlen (buf.data ()));
13537 putpkt (buf.data ());
13538 remote_get_noisy_reply ();
13539 if (strcmp (rs->buf.data (), "OK"))
13540 warning (_("Target does not support source download."));
13541 }
13542 remote_download_command_source (b->number, loc->address,
13543 breakpoint_commands (b));
13544 }
13545 }
13546
13547 bool
13548 remote_target::can_download_tracepoint ()
13549 {
13550 struct remote_state *rs = get_remote_state ();
13551 struct trace_status *ts;
13552 int status;
13553
13554 /* Don't try to install tracepoints until we've relocated our
13555 symbols, and fetched and merged the target's tracepoint list with
13556 ours. */
13557 if (rs->starting_up)
13558 return false;
13559
13560 ts = current_trace_status ();
13561 status = get_trace_status (ts);
13562
13563 if (status == -1 || !ts->running_known || !ts->running)
13564 return false;
13565
13566 /* If we are in a tracing experiment, but remote stub doesn't support
13567 installing tracepoint in trace, we have to return. */
13568 if (!remote_supports_install_in_trace ())
13569 return false;
13570
13571 return true;
13572 }
13573
13574
13575 void
13576 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13577 {
13578 struct remote_state *rs = get_remote_state ();
13579 char *p;
13580
13581 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13582 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13583 tsv.builtin);
13584 p = rs->buf.data () + strlen (rs->buf.data ());
13585 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13586 >= get_remote_packet_size ())
13587 error (_("Trace state variable name too long for tsv definition packet"));
13588 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13589 *p++ = '\0';
13590 putpkt (rs->buf);
13591 remote_get_noisy_reply ();
13592 if (rs->buf[0] == '\0')
13593 error (_("Target does not support this command."));
13594 if (strcmp (rs->buf.data (), "OK") != 0)
13595 error (_("Error on target while downloading trace state variable."));
13596 }
13597
13598 void
13599 remote_target::enable_tracepoint (struct bp_location *location)
13600 {
13601 struct remote_state *rs = get_remote_state ();
13602
13603 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13604 location->owner->number,
13605 phex (location->address, sizeof (CORE_ADDR)));
13606 putpkt (rs->buf);
13607 remote_get_noisy_reply ();
13608 if (rs->buf[0] == '\0')
13609 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13610 if (strcmp (rs->buf.data (), "OK") != 0)
13611 error (_("Error on target while enabling tracepoint."));
13612 }
13613
13614 void
13615 remote_target::disable_tracepoint (struct bp_location *location)
13616 {
13617 struct remote_state *rs = get_remote_state ();
13618
13619 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13620 location->owner->number,
13621 phex (location->address, sizeof (CORE_ADDR)));
13622 putpkt (rs->buf);
13623 remote_get_noisy_reply ();
13624 if (rs->buf[0] == '\0')
13625 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13626 if (strcmp (rs->buf.data (), "OK") != 0)
13627 error (_("Error on target while disabling tracepoint."));
13628 }
13629
13630 void
13631 remote_target::trace_set_readonly_regions ()
13632 {
13633 asection *s;
13634 bfd_size_type size;
13635 bfd_vma vma;
13636 int anysecs = 0;
13637 int offset = 0;
13638 bfd *abfd = current_program_space->exec_bfd ();
13639
13640 if (!abfd)
13641 return; /* No information to give. */
13642
13643 struct remote_state *rs = get_remote_state ();
13644
13645 strcpy (rs->buf.data (), "QTro");
13646 offset = strlen (rs->buf.data ());
13647 for (s = abfd->sections; s; s = s->next)
13648 {
13649 char tmp1[40], tmp2[40];
13650 int sec_length;
13651
13652 if ((s->flags & SEC_LOAD) == 0
13653 /* || (s->flags & SEC_CODE) == 0 */
13654 || (s->flags & SEC_READONLY) == 0)
13655 continue;
13656
13657 anysecs = 1;
13658 vma = bfd_section_vma (s);
13659 size = bfd_section_size (s);
13660 bfd_sprintf_vma (abfd, tmp1, vma);
13661 bfd_sprintf_vma (abfd, tmp2, vma + size);
13662 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13663 if (offset + sec_length + 1 > rs->buf.size ())
13664 {
13665 if (m_features.packet_support (PACKET_qXfer_traceframe_info)
13666 != PACKET_ENABLE)
13667 warning (_("\
13668 Too many sections for read-only sections definition packet."));
13669 break;
13670 }
13671 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13672 tmp1, tmp2);
13673 offset += sec_length;
13674 }
13675 if (anysecs)
13676 {
13677 putpkt (rs->buf);
13678 getpkt (&rs->buf);
13679 }
13680 }
13681
13682 void
13683 remote_target::trace_start ()
13684 {
13685 struct remote_state *rs = get_remote_state ();
13686
13687 putpkt ("QTStart");
13688 remote_get_noisy_reply ();
13689 if (rs->buf[0] == '\0')
13690 error (_("Target does not support this command."));
13691 if (strcmp (rs->buf.data (), "OK") != 0)
13692 error (_("Bogus reply from target: %s"), rs->buf.data ());
13693 }
13694
13695 int
13696 remote_target::get_trace_status (struct trace_status *ts)
13697 {
13698 /* Initialize it just to avoid a GCC false warning. */
13699 char *p = NULL;
13700 enum packet_result result;
13701 struct remote_state *rs = get_remote_state ();
13702
13703 if (m_features.packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13704 return -1;
13705
13706 /* FIXME we need to get register block size some other way. */
13707 trace_regblock_size
13708 = rs->get_remote_arch_state (current_inferior ()->arch ())->sizeof_g_packet;
13709
13710 putpkt ("qTStatus");
13711
13712 try
13713 {
13714 p = remote_get_noisy_reply ();
13715 }
13716 catch (const gdb_exception_error &ex)
13717 {
13718 if (ex.error != TARGET_CLOSE_ERROR)
13719 {
13720 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13721 return -1;
13722 }
13723 throw;
13724 }
13725
13726 result = m_features.packet_ok (p, PACKET_qTStatus);
13727
13728 /* If the remote target doesn't do tracing, flag it. */
13729 if (result == PACKET_UNKNOWN)
13730 return -1;
13731
13732 /* We're working with a live target. */
13733 ts->filename = NULL;
13734
13735 if (*p++ != 'T')
13736 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13737
13738 /* Function 'parse_trace_status' sets default value of each field of
13739 'ts' at first, so we don't have to do it here. */
13740 parse_trace_status (p, ts);
13741
13742 return ts->running;
13743 }
13744
13745 void
13746 remote_target::get_tracepoint_status (tracepoint *tp,
13747 struct uploaded_tp *utp)
13748 {
13749 struct remote_state *rs = get_remote_state ();
13750 char *reply;
13751 size_t size = get_remote_packet_size ();
13752
13753 if (tp)
13754 {
13755 tp->hit_count = 0;
13756 tp->traceframe_usage = 0;
13757 for (bp_location &loc : tp->locations ())
13758 {
13759 /* If the tracepoint was never downloaded, don't go asking for
13760 any status. */
13761 if (tp->number_on_target == 0)
13762 continue;
13763 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13764 phex_nz (loc.address, 0));
13765 putpkt (rs->buf);
13766 reply = remote_get_noisy_reply ();
13767 if (reply && *reply)
13768 {
13769 if (*reply == 'V')
13770 parse_tracepoint_status (reply + 1, tp, utp);
13771 }
13772 }
13773 }
13774 else if (utp)
13775 {
13776 utp->hit_count = 0;
13777 utp->traceframe_usage = 0;
13778 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13779 phex_nz (utp->addr, 0));
13780 putpkt (rs->buf);
13781 reply = remote_get_noisy_reply ();
13782 if (reply && *reply)
13783 {
13784 if (*reply == 'V')
13785 parse_tracepoint_status (reply + 1, tp, utp);
13786 }
13787 }
13788 }
13789
13790 void
13791 remote_target::trace_stop ()
13792 {
13793 struct remote_state *rs = get_remote_state ();
13794
13795 putpkt ("QTStop");
13796 remote_get_noisy_reply ();
13797 if (rs->buf[0] == '\0')
13798 error (_("Target does not support this command."));
13799 if (strcmp (rs->buf.data (), "OK") != 0)
13800 error (_("Bogus reply from target: %s"), rs->buf.data ());
13801 }
13802
13803 int
13804 remote_target::trace_find (enum trace_find_type type, int num,
13805 CORE_ADDR addr1, CORE_ADDR addr2,
13806 int *tpp)
13807 {
13808 struct remote_state *rs = get_remote_state ();
13809 char *endbuf = rs->buf.data () + get_remote_packet_size ();
13810 char *p, *reply;
13811 int target_frameno = -1, target_tracept = -1;
13812
13813 /* Lookups other than by absolute frame number depend on the current
13814 trace selected, so make sure it is correct on the remote end
13815 first. */
13816 if (type != tfind_number)
13817 set_remote_traceframe ();
13818
13819 p = rs->buf.data ();
13820 strcpy (p, "QTFrame:");
13821 p = strchr (p, '\0');
13822 switch (type)
13823 {
13824 case tfind_number:
13825 xsnprintf (p, endbuf - p, "%x", num);
13826 break;
13827 case tfind_pc:
13828 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13829 break;
13830 case tfind_tp:
13831 xsnprintf (p, endbuf - p, "tdp:%x", num);
13832 break;
13833 case tfind_range:
13834 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13835 phex_nz (addr2, 0));
13836 break;
13837 case tfind_outside:
13838 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13839 phex_nz (addr2, 0));
13840 break;
13841 default:
13842 error (_("Unknown trace find type %d"), type);
13843 }
13844
13845 putpkt (rs->buf);
13846 reply = remote_get_noisy_reply ();
13847 if (*reply == '\0')
13848 error (_("Target does not support this command."));
13849
13850 while (reply && *reply)
13851 switch (*reply)
13852 {
13853 case 'F':
13854 p = ++reply;
13855 target_frameno = (int) strtol (p, &reply, 16);
13856 if (reply == p)
13857 error (_("Unable to parse trace frame number"));
13858 /* Don't update our remote traceframe number cache on failure
13859 to select a remote traceframe. */
13860 if (target_frameno == -1)
13861 return -1;
13862 break;
13863 case 'T':
13864 p = ++reply;
13865 target_tracept = (int) strtol (p, &reply, 16);
13866 if (reply == p)
13867 error (_("Unable to parse tracepoint number"));
13868 break;
13869 case 'O': /* "OK"? */
13870 if (reply[1] == 'K' && reply[2] == '\0')
13871 reply += 2;
13872 else
13873 error (_("Bogus reply from target: %s"), reply);
13874 break;
13875 default:
13876 error (_("Bogus reply from target: %s"), reply);
13877 }
13878 if (tpp)
13879 *tpp = target_tracept;
13880
13881 rs->remote_traceframe_number = target_frameno;
13882 return target_frameno;
13883 }
13884
13885 bool
13886 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13887 {
13888 struct remote_state *rs = get_remote_state ();
13889 char *reply;
13890 ULONGEST uval;
13891
13892 set_remote_traceframe ();
13893
13894 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
13895 putpkt (rs->buf);
13896 reply = remote_get_noisy_reply ();
13897 if (reply && *reply)
13898 {
13899 if (*reply == 'V')
13900 {
13901 unpack_varlen_hex (reply + 1, &uval);
13902 *val = (LONGEST) uval;
13903 return true;
13904 }
13905 }
13906 return false;
13907 }
13908
13909 int
13910 remote_target::save_trace_data (const char *filename)
13911 {
13912 struct remote_state *rs = get_remote_state ();
13913 char *p, *reply;
13914
13915 p = rs->buf.data ();
13916 strcpy (p, "QTSave:");
13917 p += strlen (p);
13918 if ((p - rs->buf.data ()) + strlen (filename) * 2
13919 >= get_remote_packet_size ())
13920 error (_("Remote file name too long for trace save packet"));
13921 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13922 *p++ = '\0';
13923 putpkt (rs->buf);
13924 reply = remote_get_noisy_reply ();
13925 if (*reply == '\0')
13926 error (_("Target does not support this command."));
13927 if (strcmp (reply, "OK") != 0)
13928 error (_("Bogus reply from target: %s"), reply);
13929 return 0;
13930 }
13931
13932 /* This is basically a memory transfer, but needs to be its own packet
13933 because we don't know how the target actually organizes its trace
13934 memory, plus we want to be able to ask for as much as possible, but
13935 not be unhappy if we don't get as much as we ask for. */
13936
13937 LONGEST
13938 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13939 {
13940 struct remote_state *rs = get_remote_state ();
13941 char *reply;
13942 char *p;
13943 int rslt;
13944
13945 p = rs->buf.data ();
13946 strcpy (p, "qTBuffer:");
13947 p += strlen (p);
13948 p += hexnumstr (p, offset);
13949 *p++ = ',';
13950 p += hexnumstr (p, len);
13951 *p++ = '\0';
13952
13953 putpkt (rs->buf);
13954 reply = remote_get_noisy_reply ();
13955 if (reply && *reply)
13956 {
13957 /* 'l' by itself means we're at the end of the buffer and
13958 there is nothing more to get. */
13959 if (*reply == 'l')
13960 return 0;
13961
13962 /* Convert the reply into binary. Limit the number of bytes to
13963 convert according to our passed-in buffer size, rather than
13964 what was returned in the packet; if the target is
13965 unexpectedly generous and gives us a bigger reply than we
13966 asked for, we don't want to crash. */
13967 rslt = hex2bin (reply, buf, len);
13968 return rslt;
13969 }
13970
13971 /* Something went wrong, flag as an error. */
13972 return -1;
13973 }
13974
13975 void
13976 remote_target::set_disconnected_tracing (int val)
13977 {
13978 struct remote_state *rs = get_remote_state ();
13979
13980 if (m_features.packet_support (PACKET_DisconnectedTracing_feature)
13981 == PACKET_ENABLE)
13982 {
13983 char *reply;
13984
13985 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13986 "QTDisconnected:%x", val);
13987 putpkt (rs->buf);
13988 reply = remote_get_noisy_reply ();
13989 if (*reply == '\0')
13990 error (_("Target does not support this command."));
13991 if (strcmp (reply, "OK") != 0)
13992 error (_("Bogus reply from target: %s"), reply);
13993 }
13994 else if (val)
13995 warning (_("Target does not support disconnected tracing."));
13996 }
13997
13998 int
13999 remote_target::core_of_thread (ptid_t ptid)
14000 {
14001 thread_info *info = this->find_thread (ptid);
14002
14003 if (info != NULL && info->priv != NULL)
14004 return get_remote_thread_info (info)->core;
14005
14006 return -1;
14007 }
14008
14009 void
14010 remote_target::set_circular_trace_buffer (int val)
14011 {
14012 struct remote_state *rs = get_remote_state ();
14013 char *reply;
14014
14015 xsnprintf (rs->buf.data (), get_remote_packet_size (),
14016 "QTBuffer:circular:%x", val);
14017 putpkt (rs->buf);
14018 reply = remote_get_noisy_reply ();
14019 if (*reply == '\0')
14020 error (_("Target does not support this command."));
14021 if (strcmp (reply, "OK") != 0)
14022 error (_("Bogus reply from target: %s"), reply);
14023 }
14024
14025 traceframe_info_up
14026 remote_target::traceframe_info ()
14027 {
14028 gdb::optional<gdb::char_vector> text
14029 = target_read_stralloc (current_inferior ()->top_target (),
14030 TARGET_OBJECT_TRACEFRAME_INFO,
14031 NULL);
14032 if (text)
14033 return parse_traceframe_info (text->data ());
14034
14035 return NULL;
14036 }
14037
14038 /* Handle the qTMinFTPILen packet. Returns the minimum length of
14039 instruction on which a fast tracepoint may be placed. Returns -1
14040 if the packet is not supported, and 0 if the minimum instruction
14041 length is unknown. */
14042
14043 int
14044 remote_target::get_min_fast_tracepoint_insn_len ()
14045 {
14046 struct remote_state *rs = get_remote_state ();
14047 char *reply;
14048
14049 /* If we're not debugging a process yet, the IPA can't be
14050 loaded. */
14051 if (!target_has_execution ())
14052 return 0;
14053
14054 /* Make sure the remote is pointing at the right process. */
14055 set_general_process ();
14056
14057 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
14058 putpkt (rs->buf);
14059 reply = remote_get_noisy_reply ();
14060 if (*reply == '\0')
14061 return -1;
14062 else
14063 {
14064 ULONGEST min_insn_len;
14065
14066 unpack_varlen_hex (reply, &min_insn_len);
14067
14068 return (int) min_insn_len;
14069 }
14070 }
14071
14072 void
14073 remote_target::set_trace_buffer_size (LONGEST val)
14074 {
14075 if (m_features.packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
14076 {
14077 struct remote_state *rs = get_remote_state ();
14078 char *buf = rs->buf.data ();
14079 char *endbuf = buf + get_remote_packet_size ();
14080 enum packet_result result;
14081
14082 gdb_assert (val >= 0 || val == -1);
14083 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
14084 /* Send -1 as literal "-1" to avoid host size dependency. */
14085 if (val < 0)
14086 {
14087 *buf++ = '-';
14088 buf += hexnumstr (buf, (ULONGEST) -val);
14089 }
14090 else
14091 buf += hexnumstr (buf, (ULONGEST) val);
14092
14093 putpkt (rs->buf);
14094 remote_get_noisy_reply ();
14095 result = m_features.packet_ok (rs->buf, PACKET_QTBuffer_size);
14096
14097 if (result != PACKET_OK)
14098 warning (_("Bogus reply from target: %s"), rs->buf.data ());
14099 }
14100 }
14101
14102 bool
14103 remote_target::set_trace_notes (const char *user, const char *notes,
14104 const char *stop_notes)
14105 {
14106 struct remote_state *rs = get_remote_state ();
14107 char *reply;
14108 char *buf = rs->buf.data ();
14109 char *endbuf = buf + get_remote_packet_size ();
14110 int nbytes;
14111
14112 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
14113 if (user)
14114 {
14115 buf += xsnprintf (buf, endbuf - buf, "user:");
14116 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
14117 buf += 2 * nbytes;
14118 *buf++ = ';';
14119 }
14120 if (notes)
14121 {
14122 buf += xsnprintf (buf, endbuf - buf, "notes:");
14123 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
14124 buf += 2 * nbytes;
14125 *buf++ = ';';
14126 }
14127 if (stop_notes)
14128 {
14129 buf += xsnprintf (buf, endbuf - buf, "tstop:");
14130 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
14131 buf += 2 * nbytes;
14132 *buf++ = ';';
14133 }
14134 /* Ensure the buffer is terminated. */
14135 *buf = '\0';
14136
14137 putpkt (rs->buf);
14138 reply = remote_get_noisy_reply ();
14139 if (*reply == '\0')
14140 return false;
14141
14142 if (strcmp (reply, "OK") != 0)
14143 error (_("Bogus reply from target: %s"), reply);
14144
14145 return true;
14146 }
14147
14148 bool
14149 remote_target::use_agent (bool use)
14150 {
14151 if (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE)
14152 {
14153 struct remote_state *rs = get_remote_state ();
14154
14155 /* If the stub supports QAgent. */
14156 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
14157 putpkt (rs->buf);
14158 getpkt (&rs->buf);
14159
14160 if (strcmp (rs->buf.data (), "OK") == 0)
14161 {
14162 ::use_agent = use;
14163 return true;
14164 }
14165 }
14166
14167 return false;
14168 }
14169
14170 bool
14171 remote_target::can_use_agent ()
14172 {
14173 return (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE);
14174 }
14175
14176 #if defined (HAVE_LIBEXPAT)
14177
14178 /* Check the btrace document version. */
14179
14180 static void
14181 check_xml_btrace_version (struct gdb_xml_parser *parser,
14182 const struct gdb_xml_element *element,
14183 void *user_data,
14184 std::vector<gdb_xml_value> &attributes)
14185 {
14186 const char *version
14187 = (const char *) xml_find_attribute (attributes, "version")->value.get ();
14188
14189 if (strcmp (version, "1.0") != 0)
14190 gdb_xml_error (parser, _("Unsupported btrace version: \"%s\""), version);
14191 }
14192
14193 /* Parse a btrace "block" xml record. */
14194
14195 static void
14196 parse_xml_btrace_block (struct gdb_xml_parser *parser,
14197 const struct gdb_xml_element *element,
14198 void *user_data,
14199 std::vector<gdb_xml_value> &attributes)
14200 {
14201 struct btrace_data *btrace;
14202 ULONGEST *begin, *end;
14203
14204 btrace = (struct btrace_data *) user_data;
14205
14206 switch (btrace->format)
14207 {
14208 case BTRACE_FORMAT_BTS:
14209 break;
14210
14211 case BTRACE_FORMAT_NONE:
14212 btrace->format = BTRACE_FORMAT_BTS;
14213 btrace->variant.bts.blocks = new std::vector<btrace_block>;
14214 break;
14215
14216 default:
14217 gdb_xml_error (parser, _("Btrace format error."));
14218 }
14219
14220 begin = (ULONGEST *) xml_find_attribute (attributes, "begin")->value.get ();
14221 end = (ULONGEST *) xml_find_attribute (attributes, "end")->value.get ();
14222 btrace->variant.bts.blocks->emplace_back (*begin, *end);
14223 }
14224
14225 /* Parse a "raw" xml record. */
14226
14227 static void
14228 parse_xml_raw (struct gdb_xml_parser *parser, const char *body_text,
14229 gdb_byte **pdata, size_t *psize)
14230 {
14231 gdb_byte *bin;
14232 size_t len, size;
14233
14234 len = strlen (body_text);
14235 if (len % 2 != 0)
14236 gdb_xml_error (parser, _("Bad raw data size."));
14237
14238 size = len / 2;
14239
14240 gdb::unique_xmalloc_ptr<gdb_byte> data ((gdb_byte *) xmalloc (size));
14241 bin = data.get ();
14242
14243 /* We use hex encoding - see gdbsupport/rsp-low.h. */
14244 while (len > 0)
14245 {
14246 char hi, lo;
14247
14248 hi = *body_text++;
14249 lo = *body_text++;
14250
14251 if (hi == 0 || lo == 0)
14252 gdb_xml_error (parser, _("Bad hex encoding."));
14253
14254 *bin++ = fromhex (hi) * 16 + fromhex (lo);
14255 len -= 2;
14256 }
14257
14258 *pdata = data.release ();
14259 *psize = size;
14260 }
14261
14262 /* Parse a btrace pt-config "cpu" xml record. */
14263
14264 static void
14265 parse_xml_btrace_pt_config_cpu (struct gdb_xml_parser *parser,
14266 const struct gdb_xml_element *element,
14267 void *user_data,
14268 std::vector<gdb_xml_value> &attributes)
14269 {
14270 struct btrace_data *btrace;
14271 const char *vendor;
14272 ULONGEST *family, *model, *stepping;
14273
14274 vendor
14275 = (const char *) xml_find_attribute (attributes, "vendor")->value.get ();
14276 family
14277 = (ULONGEST *) xml_find_attribute (attributes, "family")->value.get ();
14278 model
14279 = (ULONGEST *) xml_find_attribute (attributes, "model")->value.get ();
14280 stepping
14281 = (ULONGEST *) xml_find_attribute (attributes, "stepping")->value.get ();
14282
14283 btrace = (struct btrace_data *) user_data;
14284
14285 if (strcmp (vendor, "GenuineIntel") == 0)
14286 btrace->variant.pt.config.cpu.vendor = CV_INTEL;
14287
14288 btrace->variant.pt.config.cpu.family = *family;
14289 btrace->variant.pt.config.cpu.model = *model;
14290 btrace->variant.pt.config.cpu.stepping = *stepping;
14291 }
14292
14293 /* Parse a btrace pt "raw" xml record. */
14294
14295 static void
14296 parse_xml_btrace_pt_raw (struct gdb_xml_parser *parser,
14297 const struct gdb_xml_element *element,
14298 void *user_data, const char *body_text)
14299 {
14300 struct btrace_data *btrace;
14301
14302 btrace = (struct btrace_data *) user_data;
14303 parse_xml_raw (parser, body_text, &btrace->variant.pt.data,
14304 &btrace->variant.pt.size);
14305 }
14306
14307 /* Parse a btrace "pt" xml record. */
14308
14309 static void
14310 parse_xml_btrace_pt (struct gdb_xml_parser *parser,
14311 const struct gdb_xml_element *element,
14312 void *user_data,
14313 std::vector<gdb_xml_value> &attributes)
14314 {
14315 struct btrace_data *btrace;
14316
14317 btrace = (struct btrace_data *) user_data;
14318 btrace->format = BTRACE_FORMAT_PT;
14319 btrace->variant.pt.config.cpu.vendor = CV_UNKNOWN;
14320 btrace->variant.pt.data = NULL;
14321 btrace->variant.pt.size = 0;
14322 }
14323
14324 static const struct gdb_xml_attribute block_attributes[] = {
14325 { "begin", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14326 { "end", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14327 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14328 };
14329
14330 static const struct gdb_xml_attribute btrace_pt_config_cpu_attributes[] = {
14331 { "vendor", GDB_XML_AF_NONE, NULL, NULL },
14332 { "family", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14333 { "model", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14334 { "stepping", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14335 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14336 };
14337
14338 static const struct gdb_xml_element btrace_pt_config_children[] = {
14339 { "cpu", btrace_pt_config_cpu_attributes, NULL, GDB_XML_EF_OPTIONAL,
14340 parse_xml_btrace_pt_config_cpu, NULL },
14341 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14342 };
14343
14344 static const struct gdb_xml_element btrace_pt_children[] = {
14345 { "pt-config", NULL, btrace_pt_config_children, GDB_XML_EF_OPTIONAL, NULL,
14346 NULL },
14347 { "raw", NULL, NULL, GDB_XML_EF_OPTIONAL, NULL, parse_xml_btrace_pt_raw },
14348 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14349 };
14350
14351 static const struct gdb_xml_attribute btrace_attributes[] = {
14352 { "version", GDB_XML_AF_NONE, NULL, NULL },
14353 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14354 };
14355
14356 static const struct gdb_xml_element btrace_children[] = {
14357 { "block", block_attributes, NULL,
14358 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL, parse_xml_btrace_block, NULL },
14359 { "pt", NULL, btrace_pt_children, GDB_XML_EF_OPTIONAL, parse_xml_btrace_pt,
14360 NULL },
14361 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14362 };
14363
14364 static const struct gdb_xml_element btrace_elements[] = {
14365 { "btrace", btrace_attributes, btrace_children, GDB_XML_EF_NONE,
14366 check_xml_btrace_version, NULL },
14367 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14368 };
14369
14370 #endif /* defined (HAVE_LIBEXPAT) */
14371
14372 /* Parse a branch trace xml document XML into DATA. */
14373
14374 static void
14375 parse_xml_btrace (struct btrace_data *btrace, const char *buffer)
14376 {
14377 #if defined (HAVE_LIBEXPAT)
14378
14379 int errcode;
14380 btrace_data result;
14381 result.format = BTRACE_FORMAT_NONE;
14382
14383 errcode = gdb_xml_parse_quick (_("btrace"), "btrace.dtd", btrace_elements,
14384 buffer, &result);
14385 if (errcode != 0)
14386 error (_("Error parsing branch trace."));
14387
14388 /* Keep parse results. */
14389 *btrace = std::move (result);
14390
14391 #else /* !defined (HAVE_LIBEXPAT) */
14392
14393 error (_("Cannot process branch trace. XML support was disabled at "
14394 "compile time."));
14395
14396 #endif /* !defined (HAVE_LIBEXPAT) */
14397 }
14398
14399 #if defined (HAVE_LIBEXPAT)
14400
14401 /* Parse a btrace-conf "bts" xml record. */
14402
14403 static void
14404 parse_xml_btrace_conf_bts (struct gdb_xml_parser *parser,
14405 const struct gdb_xml_element *element,
14406 void *user_data,
14407 std::vector<gdb_xml_value> &attributes)
14408 {
14409 struct btrace_config *conf;
14410 struct gdb_xml_value *size;
14411
14412 conf = (struct btrace_config *) user_data;
14413 conf->format = BTRACE_FORMAT_BTS;
14414 conf->bts.size = 0;
14415
14416 size = xml_find_attribute (attributes, "size");
14417 if (size != NULL)
14418 conf->bts.size = (unsigned int) *(ULONGEST *) size->value.get ();
14419 }
14420
14421 /* Parse a btrace-conf "pt" xml record. */
14422
14423 static void
14424 parse_xml_btrace_conf_pt (struct gdb_xml_parser *parser,
14425 const struct gdb_xml_element *element,
14426 void *user_data,
14427 std::vector<gdb_xml_value> &attributes)
14428 {
14429 struct btrace_config *conf;
14430 struct gdb_xml_value *size;
14431
14432 conf = (struct btrace_config *) user_data;
14433 conf->format = BTRACE_FORMAT_PT;
14434 conf->pt.size = 0;
14435
14436 size = xml_find_attribute (attributes, "size");
14437 if (size != NULL)
14438 conf->pt.size = (unsigned int) *(ULONGEST *) size->value.get ();
14439 }
14440
14441 static const struct gdb_xml_attribute btrace_conf_pt_attributes[] = {
14442 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14443 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14444 };
14445
14446 static const struct gdb_xml_attribute btrace_conf_bts_attributes[] = {
14447 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14448 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14449 };
14450
14451 static const struct gdb_xml_element btrace_conf_children[] = {
14452 { "bts", btrace_conf_bts_attributes, NULL, GDB_XML_EF_OPTIONAL,
14453 parse_xml_btrace_conf_bts, NULL },
14454 { "pt", btrace_conf_pt_attributes, NULL, GDB_XML_EF_OPTIONAL,
14455 parse_xml_btrace_conf_pt, NULL },
14456 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14457 };
14458
14459 static const struct gdb_xml_attribute btrace_conf_attributes[] = {
14460 { "version", GDB_XML_AF_NONE, NULL, NULL },
14461 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14462 };
14463
14464 static const struct gdb_xml_element btrace_conf_elements[] = {
14465 { "btrace-conf", btrace_conf_attributes, btrace_conf_children,
14466 GDB_XML_EF_NONE, NULL, NULL },
14467 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14468 };
14469
14470 #endif /* defined (HAVE_LIBEXPAT) */
14471
14472 /* Parse a branch trace configuration xml document XML into CONF. */
14473
14474 static void
14475 parse_xml_btrace_conf (struct btrace_config *conf, const char *xml)
14476 {
14477 #if defined (HAVE_LIBEXPAT)
14478
14479 int errcode;
14480 errcode = gdb_xml_parse_quick (_("btrace-conf"), "btrace-conf.dtd",
14481 btrace_conf_elements, xml, conf);
14482 if (errcode != 0)
14483 error (_("Error parsing branch trace configuration."));
14484
14485 #else /* !defined (HAVE_LIBEXPAT) */
14486
14487 error (_("Cannot process the branch trace configuration. XML support "
14488 "was disabled at compile time."));
14489
14490 #endif /* !defined (HAVE_LIBEXPAT) */
14491 }
14492
14493 /* Reset our idea of our target's btrace configuration. */
14494
14495 static void
14496 remote_btrace_reset (remote_state *rs)
14497 {
14498 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14499 }
14500
14501 /* Synchronize the configuration with the target. */
14502
14503 void
14504 remote_target::btrace_sync_conf (const btrace_config *conf)
14505 {
14506 struct remote_state *rs;
14507 char *buf, *pos, *endbuf;
14508
14509 rs = get_remote_state ();
14510 buf = rs->buf.data ();
14511 endbuf = buf + get_remote_packet_size ();
14512
14513 if (m_features.packet_support (PACKET_Qbtrace_conf_bts_size) == PACKET_ENABLE
14514 && conf->bts.size != rs->btrace_config.bts.size)
14515 {
14516 pos = buf;
14517 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14518 packets_descriptions[PACKET_Qbtrace_conf_bts_size].name,
14519 conf->bts.size);
14520
14521 putpkt (buf);
14522 getpkt (&rs->buf);
14523
14524 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_bts_size)
14525 == PACKET_ERROR)
14526 {
14527 if (buf[0] == 'E' && buf[1] == '.')
14528 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14529 else
14530 error (_("Failed to configure the BTS buffer size."));
14531 }
14532
14533 rs->btrace_config.bts.size = conf->bts.size;
14534 }
14535
14536 if (m_features.packet_support (PACKET_Qbtrace_conf_pt_size) == PACKET_ENABLE
14537 && conf->pt.size != rs->btrace_config.pt.size)
14538 {
14539 pos = buf;
14540 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14541 packets_descriptions[PACKET_Qbtrace_conf_pt_size].name,
14542 conf->pt.size);
14543
14544 putpkt (buf);
14545 getpkt (&rs->buf);
14546
14547 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_size)
14548 == PACKET_ERROR)
14549 {
14550 if (buf[0] == 'E' && buf[1] == '.')
14551 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14552 else
14553 error (_("Failed to configure the trace buffer size."));
14554 }
14555
14556 rs->btrace_config.pt.size = conf->pt.size;
14557 }
14558 }
14559
14560 /* Read TP's btrace configuration from the target and store it into CONF. */
14561
14562 static void
14563 btrace_read_config (thread_info *tp, btrace_config *conf)
14564 {
14565 /* target_read_stralloc relies on INFERIOR_PTID. */
14566 scoped_restore_current_thread restore_thread;
14567 switch_to_thread (tp);
14568
14569 gdb::optional<gdb::char_vector> xml
14570 = target_read_stralloc (current_inferior ()->top_target (),
14571 TARGET_OBJECT_BTRACE_CONF, "");
14572 if (xml)
14573 parse_xml_btrace_conf (conf, xml->data ());
14574 }
14575
14576 /* Maybe reopen target btrace. */
14577
14578 void
14579 remote_target::remote_btrace_maybe_reopen ()
14580 {
14581 struct remote_state *rs = get_remote_state ();
14582 int btrace_target_pushed = 0;
14583 #if !defined (HAVE_LIBIPT)
14584 int warned = 0;
14585 #endif
14586
14587 /* Don't bother walking the entirety of the remote thread list when
14588 we know the feature isn't supported by the remote. */
14589 if (m_features.packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14590 return;
14591
14592 for (thread_info *tp : all_non_exited_threads (this))
14593 {
14594 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14595 btrace_read_config (tp, &rs->btrace_config);
14596
14597 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14598 continue;
14599
14600 #if !defined (HAVE_LIBIPT)
14601 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14602 {
14603 if (!warned)
14604 {
14605 warned = 1;
14606 warning (_("Target is recording using Intel Processor Trace "
14607 "but support was disabled at compile time."));
14608 }
14609
14610 continue;
14611 }
14612 #endif /* !defined (HAVE_LIBIPT) */
14613
14614 /* Push target, once, but before anything else happens. This way our
14615 changes to the threads will be cleaned up by unpushing the target
14616 in case btrace_read_config () throws. */
14617 if (!btrace_target_pushed)
14618 {
14619 btrace_target_pushed = 1;
14620 record_btrace_push_target ();
14621 gdb_printf (_("Target is recording using %s.\n"),
14622 btrace_format_string (rs->btrace_config.format));
14623 }
14624
14625 tp->btrace.target
14626 = new btrace_target_info { tp->ptid, rs->btrace_config };
14627 }
14628 }
14629
14630 /* Enable branch tracing. */
14631
14632 struct btrace_target_info *
14633 remote_target::enable_btrace (thread_info *tp,
14634 const struct btrace_config *conf)
14635 {
14636 struct packet_config *packet = NULL;
14637 struct remote_state *rs = get_remote_state ();
14638 char *buf = rs->buf.data ();
14639 char *endbuf = buf + get_remote_packet_size ();
14640
14641 unsigned int which_packet;
14642 switch (conf->format)
14643 {
14644 case BTRACE_FORMAT_BTS:
14645 which_packet = PACKET_Qbtrace_bts;
14646 break;
14647 case BTRACE_FORMAT_PT:
14648 which_packet = PACKET_Qbtrace_pt;
14649 break;
14650 default:
14651 internal_error (_("Bad branch btrace format: %u."),
14652 (unsigned int) conf->format);
14653 }
14654
14655 packet = &m_features.m_protocol_packets[which_packet];
14656 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14657 error (_("Target does not support branch tracing."));
14658
14659 btrace_sync_conf (conf);
14660
14661 ptid_t ptid = tp->ptid;
14662 set_general_thread (ptid);
14663
14664 buf += xsnprintf (buf, endbuf - buf, "%s",
14665 packets_descriptions[which_packet].name);
14666 putpkt (rs->buf);
14667 getpkt (&rs->buf);
14668
14669 if (m_features.packet_ok (rs->buf, which_packet) == PACKET_ERROR)
14670 {
14671 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14672 error (_("Could not enable branch tracing for %s: %s"),
14673 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14674 else
14675 error (_("Could not enable branch tracing for %s."),
14676 target_pid_to_str (ptid).c_str ());
14677 }
14678
14679 btrace_target_info *tinfo = new btrace_target_info { ptid };
14680
14681 /* If we fail to read the configuration, we lose some information, but the
14682 tracing itself is not impacted. */
14683 try
14684 {
14685 btrace_read_config (tp, &tinfo->conf);
14686 }
14687 catch (const gdb_exception_error &err)
14688 {
14689 if (err.message != NULL)
14690 warning ("%s", err.what ());
14691 }
14692
14693 return tinfo;
14694 }
14695
14696 /* Disable branch tracing. */
14697
14698 void
14699 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14700 {
14701 struct remote_state *rs = get_remote_state ();
14702 char *buf = rs->buf.data ();
14703 char *endbuf = buf + get_remote_packet_size ();
14704
14705 if (m_features.packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
14706 error (_("Target does not support branch tracing."));
14707
14708 set_general_thread (tinfo->ptid);
14709
14710 buf += xsnprintf (buf, endbuf - buf, "%s",
14711 packets_descriptions[PACKET_Qbtrace_off].name);
14712 putpkt (rs->buf);
14713 getpkt (&rs->buf);
14714
14715 if (m_features.packet_ok (rs->buf, PACKET_Qbtrace_off) == PACKET_ERROR)
14716 {
14717 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14718 error (_("Could not disable branch tracing for %s: %s"),
14719 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14720 else
14721 error (_("Could not disable branch tracing for %s."),
14722 target_pid_to_str (tinfo->ptid).c_str ());
14723 }
14724
14725 delete tinfo;
14726 }
14727
14728 /* Teardown branch tracing. */
14729
14730 void
14731 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14732 {
14733 /* We must not talk to the target during teardown. */
14734 delete tinfo;
14735 }
14736
14737 /* Read the branch trace. */
14738
14739 enum btrace_error
14740 remote_target::read_btrace (struct btrace_data *btrace,
14741 struct btrace_target_info *tinfo,
14742 enum btrace_read_type type)
14743 {
14744 const char *annex;
14745
14746 if (m_features.packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
14747 error (_("Target does not support branch tracing."));
14748
14749 #if !defined(HAVE_LIBEXPAT)
14750 error (_("Cannot process branch tracing result. XML parsing not supported."));
14751 #endif
14752
14753 switch (type)
14754 {
14755 case BTRACE_READ_ALL:
14756 annex = "all";
14757 break;
14758 case BTRACE_READ_NEW:
14759 annex = "new";
14760 break;
14761 case BTRACE_READ_DELTA:
14762 annex = "delta";
14763 break;
14764 default:
14765 internal_error (_("Bad branch tracing read type: %u."),
14766 (unsigned int) type);
14767 }
14768
14769 gdb::optional<gdb::char_vector> xml
14770 = target_read_stralloc (current_inferior ()->top_target (),
14771 TARGET_OBJECT_BTRACE, annex);
14772 if (!xml)
14773 return BTRACE_ERR_UNKNOWN;
14774
14775 parse_xml_btrace (btrace, xml->data ());
14776
14777 return BTRACE_ERR_NONE;
14778 }
14779
14780 const struct btrace_config *
14781 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14782 {
14783 return &tinfo->conf;
14784 }
14785
14786 bool
14787 remote_target::augmented_libraries_svr4_read ()
14788 {
14789 return
14790 (m_features.packet_support (PACKET_augmented_libraries_svr4_read_feature)
14791 == PACKET_ENABLE);
14792 }
14793
14794 /* Implementation of to_load. */
14795
14796 void
14797 remote_target::load (const char *name, int from_tty)
14798 {
14799 generic_load (name, from_tty);
14800 }
14801
14802 /* Accepts an integer PID; returns a string representing a file that
14803 can be opened on the remote side to get the symbols for the child
14804 process. Returns NULL if the operation is not supported. */
14805
14806 const char *
14807 remote_target::pid_to_exec_file (int pid)
14808 {
14809 static gdb::optional<gdb::char_vector> filename;
14810 char *annex = NULL;
14811
14812 if (m_features.packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14813 return NULL;
14814
14815 inferior *inf = find_inferior_pid (this, pid);
14816 if (inf == NULL)
14817 internal_error (_("not currently attached to process %d"), pid);
14818
14819 if (!inf->fake_pid_p)
14820 {
14821 const int annex_size = 9;
14822
14823 annex = (char *) alloca (annex_size);
14824 xsnprintf (annex, annex_size, "%x", pid);
14825 }
14826
14827 filename = target_read_stralloc (current_inferior ()->top_target (),
14828 TARGET_OBJECT_EXEC_FILE, annex);
14829
14830 return filename ? filename->data () : nullptr;
14831 }
14832
14833 /* Implement the to_can_do_single_step target_ops method. */
14834
14835 int
14836 remote_target::can_do_single_step ()
14837 {
14838 /* We can only tell whether target supports single step or not by
14839 supported s and S vCont actions if the stub supports vContSupported
14840 feature. If the stub doesn't support vContSupported feature,
14841 we have conservatively to think target doesn't supports single
14842 step. */
14843 if (m_features.packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14844 {
14845 struct remote_state *rs = get_remote_state ();
14846
14847 return rs->supports_vCont.s && rs->supports_vCont.S;
14848 }
14849 else
14850 return 0;
14851 }
14852
14853 /* Implementation of the to_execution_direction method for the remote
14854 target. */
14855
14856 enum exec_direction_kind
14857 remote_target::execution_direction ()
14858 {
14859 struct remote_state *rs = get_remote_state ();
14860
14861 return rs->last_resume_exec_dir;
14862 }
14863
14864 /* Return pointer to the thread_info struct which corresponds to
14865 THREAD_HANDLE (having length HANDLE_LEN). */
14866
14867 thread_info *
14868 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14869 int handle_len,
14870 inferior *inf)
14871 {
14872 for (thread_info *tp : all_non_exited_threads (this))
14873 {
14874 remote_thread_info *priv = get_remote_thread_info (tp);
14875
14876 if (tp->inf == inf && priv != NULL)
14877 {
14878 if (handle_len != priv->thread_handle.size ())
14879 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14880 handle_len, priv->thread_handle.size ());
14881 if (memcmp (thread_handle, priv->thread_handle.data (),
14882 handle_len) == 0)
14883 return tp;
14884 }
14885 }
14886
14887 return NULL;
14888 }
14889
14890 gdb::array_view<const gdb_byte>
14891 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14892 {
14893 remote_thread_info *priv = get_remote_thread_info (tp);
14894 return priv->thread_handle;
14895 }
14896
14897 bool
14898 remote_target::can_async_p ()
14899 {
14900 /* This flag should be checked in the common target.c code. */
14901 gdb_assert (target_async_permitted);
14902
14903 /* We're async whenever the serial device can. */
14904 return get_remote_state ()->can_async_p ();
14905 }
14906
14907 bool
14908 remote_target::is_async_p ()
14909 {
14910 /* We're async whenever the serial device is. */
14911 return get_remote_state ()->is_async_p ();
14912 }
14913
14914 /* Pass the SERIAL event on and up to the client. One day this code
14915 will be able to delay notifying the client of an event until the
14916 point where an entire packet has been received. */
14917
14918 static serial_event_ftype remote_async_serial_handler;
14919
14920 static void
14921 remote_async_serial_handler (struct serial *scb, void *context)
14922 {
14923 /* Don't propogate error information up to the client. Instead let
14924 the client find out about the error by querying the target. */
14925 inferior_event_handler (INF_REG_EVENT);
14926 }
14927
14928 int
14929 remote_target::async_wait_fd ()
14930 {
14931 struct remote_state *rs = get_remote_state ();
14932 return rs->remote_desc->fd;
14933 }
14934
14935 void
14936 remote_target::async (bool enable)
14937 {
14938 struct remote_state *rs = get_remote_state ();
14939
14940 if (enable)
14941 {
14942 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14943
14944 /* If there are pending events in the stop reply queue tell the
14945 event loop to process them. */
14946 if (!rs->stop_reply_queue.empty ())
14947 rs->mark_async_event_handler ();
14948
14949 /* For simplicity, below we clear the pending events token
14950 without remembering whether it is marked, so here we always
14951 mark it. If there's actually no pending notification to
14952 process, this ends up being a no-op (other than a spurious
14953 event-loop wakeup). */
14954 if (target_is_non_stop_p ())
14955 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14956 }
14957 else
14958 {
14959 serial_async (rs->remote_desc, NULL, NULL);
14960 /* If the core is disabling async, it doesn't want to be
14961 disturbed with target events. Clear all async event sources
14962 too. */
14963 rs->clear_async_event_handler ();
14964
14965 if (target_is_non_stop_p ())
14966 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14967 }
14968 }
14969
14970 /* Implementation of the to_thread_events method. */
14971
14972 void
14973 remote_target::thread_events (int enable)
14974 {
14975 struct remote_state *rs = get_remote_state ();
14976 size_t size = get_remote_packet_size ();
14977
14978 if (m_features.packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14979 return;
14980
14981 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
14982 putpkt (rs->buf);
14983 getpkt (&rs->buf);
14984
14985 switch (m_features.packet_ok (rs->buf, PACKET_QThreadEvents))
14986 {
14987 case PACKET_OK:
14988 if (strcmp (rs->buf.data (), "OK") != 0)
14989 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
14990 break;
14991 case PACKET_ERROR:
14992 warning (_("Remote failure reply: %s"), rs->buf.data ());
14993 break;
14994 case PACKET_UNKNOWN:
14995 break;
14996 }
14997 }
14998
14999 static void
15000 show_remote_cmd (const char *args, int from_tty)
15001 {
15002 /* We can't just use cmd_show_list here, because we want to skip
15003 the redundant "show remote Z-packet" and the legacy aliases. */
15004 struct cmd_list_element *list = remote_show_cmdlist;
15005 struct ui_out *uiout = current_uiout;
15006
15007 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
15008 for (; list != NULL; list = list->next)
15009 if (strcmp (list->name, "Z-packet") == 0)
15010 continue;
15011 else if (list->type == not_set_cmd)
15012 /* Alias commands are exactly like the original, except they
15013 don't have the normal type. */
15014 continue;
15015 else
15016 {
15017 ui_out_emit_tuple option_emitter (uiout, "option");
15018
15019 uiout->field_string ("name", list->name);
15020 uiout->text (": ");
15021 if (list->type == show_cmd)
15022 do_show_command (NULL, from_tty, list);
15023 else
15024 cmd_func (list, NULL, from_tty);
15025 }
15026 }
15027
15028 /* Some change happened in PSPACE's objfile list (obfiles added or removed),
15029 offer all inferiors using that program space a change to look up symbols. */
15030
15031 static void
15032 remote_objfile_changed_check_symbols (program_space *pspace)
15033 {
15034 /* The affected program space is possibly shared by multiple inferiors.
15035 Consider sending a qSymbol packet for each of the inferiors using that
15036 program space. */
15037 for (inferior *inf : all_inferiors ())
15038 {
15039 if (inf->pspace != pspace)
15040 continue;
15041
15042 /* Check whether the inferior's process target is a remote target. */
15043 remote_target *remote = as_remote_target (inf->process_target ());
15044 if (remote == nullptr)
15045 continue;
15046
15047 /* When we are attaching or handling a fork child and the shared library
15048 subsystem reads the list of loaded libraries, we receive new objfile
15049 events in between each found library. The libraries are read in an
15050 undefined order, so if we gave the remote side a chance to look up
15051 symbols between each objfile, we might give it an inconsistent picture
15052 of the inferior. It could appear that a library A appears loaded but
15053 a library B does not, even though library A requires library B. That
15054 would present a state that couldn't normally exist in the inferior.
15055
15056 So, skip these events, we'll give the remote a chance to look up
15057 symbols once all the loaded libraries and their symbols are known to
15058 GDB. */
15059 if (inf->in_initial_library_scan)
15060 continue;
15061
15062 if (!remote->has_execution (inf))
15063 continue;
15064
15065 /* Need to switch to a specific thread, because remote_check_symbols will
15066 set the general thread using INFERIOR_PTID.
15067
15068 It's possible to have inferiors with no thread here, because we are
15069 called very early in the connection process, while the inferior is
15070 being set up, before threads are added. Just skip it, start_remote_1
15071 also calls remote_check_symbols when it's done setting things up. */
15072 thread_info *thread = any_thread_of_inferior (inf);
15073 if (thread != nullptr)
15074 {
15075 scoped_restore_current_thread restore_thread;
15076 switch_to_thread (thread);
15077 remote->remote_check_symbols ();
15078 }
15079 }
15080 }
15081
15082 /* Function to be called whenever a new objfile (shlib) is detected. */
15083
15084 static void
15085 remote_new_objfile (struct objfile *objfile)
15086 {
15087 remote_objfile_changed_check_symbols (objfile->pspace);
15088 }
15089
15090 /* Pull all the tracepoints defined on the target and create local
15091 data structures representing them. We don't want to create real
15092 tracepoints yet, we don't want to mess up the user's existing
15093 collection. */
15094
15095 int
15096 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
15097 {
15098 struct remote_state *rs = get_remote_state ();
15099 char *p;
15100
15101 /* Ask for a first packet of tracepoint definition. */
15102 putpkt ("qTfP");
15103 getpkt (&rs->buf);
15104 p = rs->buf.data ();
15105 while (*p && *p != 'l')
15106 {
15107 parse_tracepoint_definition (p, utpp);
15108 /* Ask for another packet of tracepoint definition. */
15109 putpkt ("qTsP");
15110 getpkt (&rs->buf);
15111 p = rs->buf.data ();
15112 }
15113 return 0;
15114 }
15115
15116 int
15117 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
15118 {
15119 struct remote_state *rs = get_remote_state ();
15120 char *p;
15121
15122 /* Ask for a first packet of variable definition. */
15123 putpkt ("qTfV");
15124 getpkt (&rs->buf);
15125 p = rs->buf.data ();
15126 while (*p && *p != 'l')
15127 {
15128 parse_tsv_definition (p, utsvp);
15129 /* Ask for another packet of variable definition. */
15130 putpkt ("qTsV");
15131 getpkt (&rs->buf);
15132 p = rs->buf.data ();
15133 }
15134 return 0;
15135 }
15136
15137 /* The "set/show range-stepping" show hook. */
15138
15139 static void
15140 show_range_stepping (struct ui_file *file, int from_tty,
15141 struct cmd_list_element *c,
15142 const char *value)
15143 {
15144 gdb_printf (file,
15145 _("Debugger's willingness to use range stepping "
15146 "is %s.\n"), value);
15147 }
15148
15149 /* Return true if the vCont;r action is supported by the remote
15150 stub. */
15151
15152 bool
15153 remote_target::vcont_r_supported ()
15154 {
15155 return (m_features.packet_support (PACKET_vCont) == PACKET_ENABLE
15156 && get_remote_state ()->supports_vCont.r);
15157 }
15158
15159 /* The "set/show range-stepping" set hook. */
15160
15161 static void
15162 set_range_stepping (const char *ignore_args, int from_tty,
15163 struct cmd_list_element *c)
15164 {
15165 /* When enabling, check whether range stepping is actually supported
15166 by the target, and warn if not. */
15167 if (use_range_stepping)
15168 {
15169 remote_target *remote = get_current_remote_target ();
15170 if (remote == NULL
15171 || !remote->vcont_r_supported ())
15172 warning (_("Range stepping is not supported by the current target"));
15173 }
15174 }
15175
15176 static void
15177 show_remote_debug (struct ui_file *file, int from_tty,
15178 struct cmd_list_element *c, const char *value)
15179 {
15180 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
15181 value);
15182 }
15183
15184 static void
15185 show_remote_timeout (struct ui_file *file, int from_tty,
15186 struct cmd_list_element *c, const char *value)
15187 {
15188 gdb_printf (file,
15189 _("Timeout limit to wait for target to respond is %s.\n"),
15190 value);
15191 }
15192
15193 /* Implement the "supports_memory_tagging" target_ops method. */
15194
15195 bool
15196 remote_target::supports_memory_tagging ()
15197 {
15198 return m_features.remote_memory_tagging_p ();
15199 }
15200
15201 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
15202
15203 static void
15204 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15205 size_t len, int type)
15206 {
15207 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15208
15209 std::string request = string_printf ("qMemTags:%s,%s:%s",
15210 phex_nz (address, addr_size),
15211 phex_nz (len, sizeof (len)),
15212 phex_nz (type, sizeof (type)));
15213
15214 strcpy (packet.data (), request.c_str ());
15215 }
15216
15217 /* Parse the qMemTags packet reply into TAGS.
15218
15219 Return true if successful, false otherwise. */
15220
15221 static bool
15222 parse_fetch_memtags_reply (const gdb::char_vector &reply,
15223 gdb::byte_vector &tags)
15224 {
15225 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
15226 return false;
15227
15228 /* Copy the tag data. */
15229 tags = hex2bin (reply.data () + 1);
15230
15231 return true;
15232 }
15233
15234 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
15235
15236 static void
15237 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15238 size_t len, int type,
15239 const gdb::byte_vector &tags)
15240 {
15241 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15242
15243 /* Put together the main packet, address and length. */
15244 std::string request = string_printf ("QMemTags:%s,%s:%s:",
15245 phex_nz (address, addr_size),
15246 phex_nz (len, sizeof (len)),
15247 phex_nz (type, sizeof (type)));
15248 request += bin2hex (tags.data (), tags.size ());
15249
15250 /* Check if we have exceeded the maximum packet size. */
15251 if (packet.size () < request.length ())
15252 error (_("Contents too big for packet QMemTags."));
15253
15254 strcpy (packet.data (), request.c_str ());
15255 }
15256
15257 /* Implement the "fetch_memtags" target_ops method. */
15258
15259 bool
15260 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
15261 gdb::byte_vector &tags, int type)
15262 {
15263 /* Make sure the qMemTags packet is supported. */
15264 if (!m_features.remote_memory_tagging_p ())
15265 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
15266
15267 struct remote_state *rs = get_remote_state ();
15268
15269 create_fetch_memtags_request (rs->buf, address, len, type);
15270
15271 putpkt (rs->buf);
15272 getpkt (&rs->buf);
15273
15274 return parse_fetch_memtags_reply (rs->buf, tags);
15275 }
15276
15277 /* Implement the "store_memtags" target_ops method. */
15278
15279 bool
15280 remote_target::store_memtags (CORE_ADDR address, size_t len,
15281 const gdb::byte_vector &tags, int type)
15282 {
15283 /* Make sure the QMemTags packet is supported. */
15284 if (!m_features.remote_memory_tagging_p ())
15285 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
15286
15287 struct remote_state *rs = get_remote_state ();
15288
15289 create_store_memtags_request (rs->buf, address, len, type, tags);
15290
15291 putpkt (rs->buf);
15292 getpkt (&rs->buf);
15293
15294 /* Verify if the request was successful. */
15295 return packet_check_result (rs->buf.data ()) == PACKET_OK;
15296 }
15297
15298 /* Return true if remote target T is non-stop. */
15299
15300 bool
15301 remote_target_is_non_stop_p (remote_target *t)
15302 {
15303 scoped_restore_current_thread restore_thread;
15304 switch_to_target_no_thread (t);
15305
15306 return target_is_non_stop_p ();
15307 }
15308
15309 #if GDB_SELF_TEST
15310
15311 namespace selftests {
15312
15313 static void
15314 test_memory_tagging_functions ()
15315 {
15316 remote_target remote;
15317
15318 struct packet_config *config
15319 = &remote.m_features.m_protocol_packets[PACKET_memory_tagging_feature];
15320
15321 scoped_restore restore_memtag_support_
15322 = make_scoped_restore (&config->support);
15323
15324 /* Test memory tagging packet support. */
15325 config->support = PACKET_SUPPORT_UNKNOWN;
15326 SELF_CHECK (remote.supports_memory_tagging () == false);
15327 config->support = PACKET_DISABLE;
15328 SELF_CHECK (remote.supports_memory_tagging () == false);
15329 config->support = PACKET_ENABLE;
15330 SELF_CHECK (remote.supports_memory_tagging () == true);
15331
15332 /* Setup testing. */
15333 gdb::char_vector packet;
15334 gdb::byte_vector tags, bv;
15335 std::string expected, reply;
15336 packet.resize (32000);
15337
15338 /* Test creating a qMemTags request. */
15339
15340 expected = "qMemTags:0,0:0";
15341 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
15342 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15343
15344 expected = "qMemTags:deadbeef,10:1";
15345 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
15346 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15347
15348 /* Test parsing a qMemTags reply. */
15349
15350 /* Error reply, tags vector unmodified. */
15351 reply = "E00";
15352 strcpy (packet.data (), reply.c_str ());
15353 tags.resize (0);
15354 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
15355 SELF_CHECK (tags.size () == 0);
15356
15357 /* Valid reply, tags vector updated. */
15358 tags.resize (0);
15359 bv.resize (0);
15360
15361 for (int i = 0; i < 5; i++)
15362 bv.push_back (i);
15363
15364 reply = "m" + bin2hex (bv.data (), bv.size ());
15365 strcpy (packet.data (), reply.c_str ());
15366
15367 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
15368 SELF_CHECK (tags.size () == 5);
15369
15370 for (int i = 0; i < 5; i++)
15371 SELF_CHECK (tags[i] == i);
15372
15373 /* Test creating a QMemTags request. */
15374
15375 /* Empty tag data. */
15376 tags.resize (0);
15377 expected = "QMemTags:0,0:0:";
15378 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
15379 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15380 expected.length ()) == 0);
15381
15382 /* Non-empty tag data. */
15383 tags.resize (0);
15384 for (int i = 0; i < 5; i++)
15385 tags.push_back (i);
15386 expected = "QMemTags:deadbeef,ff:1:0001020304";
15387 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
15388 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15389 expected.length ()) == 0);
15390 }
15391
15392 } // namespace selftests
15393 #endif /* GDB_SELF_TEST */
15394
15395 void _initialize_remote ();
15396 void
15397 _initialize_remote ()
15398 {
15399 add_target (remote_target_info, remote_target::open);
15400 add_target (extended_remote_target_info, extended_remote_target::open);
15401
15402 /* Hook into new objfile notification. */
15403 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
15404 gdb::observers::all_objfiles_removed.attach
15405 (remote_objfile_changed_check_symbols, "remote");
15406
15407 #if 0
15408 init_remote_threadtests ();
15409 #endif
15410
15411 /* set/show remote ... */
15412
15413 add_basic_prefix_cmd ("remote", class_maintenance, _("\
15414 Remote protocol specific variables.\n\
15415 Configure various remote-protocol specific variables such as\n\
15416 the packets being used."),
15417 &remote_set_cmdlist,
15418 0 /* allow-unknown */, &setlist);
15419 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
15420 Remote protocol specific variables.\n\
15421 Configure various remote-protocol specific variables such as\n\
15422 the packets being used."),
15423 &remote_show_cmdlist,
15424 0 /* allow-unknown */, &showlist);
15425
15426 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
15427 Compare section data on target to the exec file.\n\
15428 Argument is a single section name (default: all loaded sections).\n\
15429 To compare only read-only loaded sections, specify the -r option."),
15430 &cmdlist);
15431
15432 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
15433 Send an arbitrary packet to a remote target.\n\
15434 maintenance packet TEXT\n\
15435 If GDB is talking to an inferior via the GDB serial protocol, then\n\
15436 this command sends the string TEXT to the inferior, and displays the\n\
15437 response packet. GDB supplies the initial `$' character, and the\n\
15438 terminating `#' character and checksum."),
15439 &maintenancelist);
15440
15441 set_show_commands remotebreak_cmds
15442 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
15443 Set whether to send break if interrupted."), _("\
15444 Show whether to send break if interrupted."), _("\
15445 If set, a break, instead of a cntrl-c, is sent to the remote target."),
15446 set_remotebreak, show_remotebreak,
15447 &setlist, &showlist);
15448 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
15449 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
15450
15451 add_setshow_enum_cmd ("interrupt-sequence", class_support,
15452 interrupt_sequence_modes, &interrupt_sequence_mode,
15453 _("\
15454 Set interrupt sequence to remote target."), _("\
15455 Show interrupt sequence to remote target."), _("\
15456 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
15457 NULL, show_interrupt_sequence,
15458 &remote_set_cmdlist,
15459 &remote_show_cmdlist);
15460
15461 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
15462 &interrupt_on_connect, _("\
15463 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15464 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15465 If set, interrupt sequence is sent to remote target."),
15466 NULL, NULL,
15467 &remote_set_cmdlist, &remote_show_cmdlist);
15468
15469 /* Install commands for configuring memory read/write packets. */
15470
15471 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
15472 Set the maximum number of bytes per memory write packet (deprecated)."),
15473 &setlist);
15474 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
15475 Show the maximum number of bytes per memory write packet (deprecated)."),
15476 &showlist);
15477 add_cmd ("memory-write-packet-size", no_class,
15478 set_memory_write_packet_size, _("\
15479 Set the maximum number of bytes per memory-write packet.\n\
15480 Specify the number of bytes in a packet or 0 (zero) for the\n\
15481 default packet size. The actual limit is further reduced\n\
15482 dependent on the target. Specify \"fixed\" to disable the\n\
15483 further restriction and \"limit\" to enable that restriction."),
15484 &remote_set_cmdlist);
15485 add_cmd ("memory-read-packet-size", no_class,
15486 set_memory_read_packet_size, _("\
15487 Set the maximum number of bytes per memory-read packet.\n\
15488 Specify the number of bytes in a packet or 0 (zero) for the\n\
15489 default packet size. The actual limit is further reduced\n\
15490 dependent on the target. Specify \"fixed\" to disable the\n\
15491 further restriction and \"limit\" to enable that restriction."),
15492 &remote_set_cmdlist);
15493 add_cmd ("memory-write-packet-size", no_class,
15494 show_memory_write_packet_size,
15495 _("Show the maximum number of bytes per memory-write packet."),
15496 &remote_show_cmdlist);
15497 add_cmd ("memory-read-packet-size", no_class,
15498 show_memory_read_packet_size,
15499 _("Show the maximum number of bytes per memory-read packet."),
15500 &remote_show_cmdlist);
15501
15502 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
15503 &remote_hw_watchpoint_limit, _("\
15504 Set the maximum number of target hardware watchpoints."), _("\
15505 Show the maximum number of target hardware watchpoints."), _("\
15506 Specify \"unlimited\" for unlimited hardware watchpoints."),
15507 NULL, show_hardware_watchpoint_limit,
15508 &remote_set_cmdlist,
15509 &remote_show_cmdlist);
15510 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15511 no_class,
15512 &remote_hw_watchpoint_length_limit, _("\
15513 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15514 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15515 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15516 NULL, show_hardware_watchpoint_length_limit,
15517 &remote_set_cmdlist, &remote_show_cmdlist);
15518 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
15519 &remote_hw_breakpoint_limit, _("\
15520 Set the maximum number of target hardware breakpoints."), _("\
15521 Show the maximum number of target hardware breakpoints."), _("\
15522 Specify \"unlimited\" for unlimited hardware breakpoints."),
15523 NULL, show_hardware_breakpoint_limit,
15524 &remote_set_cmdlist, &remote_show_cmdlist);
15525
15526 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15527 &remote_address_size, _("\
15528 Set the maximum size of the address (in bits) in a memory packet."), _("\
15529 Show the maximum size of the address (in bits) in a memory packet."), NULL,
15530 NULL,
15531 NULL, /* FIXME: i18n: */
15532 &setlist, &showlist);
15533
15534 init_all_packet_configs ();
15535
15536 add_packet_config_cmd (PACKET_X, "X", "binary-download", 1);
15537
15538 add_packet_config_cmd (PACKET_vCont, "vCont", "verbose-resume", 0);
15539
15540 add_packet_config_cmd (PACKET_QPassSignals, "QPassSignals", "pass-signals",
15541 0);
15542
15543 add_packet_config_cmd (PACKET_QCatchSyscalls, "QCatchSyscalls",
15544 "catch-syscalls", 0);
15545
15546 add_packet_config_cmd (PACKET_QProgramSignals, "QProgramSignals",
15547 "program-signals", 0);
15548
15549 add_packet_config_cmd (PACKET_QSetWorkingDir, "QSetWorkingDir",
15550 "set-working-dir", 0);
15551
15552 add_packet_config_cmd (PACKET_QStartupWithShell, "QStartupWithShell",
15553 "startup-with-shell", 0);
15554
15555 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded,"QEnvironmentHexEncoded",
15556 "environment-hex-encoded", 0);
15557
15558 add_packet_config_cmd (PACKET_QEnvironmentReset, "QEnvironmentReset",
15559 "environment-reset", 0);
15560
15561 add_packet_config_cmd (PACKET_QEnvironmentUnset, "QEnvironmentUnset",
15562 "environment-unset", 0);
15563
15564 add_packet_config_cmd (PACKET_qSymbol, "qSymbol", "symbol-lookup", 0);
15565
15566 add_packet_config_cmd (PACKET_P, "P", "set-register", 1);
15567
15568 add_packet_config_cmd (PACKET_p, "p", "fetch-register", 1);
15569
15570 add_packet_config_cmd (PACKET_Z0, "Z0", "software-breakpoint", 0);
15571
15572 add_packet_config_cmd (PACKET_Z1, "Z1", "hardware-breakpoint", 0);
15573
15574 add_packet_config_cmd (PACKET_Z2, "Z2", "write-watchpoint", 0);
15575
15576 add_packet_config_cmd (PACKET_Z3, "Z3", "read-watchpoint", 0);
15577
15578 add_packet_config_cmd (PACKET_Z4, "Z4", "access-watchpoint", 0);
15579
15580 add_packet_config_cmd (PACKET_qXfer_auxv, "qXfer:auxv:read",
15581 "read-aux-vector", 0);
15582
15583 add_packet_config_cmd (PACKET_qXfer_exec_file, "qXfer:exec-file:read",
15584 "pid-to-exec-file", 0);
15585
15586 add_packet_config_cmd (PACKET_qXfer_features,
15587 "qXfer:features:read", "target-features", 0);
15588
15589 add_packet_config_cmd (PACKET_qXfer_libraries, "qXfer:libraries:read",
15590 "library-info", 0);
15591
15592 add_packet_config_cmd (PACKET_qXfer_libraries_svr4,
15593 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15594
15595 add_packet_config_cmd (PACKET_qXfer_memory_map, "qXfer:memory-map:read",
15596 "memory-map", 0);
15597
15598 add_packet_config_cmd (PACKET_qXfer_osdata, "qXfer:osdata:read", "osdata", 0);
15599
15600 add_packet_config_cmd (PACKET_qXfer_threads, "qXfer:threads:read", "threads",
15601 0);
15602
15603 add_packet_config_cmd (PACKET_qXfer_siginfo_read, "qXfer:siginfo:read",
15604 "read-siginfo-object", 0);
15605
15606 add_packet_config_cmd (PACKET_qXfer_siginfo_write, "qXfer:siginfo:write",
15607 "write-siginfo-object", 0);
15608
15609 add_packet_config_cmd (PACKET_qXfer_traceframe_info,
15610 "qXfer:traceframe-info:read", "traceframe-info", 0);
15611
15612 add_packet_config_cmd (PACKET_qXfer_uib, "qXfer:uib:read",
15613 "unwind-info-block", 0);
15614
15615 add_packet_config_cmd (PACKET_qGetTLSAddr, "qGetTLSAddr",
15616 "get-thread-local-storage-address", 0);
15617
15618 add_packet_config_cmd (PACKET_qGetTIBAddr, "qGetTIBAddr",
15619 "get-thread-information-block-address", 0);
15620
15621 add_packet_config_cmd (PACKET_bc, "bc", "reverse-continue", 0);
15622
15623 add_packet_config_cmd (PACKET_bs, "bs", "reverse-step", 0);
15624
15625 add_packet_config_cmd (PACKET_qSupported, "qSupported", "supported-packets",
15626 0);
15627
15628 add_packet_config_cmd (PACKET_qSearch_memory, "qSearch:memory",
15629 "search-memory", 0);
15630
15631 add_packet_config_cmd (PACKET_qTStatus, "qTStatus", "trace-status", 0);
15632
15633 add_packet_config_cmd (PACKET_vFile_setfs, "vFile:setfs", "hostio-setfs", 0);
15634
15635 add_packet_config_cmd (PACKET_vFile_open, "vFile:open", "hostio-open", 0);
15636
15637 add_packet_config_cmd (PACKET_vFile_pread, "vFile:pread", "hostio-pread", 0);
15638
15639 add_packet_config_cmd (PACKET_vFile_pwrite, "vFile:pwrite", "hostio-pwrite",
15640 0);
15641
15642 add_packet_config_cmd (PACKET_vFile_close, "vFile:close", "hostio-close", 0);
15643
15644 add_packet_config_cmd (PACKET_vFile_unlink, "vFile:unlink", "hostio-unlink",
15645 0);
15646
15647 add_packet_config_cmd (PACKET_vFile_readlink, "vFile:readlink",
15648 "hostio-readlink", 0);
15649
15650 add_packet_config_cmd (PACKET_vFile_fstat, "vFile:fstat", "hostio-fstat", 0);
15651
15652 add_packet_config_cmd (PACKET_vAttach, "vAttach", "attach", 0);
15653
15654 add_packet_config_cmd (PACKET_vRun, "vRun", "run", 0);
15655
15656 add_packet_config_cmd (PACKET_QStartNoAckMode, "QStartNoAckMode", "noack", 0);
15657
15658 add_packet_config_cmd (PACKET_vKill, "vKill", "kill", 0);
15659
15660 add_packet_config_cmd (PACKET_qAttached, "qAttached", "query-attached", 0);
15661
15662 add_packet_config_cmd (PACKET_ConditionalTracepoints,
15663 "ConditionalTracepoints", "conditional-tracepoints",
15664 0);
15665
15666 add_packet_config_cmd (PACKET_ConditionalBreakpoints,
15667 "ConditionalBreakpoints", "conditional-breakpoints",
15668 0);
15669
15670 add_packet_config_cmd (PACKET_BreakpointCommands, "BreakpointCommands",
15671 "breakpoint-commands", 0);
15672
15673 add_packet_config_cmd (PACKET_FastTracepoints, "FastTracepoints",
15674 "fast-tracepoints", 0);
15675
15676 add_packet_config_cmd (PACKET_TracepointSource, "TracepointSource",
15677 "TracepointSource", 0);
15678
15679 add_packet_config_cmd (PACKET_QAllow, "QAllow", "allow", 0);
15680
15681 add_packet_config_cmd (PACKET_StaticTracepoints, "StaticTracepoints",
15682 "static-tracepoints", 0);
15683
15684 add_packet_config_cmd (PACKET_InstallInTrace, "InstallInTrace",
15685 "install-in-trace", 0);
15686
15687 add_packet_config_cmd (PACKET_qXfer_statictrace_read,
15688 "qXfer:statictrace:read", "read-sdata-object", 0);
15689
15690 add_packet_config_cmd (PACKET_qXfer_fdpic, "qXfer:fdpic:read",
15691 "read-fdpic-loadmap", 0);
15692
15693 add_packet_config_cmd (PACKET_QDisableRandomization, "QDisableRandomization",
15694 "disable-randomization", 0);
15695
15696 add_packet_config_cmd (PACKET_QAgent, "QAgent", "agent", 0);
15697
15698 add_packet_config_cmd (PACKET_QTBuffer_size, "QTBuffer:size",
15699 "trace-buffer-size", 0);
15700
15701 add_packet_config_cmd (PACKET_Qbtrace_off, "Qbtrace:off", "disable-btrace",
15702 0);
15703
15704 add_packet_config_cmd (PACKET_Qbtrace_bts, "Qbtrace:bts", "enable-btrace-bts",
15705 0);
15706
15707 add_packet_config_cmd (PACKET_Qbtrace_pt, "Qbtrace:pt", "enable-btrace-pt",
15708 0);
15709
15710 add_packet_config_cmd (PACKET_qXfer_btrace, "qXfer:btrace", "read-btrace", 0);
15711
15712 add_packet_config_cmd (PACKET_qXfer_btrace_conf, "qXfer:btrace-conf",
15713 "read-btrace-conf", 0);
15714
15715 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size, "Qbtrace-conf:bts:size",
15716 "btrace-conf-bts-size", 0);
15717
15718 add_packet_config_cmd (PACKET_multiprocess_feature, "multiprocess-feature",
15719 "multiprocess-feature", 0);
15720
15721 add_packet_config_cmd (PACKET_swbreak_feature, "swbreak-feature",
15722 "swbreak-feature", 0);
15723
15724 add_packet_config_cmd (PACKET_hwbreak_feature, "hwbreak-feature",
15725 "hwbreak-feature", 0);
15726
15727 add_packet_config_cmd (PACKET_fork_event_feature, "fork-event-feature",
15728 "fork-event-feature", 0);
15729
15730 add_packet_config_cmd (PACKET_vfork_event_feature, "vfork-event-feature",
15731 "vfork-event-feature", 0);
15732
15733 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size, "Qbtrace-conf:pt:size",
15734 "btrace-conf-pt-size", 0);
15735
15736 add_packet_config_cmd (PACKET_vContSupported, "vContSupported",
15737 "verbose-resume-supported", 0);
15738
15739 add_packet_config_cmd (PACKET_exec_event_feature, "exec-event-feature",
15740 "exec-event-feature", 0);
15741
15742 add_packet_config_cmd (PACKET_vCtrlC, "vCtrlC", "ctrl-c", 0);
15743
15744 add_packet_config_cmd (PACKET_QThreadEvents, "QThreadEvents", "thread-events",
15745 0);
15746
15747 add_packet_config_cmd (PACKET_no_resumed, "N stop reply",
15748 "no-resumed-stop-reply", 0);
15749
15750 add_packet_config_cmd (PACKET_memory_tagging_feature,
15751 "memory-tagging-feature", "memory-tagging-feature", 0);
15752
15753 /* Assert that we've registered "set remote foo-packet" commands
15754 for all packet configs. */
15755 {
15756 int i;
15757
15758 for (i = 0; i < PACKET_MAX; i++)
15759 {
15760 /* Ideally all configs would have a command associated. Some
15761 still don't though. */
15762 int excepted;
15763
15764 switch (i)
15765 {
15766 case PACKET_QNonStop:
15767 case PACKET_EnableDisableTracepoints_feature:
15768 case PACKET_tracenz_feature:
15769 case PACKET_DisconnectedTracing_feature:
15770 case PACKET_augmented_libraries_svr4_read_feature:
15771 case PACKET_qCRC:
15772 /* Additions to this list need to be well justified:
15773 pre-existing packets are OK; new packets are not. */
15774 excepted = 1;
15775 break;
15776 default:
15777 excepted = 0;
15778 break;
15779 }
15780
15781 /* This catches both forgetting to add a config command, and
15782 forgetting to remove a packet from the exception list. */
15783 gdb_assert (excepted == (packets_descriptions[i].name == NULL));
15784 }
15785 }
15786
15787 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15788 Z sub-packet has its own set and show commands, but users may
15789 have sets to this variable in their .gdbinit files (or in their
15790 documentation). */
15791 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
15792 &remote_Z_packet_detect, _("\
15793 Set use of remote protocol `Z' packets."), _("\
15794 Show use of remote protocol `Z' packets."), _("\
15795 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
15796 packets."),
15797 set_remote_protocol_Z_packet_cmd,
15798 show_remote_protocol_Z_packet_cmd,
15799 /* FIXME: i18n: Use of remote protocol
15800 `Z' packets is %s. */
15801 &remote_set_cmdlist, &remote_show_cmdlist);
15802
15803 add_basic_prefix_cmd ("remote", class_files, _("\
15804 Manipulate files on the remote system.\n\
15805 Transfer files to and from the remote target system."),
15806 &remote_cmdlist,
15807 0 /* allow-unknown */, &cmdlist);
15808
15809 add_cmd ("put", class_files, remote_put_command,
15810 _("Copy a local file to the remote system."),
15811 &remote_cmdlist);
15812
15813 add_cmd ("get", class_files, remote_get_command,
15814 _("Copy a remote file to the local system."),
15815 &remote_cmdlist);
15816
15817 add_cmd ("delete", class_files, remote_delete_command,
15818 _("Delete a remote file."),
15819 &remote_cmdlist);
15820
15821 add_setshow_string_noescape_cmd ("exec-file", class_files,
15822 &remote_exec_file_var, _("\
15823 Set the remote pathname for \"run\"."), _("\
15824 Show the remote pathname for \"run\"."), NULL,
15825 set_remote_exec_file,
15826 show_remote_exec_file,
15827 &remote_set_cmdlist,
15828 &remote_show_cmdlist);
15829
15830 add_setshow_boolean_cmd ("range-stepping", class_run,
15831 &use_range_stepping, _("\
15832 Enable or disable range stepping."), _("\
15833 Show whether target-assisted range stepping is enabled."), _("\
15834 If on, and the target supports it, when stepping a source line, GDB\n\
15835 tells the target to step the corresponding range of addresses itself instead\n\
15836 of issuing multiple single-steps. This speeds up source level\n\
15837 stepping. If off, GDB always issues single-steps, even if range\n\
15838 stepping is supported by the target. The default is on."),
15839 set_range_stepping,
15840 show_range_stepping,
15841 &setlist,
15842 &showlist);
15843
15844 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15845 Set watchdog timer."), _("\
15846 Show watchdog timer."), _("\
15847 When non-zero, this timeout is used instead of waiting forever for a target\n\
15848 to finish a low-level step or continue operation. If the specified amount\n\
15849 of time passes without a response from the target, an error occurs."),
15850 NULL,
15851 show_watchdog,
15852 &setlist, &showlist);
15853
15854 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15855 &remote_packet_max_chars, _("\
15856 Set the maximum number of characters to display for each remote packet."), _("\
15857 Show the maximum number of characters to display for each remote packet."), _("\
15858 Specify \"unlimited\" to display all the characters."),
15859 NULL, show_remote_packet_max_chars,
15860 &setdebuglist, &showdebuglist);
15861
15862 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15863 _("Set debugging of remote protocol."),
15864 _("Show debugging of remote protocol."),
15865 _("\
15866 When enabled, each packet sent or received with the remote target\n\
15867 is displayed."),
15868 NULL,
15869 show_remote_debug,
15870 &setdebuglist, &showdebuglist);
15871
15872 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15873 &remote_timeout, _("\
15874 Set timeout limit to wait for target to respond."), _("\
15875 Show timeout limit to wait for target to respond."), _("\
15876 This value is used to set the time limit for gdb to wait for a response\n\
15877 from the target."),
15878 NULL,
15879 show_remote_timeout,
15880 &setlist, &showlist);
15881
15882 /* Eventually initialize fileio. See fileio.c */
15883 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
15884
15885 #if GDB_SELF_TEST
15886 selftests::register_test ("remote_memory_tagging",
15887 selftests::test_memory_tagging_functions);
15888 #endif
15889 }