]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/remote.c
gdb: make remote_state's async token private
[thirdparty/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 { ::mark_async_event_handler (m_async_event_handler_token); }
429
430 void clear_async_event_handler ()
431 { ::clear_async_event_handler (m_async_event_handler_token); }
432
433 bool async_event_handler_marked () const
434 { return ::async_event_handler_marked (m_async_event_handler_token); }
435
436 void delete_async_event_handler ()
437 {
438 if (m_async_event_handler_token != nullptr)
439 ::delete_async_event_handler (&m_async_event_handler_token);
440 }
441
442 public: /* data */
443
444 /* A buffer to use for incoming packets, and its current size. The
445 buffer is grown dynamically for larger incoming packets.
446 Outgoing packets may also be constructed in this buffer.
447 The size of the buffer is always at least REMOTE_PACKET_SIZE;
448 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
449 packets. */
450 gdb::char_vector buf;
451
452 /* True if we're going through initial connection setup (finding out
453 about the remote side's threads, relocating symbols, etc.). */
454 bool starting_up = false;
455
456 /* If we negotiated packet size explicitly (and thus can bypass
457 heuristics for the largest packet size that will not overflow
458 a buffer in the stub), this will be set to that packet size.
459 Otherwise zero, meaning to use the guessed size. */
460 long explicit_packet_size = 0;
461
462 /* True, if in no ack mode. That is, neither GDB nor the stub will
463 expect acks from each other. The connection is assumed to be
464 reliable. */
465 bool noack_mode = false;
466
467 /* True if we're connected in extended remote mode. */
468 bool extended = false;
469
470 /* True if we resumed the target and we're waiting for the target to
471 stop. In the mean time, we can't start another command/query.
472 The remote server wouldn't be ready to process it, so we'd
473 timeout waiting for a reply that would never come and eventually
474 we'd close the connection. This can happen in asynchronous mode
475 because we allow GDB commands while the target is running. */
476 bool waiting_for_stop_reply = false;
477
478 /* The status of the stub support for the various vCont actions. */
479 vCont_action_support supports_vCont;
480
481 /* True if the user has pressed Ctrl-C, but the target hasn't
482 responded to that. */
483 bool ctrlc_pending_p = false;
484
485 /* True if we saw a Ctrl-C while reading or writing from/to the
486 remote descriptor. At that point it is not safe to send a remote
487 interrupt packet, so we instead remember we saw the Ctrl-C and
488 process it once we're done with sending/receiving the current
489 packet, which should be shortly. If however that takes too long,
490 and the user presses Ctrl-C again, we offer to disconnect. */
491 bool got_ctrlc_during_io = false;
492
493 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
494 remote_open knows that we don't have a file open when the program
495 starts. */
496 struct serial *remote_desc = nullptr;
497
498 /* These are the threads which we last sent to the remote system. The
499 TID member will be -1 for all or -2 for not sent yet. */
500 ptid_t general_thread = null_ptid;
501 ptid_t continue_thread = null_ptid;
502
503 /* This is the traceframe which we last selected on the remote system.
504 It will be -1 if no traceframe is selected. */
505 int remote_traceframe_number = -1;
506
507 char *last_pass_packet = nullptr;
508
509 /* The last QProgramSignals packet sent to the target. We bypass
510 sending a new program signals list down to the target if the new
511 packet is exactly the same as the last we sent. IOW, we only let
512 the target know about program signals list changes. */
513 char *last_program_signals_packet = nullptr;
514
515 gdb_signal last_sent_signal = GDB_SIGNAL_0;
516
517 bool last_sent_step = false;
518
519 /* The execution direction of the last resume we got. */
520 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
521
522 char *finished_object = nullptr;
523 char *finished_annex = nullptr;
524 ULONGEST finished_offset = 0;
525
526 /* Should we try the 'ThreadInfo' query packet?
527
528 This variable (NOT available to the user: auto-detect only!)
529 determines whether GDB will use the new, simpler "ThreadInfo"
530 query or the older, more complex syntax for thread queries.
531 This is an auto-detect variable (set to true at each connect,
532 and set to false when the target fails to recognize it). */
533 bool use_threadinfo_query = false;
534 bool use_threadextra_query = false;
535
536 threadref echo_nextthread {};
537 threadref nextthread {};
538 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
539
540 /* The state of remote notification. */
541 struct remote_notif_state *notif_state = nullptr;
542
543 /* The branch trace configuration. */
544 struct btrace_config btrace_config {};
545
546 /* The argument to the last "vFile:setfs:" packet we sent, used
547 to avoid sending repeated unnecessary "vFile:setfs:" packets.
548 Initialized to -1 to indicate that no "vFile:setfs:" packet
549 has yet been sent. */
550 int fs_pid = -1;
551
552 /* A readahead cache for vFile:pread. Often, reading a binary
553 involves a sequence of small reads. E.g., when parsing an ELF
554 file. A readahead cache helps mostly the case of remote
555 debugging on a connection with higher latency, due to the
556 request/reply nature of the RSP. We only cache data for a single
557 file descriptor at a time. */
558 struct readahead_cache readahead_cache;
559
560 /* The list of already fetched and acknowledged stop events. This
561 queue is used for notification Stop, and other notifications
562 don't need queue for their events, because the notification
563 events of Stop can't be consumed immediately, so that events
564 should be queued first, and be consumed by remote_wait_{ns,as}
565 one per time. Other notifications can consume their events
566 immediately, so queue is not needed for them. */
567 std::vector<stop_reply_up> stop_reply_queue;
568
569 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
570 ``forever'' still use the normal timeout mechanism. This is
571 currently used by the ASYNC code to guarentee that target reads
572 during the initial connect always time-out. Once getpkt has been
573 modified to return a timeout indication and, in turn
574 remote_wait()/wait_for_inferior() have gained a timeout parameter
575 this can go away. */
576 bool wait_forever_enabled_p = true;
577
578 private:
579 /* Asynchronous signal handle registered as event loop source for
580 when we have pending events ready to be passed to the core. */
581 async_event_handler *m_async_event_handler_token = nullptr;
582
583 /* Mapping of remote protocol data for each gdbarch. Usually there
584 is only one entry here, though we may see more with stubs that
585 support multi-process. */
586 std::unordered_map<struct gdbarch *, remote_arch_state>
587 m_arch_states;
588 };
589
590 static const target_info remote_target_info = {
591 "remote",
592 N_("Remote target using gdb-specific protocol"),
593 remote_doc
594 };
595
596 /* Description of a remote packet. */
597
598 struct packet_description
599 {
600 /* Name of the packet used for gdb output. */
601 const char *name;
602
603 /* Title of the packet, used by the set/show remote name-packet
604 commands to identify the individual packages and gdb output. */
605 const char *title;
606 };
607
608 /* Configuration of a remote packet. */
609
610 struct packet_config
611 {
612 /* If auto, GDB auto-detects support for this packet or feature,
613 either through qSupported, or by trying the packet and looking
614 at the response. If true, GDB assumes the target supports this
615 packet. If false, the packet is disabled. Configs that don't
616 have an associated command always have this set to auto. */
617 enum auto_boolean detect;
618
619 /* Does the target support this packet? */
620 enum packet_support support;
621 };
622
623 /* User configurable variables for the number of characters in a
624 memory read/write packet. MIN (rsa->remote_packet_size,
625 rsa->sizeof_g_packet) is the default. Some targets need smaller
626 values (fifo overruns, et.al.) and some users need larger values
627 (speed up transfers). The variables ``preferred_*'' (the user
628 request), ``current_*'' (what was actually set) and ``forced_*''
629 (Positive - a soft limit, negative - a hard limit). */
630
631 struct memory_packet_config
632 {
633 const char *name;
634 long size;
635 int fixed_p;
636 };
637
638 /* These global variables contain the default configuration for every new
639 remote_feature object. */
640 static memory_packet_config memory_read_packet_config =
641 {
642 "memory-read-packet-size",
643 };
644 static memory_packet_config memory_write_packet_config =
645 {
646 "memory-write-packet-size",
647 };
648
649 /* This global array contains packet descriptions (name and title). */
650 static packet_description packets_descriptions[PACKET_MAX];
651 /* This global array contains the default configuration for every new
652 per-remote target array. */
653 static packet_config remote_protocol_packets[PACKET_MAX];
654
655 /* Description of a remote target's features. It stores the configuration
656 and provides functions to determine supported features of the target. */
657
658 struct remote_features
659 {
660 remote_features ()
661 {
662 m_memory_read_packet_config = memory_read_packet_config;
663 m_memory_write_packet_config = memory_write_packet_config;
664
665 std::copy (std::begin (remote_protocol_packets),
666 std::end (remote_protocol_packets),
667 std::begin (m_protocol_packets));
668 }
669 ~remote_features () = default;
670
671 DISABLE_COPY_AND_ASSIGN (remote_features);
672
673 /* Returns whether a given packet defined by its enum value is supported. */
674 enum packet_support packet_support (int) const;
675
676 /* Returns the packet's corresponding "set remote foo-packet" command
677 state. See struct packet_config for more details. */
678 enum auto_boolean packet_set_cmd_state (int packet) const
679 { return m_protocol_packets[packet].detect; }
680
681 /* Returns true if the multi-process extensions are in effect. */
682 int remote_multi_process_p () const
683 { return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE; }
684
685 /* Returns true if fork events are supported. */
686 int remote_fork_event_p () const
687 { return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE; }
688
689 /* Returns true if vfork events are supported. */
690 int remote_vfork_event_p () const
691 { return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE; }
692
693 /* Returns true if exec events are supported. */
694 int remote_exec_event_p () const
695 { return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE; }
696
697 /* Returns true if memory tagging is supported, false otherwise. */
698 bool remote_memory_tagging_p () const
699 { return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE; }
700
701 /* Reset all packets back to "unknown support". Called when opening a
702 new connection to a remote target. */
703 void reset_all_packet_configs_support ();
704
705 /* Check result value in BUF for packet WHICH_PACKET and update the packet's
706 support configuration accordingly. */
707 packet_result packet_ok (const char *buf, const int which_packet);
708 packet_result packet_ok (const gdb::char_vector &buf, const int which_packet);
709
710 /* Configuration of a remote target's memory read packet. */
711 memory_packet_config m_memory_read_packet_config;
712 /* Configuration of a remote target's memory write packet. */
713 memory_packet_config m_memory_write_packet_config;
714
715 /* The per-remote target array which stores a remote's packet
716 configurations. */
717 packet_config m_protocol_packets[PACKET_MAX];
718 };
719
720 class remote_target : public process_stratum_target
721 {
722 public:
723 remote_target () = default;
724 ~remote_target () override;
725
726 const target_info &info () const override
727 { return remote_target_info; }
728
729 const char *connection_string () override;
730
731 thread_control_capabilities get_thread_control_capabilities () override
732 { return tc_schedlock; }
733
734 /* Open a remote connection. */
735 static void open (const char *, int);
736
737 void close () override;
738
739 void detach (inferior *, int) override;
740 void disconnect (const char *, int) override;
741
742 void commit_resumed () override;
743 void resume (ptid_t, int, enum gdb_signal) override;
744 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
745 bool has_pending_events () override;
746
747 void fetch_registers (struct regcache *, int) override;
748 void store_registers (struct regcache *, int) override;
749 void prepare_to_store (struct regcache *) override;
750
751 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
752
753 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
754 enum remove_bp_reason) override;
755
756
757 bool stopped_by_sw_breakpoint () override;
758 bool supports_stopped_by_sw_breakpoint () override;
759
760 bool stopped_by_hw_breakpoint () override;
761
762 bool supports_stopped_by_hw_breakpoint () override;
763
764 bool stopped_by_watchpoint () override;
765
766 bool stopped_data_address (CORE_ADDR *) override;
767
768 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
769
770 int can_use_hw_breakpoint (enum bptype, int, int) override;
771
772 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
773
774 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
775
776 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
777
778 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
779 struct expression *) override;
780
781 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
782 struct expression *) override;
783
784 void kill () override;
785
786 void load (const char *, int) override;
787
788 void mourn_inferior () override;
789
790 void pass_signals (gdb::array_view<const unsigned char>) override;
791
792 int set_syscall_catchpoint (int, bool, int,
793 gdb::array_view<const int>) override;
794
795 void program_signals (gdb::array_view<const unsigned char>) override;
796
797 bool thread_alive (ptid_t ptid) override;
798
799 const char *thread_name (struct thread_info *) override;
800
801 void update_thread_list () override;
802
803 std::string pid_to_str (ptid_t) override;
804
805 const char *extra_thread_info (struct thread_info *) override;
806
807 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
808
809 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
810 int handle_len,
811 inferior *inf) override;
812
813 gdb::array_view<const gdb_byte> thread_info_to_thread_handle (struct thread_info *tp)
814 override;
815
816 void stop (ptid_t) override;
817
818 void interrupt () override;
819
820 void pass_ctrlc () override;
821
822 enum target_xfer_status xfer_partial (enum target_object object,
823 const char *annex,
824 gdb_byte *readbuf,
825 const gdb_byte *writebuf,
826 ULONGEST offset, ULONGEST len,
827 ULONGEST *xfered_len) override;
828
829 ULONGEST get_memory_xfer_limit () override;
830
831 void rcmd (const char *command, struct ui_file *output) override;
832
833 const char *pid_to_exec_file (int pid) override;
834
835 void log_command (const char *cmd) override
836 {
837 serial_log_command (this, cmd);
838 }
839
840 CORE_ADDR get_thread_local_address (ptid_t ptid,
841 CORE_ADDR load_module_addr,
842 CORE_ADDR offset) override;
843
844 bool can_execute_reverse () override;
845
846 std::vector<mem_region> memory_map () override;
847
848 void flash_erase (ULONGEST address, LONGEST length) override;
849
850 void flash_done () override;
851
852 const struct target_desc *read_description () override;
853
854 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
855 const gdb_byte *pattern, ULONGEST pattern_len,
856 CORE_ADDR *found_addrp) override;
857
858 bool can_async_p () override;
859
860 bool is_async_p () override;
861
862 void async (bool) override;
863
864 int async_wait_fd () override;
865
866 void thread_events (int) override;
867
868 int can_do_single_step () override;
869
870 void terminal_inferior () override;
871
872 void terminal_ours () override;
873
874 bool supports_non_stop () override;
875
876 bool supports_multi_process () override;
877
878 bool supports_disable_randomization () override;
879
880 bool filesystem_is_local () override;
881
882
883 int fileio_open (struct inferior *inf, const char *filename,
884 int flags, int mode, int warn_if_slow,
885 fileio_error *target_errno) override;
886
887 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
888 ULONGEST offset, fileio_error *target_errno) override;
889
890 int fileio_pread (int fd, gdb_byte *read_buf, int len,
891 ULONGEST offset, fileio_error *target_errno) override;
892
893 int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
894
895 int fileio_close (int fd, fileio_error *target_errno) override;
896
897 int fileio_unlink (struct inferior *inf,
898 const char *filename,
899 fileio_error *target_errno) override;
900
901 gdb::optional<std::string>
902 fileio_readlink (struct inferior *inf,
903 const char *filename,
904 fileio_error *target_errno) override;
905
906 bool supports_enable_disable_tracepoint () override;
907
908 bool supports_string_tracing () override;
909
910 int remote_supports_cond_tracepoints ();
911
912 bool supports_evaluation_of_breakpoint_conditions () override;
913
914 int remote_supports_fast_tracepoints ();
915
916 int remote_supports_static_tracepoints ();
917
918 int remote_supports_install_in_trace ();
919
920 bool can_run_breakpoint_commands () override;
921
922 void trace_init () override;
923
924 void download_tracepoint (struct bp_location *location) override;
925
926 bool can_download_tracepoint () override;
927
928 void download_trace_state_variable (const trace_state_variable &tsv) override;
929
930 void enable_tracepoint (struct bp_location *location) override;
931
932 void disable_tracepoint (struct bp_location *location) override;
933
934 void trace_set_readonly_regions () override;
935
936 void trace_start () override;
937
938 int get_trace_status (struct trace_status *ts) override;
939
940 void get_tracepoint_status (tracepoint *tp, struct uploaded_tp *utp)
941 override;
942
943 void trace_stop () override;
944
945 int trace_find (enum trace_find_type type, int num,
946 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
947
948 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
949
950 int save_trace_data (const char *filename) override;
951
952 int upload_tracepoints (struct uploaded_tp **utpp) override;
953
954 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
955
956 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
957
958 int get_min_fast_tracepoint_insn_len () override;
959
960 void set_disconnected_tracing (int val) override;
961
962 void set_circular_trace_buffer (int val) override;
963
964 void set_trace_buffer_size (LONGEST val) override;
965
966 bool set_trace_notes (const char *user, const char *notes,
967 const char *stopnotes) override;
968
969 int core_of_thread (ptid_t ptid) override;
970
971 int verify_memory (const gdb_byte *data,
972 CORE_ADDR memaddr, ULONGEST size) override;
973
974
975 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
976
977 void set_permissions () override;
978
979 bool static_tracepoint_marker_at (CORE_ADDR,
980 struct static_tracepoint_marker *marker)
981 override;
982
983 std::vector<static_tracepoint_marker>
984 static_tracepoint_markers_by_strid (const char *id) override;
985
986 traceframe_info_up traceframe_info () override;
987
988 bool use_agent (bool use) override;
989 bool can_use_agent () override;
990
991 struct btrace_target_info *
992 enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
993
994 void disable_btrace (struct btrace_target_info *tinfo) override;
995
996 void teardown_btrace (struct btrace_target_info *tinfo) override;
997
998 enum btrace_error read_btrace (struct btrace_data *data,
999 struct btrace_target_info *btinfo,
1000 enum btrace_read_type type) override;
1001
1002 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
1003 bool augmented_libraries_svr4_read () override;
1004 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
1005 void follow_exec (inferior *, ptid_t, const char *) override;
1006 int insert_fork_catchpoint (int) override;
1007 int remove_fork_catchpoint (int) override;
1008 int insert_vfork_catchpoint (int) override;
1009 int remove_vfork_catchpoint (int) override;
1010 int insert_exec_catchpoint (int) override;
1011 int remove_exec_catchpoint (int) override;
1012 enum exec_direction_kind execution_direction () override;
1013
1014 bool supports_memory_tagging () override;
1015
1016 bool fetch_memtags (CORE_ADDR address, size_t len,
1017 gdb::byte_vector &tags, int type) override;
1018
1019 bool store_memtags (CORE_ADDR address, size_t len,
1020 const gdb::byte_vector &tags, int type) override;
1021
1022 public: /* Remote specific methods. */
1023
1024 void remote_download_command_source (int num, ULONGEST addr,
1025 struct command_line *cmds);
1026
1027 void remote_file_put (const char *local_file, const char *remote_file,
1028 int from_tty);
1029 void remote_file_get (const char *remote_file, const char *local_file,
1030 int from_tty);
1031 void remote_file_delete (const char *remote_file, int from_tty);
1032
1033 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
1034 ULONGEST offset, fileio_error *remote_errno);
1035 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
1036 ULONGEST offset, fileio_error *remote_errno);
1037 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
1038 ULONGEST offset, fileio_error *remote_errno);
1039
1040 int remote_hostio_send_command (int command_bytes, int which_packet,
1041 fileio_error *remote_errno, const char **attachment,
1042 int *attachment_len);
1043 int remote_hostio_set_filesystem (struct inferior *inf,
1044 fileio_error *remote_errno);
1045 /* We should get rid of this and use fileio_open directly. */
1046 int remote_hostio_open (struct inferior *inf, const char *filename,
1047 int flags, int mode, int warn_if_slow,
1048 fileio_error *remote_errno);
1049 int remote_hostio_close (int fd, fileio_error *remote_errno);
1050
1051 int remote_hostio_unlink (inferior *inf, const char *filename,
1052 fileio_error *remote_errno);
1053
1054 struct remote_state *get_remote_state ();
1055
1056 long get_remote_packet_size (void);
1057 long get_memory_packet_size (struct memory_packet_config *config);
1058
1059 long get_memory_write_packet_size ();
1060 long get_memory_read_packet_size ();
1061
1062 char *append_pending_thread_resumptions (char *p, char *endp,
1063 ptid_t ptid);
1064 static void open_1 (const char *name, int from_tty, int extended_p);
1065 void start_remote (int from_tty, int extended_p);
1066 void remote_detach_1 (struct inferior *inf, int from_tty);
1067
1068 char *append_resumption (char *p, char *endp,
1069 ptid_t ptid, int step, gdb_signal siggnal);
1070 int remote_resume_with_vcont (ptid_t scope_ptid, int step,
1071 gdb_signal siggnal);
1072
1073 thread_info *add_current_inferior_and_thread (const char *wait_status);
1074
1075 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
1076 target_wait_flags options);
1077 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
1078 target_wait_flags options);
1079
1080 ptid_t process_stop_reply (struct stop_reply *stop_reply,
1081 target_waitstatus *status);
1082
1083 ptid_t select_thread_for_ambiguous_stop_reply
1084 (const struct target_waitstatus &status);
1085
1086 void remote_notice_new_inferior (ptid_t currthread, bool executing);
1087
1088 void print_one_stopped_thread (thread_info *thread);
1089 void process_initial_stop_replies (int from_tty);
1090
1091 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
1092 bool silent_p);
1093
1094 void btrace_sync_conf (const btrace_config *conf);
1095
1096 void remote_btrace_maybe_reopen ();
1097
1098 void remove_new_fork_children (threads_listing_context *context);
1099 void kill_new_fork_children (inferior *inf);
1100 void discard_pending_stop_replies (struct inferior *inf);
1101 int stop_reply_queue_length ();
1102
1103 void check_pending_events_prevent_wildcard_vcont
1104 (bool *may_global_wildcard_vcont);
1105
1106 void discard_pending_stop_replies_in_queue ();
1107 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
1108 struct stop_reply *queued_stop_reply (ptid_t ptid);
1109 int peek_stop_reply (ptid_t ptid);
1110 void remote_parse_stop_reply (const char *buf, stop_reply *event);
1111
1112 void remote_stop_ns (ptid_t ptid);
1113 void remote_interrupt_as ();
1114 void remote_interrupt_ns ();
1115
1116 char *remote_get_noisy_reply ();
1117 int remote_query_attached (int pid);
1118 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
1119 int try_open_exec);
1120
1121 ptid_t remote_current_thread (ptid_t oldpid);
1122 ptid_t get_current_thread (const char *wait_status);
1123
1124 void set_thread (ptid_t ptid, int gen);
1125 void set_general_thread (ptid_t ptid);
1126 void set_continue_thread (ptid_t ptid);
1127 void set_general_process ();
1128
1129 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
1130
1131 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
1132 gdb_ext_thread_info *info);
1133 int remote_get_threadinfo (threadref *threadid, int fieldset,
1134 gdb_ext_thread_info *info);
1135
1136 int parse_threadlist_response (const char *pkt, int result_limit,
1137 threadref *original_echo,
1138 threadref *resultlist,
1139 int *doneflag);
1140 int remote_get_threadlist (int startflag, threadref *nextthread,
1141 int result_limit, int *done, int *result_count,
1142 threadref *threadlist);
1143
1144 int remote_threadlist_iterator (rmt_thread_action stepfunction,
1145 void *context, int looplimit);
1146
1147 int remote_get_threads_with_ql (threads_listing_context *context);
1148 int remote_get_threads_with_qxfer (threads_listing_context *context);
1149 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
1150
1151 void extended_remote_restart ();
1152
1153 void get_offsets ();
1154
1155 void remote_check_symbols ();
1156
1157 void remote_supported_packet (const struct protocol_feature *feature,
1158 enum packet_support support,
1159 const char *argument);
1160
1161 void remote_query_supported ();
1162
1163 void remote_packet_size (const protocol_feature *feature,
1164 packet_support support, const char *value);
1165
1166 void remote_serial_quit_handler ();
1167
1168 void remote_detach_pid (int pid);
1169
1170 void remote_vcont_probe ();
1171
1172 void remote_resume_with_hc (ptid_t ptid, int step,
1173 gdb_signal siggnal);
1174
1175 void send_interrupt_sequence ();
1176 void interrupt_query ();
1177
1178 void remote_notif_get_pending_events (const notif_client *nc);
1179
1180 int fetch_register_using_p (struct regcache *regcache,
1181 packet_reg *reg);
1182 int send_g_packet ();
1183 void process_g_packet (struct regcache *regcache);
1184 void fetch_registers_using_g (struct regcache *regcache);
1185 int store_register_using_P (const struct regcache *regcache,
1186 packet_reg *reg);
1187 void store_registers_using_G (const struct regcache *regcache);
1188
1189 void set_remote_traceframe ();
1190
1191 void check_binary_download (CORE_ADDR addr);
1192
1193 target_xfer_status remote_write_bytes_aux (const char *header,
1194 CORE_ADDR memaddr,
1195 const gdb_byte *myaddr,
1196 ULONGEST len_units,
1197 int unit_size,
1198 ULONGEST *xfered_len_units,
1199 char packet_format,
1200 int use_length);
1201
1202 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
1203 const gdb_byte *myaddr, ULONGEST len,
1204 int unit_size, ULONGEST *xfered_len);
1205
1206 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
1207 ULONGEST len_units,
1208 int unit_size, ULONGEST *xfered_len_units);
1209
1210 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
1211 ULONGEST memaddr,
1212 ULONGEST len,
1213 int unit_size,
1214 ULONGEST *xfered_len);
1215
1216 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
1217 gdb_byte *myaddr, ULONGEST len,
1218 int unit_size,
1219 ULONGEST *xfered_len);
1220
1221 packet_result remote_send_printf (const char *format, ...)
1222 ATTRIBUTE_PRINTF (2, 3);
1223
1224 target_xfer_status remote_flash_write (ULONGEST address,
1225 ULONGEST length, ULONGEST *xfered_len,
1226 const gdb_byte *data);
1227
1228 int readchar (int timeout);
1229
1230 void remote_serial_write (const char *str, int len);
1231
1232 int putpkt (const char *buf);
1233 int putpkt_binary (const char *buf, int cnt);
1234
1235 int putpkt (const gdb::char_vector &buf)
1236 {
1237 return putpkt (buf.data ());
1238 }
1239
1240 void skip_frame ();
1241 long read_frame (gdb::char_vector *buf_p);
1242 int getpkt (gdb::char_vector *buf, bool forever = false,
1243 bool *is_notif = nullptr);
1244 int remote_vkill (int pid);
1245 void remote_kill_k ();
1246
1247 void extended_remote_disable_randomization (int val);
1248 int extended_remote_run (const std::string &args);
1249
1250 void send_environment_packet (const char *action,
1251 const char *packet,
1252 const char *value);
1253
1254 void extended_remote_environment_support ();
1255 void extended_remote_set_inferior_cwd ();
1256
1257 target_xfer_status remote_write_qxfer (const char *object_name,
1258 const char *annex,
1259 const gdb_byte *writebuf,
1260 ULONGEST offset, LONGEST len,
1261 ULONGEST *xfered_len,
1262 const unsigned int which_packet);
1263
1264 target_xfer_status remote_read_qxfer (const char *object_name,
1265 const char *annex,
1266 gdb_byte *readbuf, ULONGEST offset,
1267 LONGEST len,
1268 ULONGEST *xfered_len,
1269 const unsigned int which_packet);
1270
1271 void push_stop_reply (struct stop_reply *new_event);
1272
1273 bool vcont_r_supported ();
1274
1275 remote_features m_features;
1276
1277 private:
1278
1279 bool start_remote_1 (int from_tty, int extended_p);
1280
1281 /* The remote state. Don't reference this directly. Use the
1282 get_remote_state method instead. */
1283 remote_state m_remote_state;
1284 };
1285
1286 static const target_info extended_remote_target_info = {
1287 "extended-remote",
1288 N_("Extended remote target using gdb-specific protocol"),
1289 remote_doc
1290 };
1291
1292 /* Set up the extended remote target by extending the standard remote
1293 target and adding to it. */
1294
1295 class extended_remote_target final : public remote_target
1296 {
1297 public:
1298 const target_info &info () const override
1299 { return extended_remote_target_info; }
1300
1301 /* Open an extended-remote connection. */
1302 static void open (const char *, int);
1303
1304 bool can_create_inferior () override { return true; }
1305 void create_inferior (const char *, const std::string &,
1306 char **, int) override;
1307
1308 void detach (inferior *, int) override;
1309
1310 bool can_attach () override { return true; }
1311 void attach (const char *, int) override;
1312
1313 void post_attach (int) override;
1314 bool supports_disable_randomization () override;
1315 };
1316
1317 struct stop_reply : public notif_event
1318 {
1319 ~stop_reply ();
1320
1321 /* The identifier of the thread about this event */
1322 ptid_t ptid;
1323
1324 /* The remote state this event is associated with. When the remote
1325 connection, represented by a remote_state object, is closed,
1326 all the associated stop_reply events should be released. */
1327 struct remote_state *rs;
1328
1329 struct target_waitstatus ws;
1330
1331 /* The architecture associated with the expedited registers. */
1332 gdbarch *arch;
1333
1334 /* Expedited registers. This makes remote debugging a bit more
1335 efficient for those targets that provide critical registers as
1336 part of their normal status mechanism (as another roundtrip to
1337 fetch them is avoided). */
1338 std::vector<cached_reg_t> regcache;
1339
1340 enum target_stop_reason stop_reason;
1341
1342 CORE_ADDR watch_data_address;
1343
1344 int core;
1345 };
1346
1347 /* Return TARGET as a remote_target if it is one, else nullptr. */
1348
1349 static remote_target *
1350 as_remote_target (process_stratum_target *target)
1351 {
1352 return dynamic_cast<remote_target *> (target);
1353 }
1354
1355 /* See remote.h. */
1356
1357 bool
1358 is_remote_target (process_stratum_target *target)
1359 {
1360 return as_remote_target (target) != nullptr;
1361 }
1362
1363 /* Per-program-space data key. */
1364 static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
1365 remote_pspace_data;
1366
1367 /* The variable registered as the control variable used by the
1368 remote exec-file commands. While the remote exec-file setting is
1369 per-program-space, the set/show machinery uses this as the
1370 location of the remote exec-file value. */
1371 static std::string remote_exec_file_var;
1372
1373 /* The size to align memory write packets, when practical. The protocol
1374 does not guarantee any alignment, and gdb will generate short
1375 writes and unaligned writes, but even as a best-effort attempt this
1376 can improve bulk transfers. For instance, if a write is misaligned
1377 relative to the target's data bus, the stub may need to make an extra
1378 round trip fetching data from the target. This doesn't make a
1379 huge difference, but it's easy to do, so we try to be helpful.
1380
1381 The alignment chosen is arbitrary; usually data bus width is
1382 important here, not the possibly larger cache line size. */
1383 enum { REMOTE_ALIGN_WRITES = 16 };
1384
1385 /* Prototypes for local functions. */
1386
1387 static int hexnumlen (ULONGEST num);
1388
1389 static int stubhex (int ch);
1390
1391 static int hexnumstr (char *, ULONGEST);
1392
1393 static int hexnumnstr (char *, ULONGEST, int);
1394
1395 static CORE_ADDR remote_address_masked (CORE_ADDR);
1396
1397 static int stub_unpack_int (const char *buff, int fieldlength);
1398
1399 static void set_remote_protocol_packet_cmd (const char *args, int from_tty,
1400 cmd_list_element *c);
1401
1402 static void show_packet_config_cmd (ui_file *file,
1403 const unsigned int which_packet,
1404 remote_target *remote);
1405
1406 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1407 int from_tty,
1408 struct cmd_list_element *c,
1409 const char *value);
1410
1411 static ptid_t read_ptid (const char *buf, const char **obuf);
1412
1413 static bool remote_read_description_p (struct target_ops *target);
1414
1415 static void remote_console_output (const char *msg);
1416
1417 static void remote_btrace_reset (remote_state *rs);
1418
1419 static void remote_unpush_and_throw (remote_target *target);
1420
1421 /* For "remote". */
1422
1423 static struct cmd_list_element *remote_cmdlist;
1424
1425 /* For "set remote" and "show remote". */
1426
1427 static struct cmd_list_element *remote_set_cmdlist;
1428 static struct cmd_list_element *remote_show_cmdlist;
1429
1430 /* Controls whether GDB is willing to use range stepping. */
1431
1432 static bool use_range_stepping = true;
1433
1434 /* From the remote target's point of view, each thread is in one of these three
1435 states. */
1436 enum class resume_state
1437 {
1438 /* Not resumed - we haven't been asked to resume this thread. */
1439 NOT_RESUMED,
1440
1441 /* We have been asked to resume this thread, but haven't sent a vCont action
1442 for it yet. We'll need to consider it next time commit_resume is
1443 called. */
1444 RESUMED_PENDING_VCONT,
1445
1446 /* We have been asked to resume this thread, and we have sent a vCont action
1447 for it. */
1448 RESUMED,
1449 };
1450
1451 /* Information about a thread's pending vCont-resume. Used when a thread is in
1452 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1453 stores this information which is then picked up by
1454 remote_target::commit_resume to know which is the proper action for this
1455 thread to include in the vCont packet. */
1456 struct resumed_pending_vcont_info
1457 {
1458 /* True if the last resume call for this thread was a step request, false
1459 if a continue request. */
1460 bool step;
1461
1462 /* The signal specified in the last resume call for this thread. */
1463 gdb_signal sig;
1464 };
1465
1466 /* Private data that we'll store in (struct thread_info)->priv. */
1467 struct remote_thread_info : public private_thread_info
1468 {
1469 std::string extra;
1470 std::string name;
1471 int core = -1;
1472
1473 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1474 sequence of bytes. */
1475 gdb::byte_vector thread_handle;
1476
1477 /* Whether the target stopped for a breakpoint/watchpoint. */
1478 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1479
1480 /* This is set to the data address of the access causing the target
1481 to stop for a watchpoint. */
1482 CORE_ADDR watch_data_address = 0;
1483
1484 /* Get the thread's resume state. */
1485 enum resume_state get_resume_state () const
1486 {
1487 return m_resume_state;
1488 }
1489
1490 /* Put the thread in the NOT_RESUMED state. */
1491 void set_not_resumed ()
1492 {
1493 m_resume_state = resume_state::NOT_RESUMED;
1494 }
1495
1496 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1497 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1498 {
1499 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1500 m_resumed_pending_vcont_info.step = step;
1501 m_resumed_pending_vcont_info.sig = sig;
1502 }
1503
1504 /* Get the information this thread's pending vCont-resumption.
1505
1506 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1507 state. */
1508 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1509 {
1510 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1511
1512 return m_resumed_pending_vcont_info;
1513 }
1514
1515 /* Put the thread in the VCONT_RESUMED state. */
1516 void set_resumed ()
1517 {
1518 m_resume_state = resume_state::RESUMED;
1519 }
1520
1521 private:
1522 /* Resume state for this thread. This is used to implement vCont action
1523 coalescing (only when the target operates in non-stop mode).
1524
1525 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1526 which notes that this thread must be considered in the next commit_resume
1527 call.
1528
1529 remote_target::commit_resume sends a vCont packet with actions for the
1530 threads in the RESUMED_PENDING_VCONT state and moves them to the
1531 VCONT_RESUMED state.
1532
1533 When reporting a stop to the core for a thread, that thread is moved back
1534 to the NOT_RESUMED state. */
1535 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1536
1537 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1538 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1539 };
1540
1541 remote_state::remote_state ()
1542 : buf (400)
1543 {
1544 }
1545
1546 remote_state::~remote_state ()
1547 {
1548 xfree (this->last_pass_packet);
1549 xfree (this->last_program_signals_packet);
1550 xfree (this->finished_object);
1551 xfree (this->finished_annex);
1552 }
1553
1554 /* Utility: generate error from an incoming stub packet. */
1555 static void
1556 trace_error (char *buf)
1557 {
1558 if (*buf++ != 'E')
1559 return; /* not an error msg */
1560 switch (*buf)
1561 {
1562 case '1': /* malformed packet error */
1563 if (*++buf == '0') /* general case: */
1564 error (_("remote.c: error in outgoing packet."));
1565 else
1566 error (_("remote.c: error in outgoing packet at field #%ld."),
1567 strtol (buf, NULL, 16));
1568 default:
1569 error (_("Target returns error code '%s'."), buf);
1570 }
1571 }
1572
1573 /* Utility: wait for reply from stub, while accepting "O" packets. */
1574
1575 char *
1576 remote_target::remote_get_noisy_reply ()
1577 {
1578 struct remote_state *rs = get_remote_state ();
1579
1580 do /* Loop on reply from remote stub. */
1581 {
1582 char *buf;
1583
1584 QUIT; /* Allow user to bail out with ^C. */
1585 getpkt (&rs->buf);
1586 buf = rs->buf.data ();
1587 if (buf[0] == 'E')
1588 trace_error (buf);
1589 else if (startswith (buf, "qRelocInsn:"))
1590 {
1591 ULONGEST ul;
1592 CORE_ADDR from, to, org_to;
1593 const char *p, *pp;
1594 int adjusted_size = 0;
1595 int relocated = 0;
1596
1597 p = buf + strlen ("qRelocInsn:");
1598 pp = unpack_varlen_hex (p, &ul);
1599 if (*pp != ';')
1600 error (_("invalid qRelocInsn packet: %s"), buf);
1601 from = ul;
1602
1603 p = pp + 1;
1604 unpack_varlen_hex (p, &ul);
1605 to = ul;
1606
1607 org_to = to;
1608
1609 try
1610 {
1611 gdbarch_relocate_instruction (current_inferior ()->arch (),
1612 &to, from);
1613 relocated = 1;
1614 }
1615 catch (const gdb_exception &ex)
1616 {
1617 if (ex.error == MEMORY_ERROR)
1618 {
1619 /* Propagate memory errors silently back to the
1620 target. The stub may have limited the range of
1621 addresses we can write to, for example. */
1622 }
1623 else
1624 {
1625 /* Something unexpectedly bad happened. Be verbose
1626 so we can tell what, and propagate the error back
1627 to the stub, so it doesn't get stuck waiting for
1628 a response. */
1629 exception_fprintf (gdb_stderr, ex,
1630 _("warning: relocating instruction: "));
1631 }
1632 putpkt ("E01");
1633 }
1634
1635 if (relocated)
1636 {
1637 adjusted_size = to - org_to;
1638
1639 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1640 putpkt (buf);
1641 }
1642 }
1643 else if (buf[0] == 'O' && buf[1] != 'K')
1644 remote_console_output (buf + 1); /* 'O' message from stub */
1645 else
1646 return buf; /* Here's the actual reply. */
1647 }
1648 while (1);
1649 }
1650
1651 struct remote_arch_state *
1652 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1653 {
1654 remote_arch_state *rsa;
1655
1656 auto it = this->m_arch_states.find (gdbarch);
1657 if (it == this->m_arch_states.end ())
1658 {
1659 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1660 std::forward_as_tuple (gdbarch),
1661 std::forward_as_tuple (gdbarch));
1662 rsa = &p.first->second;
1663
1664 /* Make sure that the packet buffer is plenty big enough for
1665 this architecture. */
1666 if (this->buf.size () < rsa->remote_packet_size)
1667 this->buf.resize (2 * rsa->remote_packet_size);
1668 }
1669 else
1670 rsa = &it->second;
1671
1672 return rsa;
1673 }
1674
1675 /* Fetch the global remote target state. */
1676
1677 remote_state *
1678 remote_target::get_remote_state ()
1679 {
1680 /* Make sure that the remote architecture state has been
1681 initialized, because doing so might reallocate rs->buf. Any
1682 function which calls getpkt also needs to be mindful of changes
1683 to rs->buf, but this call limits the number of places which run
1684 into trouble. */
1685 m_remote_state.get_remote_arch_state (current_inferior ()->arch ());
1686
1687 return &m_remote_state;
1688 }
1689
1690 /* Fetch the remote exec-file from the current program space. */
1691
1692 static const char *
1693 get_remote_exec_file (void)
1694 {
1695 char *remote_exec_file;
1696
1697 remote_exec_file = remote_pspace_data.get (current_program_space);
1698 if (remote_exec_file == NULL)
1699 return "";
1700
1701 return remote_exec_file;
1702 }
1703
1704 /* Set the remote exec file for PSPACE. */
1705
1706 static void
1707 set_pspace_remote_exec_file (struct program_space *pspace,
1708 const char *remote_exec_file)
1709 {
1710 char *old_file = remote_pspace_data.get (pspace);
1711
1712 xfree (old_file);
1713 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1714 }
1715
1716 /* The "set/show remote exec-file" set command hook. */
1717
1718 static void
1719 set_remote_exec_file (const char *ignored, int from_tty,
1720 struct cmd_list_element *c)
1721 {
1722 set_pspace_remote_exec_file (current_program_space,
1723 remote_exec_file_var.c_str ());
1724 }
1725
1726 /* The "set/show remote exec-file" show command hook. */
1727
1728 static void
1729 show_remote_exec_file (struct ui_file *file, int from_tty,
1730 struct cmd_list_element *cmd, const char *value)
1731 {
1732 gdb_printf (file, "%s\n", get_remote_exec_file ());
1733 }
1734
1735 static int
1736 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1737 {
1738 int regnum, num_remote_regs, offset;
1739 struct packet_reg **remote_regs;
1740
1741 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1742 {
1743 struct packet_reg *r = &regs[regnum];
1744
1745 if (register_size (gdbarch, regnum) == 0)
1746 /* Do not try to fetch zero-sized (placeholder) registers. */
1747 r->pnum = -1;
1748 else
1749 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1750
1751 r->regnum = regnum;
1752 }
1753
1754 /* Define the g/G packet format as the contents of each register
1755 with a remote protocol number, in order of ascending protocol
1756 number. */
1757
1758 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1759 for (num_remote_regs = 0, regnum = 0;
1760 regnum < gdbarch_num_regs (gdbarch);
1761 regnum++)
1762 if (regs[regnum].pnum != -1)
1763 remote_regs[num_remote_regs++] = &regs[regnum];
1764
1765 std::sort (remote_regs, remote_regs + num_remote_regs,
1766 [] (const packet_reg *a, const packet_reg *b)
1767 { return a->pnum < b->pnum; });
1768
1769 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1770 {
1771 remote_regs[regnum]->in_g_packet = 1;
1772 remote_regs[regnum]->offset = offset;
1773 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1774 }
1775
1776 return offset;
1777 }
1778
1779 /* Given the architecture described by GDBARCH, return the remote
1780 protocol register's number and the register's offset in the g/G
1781 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1782 If the target does not have a mapping for REGNUM, return false,
1783 otherwise, return true. */
1784
1785 int
1786 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1787 int *pnum, int *poffset)
1788 {
1789 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1790
1791 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1792
1793 map_regcache_remote_table (gdbarch, regs.data ());
1794
1795 *pnum = regs[regnum].pnum;
1796 *poffset = regs[regnum].offset;
1797
1798 return *pnum != -1;
1799 }
1800
1801 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1802 {
1803 /* Use the architecture to build a regnum<->pnum table, which will be
1804 1:1 unless a feature set specifies otherwise. */
1805 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1806
1807 /* Record the maximum possible size of the g packet - it may turn out
1808 to be smaller. */
1809 this->sizeof_g_packet
1810 = map_regcache_remote_table (gdbarch, this->regs.get ());
1811
1812 /* Default maximum number of characters in a packet body. Many
1813 remote stubs have a hardwired buffer size of 400 bytes
1814 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1815 as the maximum packet-size to ensure that the packet and an extra
1816 NUL character can always fit in the buffer. This stops GDB
1817 trashing stubs that try to squeeze an extra NUL into what is
1818 already a full buffer (As of 1999-12-04 that was most stubs). */
1819 this->remote_packet_size = 400 - 1;
1820
1821 /* This one is filled in when a ``g'' packet is received. */
1822 this->actual_register_packet_size = 0;
1823
1824 /* Should rsa->sizeof_g_packet needs more space than the
1825 default, adjust the size accordingly. Remember that each byte is
1826 encoded as two characters. 32 is the overhead for the packet
1827 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1828 (``$NN:G...#NN'') is a better guess, the below has been padded a
1829 little. */
1830 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1831 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1832 }
1833
1834 /* Get a pointer to the current remote target. If not connected to a
1835 remote target, return NULL. */
1836
1837 static remote_target *
1838 get_current_remote_target ()
1839 {
1840 target_ops *proc_target = current_inferior ()->process_target ();
1841 return dynamic_cast<remote_target *> (proc_target);
1842 }
1843
1844 /* Return the current allowed size of a remote packet. This is
1845 inferred from the current architecture, and should be used to
1846 limit the length of outgoing packets. */
1847 long
1848 remote_target::get_remote_packet_size ()
1849 {
1850 struct remote_state *rs = get_remote_state ();
1851 remote_arch_state *rsa
1852 = rs->get_remote_arch_state (current_inferior ()->arch ());
1853
1854 if (rs->explicit_packet_size)
1855 return rs->explicit_packet_size;
1856
1857 return rsa->remote_packet_size;
1858 }
1859
1860 static struct packet_reg *
1861 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1862 long regnum)
1863 {
1864 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1865 return NULL;
1866 else
1867 {
1868 struct packet_reg *r = &rsa->regs[regnum];
1869
1870 gdb_assert (r->regnum == regnum);
1871 return r;
1872 }
1873 }
1874
1875 static struct packet_reg *
1876 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1877 LONGEST pnum)
1878 {
1879 int i;
1880
1881 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1882 {
1883 struct packet_reg *r = &rsa->regs[i];
1884
1885 if (r->pnum == pnum)
1886 return r;
1887 }
1888 return NULL;
1889 }
1890
1891 /* Allow the user to specify what sequence to send to the remote
1892 when he requests a program interruption: Although ^C is usually
1893 what remote systems expect (this is the default, here), it is
1894 sometimes preferable to send a break. On other systems such
1895 as the Linux kernel, a break followed by g, which is Magic SysRq g
1896 is required in order to interrupt the execution. */
1897 const char interrupt_sequence_control_c[] = "Ctrl-C";
1898 const char interrupt_sequence_break[] = "BREAK";
1899 const char interrupt_sequence_break_g[] = "BREAK-g";
1900 static const char *const interrupt_sequence_modes[] =
1901 {
1902 interrupt_sequence_control_c,
1903 interrupt_sequence_break,
1904 interrupt_sequence_break_g,
1905 NULL
1906 };
1907 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1908
1909 static void
1910 show_interrupt_sequence (struct ui_file *file, int from_tty,
1911 struct cmd_list_element *c,
1912 const char *value)
1913 {
1914 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1915 gdb_printf (file,
1916 _("Send the ASCII ETX character (Ctrl-c) "
1917 "to the remote target to interrupt the "
1918 "execution of the program.\n"));
1919 else if (interrupt_sequence_mode == interrupt_sequence_break)
1920 gdb_printf (file,
1921 _("send a break signal to the remote target "
1922 "to interrupt the execution of the program.\n"));
1923 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1924 gdb_printf (file,
1925 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1926 "the remote target to interrupt the execution "
1927 "of Linux kernel.\n"));
1928 else
1929 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
1930 interrupt_sequence_mode);
1931 }
1932
1933 /* This boolean variable specifies whether interrupt_sequence is sent
1934 to the remote target when gdb connects to it.
1935 This is mostly needed when you debug the Linux kernel: The Linux kernel
1936 expects BREAK g which is Magic SysRq g for connecting gdb. */
1937 static bool interrupt_on_connect = false;
1938
1939 /* This variable is used to implement the "set/show remotebreak" commands.
1940 Since these commands are now deprecated in favor of "set/show remote
1941 interrupt-sequence", it no longer has any effect on the code. */
1942 static bool remote_break;
1943
1944 static void
1945 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1946 {
1947 if (remote_break)
1948 interrupt_sequence_mode = interrupt_sequence_break;
1949 else
1950 interrupt_sequence_mode = interrupt_sequence_control_c;
1951 }
1952
1953 static void
1954 show_remotebreak (struct ui_file *file, int from_tty,
1955 struct cmd_list_element *c,
1956 const char *value)
1957 {
1958 }
1959
1960 /* This variable sets the number of bits in an address that are to be
1961 sent in a memory ("M" or "m") packet. Normally, after stripping
1962 leading zeros, the entire address would be sent. This variable
1963 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1964 initial implementation of remote.c restricted the address sent in
1965 memory packets to ``host::sizeof long'' bytes - (typically 32
1966 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1967 address was never sent. Since fixing this bug may cause a break in
1968 some remote targets this variable is principally provided to
1969 facilitate backward compatibility. */
1970
1971 static unsigned int remote_address_size;
1972
1973 \f
1974 /* The default max memory-write-packet-size, when the setting is
1975 "fixed". The 16k is historical. (It came from older GDB's using
1976 alloca for buffers and the knowledge (folklore?) that some hosts
1977 don't cope very well with large alloca calls.) */
1978 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1979
1980 /* The minimum remote packet size for memory transfers. Ensures we
1981 can write at least one byte. */
1982 #define MIN_MEMORY_PACKET_SIZE 20
1983
1984 /* Get the memory packet size, assuming it is fixed. */
1985
1986 static long
1987 get_fixed_memory_packet_size (struct memory_packet_config *config)
1988 {
1989 gdb_assert (config->fixed_p);
1990
1991 if (config->size <= 0)
1992 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1993 else
1994 return config->size;
1995 }
1996
1997 /* Compute the current size of a read/write packet. Since this makes
1998 use of ``actual_register_packet_size'' the computation is dynamic. */
1999
2000 long
2001 remote_target::get_memory_packet_size (struct memory_packet_config *config)
2002 {
2003 struct remote_state *rs = get_remote_state ();
2004 remote_arch_state *rsa
2005 = rs->get_remote_arch_state (current_inferior ()->arch ());
2006
2007 long what_they_get;
2008 if (config->fixed_p)
2009 what_they_get = get_fixed_memory_packet_size (config);
2010 else
2011 {
2012 what_they_get = get_remote_packet_size ();
2013 /* Limit the packet to the size specified by the user. */
2014 if (config->size > 0
2015 && what_they_get > config->size)
2016 what_they_get = config->size;
2017
2018 /* Limit it to the size of the targets ``g'' response unless we have
2019 permission from the stub to use a larger packet size. */
2020 if (rs->explicit_packet_size == 0
2021 && rsa->actual_register_packet_size > 0
2022 && what_they_get > rsa->actual_register_packet_size)
2023 what_they_get = rsa->actual_register_packet_size;
2024 }
2025 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
2026 what_they_get = MIN_MEMORY_PACKET_SIZE;
2027
2028 /* Make sure there is room in the global buffer for this packet
2029 (including its trailing NUL byte). */
2030 if (rs->buf.size () < what_they_get + 1)
2031 rs->buf.resize (2 * what_they_get);
2032
2033 return what_they_get;
2034 }
2035
2036 /* Update the size of a read/write packet. If they user wants
2037 something really big then do a sanity check. */
2038
2039 static void
2040 set_memory_packet_size (const char *args, struct memory_packet_config *config,
2041 bool target_connected)
2042 {
2043 int fixed_p = config->fixed_p;
2044 long size = config->size;
2045
2046 if (args == NULL)
2047 error (_("Argument required (integer, \"fixed\" or \"limit\")."));
2048 else if (strcmp (args, "hard") == 0
2049 || strcmp (args, "fixed") == 0)
2050 fixed_p = 1;
2051 else if (strcmp (args, "soft") == 0
2052 || strcmp (args, "limit") == 0)
2053 fixed_p = 0;
2054 else
2055 {
2056 char *end;
2057
2058 size = strtoul (args, &end, 0);
2059 if (args == end)
2060 error (_("Invalid %s (bad syntax)."), config->name);
2061
2062 /* Instead of explicitly capping the size of a packet to or
2063 disallowing it, the user is allowed to set the size to
2064 something arbitrarily large. */
2065 }
2066
2067 /* Extra checks? */
2068 if (fixed_p && !config->fixed_p)
2069 {
2070 /* So that the query shows the correct value. */
2071 long query_size = (size <= 0
2072 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
2073 : size);
2074
2075 if (target_connected
2076 && !query (_("The target may not be able to correctly handle a %s\n"
2077 "of %ld bytes. Change the packet size? "),
2078 config->name, query_size))
2079 error (_("Packet size not changed."));
2080 else if (!target_connected
2081 && !query (_("Future remote targets may not be able to "
2082 "correctly handle a %s\nof %ld bytes. Change the "
2083 "packet size for future remote targets? "),
2084 config->name, query_size))
2085 error (_("Packet size not changed."));
2086 }
2087 /* Update the config. */
2088 config->fixed_p = fixed_p;
2089 config->size = size;
2090
2091 const char *target_type = get_target_type_name (target_connected);
2092 gdb_printf (_("The %s %s is set to \"%s\".\n"), config->name, target_type,
2093 args);
2094
2095 }
2096
2097 /* Show the memory-read or write-packet size configuration CONFIG of the
2098 target REMOTE. If REMOTE is nullptr, the default configuration for future
2099 remote targets should be passed in CONFIG. */
2100
2101 static void
2102 show_memory_packet_size (memory_packet_config *config, remote_target *remote)
2103 {
2104 const char *target_type = get_target_type_name (remote != nullptr);
2105
2106 if (config->size == 0)
2107 gdb_printf (_("The %s %s is 0 (default). "), config->name, target_type);
2108 else
2109 gdb_printf (_("The %s %s is %ld. "), config->name, target_type,
2110 config->size);
2111
2112 if (config->fixed_p)
2113 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
2114 get_fixed_memory_packet_size (config));
2115 else
2116 {
2117 if (remote != nullptr)
2118 gdb_printf (_("Packets are limited to %ld bytes.\n"),
2119 remote->get_memory_packet_size (config));
2120 else
2121 gdb_puts ("The actual limit will be further reduced "
2122 "dependent on the target.\n");
2123 }
2124 }
2125
2126 /* Configure the memory-write-packet size of the currently selected target. If
2127 no target is available, the default configuration for future remote targets
2128 is configured. */
2129
2130 static void
2131 set_memory_write_packet_size (const char *args, int from_tty)
2132 {
2133 remote_target *remote = get_current_remote_target ();
2134 if (remote != nullptr)
2135 {
2136 set_memory_packet_size
2137 (args, &remote->m_features.m_memory_write_packet_config, true);
2138 }
2139 else
2140 {
2141 memory_packet_config* config = &memory_write_packet_config;
2142 set_memory_packet_size (args, config, false);
2143 }
2144 }
2145
2146 /* Display the memory-write-packet size of the currently selected target. If
2147 no target is available, the default configuration for future remote targets
2148 is shown. */
2149
2150 static void
2151 show_memory_write_packet_size (const char *args, int from_tty)
2152 {
2153 remote_target *remote = get_current_remote_target ();
2154 if (remote != nullptr)
2155 show_memory_packet_size (&remote->m_features.m_memory_write_packet_config,
2156 remote);
2157 else
2158 show_memory_packet_size (&memory_write_packet_config, nullptr);
2159 }
2160
2161 /* Show the number of hardware watchpoints that can be used. */
2162
2163 static void
2164 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
2165 struct cmd_list_element *c,
2166 const char *value)
2167 {
2168 gdb_printf (file, _("The maximum number of target hardware "
2169 "watchpoints is %s.\n"), value);
2170 }
2171
2172 /* Show the length limit (in bytes) for hardware watchpoints. */
2173
2174 static void
2175 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
2176 struct cmd_list_element *c,
2177 const char *value)
2178 {
2179 gdb_printf (file, _("The maximum length (in bytes) of a target "
2180 "hardware watchpoint is %s.\n"), value);
2181 }
2182
2183 /* Show the number of hardware breakpoints that can be used. */
2184
2185 static void
2186 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
2187 struct cmd_list_element *c,
2188 const char *value)
2189 {
2190 gdb_printf (file, _("The maximum number of target hardware "
2191 "breakpoints is %s.\n"), value);
2192 }
2193
2194 /* Controls the maximum number of characters to display in the debug output
2195 for each remote packet. The remaining characters are omitted. */
2196
2197 static int remote_packet_max_chars = 512;
2198
2199 /* Show the maximum number of characters to display for each remote packet
2200 when remote debugging is enabled. */
2201
2202 static void
2203 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
2204 struct cmd_list_element *c,
2205 const char *value)
2206 {
2207 gdb_printf (file, _("Number of remote packet characters to "
2208 "display is %s.\n"), value);
2209 }
2210
2211 long
2212 remote_target::get_memory_write_packet_size ()
2213 {
2214 return get_memory_packet_size (&m_features.m_memory_write_packet_config);
2215 }
2216
2217 /* Configure the memory-read-packet size of the currently selected target. If
2218 no target is available, the default configuration for future remote targets
2219 is adapted. */
2220
2221 static void
2222 set_memory_read_packet_size (const char *args, int from_tty)
2223 {
2224 remote_target *remote = get_current_remote_target ();
2225 if (remote != nullptr)
2226 set_memory_packet_size
2227 (args, &remote->m_features.m_memory_read_packet_config, true);
2228 else
2229 {
2230 memory_packet_config* config = &memory_read_packet_config;
2231 set_memory_packet_size (args, config, false);
2232 }
2233
2234 }
2235
2236 /* Display the memory-read-packet size of the currently selected target. If
2237 no target is available, the default configuration for future remote targets
2238 is shown. */
2239
2240 static void
2241 show_memory_read_packet_size (const char *args, int from_tty)
2242 {
2243 remote_target *remote = get_current_remote_target ();
2244 if (remote != nullptr)
2245 show_memory_packet_size (&remote->m_features.m_memory_read_packet_config,
2246 remote);
2247 else
2248 show_memory_packet_size (&memory_read_packet_config, nullptr);
2249 }
2250
2251 long
2252 remote_target::get_memory_read_packet_size ()
2253 {
2254 long size = get_memory_packet_size (&m_features.m_memory_read_packet_config);
2255
2256 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
2257 extra buffer size argument before the memory read size can be
2258 increased beyond this. */
2259 if (size > get_remote_packet_size ())
2260 size = get_remote_packet_size ();
2261 return size;
2262 }
2263
2264 static enum packet_support packet_config_support (const packet_config *config);
2265
2266
2267 static void
2268 set_remote_protocol_packet_cmd (const char *args, int from_tty,
2269 cmd_list_element *c)
2270 {
2271 remote_target *remote = get_current_remote_target ();
2272 gdb_assert (c->var.has_value ());
2273
2274 auto *default_config = static_cast<packet_config *> (c->context ());
2275 const int packet_idx = std::distance (remote_protocol_packets,
2276 default_config);
2277
2278 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2279 {
2280 const char *name = packets_descriptions[packet_idx].name;
2281 const auto_boolean value = c->var->get<auto_boolean> ();
2282 const char *support = get_packet_support_name (value);
2283 const char *target_type = get_target_type_name (remote != nullptr);
2284
2285 if (remote != nullptr)
2286 remote->m_features.m_protocol_packets[packet_idx].detect = value;
2287 else
2288 remote_protocol_packets[packet_idx].detect = value;
2289
2290 gdb_printf (_("Support for the '%s' packet %s is set to \"%s\".\n"), name,
2291 target_type, support);
2292 return;
2293 }
2294
2295 internal_error (_("Could not find config for %s"), c->name);
2296 }
2297
2298 static void
2299 show_packet_config_cmd (ui_file *file, const unsigned int which_packet,
2300 remote_target *remote)
2301 {
2302 const char *support = "internal-error";
2303 const char *target_type = get_target_type_name (remote != nullptr);
2304
2305 packet_config *config;
2306 if (remote != nullptr)
2307 config = &remote->m_features.m_protocol_packets[which_packet];
2308 else
2309 config = &remote_protocol_packets[which_packet];
2310
2311 switch (packet_config_support (config))
2312 {
2313 case PACKET_ENABLE:
2314 support = "enabled";
2315 break;
2316 case PACKET_DISABLE:
2317 support = "disabled";
2318 break;
2319 case PACKET_SUPPORT_UNKNOWN:
2320 support = "unknown";
2321 break;
2322 }
2323 switch (config->detect)
2324 {
2325 case AUTO_BOOLEAN_AUTO:
2326 gdb_printf (file,
2327 _("Support for the '%s' packet %s is \"auto\", "
2328 "currently %s.\n"),
2329 packets_descriptions[which_packet].name, target_type,
2330 support);
2331 break;
2332 case AUTO_BOOLEAN_TRUE:
2333 case AUTO_BOOLEAN_FALSE:
2334 gdb_printf (file,
2335 _("Support for the '%s' packet %s is \"%s\".\n"),
2336 packets_descriptions[which_packet].name, target_type,
2337 get_packet_support_name (config->detect));
2338 break;
2339 }
2340 }
2341
2342 static void
2343 add_packet_config_cmd (const unsigned int which_packet, const char *name,
2344 const char *title, int legacy)
2345 {
2346 packets_descriptions[which_packet].name = name;
2347 packets_descriptions[which_packet].title = title;
2348
2349 packet_config *config = &remote_protocol_packets[which_packet];
2350
2351 gdb::unique_xmalloc_ptr<char> set_doc
2352 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
2353 name, title);
2354 gdb::unique_xmalloc_ptr<char> show_doc
2355 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
2356 name, title);
2357 /* set/show TITLE-packet {auto,on,off} */
2358 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
2359 set_show_commands cmds
2360 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
2361 &config->detect, set_doc.get (),
2362 show_doc.get (), NULL, /* help_doc */
2363 set_remote_protocol_packet_cmd,
2364 show_remote_protocol_packet_cmd,
2365 &remote_set_cmdlist, &remote_show_cmdlist);
2366 cmds.show->set_context (config);
2367 cmds.set->set_context (config);
2368
2369 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
2370 if (legacy)
2371 {
2372 /* It's not clear who should take ownership of the LEGACY_NAME string
2373 created below, so, for now, place the string into a static vector
2374 which ensures the strings is released when GDB exits. */
2375 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
2376 gdb::unique_xmalloc_ptr<char> legacy_name
2377 = xstrprintf ("%s-packet", name);
2378 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
2379 &remote_set_cmdlist);
2380 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
2381 &remote_show_cmdlist);
2382 legacy_names.emplace_back (std::move (legacy_name));
2383 }
2384 }
2385
2386 static enum packet_result
2387 packet_check_result (const char *buf)
2388 {
2389 if (buf[0] != '\0')
2390 {
2391 /* The stub recognized the packet request. Check that the
2392 operation succeeded. */
2393 if (buf[0] == 'E'
2394 && isxdigit (buf[1]) && isxdigit (buf[2])
2395 && buf[3] == '\0')
2396 /* "Enn" - definitely an error. */
2397 return PACKET_ERROR;
2398
2399 /* Always treat "E." as an error. This will be used for
2400 more verbose error messages, such as E.memtypes. */
2401 if (buf[0] == 'E' && buf[1] == '.')
2402 return PACKET_ERROR;
2403
2404 /* The packet may or may not be OK. Just assume it is. */
2405 return PACKET_OK;
2406 }
2407 else
2408 /* The stub does not support the packet. */
2409 return PACKET_UNKNOWN;
2410 }
2411
2412 static enum packet_result
2413 packet_check_result (const gdb::char_vector &buf)
2414 {
2415 return packet_check_result (buf.data ());
2416 }
2417
2418 packet_result
2419 remote_features::packet_ok (const char *buf, const int which_packet)
2420 {
2421 packet_config *config = &m_protocol_packets[which_packet];
2422 packet_description *descr = &packets_descriptions[which_packet];
2423
2424 enum packet_result result;
2425
2426 if (config->detect != AUTO_BOOLEAN_TRUE
2427 && config->support == PACKET_DISABLE)
2428 internal_error (_("packet_ok: attempt to use a disabled packet"));
2429
2430 result = packet_check_result (buf);
2431 switch (result)
2432 {
2433 case PACKET_OK:
2434 case PACKET_ERROR:
2435 /* The stub recognized the packet request. */
2436 if (config->support == PACKET_SUPPORT_UNKNOWN)
2437 {
2438 remote_debug_printf ("Packet %s (%s) is supported",
2439 descr->name, descr->title);
2440 config->support = PACKET_ENABLE;
2441 }
2442 break;
2443 case PACKET_UNKNOWN:
2444 /* The stub does not support the packet. */
2445 if (config->detect == AUTO_BOOLEAN_AUTO
2446 && config->support == PACKET_ENABLE)
2447 {
2448 /* If the stub previously indicated that the packet was
2449 supported then there is a protocol error. */
2450 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2451 descr->name, descr->title);
2452 }
2453 else if (config->detect == AUTO_BOOLEAN_TRUE)
2454 {
2455 /* The user set it wrong. */
2456 error (_("Enabled packet %s (%s) not recognized by stub"),
2457 descr->name, descr->title);
2458 }
2459
2460 remote_debug_printf ("Packet %s (%s) is NOT supported", descr->name,
2461 descr->title);
2462 config->support = PACKET_DISABLE;
2463 break;
2464 }
2465
2466 return result;
2467 }
2468
2469 packet_result
2470 remote_features::packet_ok (const gdb::char_vector &buf, const int which_packet)
2471 {
2472 return packet_ok (buf.data (), which_packet);
2473 }
2474
2475 /* Returns whether a given packet or feature is supported. This takes
2476 into account the state of the corresponding "set remote foo-packet"
2477 command, which may be used to bypass auto-detection. */
2478
2479 static enum packet_support
2480 packet_config_support (const packet_config *config)
2481 {
2482 switch (config->detect)
2483 {
2484 case AUTO_BOOLEAN_TRUE:
2485 return PACKET_ENABLE;
2486 case AUTO_BOOLEAN_FALSE:
2487 return PACKET_DISABLE;
2488 case AUTO_BOOLEAN_AUTO:
2489 return config->support;
2490 default:
2491 gdb_assert_not_reached ("bad switch");
2492 }
2493 }
2494
2495 packet_support
2496 remote_features::packet_support (int packet) const
2497 {
2498 const packet_config *config = &m_protocol_packets[packet];
2499 return packet_config_support (config);
2500 }
2501
2502 static void
2503 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2504 struct cmd_list_element *c,
2505 const char *value)
2506 {
2507 remote_target *remote = get_current_remote_target ();
2508 gdb_assert (c->var.has_value ());
2509
2510 auto *default_config = static_cast<packet_config *> (c->context ());
2511 const int packet_idx = std::distance (remote_protocol_packets,
2512 default_config);
2513
2514 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2515 {
2516 show_packet_config_cmd (file, packet_idx, remote);
2517 return;
2518 }
2519 internal_error (_("Could not find config for %s"), c->name);
2520 }
2521
2522 /* Should we try one of the 'Z' requests? */
2523
2524 enum Z_packet_type
2525 {
2526 Z_PACKET_SOFTWARE_BP,
2527 Z_PACKET_HARDWARE_BP,
2528 Z_PACKET_WRITE_WP,
2529 Z_PACKET_READ_WP,
2530 Z_PACKET_ACCESS_WP,
2531 NR_Z_PACKET_TYPES
2532 };
2533
2534 /* For compatibility with older distributions. Provide a ``set remote
2535 Z-packet ...'' command that updates all the Z packet types. */
2536
2537 static enum auto_boolean remote_Z_packet_detect;
2538
2539 static void
2540 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2541 struct cmd_list_element *c)
2542 {
2543 remote_target *remote = get_current_remote_target ();
2544 int i;
2545
2546 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2547 {
2548 if (remote != nullptr)
2549 remote->m_features.m_protocol_packets[PACKET_Z0 + i].detect
2550 = remote_Z_packet_detect;
2551 else
2552 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2553 }
2554
2555 const char *support = get_packet_support_name (remote_Z_packet_detect);
2556 const char *target_type = get_target_type_name (remote != nullptr);
2557 gdb_printf (_("Use of Z packets %s is set to \"%s\".\n"), target_type,
2558 support);
2559
2560 }
2561
2562 static void
2563 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2564 struct cmd_list_element *c,
2565 const char *value)
2566 {
2567 remote_target *remote = get_current_remote_target ();
2568 int i;
2569
2570 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2571 show_packet_config_cmd (file, PACKET_Z0 + i, remote);
2572 }
2573
2574 /* Insert fork catchpoint target routine. If fork events are enabled
2575 then return success, nothing more to do. */
2576
2577 int
2578 remote_target::insert_fork_catchpoint (int pid)
2579 {
2580 return !m_features.remote_fork_event_p ();
2581 }
2582
2583 /* Remove fork catchpoint target routine. Nothing to do, just
2584 return success. */
2585
2586 int
2587 remote_target::remove_fork_catchpoint (int pid)
2588 {
2589 return 0;
2590 }
2591
2592 /* Insert vfork catchpoint target routine. If vfork events are enabled
2593 then return success, nothing more to do. */
2594
2595 int
2596 remote_target::insert_vfork_catchpoint (int pid)
2597 {
2598 return !m_features.remote_vfork_event_p ();
2599 }
2600
2601 /* Remove vfork catchpoint target routine. Nothing to do, just
2602 return success. */
2603
2604 int
2605 remote_target::remove_vfork_catchpoint (int pid)
2606 {
2607 return 0;
2608 }
2609
2610 /* Insert exec catchpoint target routine. If exec events are
2611 enabled, just return success. */
2612
2613 int
2614 remote_target::insert_exec_catchpoint (int pid)
2615 {
2616 return !m_features.remote_exec_event_p ();
2617 }
2618
2619 /* Remove exec catchpoint target routine. Nothing to do, just
2620 return success. */
2621
2622 int
2623 remote_target::remove_exec_catchpoint (int pid)
2624 {
2625 return 0;
2626 }
2627
2628 \f
2629
2630 /* Take advantage of the fact that the TID field is not used, to tag
2631 special ptids with it set to != 0. */
2632 static const ptid_t magic_null_ptid (42000, -1, 1);
2633 static const ptid_t not_sent_ptid (42000, -2, 1);
2634 static const ptid_t any_thread_ptid (42000, 0, 1);
2635
2636 /* Find out if the stub attached to PID (and hence GDB should offer to
2637 detach instead of killing it when bailing out). */
2638
2639 int
2640 remote_target::remote_query_attached (int pid)
2641 {
2642 struct remote_state *rs = get_remote_state ();
2643 size_t size = get_remote_packet_size ();
2644
2645 if (m_features.packet_support (PACKET_qAttached) == PACKET_DISABLE)
2646 return 0;
2647
2648 if (m_features.remote_multi_process_p ())
2649 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2650 else
2651 xsnprintf (rs->buf.data (), size, "qAttached");
2652
2653 putpkt (rs->buf);
2654 getpkt (&rs->buf);
2655
2656 switch (m_features.packet_ok (rs->buf, PACKET_qAttached))
2657 {
2658 case PACKET_OK:
2659 if (strcmp (rs->buf.data (), "1") == 0)
2660 return 1;
2661 break;
2662 case PACKET_ERROR:
2663 warning (_("Remote failure reply: %s"), rs->buf.data ());
2664 break;
2665 case PACKET_UNKNOWN:
2666 break;
2667 }
2668
2669 return 0;
2670 }
2671
2672 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2673 has been invented by GDB, instead of reported by the target. Since
2674 we can be connected to a remote system before before knowing about
2675 any inferior, mark the target with execution when we find the first
2676 inferior. If ATTACHED is 1, then we had just attached to this
2677 inferior. If it is 0, then we just created this inferior. If it
2678 is -1, then try querying the remote stub to find out if it had
2679 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2680 attempt to open this inferior's executable as the main executable
2681 if no main executable is open already. */
2682
2683 inferior *
2684 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2685 int try_open_exec)
2686 {
2687 struct inferior *inf;
2688
2689 /* Check whether this process we're learning about is to be
2690 considered attached, or if is to be considered to have been
2691 spawned by the stub. */
2692 if (attached == -1)
2693 attached = remote_query_attached (pid);
2694
2695 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
2696 {
2697 /* If the target shares code across all inferiors, then every
2698 attach adds a new inferior. */
2699 inf = add_inferior (pid);
2700
2701 /* ... and every inferior is bound to the same program space.
2702 However, each inferior may still have its own address
2703 space. */
2704 inf->aspace = maybe_new_address_space ();
2705 inf->pspace = current_program_space;
2706 }
2707 else
2708 {
2709 /* In the traditional debugging scenario, there's a 1-1 match
2710 between program/address spaces. We simply bind the inferior
2711 to the program space's address space. */
2712 inf = current_inferior ();
2713
2714 /* However, if the current inferior is already bound to a
2715 process, find some other empty inferior. */
2716 if (inf->pid != 0)
2717 {
2718 inf = nullptr;
2719 for (inferior *it : all_inferiors ())
2720 if (it->pid == 0)
2721 {
2722 inf = it;
2723 break;
2724 }
2725 }
2726 if (inf == nullptr)
2727 {
2728 /* Since all inferiors were already bound to a process, add
2729 a new inferior. */
2730 inf = add_inferior_with_spaces ();
2731 }
2732 switch_to_inferior_no_thread (inf);
2733 inf->push_target (this);
2734 inferior_appeared (inf, pid);
2735 }
2736
2737 inf->attach_flag = attached;
2738 inf->fake_pid_p = fake_pid_p;
2739
2740 /* If no main executable is currently open then attempt to
2741 open the file that was executed to create this inferior. */
2742 if (try_open_exec && get_exec_file (0) == NULL)
2743 exec_file_locate_attach (pid, 0, 1);
2744
2745 /* Check for exec file mismatch, and let the user solve it. */
2746 validate_exec_file (1);
2747
2748 return inf;
2749 }
2750
2751 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2752 static remote_thread_info *get_remote_thread_info (remote_target *target,
2753 ptid_t ptid);
2754
2755 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2756 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2757 remote_state::starting_up flag) is true then the new thread is added
2758 silently, otherwise the new thread will be announced to the user. */
2759
2760 thread_info *
2761 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2762 bool silent_p)
2763 {
2764 struct remote_state *rs = get_remote_state ();
2765 struct thread_info *thread;
2766
2767 /* GDB historically didn't pull threads in the initial connection
2768 setup. If the remote target doesn't even have a concept of
2769 threads (e.g., a bare-metal target), even if internally we
2770 consider that a single-threaded target, mentioning a new thread
2771 might be confusing to the user. Be silent then, preserving the
2772 age old behavior. */
2773 if (rs->starting_up || silent_p)
2774 thread = add_thread_silent (this, ptid);
2775 else
2776 thread = add_thread (this, ptid);
2777
2778 /* We start by assuming threads are resumed. That state then gets updated
2779 when we process a matching stop reply. */
2780 get_remote_thread_info (thread)->set_resumed ();
2781
2782 set_executing (this, ptid, executing);
2783 set_running (this, ptid, running);
2784
2785 return thread;
2786 }
2787
2788 /* Come here when we learn about a thread id from the remote target.
2789 It may be the first time we hear about such thread, so take the
2790 opportunity to add it to GDB's thread list. In case this is the
2791 first time we're noticing its corresponding inferior, add it to
2792 GDB's inferior list as well. EXECUTING indicates whether the
2793 thread is (internally) executing or stopped. */
2794
2795 void
2796 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2797 {
2798 /* In non-stop mode, we assume new found threads are (externally)
2799 running until proven otherwise with a stop reply. In all-stop,
2800 we can only get here if all threads are stopped. */
2801 bool running = target_is_non_stop_p ();
2802
2803 /* If this is a new thread, add it to GDB's thread list.
2804 If we leave it up to WFI to do this, bad things will happen. */
2805
2806 thread_info *tp = this->find_thread (currthread);
2807 if (tp != NULL && tp->state == THREAD_EXITED)
2808 {
2809 /* We're seeing an event on a thread id we knew had exited.
2810 This has to be a new thread reusing the old id. Add it. */
2811 remote_add_thread (currthread, running, executing, false);
2812 return;
2813 }
2814
2815 if (!in_thread_list (this, currthread))
2816 {
2817 struct inferior *inf = NULL;
2818 int pid = currthread.pid ();
2819
2820 if (inferior_ptid.is_pid ()
2821 && pid == inferior_ptid.pid ())
2822 {
2823 /* inferior_ptid has no thread member yet. This can happen
2824 with the vAttach -> remote_wait,"TAAthread:" path if the
2825 stub doesn't support qC. This is the first stop reported
2826 after an attach, so this is the main thread. Update the
2827 ptid in the thread list. */
2828 if (in_thread_list (this, ptid_t (pid)))
2829 thread_change_ptid (this, inferior_ptid, currthread);
2830 else
2831 {
2832 thread_info *thr
2833 = remote_add_thread (currthread, running, executing, false);
2834 switch_to_thread (thr);
2835 }
2836 return;
2837 }
2838
2839 if (magic_null_ptid == inferior_ptid)
2840 {
2841 /* inferior_ptid is not set yet. This can happen with the
2842 vRun -> remote_wait,"TAAthread:" path if the stub
2843 doesn't support qC. This is the first stop reported
2844 after an attach, so this is the main thread. Update the
2845 ptid in the thread list. */
2846 thread_change_ptid (this, inferior_ptid, currthread);
2847 return;
2848 }
2849
2850 /* When connecting to a target remote, or to a target
2851 extended-remote which already was debugging an inferior, we
2852 may not know about it yet. Add it before adding its child
2853 thread, so notifications are emitted in a sensible order. */
2854 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2855 {
2856 bool fake_pid_p = !m_features.remote_multi_process_p ();
2857
2858 inf = remote_add_inferior (fake_pid_p,
2859 currthread.pid (), -1, 1);
2860 }
2861
2862 /* This is really a new thread. Add it. */
2863 thread_info *new_thr
2864 = remote_add_thread (currthread, running, executing, false);
2865
2866 /* If we found a new inferior, let the common code do whatever
2867 it needs to with it (e.g., read shared libraries, insert
2868 breakpoints), unless we're just setting up an all-stop
2869 connection. */
2870 if (inf != NULL)
2871 {
2872 struct remote_state *rs = get_remote_state ();
2873
2874 if (!rs->starting_up)
2875 notice_new_inferior (new_thr, executing, 0);
2876 }
2877 }
2878 }
2879
2880 /* Return THREAD's private thread data, creating it if necessary. */
2881
2882 static remote_thread_info *
2883 get_remote_thread_info (thread_info *thread)
2884 {
2885 gdb_assert (thread != NULL);
2886
2887 if (thread->priv == NULL)
2888 thread->priv.reset (new remote_thread_info);
2889
2890 return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
2891 }
2892
2893 /* Return PTID's private thread data, creating it if necessary. */
2894
2895 static remote_thread_info *
2896 get_remote_thread_info (remote_target *target, ptid_t ptid)
2897 {
2898 thread_info *thr = target->find_thread (ptid);
2899 return get_remote_thread_info (thr);
2900 }
2901
2902 /* Call this function as a result of
2903 1) A halt indication (T packet) containing a thread id
2904 2) A direct query of currthread
2905 3) Successful execution of set thread */
2906
2907 static void
2908 record_currthread (struct remote_state *rs, ptid_t currthread)
2909 {
2910 rs->general_thread = currthread;
2911 }
2912
2913 /* If 'QPassSignals' is supported, tell the remote stub what signals
2914 it can simply pass through to the inferior without reporting. */
2915
2916 void
2917 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2918 {
2919 if (m_features.packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2920 {
2921 char *pass_packet, *p;
2922 int count = 0;
2923 struct remote_state *rs = get_remote_state ();
2924
2925 gdb_assert (pass_signals.size () < 256);
2926 for (size_t i = 0; i < pass_signals.size (); i++)
2927 {
2928 if (pass_signals[i])
2929 count++;
2930 }
2931 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2932 strcpy (pass_packet, "QPassSignals:");
2933 p = pass_packet + strlen (pass_packet);
2934 for (size_t i = 0; i < pass_signals.size (); i++)
2935 {
2936 if (pass_signals[i])
2937 {
2938 if (i >= 16)
2939 *p++ = tohex (i >> 4);
2940 *p++ = tohex (i & 15);
2941 if (count)
2942 *p++ = ';';
2943 else
2944 break;
2945 count--;
2946 }
2947 }
2948 *p = 0;
2949 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2950 {
2951 putpkt (pass_packet);
2952 getpkt (&rs->buf);
2953 m_features.packet_ok (rs->buf, PACKET_QPassSignals);
2954 xfree (rs->last_pass_packet);
2955 rs->last_pass_packet = pass_packet;
2956 }
2957 else
2958 xfree (pass_packet);
2959 }
2960 }
2961
2962 /* If 'QCatchSyscalls' is supported, tell the remote stub
2963 to report syscalls to GDB. */
2964
2965 int
2966 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2967 gdb::array_view<const int> syscall_counts)
2968 {
2969 const char *catch_packet;
2970 enum packet_result result;
2971 int n_sysno = 0;
2972
2973 if (m_features.packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2974 {
2975 /* Not supported. */
2976 return 1;
2977 }
2978
2979 if (needed && any_count == 0)
2980 {
2981 /* Count how many syscalls are to be caught. */
2982 for (size_t i = 0; i < syscall_counts.size (); i++)
2983 {
2984 if (syscall_counts[i] != 0)
2985 n_sysno++;
2986 }
2987 }
2988
2989 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
2990 pid, needed, any_count, n_sysno);
2991
2992 std::string built_packet;
2993 if (needed)
2994 {
2995 /* Prepare a packet with the sysno list, assuming max 8+1
2996 characters for a sysno. If the resulting packet size is too
2997 big, fallback on the non-selective packet. */
2998 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2999 built_packet.reserve (maxpktsz);
3000 built_packet = "QCatchSyscalls:1";
3001 if (any_count == 0)
3002 {
3003 /* Add in each syscall to be caught. */
3004 for (size_t i = 0; i < syscall_counts.size (); i++)
3005 {
3006 if (syscall_counts[i] != 0)
3007 string_appendf (built_packet, ";%zx", i);
3008 }
3009 }
3010 if (built_packet.size () > get_remote_packet_size ())
3011 {
3012 /* catch_packet too big. Fallback to less efficient
3013 non selective mode, with GDB doing the filtering. */
3014 catch_packet = "QCatchSyscalls:1";
3015 }
3016 else
3017 catch_packet = built_packet.c_str ();
3018 }
3019 else
3020 catch_packet = "QCatchSyscalls:0";
3021
3022 struct remote_state *rs = get_remote_state ();
3023
3024 putpkt (catch_packet);
3025 getpkt (&rs->buf);
3026 result = m_features.packet_ok (rs->buf, PACKET_QCatchSyscalls);
3027 if (result == PACKET_OK)
3028 return 0;
3029 else
3030 return -1;
3031 }
3032
3033 /* If 'QProgramSignals' is supported, tell the remote stub what
3034 signals it should pass through to the inferior when detaching. */
3035
3036 void
3037 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
3038 {
3039 if (m_features.packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
3040 {
3041 char *packet, *p;
3042 int count = 0;
3043 struct remote_state *rs = get_remote_state ();
3044
3045 gdb_assert (signals.size () < 256);
3046 for (size_t i = 0; i < signals.size (); i++)
3047 {
3048 if (signals[i])
3049 count++;
3050 }
3051 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
3052 strcpy (packet, "QProgramSignals:");
3053 p = packet + strlen (packet);
3054 for (size_t i = 0; i < signals.size (); i++)
3055 {
3056 if (signal_pass_state (i))
3057 {
3058 if (i >= 16)
3059 *p++ = tohex (i >> 4);
3060 *p++ = tohex (i & 15);
3061 if (count)
3062 *p++ = ';';
3063 else
3064 break;
3065 count--;
3066 }
3067 }
3068 *p = 0;
3069 if (!rs->last_program_signals_packet
3070 || strcmp (rs->last_program_signals_packet, packet) != 0)
3071 {
3072 putpkt (packet);
3073 getpkt (&rs->buf);
3074 m_features.packet_ok (rs->buf, PACKET_QProgramSignals);
3075 xfree (rs->last_program_signals_packet);
3076 rs->last_program_signals_packet = packet;
3077 }
3078 else
3079 xfree (packet);
3080 }
3081 }
3082
3083 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
3084 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
3085 thread. If GEN is set, set the general thread, if not, then set
3086 the step/continue thread. */
3087 void
3088 remote_target::set_thread (ptid_t ptid, int gen)
3089 {
3090 struct remote_state *rs = get_remote_state ();
3091 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
3092 char *buf = rs->buf.data ();
3093 char *endbuf = buf + get_remote_packet_size ();
3094
3095 if (state == ptid)
3096 return;
3097
3098 *buf++ = 'H';
3099 *buf++ = gen ? 'g' : 'c';
3100 if (ptid == magic_null_ptid)
3101 xsnprintf (buf, endbuf - buf, "0");
3102 else if (ptid == any_thread_ptid)
3103 xsnprintf (buf, endbuf - buf, "0");
3104 else if (ptid == minus_one_ptid)
3105 xsnprintf (buf, endbuf - buf, "-1");
3106 else
3107 write_ptid (buf, endbuf, ptid);
3108 putpkt (rs->buf);
3109 getpkt (&rs->buf);
3110 if (gen)
3111 rs->general_thread = ptid;
3112 else
3113 rs->continue_thread = ptid;
3114 }
3115
3116 void
3117 remote_target::set_general_thread (ptid_t ptid)
3118 {
3119 set_thread (ptid, 1);
3120 }
3121
3122 void
3123 remote_target::set_continue_thread (ptid_t ptid)
3124 {
3125 set_thread (ptid, 0);
3126 }
3127
3128 /* Change the remote current process. Which thread within the process
3129 ends up selected isn't important, as long as it is the same process
3130 as what INFERIOR_PTID points to.
3131
3132 This comes from that fact that there is no explicit notion of
3133 "selected process" in the protocol. The selected process for
3134 general operations is the process the selected general thread
3135 belongs to. */
3136
3137 void
3138 remote_target::set_general_process ()
3139 {
3140 /* If the remote can't handle multiple processes, don't bother. */
3141 if (!m_features.remote_multi_process_p ())
3142 return;
3143
3144 remote_state *rs = get_remote_state ();
3145
3146 /* We only need to change the remote current thread if it's pointing
3147 at some other process. */
3148 if (rs->general_thread.pid () != inferior_ptid.pid ())
3149 set_general_thread (inferior_ptid);
3150 }
3151
3152 \f
3153 /* Return nonzero if this is the main thread that we made up ourselves
3154 to model non-threaded targets as single-threaded. */
3155
3156 static int
3157 remote_thread_always_alive (ptid_t ptid)
3158 {
3159 if (ptid == magic_null_ptid)
3160 /* The main thread is always alive. */
3161 return 1;
3162
3163 if (ptid.pid () != 0 && ptid.lwp () == 0)
3164 /* The main thread is always alive. This can happen after a
3165 vAttach, if the remote side doesn't support
3166 multi-threading. */
3167 return 1;
3168
3169 return 0;
3170 }
3171
3172 /* Return nonzero if the thread PTID is still alive on the remote
3173 system. */
3174
3175 bool
3176 remote_target::thread_alive (ptid_t ptid)
3177 {
3178 struct remote_state *rs = get_remote_state ();
3179 char *p, *endp;
3180
3181 /* Check if this is a thread that we made up ourselves to model
3182 non-threaded targets as single-threaded. */
3183 if (remote_thread_always_alive (ptid))
3184 return 1;
3185
3186 p = rs->buf.data ();
3187 endp = p + get_remote_packet_size ();
3188
3189 *p++ = 'T';
3190 write_ptid (p, endp, ptid);
3191
3192 putpkt (rs->buf);
3193 getpkt (&rs->buf);
3194 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
3195 }
3196
3197 /* Return a pointer to a thread name if we know it and NULL otherwise.
3198 The thread_info object owns the memory for the name. */
3199
3200 const char *
3201 remote_target::thread_name (struct thread_info *info)
3202 {
3203 if (info->priv != NULL)
3204 {
3205 const std::string &name = get_remote_thread_info (info)->name;
3206 return !name.empty () ? name.c_str () : NULL;
3207 }
3208
3209 return NULL;
3210 }
3211
3212 /* About these extended threadlist and threadinfo packets. They are
3213 variable length packets but, the fields within them are often fixed
3214 length. They are redundant enough to send over UDP as is the
3215 remote protocol in general. There is a matching unit test module
3216 in libstub. */
3217
3218 /* WARNING: This threadref data structure comes from the remote O.S.,
3219 libstub protocol encoding, and remote.c. It is not particularly
3220 changeable. */
3221
3222 /* Right now, the internal structure is int. We want it to be bigger.
3223 Plan to fix this. */
3224
3225 typedef int gdb_threadref; /* Internal GDB thread reference. */
3226
3227 /* gdb_ext_thread_info is an internal GDB data structure which is
3228 equivalent to the reply of the remote threadinfo packet. */
3229
3230 struct gdb_ext_thread_info
3231 {
3232 threadref threadid; /* External form of thread reference. */
3233 int active; /* Has state interesting to GDB?
3234 regs, stack. */
3235 char display[256]; /* Brief state display, name,
3236 blocked/suspended. */
3237 char shortname[32]; /* To be used to name threads. */
3238 char more_display[256]; /* Long info, statistics, queue depth,
3239 whatever. */
3240 };
3241
3242 /* The volume of remote transfers can be limited by submitting
3243 a mask containing bits specifying the desired information.
3244 Use a union of these values as the 'selection' parameter to
3245 get_thread_info. FIXME: Make these TAG names more thread specific. */
3246
3247 #define TAG_THREADID 1
3248 #define TAG_EXISTS 2
3249 #define TAG_DISPLAY 4
3250 #define TAG_THREADNAME 8
3251 #define TAG_MOREDISPLAY 16
3252
3253 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3254
3255 static const char *unpack_nibble (const char *buf, int *val);
3256
3257 static const char *unpack_byte (const char *buf, int *value);
3258
3259 static char *pack_int (char *buf, int value);
3260
3261 static const char *unpack_int (const char *buf, int *value);
3262
3263 static const char *unpack_string (const char *src, char *dest, int length);
3264
3265 static char *pack_threadid (char *pkt, threadref *id);
3266
3267 static const char *unpack_threadid (const char *inbuf, threadref *id);
3268
3269 void int_to_threadref (threadref *id, int value);
3270
3271 static int threadref_to_int (threadref *ref);
3272
3273 static void copy_threadref (threadref *dest, threadref *src);
3274
3275 static int threadmatch (threadref *dest, threadref *src);
3276
3277 static char *pack_threadinfo_request (char *pkt, int mode,
3278 threadref *id);
3279
3280 static char *pack_threadlist_request (char *pkt, int startflag,
3281 int threadcount,
3282 threadref *nextthread);
3283
3284 static int remote_newthread_step (threadref *ref, void *context);
3285
3286
3287 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3288 buffer we're allowed to write to. Returns
3289 BUF+CHARACTERS_WRITTEN. */
3290
3291 char *
3292 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3293 {
3294 int pid, tid;
3295
3296 if (m_features.remote_multi_process_p ())
3297 {
3298 pid = ptid.pid ();
3299 if (pid < 0)
3300 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3301 else
3302 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3303 }
3304 tid = ptid.lwp ();
3305 if (tid < 0)
3306 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3307 else
3308 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3309
3310 return buf;
3311 }
3312
3313 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3314 last parsed char. Returns null_ptid if no thread id is found, and
3315 throws an error if the thread id has an invalid format. */
3316
3317 static ptid_t
3318 read_ptid (const char *buf, const char **obuf)
3319 {
3320 const char *p = buf;
3321 const char *pp;
3322 ULONGEST pid = 0, tid = 0;
3323
3324 if (*p == 'p')
3325 {
3326 /* Multi-process ptid. */
3327 pp = unpack_varlen_hex (p + 1, &pid);
3328 if (*pp != '.')
3329 error (_("invalid remote ptid: %s"), p);
3330
3331 p = pp;
3332 pp = unpack_varlen_hex (p + 1, &tid);
3333 if (obuf)
3334 *obuf = pp;
3335 return ptid_t (pid, tid);
3336 }
3337
3338 /* No multi-process. Just a tid. */
3339 pp = unpack_varlen_hex (p, &tid);
3340
3341 /* Return null_ptid when no thread id is found. */
3342 if (p == pp)
3343 {
3344 if (obuf)
3345 *obuf = pp;
3346 return null_ptid;
3347 }
3348
3349 /* Since the stub is not sending a process id, default to what's
3350 current_inferior, unless it doesn't have a PID yet. If so,
3351 then since there's no way to know the pid of the reported
3352 threads, use the magic number. */
3353 inferior *inf = current_inferior ();
3354 if (inf->pid == 0)
3355 pid = magic_null_ptid.pid ();
3356 else
3357 pid = inf->pid;
3358
3359 if (obuf)
3360 *obuf = pp;
3361 return ptid_t (pid, tid);
3362 }
3363
3364 static int
3365 stubhex (int ch)
3366 {
3367 if (ch >= 'a' && ch <= 'f')
3368 return ch - 'a' + 10;
3369 if (ch >= '0' && ch <= '9')
3370 return ch - '0';
3371 if (ch >= 'A' && ch <= 'F')
3372 return ch - 'A' + 10;
3373 return -1;
3374 }
3375
3376 static int
3377 stub_unpack_int (const char *buff, int fieldlength)
3378 {
3379 int nibble;
3380 int retval = 0;
3381
3382 while (fieldlength)
3383 {
3384 nibble = stubhex (*buff++);
3385 retval |= nibble;
3386 fieldlength--;
3387 if (fieldlength)
3388 retval = retval << 4;
3389 }
3390 return retval;
3391 }
3392
3393 static const char *
3394 unpack_nibble (const char *buf, int *val)
3395 {
3396 *val = fromhex (*buf++);
3397 return buf;
3398 }
3399
3400 static const char *
3401 unpack_byte (const char *buf, int *value)
3402 {
3403 *value = stub_unpack_int (buf, 2);
3404 return buf + 2;
3405 }
3406
3407 static char *
3408 pack_int (char *buf, int value)
3409 {
3410 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3411 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3412 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3413 buf = pack_hex_byte (buf, (value & 0xff));
3414 return buf;
3415 }
3416
3417 static const char *
3418 unpack_int (const char *buf, int *value)
3419 {
3420 *value = stub_unpack_int (buf, 8);
3421 return buf + 8;
3422 }
3423
3424 #if 0 /* Currently unused, uncomment when needed. */
3425 static char *pack_string (char *pkt, char *string);
3426
3427 static char *
3428 pack_string (char *pkt, char *string)
3429 {
3430 char ch;
3431 int len;
3432
3433 len = strlen (string);
3434 if (len > 200)
3435 len = 200; /* Bigger than most GDB packets, junk??? */
3436 pkt = pack_hex_byte (pkt, len);
3437 while (len-- > 0)
3438 {
3439 ch = *string++;
3440 if ((ch == '\0') || (ch == '#'))
3441 ch = '*'; /* Protect encapsulation. */
3442 *pkt++ = ch;
3443 }
3444 return pkt;
3445 }
3446 #endif /* 0 (unused) */
3447
3448 static const char *
3449 unpack_string (const char *src, char *dest, int length)
3450 {
3451 while (length--)
3452 *dest++ = *src++;
3453 *dest = '\0';
3454 return src;
3455 }
3456
3457 static char *
3458 pack_threadid (char *pkt, threadref *id)
3459 {
3460 char *limit;
3461 unsigned char *altid;
3462
3463 altid = (unsigned char *) id;
3464 limit = pkt + BUF_THREAD_ID_SIZE;
3465 while (pkt < limit)
3466 pkt = pack_hex_byte (pkt, *altid++);
3467 return pkt;
3468 }
3469
3470
3471 static const char *
3472 unpack_threadid (const char *inbuf, threadref *id)
3473 {
3474 char *altref;
3475 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3476 int x, y;
3477
3478 altref = (char *) id;
3479
3480 while (inbuf < limit)
3481 {
3482 x = stubhex (*inbuf++);
3483 y = stubhex (*inbuf++);
3484 *altref++ = (x << 4) | y;
3485 }
3486 return inbuf;
3487 }
3488
3489 /* Externally, threadrefs are 64 bits but internally, they are still
3490 ints. This is due to a mismatch of specifications. We would like
3491 to use 64bit thread references internally. This is an adapter
3492 function. */
3493
3494 void
3495 int_to_threadref (threadref *id, int value)
3496 {
3497 unsigned char *scan;
3498
3499 scan = (unsigned char *) id;
3500 {
3501 int i = 4;
3502 while (i--)
3503 *scan++ = 0;
3504 }
3505 *scan++ = (value >> 24) & 0xff;
3506 *scan++ = (value >> 16) & 0xff;
3507 *scan++ = (value >> 8) & 0xff;
3508 *scan++ = (value & 0xff);
3509 }
3510
3511 static int
3512 threadref_to_int (threadref *ref)
3513 {
3514 int i, value = 0;
3515 unsigned char *scan;
3516
3517 scan = *ref;
3518 scan += 4;
3519 i = 4;
3520 while (i-- > 0)
3521 value = (value << 8) | ((*scan++) & 0xff);
3522 return value;
3523 }
3524
3525 static void
3526 copy_threadref (threadref *dest, threadref *src)
3527 {
3528 int i;
3529 unsigned char *csrc, *cdest;
3530
3531 csrc = (unsigned char *) src;
3532 cdest = (unsigned char *) dest;
3533 i = 8;
3534 while (i--)
3535 *cdest++ = *csrc++;
3536 }
3537
3538 static int
3539 threadmatch (threadref *dest, threadref *src)
3540 {
3541 /* Things are broken right now, so just assume we got a match. */
3542 #if 0
3543 unsigned char *srcp, *destp;
3544 int i, result;
3545 srcp = (char *) src;
3546 destp = (char *) dest;
3547
3548 result = 1;
3549 while (i-- > 0)
3550 result &= (*srcp++ == *destp++) ? 1 : 0;
3551 return result;
3552 #endif
3553 return 1;
3554 }
3555
3556 /*
3557 threadid:1, # always request threadid
3558 context_exists:2,
3559 display:4,
3560 unique_name:8,
3561 more_display:16
3562 */
3563
3564 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3565
3566 static char *
3567 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3568 {
3569 *pkt++ = 'q'; /* Info Query */
3570 *pkt++ = 'P'; /* process or thread info */
3571 pkt = pack_int (pkt, mode); /* mode */
3572 pkt = pack_threadid (pkt, id); /* threadid */
3573 *pkt = '\0'; /* terminate */
3574 return pkt;
3575 }
3576
3577 /* These values tag the fields in a thread info response packet. */
3578 /* Tagging the fields allows us to request specific fields and to
3579 add more fields as time goes by. */
3580
3581 #define TAG_THREADID 1 /* Echo the thread identifier. */
3582 #define TAG_EXISTS 2 /* Is this process defined enough to
3583 fetch registers and its stack? */
3584 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3585 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3586 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3587 the process. */
3588
3589 int
3590 remote_target::remote_unpack_thread_info_response (const char *pkt,
3591 threadref *expectedref,
3592 gdb_ext_thread_info *info)
3593 {
3594 struct remote_state *rs = get_remote_state ();
3595 int mask, length;
3596 int tag;
3597 threadref ref;
3598 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3599 int retval = 1;
3600
3601 /* info->threadid = 0; FIXME: implement zero_threadref. */
3602 info->active = 0;
3603 info->display[0] = '\0';
3604 info->shortname[0] = '\0';
3605 info->more_display[0] = '\0';
3606
3607 /* Assume the characters indicating the packet type have been
3608 stripped. */
3609 pkt = unpack_int (pkt, &mask); /* arg mask */
3610 pkt = unpack_threadid (pkt, &ref);
3611
3612 if (mask == 0)
3613 warning (_("Incomplete response to threadinfo request."));
3614 if (!threadmatch (&ref, expectedref))
3615 { /* This is an answer to a different request. */
3616 warning (_("ERROR RMT Thread info mismatch."));
3617 return 0;
3618 }
3619 copy_threadref (&info->threadid, &ref);
3620
3621 /* Loop on tagged fields , try to bail if something goes wrong. */
3622
3623 /* Packets are terminated with nulls. */
3624 while ((pkt < limit) && mask && *pkt)
3625 {
3626 pkt = unpack_int (pkt, &tag); /* tag */
3627 pkt = unpack_byte (pkt, &length); /* length */
3628 if (!(tag & mask)) /* Tags out of synch with mask. */
3629 {
3630 warning (_("ERROR RMT: threadinfo tag mismatch."));
3631 retval = 0;
3632 break;
3633 }
3634 if (tag == TAG_THREADID)
3635 {
3636 if (length != 16)
3637 {
3638 warning (_("ERROR RMT: length of threadid is not 16."));
3639 retval = 0;
3640 break;
3641 }
3642 pkt = unpack_threadid (pkt, &ref);
3643 mask = mask & ~TAG_THREADID;
3644 continue;
3645 }
3646 if (tag == TAG_EXISTS)
3647 {
3648 info->active = stub_unpack_int (pkt, length);
3649 pkt += length;
3650 mask = mask & ~(TAG_EXISTS);
3651 if (length > 8)
3652 {
3653 warning (_("ERROR RMT: 'exists' length too long."));
3654 retval = 0;
3655 break;
3656 }
3657 continue;
3658 }
3659 if (tag == TAG_THREADNAME)
3660 {
3661 pkt = unpack_string (pkt, &info->shortname[0], length);
3662 mask = mask & ~TAG_THREADNAME;
3663 continue;
3664 }
3665 if (tag == TAG_DISPLAY)
3666 {
3667 pkt = unpack_string (pkt, &info->display[0], length);
3668 mask = mask & ~TAG_DISPLAY;
3669 continue;
3670 }
3671 if (tag == TAG_MOREDISPLAY)
3672 {
3673 pkt = unpack_string (pkt, &info->more_display[0], length);
3674 mask = mask & ~TAG_MOREDISPLAY;
3675 continue;
3676 }
3677 warning (_("ERROR RMT: unknown thread info tag."));
3678 break; /* Not a tag we know about. */
3679 }
3680 return retval;
3681 }
3682
3683 int
3684 remote_target::remote_get_threadinfo (threadref *threadid,
3685 int fieldset,
3686 gdb_ext_thread_info *info)
3687 {
3688 struct remote_state *rs = get_remote_state ();
3689 int result;
3690
3691 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3692 putpkt (rs->buf);
3693 getpkt (&rs->buf);
3694
3695 if (rs->buf[0] == '\0')
3696 return 0;
3697
3698 result = remote_unpack_thread_info_response (&rs->buf[2],
3699 threadid, info);
3700 return result;
3701 }
3702
3703 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3704
3705 static char *
3706 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3707 threadref *nextthread)
3708 {
3709 *pkt++ = 'q'; /* info query packet */
3710 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3711 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3712 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3713 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3714 *pkt = '\0';
3715 return pkt;
3716 }
3717
3718 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3719
3720 int
3721 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3722 threadref *original_echo,
3723 threadref *resultlist,
3724 int *doneflag)
3725 {
3726 struct remote_state *rs = get_remote_state ();
3727 int count, resultcount, done;
3728
3729 resultcount = 0;
3730 /* Assume the 'q' and 'M chars have been stripped. */
3731 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3732 /* done parse past here */
3733 pkt = unpack_byte (pkt, &count); /* count field */
3734 pkt = unpack_nibble (pkt, &done);
3735 /* The first threadid is the argument threadid. */
3736 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3737 while ((count-- > 0) && (pkt < limit))
3738 {
3739 pkt = unpack_threadid (pkt, resultlist++);
3740 if (resultcount++ >= result_limit)
3741 break;
3742 }
3743 if (doneflag)
3744 *doneflag = done;
3745 return resultcount;
3746 }
3747
3748 /* Fetch the next batch of threads from the remote. Returns -1 if the
3749 qL packet is not supported, 0 on error and 1 on success. */
3750
3751 int
3752 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3753 int result_limit, int *done, int *result_count,
3754 threadref *threadlist)
3755 {
3756 struct remote_state *rs = get_remote_state ();
3757 int result = 1;
3758
3759 /* Truncate result limit to be smaller than the packet size. */
3760 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3761 >= get_remote_packet_size ())
3762 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3763
3764 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3765 nextthread);
3766 putpkt (rs->buf);
3767 getpkt (&rs->buf);
3768 if (rs->buf[0] == '\0')
3769 {
3770 /* Packet not supported. */
3771 return -1;
3772 }
3773
3774 *result_count =
3775 parse_threadlist_response (&rs->buf[2], result_limit,
3776 &rs->echo_nextthread, threadlist, done);
3777
3778 if (!threadmatch (&rs->echo_nextthread, nextthread))
3779 {
3780 /* FIXME: This is a good reason to drop the packet. */
3781 /* Possibly, there is a duplicate response. */
3782 /* Possibilities :
3783 retransmit immediatly - race conditions
3784 retransmit after timeout - yes
3785 exit
3786 wait for packet, then exit
3787 */
3788 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3789 return 0; /* I choose simply exiting. */
3790 }
3791 if (*result_count <= 0)
3792 {
3793 if (*done != 1)
3794 {
3795 warning (_("RMT ERROR : failed to get remote thread list."));
3796 result = 0;
3797 }
3798 return result; /* break; */
3799 }
3800 if (*result_count > result_limit)
3801 {
3802 *result_count = 0;
3803 warning (_("RMT ERROR: threadlist response longer than requested."));
3804 return 0;
3805 }
3806 return result;
3807 }
3808
3809 /* Fetch the list of remote threads, with the qL packet, and call
3810 STEPFUNCTION for each thread found. Stops iterating and returns 1
3811 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3812 STEPFUNCTION returns false. If the packet is not supported,
3813 returns -1. */
3814
3815 int
3816 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3817 void *context, int looplimit)
3818 {
3819 struct remote_state *rs = get_remote_state ();
3820 int done, i, result_count;
3821 int startflag = 1;
3822 int result = 1;
3823 int loopcount = 0;
3824
3825 done = 0;
3826 while (!done)
3827 {
3828 if (loopcount++ > looplimit)
3829 {
3830 result = 0;
3831 warning (_("Remote fetch threadlist -infinite loop-."));
3832 break;
3833 }
3834 result = remote_get_threadlist (startflag, &rs->nextthread,
3835 MAXTHREADLISTRESULTS,
3836 &done, &result_count,
3837 rs->resultthreadlist);
3838 if (result <= 0)
3839 break;
3840 /* Clear for later iterations. */
3841 startflag = 0;
3842 /* Setup to resume next batch of thread references, set nextthread. */
3843 if (result_count >= 1)
3844 copy_threadref (&rs->nextthread,
3845 &rs->resultthreadlist[result_count - 1]);
3846 i = 0;
3847 while (result_count--)
3848 {
3849 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3850 {
3851 result = 0;
3852 break;
3853 }
3854 }
3855 }
3856 return result;
3857 }
3858
3859 /* A thread found on the remote target. */
3860
3861 struct thread_item
3862 {
3863 explicit thread_item (ptid_t ptid_)
3864 : ptid (ptid_)
3865 {}
3866
3867 thread_item (thread_item &&other) = default;
3868 thread_item &operator= (thread_item &&other) = default;
3869
3870 DISABLE_COPY_AND_ASSIGN (thread_item);
3871
3872 /* The thread's PTID. */
3873 ptid_t ptid;
3874
3875 /* The thread's extra info. */
3876 std::string extra;
3877
3878 /* The thread's name. */
3879 std::string name;
3880
3881 /* The core the thread was running on. -1 if not known. */
3882 int core = -1;
3883
3884 /* The thread handle associated with the thread. */
3885 gdb::byte_vector thread_handle;
3886 };
3887
3888 /* Context passed around to the various methods listing remote
3889 threads. As new threads are found, they're added to the ITEMS
3890 vector. */
3891
3892 struct threads_listing_context
3893 {
3894 /* Return true if this object contains an entry for a thread with ptid
3895 PTID. */
3896
3897 bool contains_thread (ptid_t ptid) const
3898 {
3899 auto match_ptid = [&] (const thread_item &item)
3900 {
3901 return item.ptid == ptid;
3902 };
3903
3904 auto it = std::find_if (this->items.begin (),
3905 this->items.end (),
3906 match_ptid);
3907
3908 return it != this->items.end ();
3909 }
3910
3911 /* Remove the thread with ptid PTID. */
3912
3913 void remove_thread (ptid_t ptid)
3914 {
3915 auto match_ptid = [&] (const thread_item &item)
3916 {
3917 return item.ptid == ptid;
3918 };
3919
3920 auto it = std::remove_if (this->items.begin (),
3921 this->items.end (),
3922 match_ptid);
3923
3924 if (it != this->items.end ())
3925 this->items.erase (it);
3926 }
3927
3928 /* The threads found on the remote target. */
3929 std::vector<thread_item> items;
3930 };
3931
3932 static int
3933 remote_newthread_step (threadref *ref, void *data)
3934 {
3935 struct threads_listing_context *context
3936 = (struct threads_listing_context *) data;
3937 int pid = inferior_ptid.pid ();
3938 int lwp = threadref_to_int (ref);
3939 ptid_t ptid (pid, lwp);
3940
3941 context->items.emplace_back (ptid);
3942
3943 return 1; /* continue iterator */
3944 }
3945
3946 #define CRAZY_MAX_THREADS 1000
3947
3948 ptid_t
3949 remote_target::remote_current_thread (ptid_t oldpid)
3950 {
3951 struct remote_state *rs = get_remote_state ();
3952
3953 putpkt ("qC");
3954 getpkt (&rs->buf);
3955 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3956 {
3957 const char *obuf;
3958 ptid_t result;
3959
3960 result = read_ptid (&rs->buf[2], &obuf);
3961 if (*obuf != '\0')
3962 remote_debug_printf ("warning: garbage in qC reply");
3963
3964 return result;
3965 }
3966 else
3967 return oldpid;
3968 }
3969
3970 /* List remote threads using the deprecated qL packet. */
3971
3972 int
3973 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3974 {
3975 if (remote_threadlist_iterator (remote_newthread_step, context,
3976 CRAZY_MAX_THREADS) >= 0)
3977 return 1;
3978
3979 return 0;
3980 }
3981
3982 #if defined(HAVE_LIBEXPAT)
3983
3984 static void
3985 start_thread (struct gdb_xml_parser *parser,
3986 const struct gdb_xml_element *element,
3987 void *user_data,
3988 std::vector<gdb_xml_value> &attributes)
3989 {
3990 struct threads_listing_context *data
3991 = (struct threads_listing_context *) user_data;
3992 struct gdb_xml_value *attr;
3993
3994 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3995 ptid_t ptid = read_ptid (id, NULL);
3996
3997 data->items.emplace_back (ptid);
3998 thread_item &item = data->items.back ();
3999
4000 attr = xml_find_attribute (attributes, "core");
4001 if (attr != NULL)
4002 item.core = *(ULONGEST *) attr->value.get ();
4003
4004 attr = xml_find_attribute (attributes, "name");
4005 if (attr != NULL)
4006 item.name = (const char *) attr->value.get ();
4007
4008 attr = xml_find_attribute (attributes, "handle");
4009 if (attr != NULL)
4010 item.thread_handle = hex2bin ((const char *) attr->value.get ());
4011 }
4012
4013 static void
4014 end_thread (struct gdb_xml_parser *parser,
4015 const struct gdb_xml_element *element,
4016 void *user_data, const char *body_text)
4017 {
4018 struct threads_listing_context *data
4019 = (struct threads_listing_context *) user_data;
4020
4021 if (body_text != NULL && *body_text != '\0')
4022 data->items.back ().extra = body_text;
4023 }
4024
4025 const struct gdb_xml_attribute thread_attributes[] = {
4026 { "id", GDB_XML_AF_NONE, NULL, NULL },
4027 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
4028 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
4029 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
4030 { NULL, GDB_XML_AF_NONE, NULL, NULL }
4031 };
4032
4033 const struct gdb_xml_element thread_children[] = {
4034 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4035 };
4036
4037 const struct gdb_xml_element threads_children[] = {
4038 { "thread", thread_attributes, thread_children,
4039 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
4040 start_thread, end_thread },
4041 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4042 };
4043
4044 const struct gdb_xml_element threads_elements[] = {
4045 { "threads", NULL, threads_children,
4046 GDB_XML_EF_NONE, NULL, NULL },
4047 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4048 };
4049
4050 #endif
4051
4052 /* List remote threads using qXfer:threads:read. */
4053
4054 int
4055 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
4056 {
4057 #if defined(HAVE_LIBEXPAT)
4058 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4059 {
4060 gdb::optional<gdb::char_vector> xml
4061 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
4062
4063 if (xml && (*xml)[0] != '\0')
4064 {
4065 gdb_xml_parse_quick (_("threads"), "threads.dtd",
4066 threads_elements, xml->data (), context);
4067 }
4068
4069 return 1;
4070 }
4071 #endif
4072
4073 return 0;
4074 }
4075
4076 /* List remote threads using qfThreadInfo/qsThreadInfo. */
4077
4078 int
4079 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
4080 {
4081 struct remote_state *rs = get_remote_state ();
4082
4083 if (rs->use_threadinfo_query)
4084 {
4085 const char *bufp;
4086
4087 putpkt ("qfThreadInfo");
4088 getpkt (&rs->buf);
4089 bufp = rs->buf.data ();
4090 if (bufp[0] != '\0') /* q packet recognized */
4091 {
4092 while (*bufp++ == 'm') /* reply contains one or more TID */
4093 {
4094 do
4095 {
4096 ptid_t ptid = read_ptid (bufp, &bufp);
4097 context->items.emplace_back (ptid);
4098 }
4099 while (*bufp++ == ','); /* comma-separated list */
4100 putpkt ("qsThreadInfo");
4101 getpkt (&rs->buf);
4102 bufp = rs->buf.data ();
4103 }
4104 return 1;
4105 }
4106 else
4107 {
4108 /* Packet not recognized. */
4109 rs->use_threadinfo_query = 0;
4110 }
4111 }
4112
4113 return 0;
4114 }
4115
4116 /* Return true if INF only has one non-exited thread. */
4117
4118 static bool
4119 has_single_non_exited_thread (inferior *inf)
4120 {
4121 int count = 0;
4122 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
4123 if (++count > 1)
4124 break;
4125 return count == 1;
4126 }
4127
4128 /* Implement the to_update_thread_list function for the remote
4129 targets. */
4130
4131 void
4132 remote_target::update_thread_list ()
4133 {
4134 struct threads_listing_context context;
4135 int got_list = 0;
4136
4137 /* We have a few different mechanisms to fetch the thread list. Try
4138 them all, starting with the most preferred one first, falling
4139 back to older methods. */
4140 if (remote_get_threads_with_qxfer (&context)
4141 || remote_get_threads_with_qthreadinfo (&context)
4142 || remote_get_threads_with_ql (&context))
4143 {
4144 got_list = 1;
4145
4146 if (context.items.empty ()
4147 && remote_thread_always_alive (inferior_ptid))
4148 {
4149 /* Some targets don't really support threads, but still
4150 reply an (empty) thread list in response to the thread
4151 listing packets, instead of replying "packet not
4152 supported". Exit early so we don't delete the main
4153 thread. */
4154 return;
4155 }
4156
4157 /* CONTEXT now holds the current thread list on the remote
4158 target end. Delete GDB-side threads no longer found on the
4159 target. */
4160 for (thread_info *tp : all_threads_safe ())
4161 {
4162 if (tp->inf->process_target () != this)
4163 continue;
4164
4165 if (!context.contains_thread (tp->ptid))
4166 {
4167 /* Do not remove the thread if it is the last thread in
4168 the inferior. This situation happens when we have a
4169 pending exit process status to process. Otherwise we
4170 may end up with a seemingly live inferior (i.e. pid
4171 != 0) that has no threads. */
4172 if (has_single_non_exited_thread (tp->inf))
4173 continue;
4174
4175 /* Not found. */
4176 delete_thread (tp);
4177 }
4178 }
4179
4180 /* Remove any unreported fork child threads from CONTEXT so
4181 that we don't interfere with follow fork, which is where
4182 creation of such threads is handled. */
4183 remove_new_fork_children (&context);
4184
4185 /* And now add threads we don't know about yet to our list. */
4186 for (thread_item &item : context.items)
4187 {
4188 if (item.ptid != null_ptid)
4189 {
4190 /* In non-stop mode, we assume new found threads are
4191 executing until proven otherwise with a stop reply.
4192 In all-stop, we can only get here if all threads are
4193 stopped. */
4194 bool executing = target_is_non_stop_p ();
4195
4196 remote_notice_new_inferior (item.ptid, executing);
4197
4198 thread_info *tp = this->find_thread (item.ptid);
4199 remote_thread_info *info = get_remote_thread_info (tp);
4200 info->core = item.core;
4201 info->extra = std::move (item.extra);
4202 info->name = std::move (item.name);
4203 info->thread_handle = std::move (item.thread_handle);
4204 }
4205 }
4206 }
4207
4208 if (!got_list)
4209 {
4210 /* If no thread listing method is supported, then query whether
4211 each known thread is alive, one by one, with the T packet.
4212 If the target doesn't support threads at all, then this is a
4213 no-op. See remote_thread_alive. */
4214 prune_threads ();
4215 }
4216 }
4217
4218 /*
4219 * Collect a descriptive string about the given thread.
4220 * The target may say anything it wants to about the thread
4221 * (typically info about its blocked / runnable state, name, etc.).
4222 * This string will appear in the info threads display.
4223 *
4224 * Optional: targets are not required to implement this function.
4225 */
4226
4227 const char *
4228 remote_target::extra_thread_info (thread_info *tp)
4229 {
4230 struct remote_state *rs = get_remote_state ();
4231 int set;
4232 threadref id;
4233 struct gdb_ext_thread_info threadinfo;
4234
4235 if (rs->remote_desc == 0) /* paranoia */
4236 internal_error (_("remote_threads_extra_info"));
4237
4238 if (tp->ptid == magic_null_ptid
4239 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4240 /* This is the main thread which was added by GDB. The remote
4241 server doesn't know about it. */
4242 return NULL;
4243
4244 std::string &extra = get_remote_thread_info (tp)->extra;
4245
4246 /* If already have cached info, use it. */
4247 if (!extra.empty ())
4248 return extra.c_str ();
4249
4250 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4251 {
4252 /* If we're using qXfer:threads:read, then the extra info is
4253 included in the XML. So if we didn't have anything cached,
4254 it's because there's really no extra info. */
4255 return NULL;
4256 }
4257
4258 if (rs->use_threadextra_query)
4259 {
4260 char *b = rs->buf.data ();
4261 char *endb = b + get_remote_packet_size ();
4262
4263 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4264 b += strlen (b);
4265 write_ptid (b, endb, tp->ptid);
4266
4267 putpkt (rs->buf);
4268 getpkt (&rs->buf);
4269 if (rs->buf[0] != 0)
4270 {
4271 extra.resize (strlen (rs->buf.data ()) / 2);
4272 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4273 return extra.c_str ();
4274 }
4275 }
4276
4277 /* If the above query fails, fall back to the old method. */
4278 rs->use_threadextra_query = 0;
4279 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4280 | TAG_MOREDISPLAY | TAG_DISPLAY;
4281 int_to_threadref (&id, tp->ptid.lwp ());
4282 if (remote_get_threadinfo (&id, set, &threadinfo))
4283 if (threadinfo.active)
4284 {
4285 if (*threadinfo.shortname)
4286 string_appendf (extra, " Name: %s", threadinfo.shortname);
4287 if (*threadinfo.display)
4288 {
4289 if (!extra.empty ())
4290 extra += ',';
4291 string_appendf (extra, " State: %s", threadinfo.display);
4292 }
4293 if (*threadinfo.more_display)
4294 {
4295 if (!extra.empty ())
4296 extra += ',';
4297 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4298 }
4299 return extra.c_str ();
4300 }
4301 return NULL;
4302 }
4303 \f
4304
4305 bool
4306 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4307 struct static_tracepoint_marker *marker)
4308 {
4309 struct remote_state *rs = get_remote_state ();
4310 char *p = rs->buf.data ();
4311
4312 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4313 p += strlen (p);
4314 p += hexnumstr (p, addr);
4315 putpkt (rs->buf);
4316 getpkt (&rs->buf);
4317 p = rs->buf.data ();
4318
4319 if (*p == 'E')
4320 error (_("Remote failure reply: %s"), p);
4321
4322 if (*p++ == 'm')
4323 {
4324 parse_static_tracepoint_marker_definition (p, NULL, marker);
4325 return true;
4326 }
4327
4328 return false;
4329 }
4330
4331 std::vector<static_tracepoint_marker>
4332 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4333 {
4334 struct remote_state *rs = get_remote_state ();
4335 std::vector<static_tracepoint_marker> markers;
4336 const char *p;
4337 static_tracepoint_marker marker;
4338
4339 /* Ask for a first packet of static tracepoint marker
4340 definition. */
4341 putpkt ("qTfSTM");
4342 getpkt (&rs->buf);
4343 p = rs->buf.data ();
4344 if (*p == 'E')
4345 error (_("Remote failure reply: %s"), p);
4346
4347 while (*p++ == 'm')
4348 {
4349 do
4350 {
4351 parse_static_tracepoint_marker_definition (p, &p, &marker);
4352
4353 if (strid == NULL || marker.str_id == strid)
4354 markers.push_back (std::move (marker));
4355 }
4356 while (*p++ == ','); /* comma-separated list */
4357 /* Ask for another packet of static tracepoint definition. */
4358 putpkt ("qTsSTM");
4359 getpkt (&rs->buf);
4360 p = rs->buf.data ();
4361 }
4362
4363 return markers;
4364 }
4365
4366 \f
4367 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4368
4369 ptid_t
4370 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4371 {
4372 return ptid_t (inferior_ptid.pid (), lwp);
4373 }
4374 \f
4375
4376 /* Restart the remote side; this is an extended protocol operation. */
4377
4378 void
4379 remote_target::extended_remote_restart ()
4380 {
4381 struct remote_state *rs = get_remote_state ();
4382
4383 /* Send the restart command; for reasons I don't understand the
4384 remote side really expects a number after the "R". */
4385 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4386 putpkt (rs->buf);
4387
4388 remote_fileio_reset ();
4389 }
4390 \f
4391 /* Clean up connection to a remote debugger. */
4392
4393 void
4394 remote_target::close ()
4395 {
4396 /* Make sure we leave stdin registered in the event loop. */
4397 terminal_ours ();
4398
4399 trace_reset_local_state ();
4400
4401 delete this;
4402 }
4403
4404 remote_target::~remote_target ()
4405 {
4406 struct remote_state *rs = get_remote_state ();
4407
4408 /* Check for NULL because we may get here with a partially
4409 constructed target/connection. */
4410 if (rs->remote_desc == nullptr)
4411 return;
4412
4413 serial_close (rs->remote_desc);
4414
4415 /* We are destroying the remote target, so we should discard
4416 everything of this target. */
4417 discard_pending_stop_replies_in_queue ();
4418
4419 rs->delete_async_event_handler ();
4420
4421 delete rs->notif_state;
4422 }
4423
4424 /* Query the remote side for the text, data and bss offsets. */
4425
4426 void
4427 remote_target::get_offsets ()
4428 {
4429 struct remote_state *rs = get_remote_state ();
4430 char *buf;
4431 char *ptr;
4432 int lose, num_segments = 0, do_sections, do_segments;
4433 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4434
4435 if (current_program_space->symfile_object_file == NULL)
4436 return;
4437
4438 putpkt ("qOffsets");
4439 getpkt (&rs->buf);
4440 buf = rs->buf.data ();
4441
4442 if (buf[0] == '\000')
4443 return; /* Return silently. Stub doesn't support
4444 this command. */
4445 if (buf[0] == 'E')
4446 {
4447 warning (_("Remote failure reply: %s"), buf);
4448 return;
4449 }
4450
4451 /* Pick up each field in turn. This used to be done with scanf, but
4452 scanf will make trouble if CORE_ADDR size doesn't match
4453 conversion directives correctly. The following code will work
4454 with any size of CORE_ADDR. */
4455 text_addr = data_addr = bss_addr = 0;
4456 ptr = buf;
4457 lose = 0;
4458
4459 if (startswith (ptr, "Text="))
4460 {
4461 ptr += 5;
4462 /* Don't use strtol, could lose on big values. */
4463 while (*ptr && *ptr != ';')
4464 text_addr = (text_addr << 4) + fromhex (*ptr++);
4465
4466 if (startswith (ptr, ";Data="))
4467 {
4468 ptr += 6;
4469 while (*ptr && *ptr != ';')
4470 data_addr = (data_addr << 4) + fromhex (*ptr++);
4471 }
4472 else
4473 lose = 1;
4474
4475 if (!lose && startswith (ptr, ";Bss="))
4476 {
4477 ptr += 5;
4478 while (*ptr && *ptr != ';')
4479 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4480
4481 if (bss_addr != data_addr)
4482 warning (_("Target reported unsupported offsets: %s"), buf);
4483 }
4484 else
4485 lose = 1;
4486 }
4487 else if (startswith (ptr, "TextSeg="))
4488 {
4489 ptr += 8;
4490 /* Don't use strtol, could lose on big values. */
4491 while (*ptr && *ptr != ';')
4492 text_addr = (text_addr << 4) + fromhex (*ptr++);
4493 num_segments = 1;
4494
4495 if (startswith (ptr, ";DataSeg="))
4496 {
4497 ptr += 9;
4498 while (*ptr && *ptr != ';')
4499 data_addr = (data_addr << 4) + fromhex (*ptr++);
4500 num_segments++;
4501 }
4502 }
4503 else
4504 lose = 1;
4505
4506 if (lose)
4507 error (_("Malformed response to offset query, %s"), buf);
4508 else if (*ptr != '\0')
4509 warning (_("Target reported unsupported offsets: %s"), buf);
4510
4511 objfile *objf = current_program_space->symfile_object_file;
4512 section_offsets offs = objf->section_offsets;
4513
4514 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
4515 do_segments = (data != NULL);
4516 do_sections = num_segments == 0;
4517
4518 if (num_segments > 0)
4519 {
4520 segments[0] = text_addr;
4521 segments[1] = data_addr;
4522 }
4523 /* If we have two segments, we can still try to relocate everything
4524 by assuming that the .text and .data offsets apply to the whole
4525 text and data segments. Convert the offsets given in the packet
4526 to base addresses for symfile_map_offsets_to_segments. */
4527 else if (data != nullptr && data->segments.size () == 2)
4528 {
4529 segments[0] = data->segments[0].base + text_addr;
4530 segments[1] = data->segments[1].base + data_addr;
4531 num_segments = 2;
4532 }
4533 /* If the object file has only one segment, assume that it is text
4534 rather than data; main programs with no writable data are rare,
4535 but programs with no code are useless. Of course the code might
4536 have ended up in the data segment... to detect that we would need
4537 the permissions here. */
4538 else if (data && data->segments.size () == 1)
4539 {
4540 segments[0] = data->segments[0].base + text_addr;
4541 num_segments = 1;
4542 }
4543 /* There's no way to relocate by segment. */
4544 else
4545 do_segments = 0;
4546
4547 if (do_segments)
4548 {
4549 int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
4550 data.get (), offs,
4551 num_segments, segments);
4552
4553 if (ret == 0 && !do_sections)
4554 error (_("Can not handle qOffsets TextSeg "
4555 "response with this symbol file"));
4556
4557 if (ret > 0)
4558 do_sections = 0;
4559 }
4560
4561 if (do_sections)
4562 {
4563 offs[SECT_OFF_TEXT (objf)] = text_addr;
4564
4565 /* This is a temporary kludge to force data and bss to use the
4566 same offsets because that's what nlmconv does now. The real
4567 solution requires changes to the stub and remote.c that I
4568 don't have time to do right now. */
4569
4570 offs[SECT_OFF_DATA (objf)] = data_addr;
4571 offs[SECT_OFF_BSS (objf)] = data_addr;
4572 }
4573
4574 objfile_relocate (objf, offs);
4575 }
4576
4577 /* Send interrupt_sequence to remote target. */
4578
4579 void
4580 remote_target::send_interrupt_sequence ()
4581 {
4582 struct remote_state *rs = get_remote_state ();
4583
4584 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4585 remote_serial_write ("\x03", 1);
4586 else if (interrupt_sequence_mode == interrupt_sequence_break)
4587 serial_send_break (rs->remote_desc);
4588 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4589 {
4590 serial_send_break (rs->remote_desc);
4591 remote_serial_write ("g", 1);
4592 }
4593 else
4594 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
4595 interrupt_sequence_mode);
4596 }
4597
4598
4599 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4600 and extract the PTID. Returns NULL_PTID if not found. */
4601
4602 static ptid_t
4603 stop_reply_extract_thread (const char *stop_reply)
4604 {
4605 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4606 {
4607 const char *p;
4608
4609 /* Txx r:val ; r:val (...) */
4610 p = &stop_reply[3];
4611
4612 /* Look for "register" named "thread". */
4613 while (*p != '\0')
4614 {
4615 const char *p1;
4616
4617 p1 = strchr (p, ':');
4618 if (p1 == NULL)
4619 return null_ptid;
4620
4621 if (strncmp (p, "thread", p1 - p) == 0)
4622 return read_ptid (++p1, &p);
4623
4624 p1 = strchr (p, ';');
4625 if (p1 == NULL)
4626 return null_ptid;
4627 p1++;
4628
4629 p = p1;
4630 }
4631 }
4632
4633 return null_ptid;
4634 }
4635
4636 /* Determine the remote side's current thread. If we have a stop
4637 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4638 "thread" register we can extract the current thread from. If not,
4639 ask the remote which is the current thread with qC. The former
4640 method avoids a roundtrip. */
4641
4642 ptid_t
4643 remote_target::get_current_thread (const char *wait_status)
4644 {
4645 ptid_t ptid = null_ptid;
4646
4647 /* Note we don't use remote_parse_stop_reply as that makes use of
4648 the target architecture, which we haven't yet fully determined at
4649 this point. */
4650 if (wait_status != NULL)
4651 ptid = stop_reply_extract_thread (wait_status);
4652 if (ptid == null_ptid)
4653 ptid = remote_current_thread (inferior_ptid);
4654
4655 return ptid;
4656 }
4657
4658 /* Query the remote target for which is the current thread/process,
4659 add it to our tables, and update INFERIOR_PTID. The caller is
4660 responsible for setting the state such that the remote end is ready
4661 to return the current thread.
4662
4663 This function is called after handling the '?' or 'vRun' packets,
4664 whose response is a stop reply from which we can also try
4665 extracting the thread. If the target doesn't support the explicit
4666 qC query, we infer the current thread from that stop reply, passed
4667 in in WAIT_STATUS, which may be NULL.
4668
4669 The function returns pointer to the main thread of the inferior. */
4670
4671 thread_info *
4672 remote_target::add_current_inferior_and_thread (const char *wait_status)
4673 {
4674 bool fake_pid_p = false;
4675
4676 switch_to_no_thread ();
4677
4678 /* Now, if we have thread information, update the current thread's
4679 ptid. */
4680 ptid_t curr_ptid = get_current_thread (wait_status);
4681
4682 if (curr_ptid != null_ptid)
4683 {
4684 if (!m_features.remote_multi_process_p ())
4685 fake_pid_p = true;
4686 }
4687 else
4688 {
4689 /* Without this, some commands which require an active target
4690 (such as kill) won't work. This variable serves (at least)
4691 double duty as both the pid of the target process (if it has
4692 such), and as a flag indicating that a target is active. */
4693 curr_ptid = magic_null_ptid;
4694 fake_pid_p = true;
4695 }
4696
4697 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4698
4699 /* Add the main thread and switch to it. Don't try reading
4700 registers yet, since we haven't fetched the target description
4701 yet. */
4702 thread_info *tp = add_thread_silent (this, curr_ptid);
4703 switch_to_thread_no_regs (tp);
4704
4705 return tp;
4706 }
4707
4708 /* Print info about a thread that was found already stopped on
4709 connection. */
4710
4711 void
4712 remote_target::print_one_stopped_thread (thread_info *thread)
4713 {
4714 target_waitstatus ws;
4715
4716 /* If there is a pending waitstatus, use it. If there isn't it's because
4717 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4718 and process_initial_stop_replies decided it wasn't interesting to save
4719 and report to the core. */
4720 if (thread->has_pending_waitstatus ())
4721 {
4722 ws = thread->pending_waitstatus ();
4723 thread->clear_pending_waitstatus ();
4724 }
4725 else
4726 {
4727 ws.set_stopped (GDB_SIGNAL_0);
4728 }
4729
4730 switch_to_thread (thread);
4731 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4732 set_current_sal_from_frame (get_current_frame ());
4733
4734 /* For "info program". */
4735 set_last_target_status (this, thread->ptid, ws);
4736
4737 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4738 {
4739 enum gdb_signal sig = ws.sig ();
4740
4741 if (signal_print_state (sig))
4742 notify_signal_received (sig);
4743 }
4744
4745 notify_normal_stop (nullptr, 1);
4746 }
4747
4748 /* Process all initial stop replies the remote side sent in response
4749 to the ? packet. These indicate threads that were already stopped
4750 on initial connection. We mark these threads as stopped and print
4751 their current frame before giving the user the prompt. */
4752
4753 void
4754 remote_target::process_initial_stop_replies (int from_tty)
4755 {
4756 int pending_stop_replies = stop_reply_queue_length ();
4757 struct thread_info *selected = NULL;
4758 struct thread_info *lowest_stopped = NULL;
4759 struct thread_info *first = NULL;
4760
4761 /* This is only used when the target is non-stop. */
4762 gdb_assert (target_is_non_stop_p ());
4763
4764 /* Consume the initial pending events. */
4765 while (pending_stop_replies-- > 0)
4766 {
4767 ptid_t waiton_ptid = minus_one_ptid;
4768 ptid_t event_ptid;
4769 struct target_waitstatus ws;
4770 int ignore_event = 0;
4771
4772 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4773 if (remote_debug)
4774 print_target_wait_results (waiton_ptid, event_ptid, ws);
4775
4776 switch (ws.kind ())
4777 {
4778 case TARGET_WAITKIND_IGNORE:
4779 case TARGET_WAITKIND_NO_RESUMED:
4780 case TARGET_WAITKIND_SIGNALLED:
4781 case TARGET_WAITKIND_EXITED:
4782 /* We shouldn't see these, but if we do, just ignore. */
4783 remote_debug_printf ("event ignored");
4784 ignore_event = 1;
4785 break;
4786
4787 default:
4788 break;
4789 }
4790
4791 if (ignore_event)
4792 continue;
4793
4794 thread_info *evthread = this->find_thread (event_ptid);
4795
4796 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4797 {
4798 enum gdb_signal sig = ws.sig ();
4799
4800 /* Stubs traditionally report SIGTRAP as initial signal,
4801 instead of signal 0. Suppress it. */
4802 if (sig == GDB_SIGNAL_TRAP)
4803 sig = GDB_SIGNAL_0;
4804 evthread->set_stop_signal (sig);
4805 ws.set_stopped (sig);
4806 }
4807
4808 if (ws.kind () != TARGET_WAITKIND_STOPPED
4809 || ws.sig () != GDB_SIGNAL_0)
4810 evthread->set_pending_waitstatus (ws);
4811
4812 set_executing (this, event_ptid, false);
4813 set_running (this, event_ptid, false);
4814 get_remote_thread_info (evthread)->set_not_resumed ();
4815 }
4816
4817 /* "Notice" the new inferiors before anything related to
4818 registers/memory. */
4819 for (inferior *inf : all_non_exited_inferiors (this))
4820 {
4821 inf->needs_setup = true;
4822
4823 if (non_stop)
4824 {
4825 thread_info *thread = any_live_thread_of_inferior (inf);
4826 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4827 from_tty);
4828 }
4829 }
4830
4831 /* If all-stop on top of non-stop, pause all threads. Note this
4832 records the threads' stop pc, so must be done after "noticing"
4833 the inferiors. */
4834 if (!non_stop)
4835 {
4836 {
4837 /* At this point, the remote target is not async. It needs to be for
4838 the poll in stop_all_threads to consider events from it, so enable
4839 it temporarily. */
4840 gdb_assert (!this->is_async_p ());
4841 SCOPE_EXIT { target_async (false); };
4842 target_async (true);
4843 stop_all_threads ("remote connect in all-stop");
4844 }
4845
4846 /* If all threads of an inferior were already stopped, we
4847 haven't setup the inferior yet. */
4848 for (inferior *inf : all_non_exited_inferiors (this))
4849 {
4850 if (inf->needs_setup)
4851 {
4852 thread_info *thread = any_live_thread_of_inferior (inf);
4853 switch_to_thread_no_regs (thread);
4854 setup_inferior (0);
4855 }
4856 }
4857 }
4858
4859 /* Now go over all threads that are stopped, and print their current
4860 frame. If all-stop, then if there's a signalled thread, pick
4861 that as current. */
4862 for (thread_info *thread : all_non_exited_threads (this))
4863 {
4864 if (first == NULL)
4865 first = thread;
4866
4867 if (!non_stop)
4868 thread->set_running (false);
4869 else if (thread->state != THREAD_STOPPED)
4870 continue;
4871
4872 if (selected == nullptr && thread->has_pending_waitstatus ())
4873 selected = thread;
4874
4875 if (lowest_stopped == NULL
4876 || thread->inf->num < lowest_stopped->inf->num
4877 || thread->per_inf_num < lowest_stopped->per_inf_num)
4878 lowest_stopped = thread;
4879
4880 if (non_stop)
4881 print_one_stopped_thread (thread);
4882 }
4883
4884 /* In all-stop, we only print the status of one thread, and leave
4885 others with their status pending. */
4886 if (!non_stop)
4887 {
4888 thread_info *thread = selected;
4889 if (thread == NULL)
4890 thread = lowest_stopped;
4891 if (thread == NULL)
4892 thread = first;
4893
4894 print_one_stopped_thread (thread);
4895 }
4896 }
4897
4898 /* Mark a remote_target as starting (by setting the starting_up flag within
4899 its remote_state) for the lifetime of this object. The reference count
4900 on the remote target is temporarily incremented, to prevent the target
4901 being deleted under our feet. */
4902
4903 struct scoped_mark_target_starting
4904 {
4905 /* Constructor, TARGET is the target to be marked as starting, its
4906 reference count will be incremented. */
4907 scoped_mark_target_starting (remote_target *target)
4908 : m_remote_target (remote_target_ref::new_reference (target)),
4909 m_restore_starting_up (set_starting_up_flag (target))
4910 { /* Nothing. */ }
4911
4912 private:
4913
4914 /* Helper function, set the starting_up flag on TARGET and return an
4915 object which, when it goes out of scope, will restore the previous
4916 value of the starting_up flag. */
4917 static scoped_restore_tmpl<bool>
4918 set_starting_up_flag (remote_target *target)
4919 {
4920 remote_state *rs = target->get_remote_state ();
4921 gdb_assert (!rs->starting_up);
4922 return make_scoped_restore (&rs->starting_up, true);
4923 }
4924
4925 /* A gdb::ref_ptr pointer to a remote_target. */
4926 using remote_target_ref = gdb::ref_ptr<remote_target, target_ops_ref_policy>;
4927
4928 /* A reference to the target on which we are operating. */
4929 remote_target_ref m_remote_target;
4930
4931 /* An object which restores the previous value of the starting_up flag
4932 when it goes out of scope. */
4933 scoped_restore_tmpl<bool> m_restore_starting_up;
4934 };
4935
4936 /* Helper for remote_target::start_remote, start the remote connection and
4937 sync state. Return true if everything goes OK, otherwise, return false.
4938 This function exists so that the scoped_restore created within it will
4939 expire before we return to remote_target::start_remote. */
4940
4941 bool
4942 remote_target::start_remote_1 (int from_tty, int extended_p)
4943 {
4944 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4945
4946 struct remote_state *rs = get_remote_state ();
4947
4948 /* Signal other parts that we're going through the initial setup,
4949 and so things may not be stable yet. E.g., we don't try to
4950 install tracepoints until we've relocated symbols. Also, a
4951 Ctrl-C before we're connected and synced up can't interrupt the
4952 target. Instead, it offers to drop the (potentially wedged)
4953 connection. */
4954 scoped_mark_target_starting target_is_starting (this);
4955
4956 QUIT;
4957
4958 if (interrupt_on_connect)
4959 send_interrupt_sequence ();
4960
4961 /* Ack any packet which the remote side has already sent. */
4962 remote_serial_write ("+", 1);
4963
4964 /* The first packet we send to the target is the optional "supported
4965 packets" request. If the target can answer this, it will tell us
4966 which later probes to skip. */
4967 remote_query_supported ();
4968
4969 /* Check vCont support and set the remote state's vCont_action_support
4970 attribute. */
4971 remote_vcont_probe ();
4972
4973 /* If the stub wants to get a QAllow, compose one and send it. */
4974 if (m_features.packet_support (PACKET_QAllow) != PACKET_DISABLE)
4975 set_permissions ();
4976
4977 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4978 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4979 as a reply to known packet. For packet "vFile:setfs:" it is an
4980 invalid reply and GDB would return error in
4981 remote_hostio_set_filesystem, making remote files access impossible.
4982 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4983 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4984 {
4985 const char v_mustreplyempty[] = "vMustReplyEmpty";
4986
4987 putpkt (v_mustreplyempty);
4988 getpkt (&rs->buf);
4989 if (strcmp (rs->buf.data (), "OK") == 0)
4990 {
4991 m_features.m_protocol_packets[PACKET_vFile_setfs].support
4992 = PACKET_DISABLE;
4993 }
4994 else if (strcmp (rs->buf.data (), "") != 0)
4995 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4996 rs->buf.data ());
4997 }
4998
4999 /* Next, we possibly activate noack mode.
5000
5001 If the QStartNoAckMode packet configuration is set to AUTO,
5002 enable noack mode if the stub reported a wish for it with
5003 qSupported.
5004
5005 If set to TRUE, then enable noack mode even if the stub didn't
5006 report it in qSupported. If the stub doesn't reply OK, the
5007 session ends with an error.
5008
5009 If FALSE, then don't activate noack mode, regardless of what the
5010 stub claimed should be the default with qSupported. */
5011
5012 if (m_features.packet_support (PACKET_QStartNoAckMode) != PACKET_DISABLE)
5013 {
5014 putpkt ("QStartNoAckMode");
5015 getpkt (&rs->buf);
5016 if (m_features.packet_ok (rs->buf, PACKET_QStartNoAckMode) == PACKET_OK)
5017 rs->noack_mode = 1;
5018 }
5019
5020 if (extended_p)
5021 {
5022 /* Tell the remote that we are using the extended protocol. */
5023 putpkt ("!");
5024 getpkt (&rs->buf);
5025 }
5026
5027 /* Let the target know which signals it is allowed to pass down to
5028 the program. */
5029 update_signals_program_target ();
5030
5031 /* Next, if the target can specify a description, read it. We do
5032 this before anything involving memory or registers. */
5033 target_find_description ();
5034
5035 /* Next, now that we know something about the target, update the
5036 address spaces in the program spaces. */
5037 update_address_spaces ();
5038
5039 /* On OSs where the list of libraries is global to all
5040 processes, we fetch them early. */
5041 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
5042 solib_add (NULL, from_tty, auto_solib_add);
5043
5044 if (target_is_non_stop_p ())
5045 {
5046 if (m_features.packet_support (PACKET_QNonStop) != PACKET_ENABLE)
5047 error (_("Non-stop mode requested, but remote "
5048 "does not support non-stop"));
5049
5050 putpkt ("QNonStop:1");
5051 getpkt (&rs->buf);
5052
5053 if (strcmp (rs->buf.data (), "OK") != 0)
5054 error (_("Remote refused setting non-stop mode with: %s"),
5055 rs->buf.data ());
5056
5057 /* Find about threads and processes the stub is already
5058 controlling. We default to adding them in the running state.
5059 The '?' query below will then tell us about which threads are
5060 stopped. */
5061 this->update_thread_list ();
5062 }
5063 else if (m_features.packet_support (PACKET_QNonStop) == PACKET_ENABLE)
5064 {
5065 /* Don't assume that the stub can operate in all-stop mode.
5066 Request it explicitly. */
5067 putpkt ("QNonStop:0");
5068 getpkt (&rs->buf);
5069
5070 if (strcmp (rs->buf.data (), "OK") != 0)
5071 error (_("Remote refused setting all-stop mode with: %s"),
5072 rs->buf.data ());
5073 }
5074
5075 /* Upload TSVs regardless of whether the target is running or not. The
5076 remote stub, such as GDBserver, may have some predefined or builtin
5077 TSVs, even if the target is not running. */
5078 if (get_trace_status (current_trace_status ()) != -1)
5079 {
5080 struct uploaded_tsv *uploaded_tsvs = NULL;
5081
5082 upload_trace_state_variables (&uploaded_tsvs);
5083 merge_uploaded_trace_state_variables (&uploaded_tsvs);
5084 }
5085
5086 /* Check whether the target is running now. */
5087 putpkt ("?");
5088 getpkt (&rs->buf);
5089
5090 if (!target_is_non_stop_p ())
5091 {
5092 char *wait_status = NULL;
5093
5094 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
5095 {
5096 if (!extended_p)
5097 error (_("The target is not running (try extended-remote?)"));
5098 return false;
5099 }
5100 else
5101 {
5102 /* Save the reply for later. */
5103 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
5104 strcpy (wait_status, rs->buf.data ());
5105 }
5106
5107 /* Fetch thread list. */
5108 target_update_thread_list ();
5109
5110 /* Let the stub know that we want it to return the thread. */
5111 set_continue_thread (minus_one_ptid);
5112
5113 if (thread_count (this) == 0)
5114 {
5115 /* Target has no concept of threads at all. GDB treats
5116 non-threaded target as single-threaded; add a main
5117 thread. */
5118 thread_info *tp = add_current_inferior_and_thread (wait_status);
5119 get_remote_thread_info (tp)->set_resumed ();
5120 }
5121 else
5122 {
5123 /* We have thread information; select the thread the target
5124 says should be current. If we're reconnecting to a
5125 multi-threaded program, this will ideally be the thread
5126 that last reported an event before GDB disconnected. */
5127 ptid_t curr_thread = get_current_thread (wait_status);
5128 if (curr_thread == null_ptid)
5129 {
5130 /* Odd... The target was able to list threads, but not
5131 tell us which thread was current (no "thread"
5132 register in T stop reply?). Just pick the first
5133 thread in the thread list then. */
5134
5135 remote_debug_printf ("warning: couldn't determine remote "
5136 "current thread; picking first in list.");
5137
5138 for (thread_info *tp : all_non_exited_threads (this,
5139 minus_one_ptid))
5140 {
5141 switch_to_thread (tp);
5142 break;
5143 }
5144 }
5145 else
5146 switch_to_thread (this->find_thread (curr_thread));
5147 }
5148
5149 /* init_wait_for_inferior should be called before get_offsets in order
5150 to manage `inserted' flag in bp loc in a correct state.
5151 breakpoint_init_inferior, called from init_wait_for_inferior, set
5152 `inserted' flag to 0, while before breakpoint_re_set, called from
5153 start_remote, set `inserted' flag to 1. In the initialization of
5154 inferior, breakpoint_init_inferior should be called first, and then
5155 breakpoint_re_set can be called. If this order is broken, state of
5156 `inserted' flag is wrong, and cause some problems on breakpoint
5157 manipulation. */
5158 init_wait_for_inferior ();
5159
5160 get_offsets (); /* Get text, data & bss offsets. */
5161
5162 /* If we could not find a description using qXfer, and we know
5163 how to do it some other way, try again. This is not
5164 supported for non-stop; it could be, but it is tricky if
5165 there are no stopped threads when we connect. */
5166 if (remote_read_description_p (this)
5167 && gdbarch_target_desc (current_inferior ()->arch ()) == NULL)
5168 {
5169 target_clear_description ();
5170 target_find_description ();
5171 }
5172
5173 /* Use the previously fetched status. */
5174 gdb_assert (wait_status != NULL);
5175 struct notif_event *reply
5176 = remote_notif_parse (this, &notif_client_stop, wait_status);
5177 push_stop_reply ((struct stop_reply *) reply);
5178
5179 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
5180 }
5181 else
5182 {
5183 /* Clear WFI global state. Do this before finding about new
5184 threads and inferiors, and setting the current inferior.
5185 Otherwise we would clear the proceed status of the current
5186 inferior when we want its stop_soon state to be preserved
5187 (see notice_new_inferior). */
5188 init_wait_for_inferior ();
5189
5190 /* In non-stop, we will either get an "OK", meaning that there
5191 are no stopped threads at this time; or, a regular stop
5192 reply. In the latter case, there may be more than one thread
5193 stopped --- we pull them all out using the vStopped
5194 mechanism. */
5195 if (strcmp (rs->buf.data (), "OK") != 0)
5196 {
5197 const notif_client *notif = &notif_client_stop;
5198
5199 /* remote_notif_get_pending_replies acks this one, and gets
5200 the rest out. */
5201 rs->notif_state->pending_event[notif_client_stop.id]
5202 = remote_notif_parse (this, notif, rs->buf.data ());
5203 remote_notif_get_pending_events (notif);
5204 }
5205
5206 if (thread_count (this) == 0)
5207 {
5208 if (!extended_p)
5209 error (_("The target is not running (try extended-remote?)"));
5210 return false;
5211 }
5212
5213 /* Report all signals during attach/startup. */
5214 pass_signals ({});
5215
5216 /* If there are already stopped threads, mark them stopped and
5217 report their stops before giving the prompt to the user. */
5218 process_initial_stop_replies (from_tty);
5219
5220 if (target_can_async_p ())
5221 target_async (true);
5222 }
5223
5224 /* Give the target a chance to look up symbols. */
5225 for (inferior *inf : all_inferiors (this))
5226 {
5227 /* The inferiors that exist at this point were created from what
5228 was found already running on the remote side, so we know they
5229 have execution. */
5230 gdb_assert (this->has_execution (inf));
5231
5232 /* No use without a symbol-file. */
5233 if (inf->pspace->symfile_object_file == nullptr)
5234 continue;
5235
5236 /* Need to switch to a specific thread, because remote_check_symbols
5237 uses INFERIOR_PTID to set the general thread. */
5238 scoped_restore_current_thread restore_thread;
5239 thread_info *thread = any_thread_of_inferior (inf);
5240 switch_to_thread (thread);
5241 this->remote_check_symbols ();
5242 }
5243
5244 /* Possibly the target has been engaged in a trace run started
5245 previously; find out where things are at. */
5246 if (get_trace_status (current_trace_status ()) != -1)
5247 {
5248 struct uploaded_tp *uploaded_tps = NULL;
5249
5250 if (current_trace_status ()->running)
5251 gdb_printf (_("Trace is already running on the target.\n"));
5252
5253 upload_tracepoints (&uploaded_tps);
5254
5255 merge_uploaded_tracepoints (&uploaded_tps);
5256 }
5257
5258 /* Possibly the target has been engaged in a btrace record started
5259 previously; find out where things are at. */
5260 remote_btrace_maybe_reopen ();
5261
5262 return true;
5263 }
5264
5265 /* Start the remote connection and sync state. */
5266
5267 void
5268 remote_target::start_remote (int from_tty, int extended_p)
5269 {
5270 if (start_remote_1 (from_tty, extended_p)
5271 && breakpoints_should_be_inserted_now ())
5272 insert_breakpoints ();
5273 }
5274
5275 const char *
5276 remote_target::connection_string ()
5277 {
5278 remote_state *rs = get_remote_state ();
5279
5280 if (rs->remote_desc->name != NULL)
5281 return rs->remote_desc->name;
5282 else
5283 return NULL;
5284 }
5285
5286 /* Open a connection to a remote debugger.
5287 NAME is the filename used for communication. */
5288
5289 void
5290 remote_target::open (const char *name, int from_tty)
5291 {
5292 open_1 (name, from_tty, 0);
5293 }
5294
5295 /* Open a connection to a remote debugger using the extended
5296 remote gdb protocol. NAME is the filename used for communication. */
5297
5298 void
5299 extended_remote_target::open (const char *name, int from_tty)
5300 {
5301 open_1 (name, from_tty, 1 /*extended_p */);
5302 }
5303
5304 void
5305 remote_features::reset_all_packet_configs_support ()
5306 {
5307 int i;
5308
5309 for (i = 0; i < PACKET_MAX; i++)
5310 m_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5311 }
5312
5313 /* Initialize all packet configs. */
5314
5315 static void
5316 init_all_packet_configs (void)
5317 {
5318 int i;
5319
5320 for (i = 0; i < PACKET_MAX; i++)
5321 {
5322 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5323 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5324 }
5325 }
5326
5327 /* Symbol look-up. */
5328
5329 void
5330 remote_target::remote_check_symbols ()
5331 {
5332 char *tmp;
5333 int end;
5334
5335 /* It doesn't make sense to send a qSymbol packet for an inferior that
5336 doesn't have execution, because the remote side doesn't know about
5337 inferiors without execution. */
5338 gdb_assert (target_has_execution ());
5339
5340 if (m_features.packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5341 return;
5342
5343 /* Make sure the remote is pointing at the right process. Note
5344 there's no way to select "no process". */
5345 set_general_process ();
5346
5347 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5348 because we need both at the same time. */
5349 gdb::char_vector msg (get_remote_packet_size ());
5350 gdb::char_vector reply (get_remote_packet_size ());
5351
5352 /* Invite target to request symbol lookups. */
5353
5354 putpkt ("qSymbol::");
5355 getpkt (&reply);
5356 m_features.packet_ok (reply, PACKET_qSymbol);
5357
5358 while (startswith (reply.data (), "qSymbol:"))
5359 {
5360 struct bound_minimal_symbol sym;
5361
5362 tmp = &reply[8];
5363 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5364 strlen (tmp) / 2);
5365 msg[end] = '\0';
5366 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5367 if (sym.minsym == NULL)
5368 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5369 &reply[8]);
5370 else
5371 {
5372 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
5373 CORE_ADDR sym_addr = sym.value_address ();
5374
5375 /* If this is a function address, return the start of code
5376 instead of any data function descriptor. */
5377 sym_addr = gdbarch_convert_from_func_ptr_addr
5378 (current_inferior ()->arch (), sym_addr,
5379 current_inferior ()->top_target ());
5380
5381 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5382 phex_nz (sym_addr, addr_size), &reply[8]);
5383 }
5384
5385 putpkt (msg.data ());
5386 getpkt (&reply);
5387 }
5388 }
5389
5390 static struct serial *
5391 remote_serial_open (const char *name)
5392 {
5393 static int udp_warning = 0;
5394
5395 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5396 of in ser-tcp.c, because it is the remote protocol assuming that the
5397 serial connection is reliable and not the serial connection promising
5398 to be. */
5399 if (!udp_warning && startswith (name, "udp:"))
5400 {
5401 warning (_("The remote protocol may be unreliable over UDP.\n"
5402 "Some events may be lost, rendering further debugging "
5403 "impossible."));
5404 udp_warning = 1;
5405 }
5406
5407 return serial_open (name);
5408 }
5409
5410 /* Inform the target of our permission settings. The permission flags
5411 work without this, but if the target knows the settings, it can do
5412 a couple things. First, it can add its own check, to catch cases
5413 that somehow manage to get by the permissions checks in target
5414 methods. Second, if the target is wired to disallow particular
5415 settings (for instance, a system in the field that is not set up to
5416 be able to stop at a breakpoint), it can object to any unavailable
5417 permissions. */
5418
5419 void
5420 remote_target::set_permissions ()
5421 {
5422 struct remote_state *rs = get_remote_state ();
5423
5424 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5425 "WriteReg:%x;WriteMem:%x;"
5426 "InsertBreak:%x;InsertTrace:%x;"
5427 "InsertFastTrace:%x;Stop:%x",
5428 may_write_registers, may_write_memory,
5429 may_insert_breakpoints, may_insert_tracepoints,
5430 may_insert_fast_tracepoints, may_stop);
5431 putpkt (rs->buf);
5432 getpkt (&rs->buf);
5433
5434 /* If the target didn't like the packet, warn the user. Do not try
5435 to undo the user's settings, that would just be maddening. */
5436 if (strcmp (rs->buf.data (), "OK") != 0)
5437 warning (_("Remote refused setting permissions with: %s"),
5438 rs->buf.data ());
5439 }
5440
5441 /* This type describes each known response to the qSupported
5442 packet. */
5443 struct protocol_feature
5444 {
5445 /* The name of this protocol feature. */
5446 const char *name;
5447
5448 /* The default for this protocol feature. */
5449 enum packet_support default_support;
5450
5451 /* The function to call when this feature is reported, or after
5452 qSupported processing if the feature is not supported.
5453 The first argument points to this structure. The second
5454 argument indicates whether the packet requested support be
5455 enabled, disabled, or probed (or the default, if this function
5456 is being called at the end of processing and this feature was
5457 not reported). The third argument may be NULL; if not NULL, it
5458 is a NUL-terminated string taken from the packet following
5459 this feature's name and an equals sign. */
5460 void (*func) (remote_target *remote, const struct protocol_feature *,
5461 enum packet_support, const char *);
5462
5463 /* The corresponding packet for this feature. Only used if
5464 FUNC is remote_supported_packet. */
5465 int packet;
5466 };
5467
5468 static void
5469 remote_supported_packet (remote_target *remote,
5470 const struct protocol_feature *feature,
5471 enum packet_support support,
5472 const char *argument)
5473 {
5474 if (argument)
5475 {
5476 warning (_("Remote qSupported response supplied an unexpected value for"
5477 " \"%s\"."), feature->name);
5478 return;
5479 }
5480
5481 remote->m_features.m_protocol_packets[feature->packet].support = support;
5482 }
5483
5484 void
5485 remote_target::remote_packet_size (const protocol_feature *feature,
5486 enum packet_support support, const char *value)
5487 {
5488 struct remote_state *rs = get_remote_state ();
5489
5490 int packet_size;
5491 char *value_end;
5492
5493 if (support != PACKET_ENABLE)
5494 return;
5495
5496 if (value == NULL || *value == '\0')
5497 {
5498 warning (_("Remote target reported \"%s\" without a size."),
5499 feature->name);
5500 return;
5501 }
5502
5503 errno = 0;
5504 packet_size = strtol (value, &value_end, 16);
5505 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5506 {
5507 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5508 feature->name, value);
5509 return;
5510 }
5511
5512 /* Record the new maximum packet size. */
5513 rs->explicit_packet_size = packet_size;
5514 }
5515
5516 static void
5517 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5518 enum packet_support support, const char *value)
5519 {
5520 remote->remote_packet_size (feature, support, value);
5521 }
5522
5523 static const struct protocol_feature remote_protocol_features[] = {
5524 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5525 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5526 PACKET_qXfer_auxv },
5527 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5528 PACKET_qXfer_exec_file },
5529 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5530 PACKET_qXfer_features },
5531 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5532 PACKET_qXfer_libraries },
5533 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5534 PACKET_qXfer_libraries_svr4 },
5535 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5536 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5537 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5538 PACKET_qXfer_memory_map },
5539 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5540 PACKET_qXfer_osdata },
5541 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5542 PACKET_qXfer_threads },
5543 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5544 PACKET_qXfer_traceframe_info },
5545 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5546 PACKET_QPassSignals },
5547 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5548 PACKET_QCatchSyscalls },
5549 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5550 PACKET_QProgramSignals },
5551 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5552 PACKET_QSetWorkingDir },
5553 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5554 PACKET_QStartupWithShell },
5555 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5556 PACKET_QEnvironmentHexEncoded },
5557 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5558 PACKET_QEnvironmentReset },
5559 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5560 PACKET_QEnvironmentUnset },
5561 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5562 PACKET_QStartNoAckMode },
5563 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5564 PACKET_multiprocess_feature },
5565 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5566 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5567 PACKET_qXfer_siginfo_read },
5568 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5569 PACKET_qXfer_siginfo_write },
5570 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5571 PACKET_ConditionalTracepoints },
5572 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5573 PACKET_ConditionalBreakpoints },
5574 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5575 PACKET_BreakpointCommands },
5576 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5577 PACKET_FastTracepoints },
5578 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5579 PACKET_StaticTracepoints },
5580 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5581 PACKET_InstallInTrace},
5582 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5583 PACKET_DisconnectedTracing_feature },
5584 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5585 PACKET_bc },
5586 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5587 PACKET_bs },
5588 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5589 PACKET_TracepointSource },
5590 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5591 PACKET_QAllow },
5592 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5593 PACKET_EnableDisableTracepoints_feature },
5594 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5595 PACKET_qXfer_fdpic },
5596 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5597 PACKET_qXfer_uib },
5598 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5599 PACKET_QDisableRandomization },
5600 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5601 { "QTBuffer:size", PACKET_DISABLE,
5602 remote_supported_packet, PACKET_QTBuffer_size},
5603 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5604 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5605 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5606 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5607 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5608 PACKET_qXfer_btrace },
5609 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5610 PACKET_qXfer_btrace_conf },
5611 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5612 PACKET_Qbtrace_conf_bts_size },
5613 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5614 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5615 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5616 PACKET_fork_event_feature },
5617 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5618 PACKET_vfork_event_feature },
5619 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5620 PACKET_exec_event_feature },
5621 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5622 PACKET_Qbtrace_conf_pt_size },
5623 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5624 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5625 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5626 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5627 PACKET_memory_tagging_feature },
5628 };
5629
5630 static char *remote_support_xml;
5631
5632 /* Register string appended to "xmlRegisters=" in qSupported query. */
5633
5634 void
5635 register_remote_support_xml (const char *xml)
5636 {
5637 #if defined(HAVE_LIBEXPAT)
5638 if (remote_support_xml == NULL)
5639 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5640 else
5641 {
5642 char *copy = xstrdup (remote_support_xml + 13);
5643 char *saveptr;
5644 char *p = strtok_r (copy, ",", &saveptr);
5645
5646 do
5647 {
5648 if (strcmp (p, xml) == 0)
5649 {
5650 /* already there */
5651 xfree (copy);
5652 return;
5653 }
5654 }
5655 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5656 xfree (copy);
5657
5658 remote_support_xml = reconcat (remote_support_xml,
5659 remote_support_xml, ",", xml,
5660 (char *) NULL);
5661 }
5662 #endif
5663 }
5664
5665 static void
5666 remote_query_supported_append (std::string *msg, const char *append)
5667 {
5668 if (!msg->empty ())
5669 msg->append (";");
5670 msg->append (append);
5671 }
5672
5673 void
5674 remote_target::remote_query_supported ()
5675 {
5676 struct remote_state *rs = get_remote_state ();
5677 char *next;
5678 int i;
5679 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5680
5681 /* The packet support flags are handled differently for this packet
5682 than for most others. We treat an error, a disabled packet, and
5683 an empty response identically: any features which must be reported
5684 to be used will be automatically disabled. An empty buffer
5685 accomplishes this, since that is also the representation for a list
5686 containing no features. */
5687
5688 rs->buf[0] = 0;
5689 if (m_features.packet_support (PACKET_qSupported) != PACKET_DISABLE)
5690 {
5691 std::string q;
5692
5693 if (m_features.packet_set_cmd_state (PACKET_multiprocess_feature)
5694 != AUTO_BOOLEAN_FALSE)
5695 remote_query_supported_append (&q, "multiprocess+");
5696
5697 if (m_features.packet_set_cmd_state (PACKET_swbreak_feature)
5698 != AUTO_BOOLEAN_FALSE)
5699 remote_query_supported_append (&q, "swbreak+");
5700
5701 if (m_features.packet_set_cmd_state (PACKET_hwbreak_feature)
5702 != AUTO_BOOLEAN_FALSE)
5703 remote_query_supported_append (&q, "hwbreak+");
5704
5705 remote_query_supported_append (&q, "qRelocInsn+");
5706
5707 if (m_features.packet_set_cmd_state (PACKET_fork_event_feature)
5708 != AUTO_BOOLEAN_FALSE)
5709 remote_query_supported_append (&q, "fork-events+");
5710
5711 if (m_features.packet_set_cmd_state (PACKET_vfork_event_feature)
5712 != AUTO_BOOLEAN_FALSE)
5713 remote_query_supported_append (&q, "vfork-events+");
5714
5715 if (m_features.packet_set_cmd_state (PACKET_exec_event_feature)
5716 != AUTO_BOOLEAN_FALSE)
5717 remote_query_supported_append (&q, "exec-events+");
5718
5719 if (m_features.packet_set_cmd_state (PACKET_vContSupported)
5720 != AUTO_BOOLEAN_FALSE)
5721 remote_query_supported_append (&q, "vContSupported+");
5722
5723 if (m_features.packet_set_cmd_state (PACKET_QThreadEvents)
5724 != AUTO_BOOLEAN_FALSE)
5725 remote_query_supported_append (&q, "QThreadEvents+");
5726
5727 if (m_features.packet_set_cmd_state (PACKET_no_resumed)
5728 != AUTO_BOOLEAN_FALSE)
5729 remote_query_supported_append (&q, "no-resumed+");
5730
5731 if (m_features.packet_set_cmd_state (PACKET_memory_tagging_feature)
5732 != AUTO_BOOLEAN_FALSE)
5733 remote_query_supported_append (&q, "memory-tagging+");
5734
5735 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5736 the qSupported:xmlRegisters=i386 handling. */
5737 if (remote_support_xml != NULL
5738 && (m_features.packet_support (PACKET_qXfer_features)
5739 != PACKET_DISABLE))
5740 remote_query_supported_append (&q, remote_support_xml);
5741
5742 q = "qSupported:" + q;
5743 putpkt (q.c_str ());
5744
5745 getpkt (&rs->buf);
5746
5747 /* If an error occurred, warn, but do not return - just reset the
5748 buffer to empty and go on to disable features. */
5749 if (m_features.packet_ok (rs->buf, PACKET_qSupported) == PACKET_ERROR)
5750 {
5751 warning (_("Remote failure reply: %s"), rs->buf.data ());
5752 rs->buf[0] = 0;
5753 }
5754 }
5755
5756 memset (seen, 0, sizeof (seen));
5757
5758 next = rs->buf.data ();
5759 while (*next)
5760 {
5761 enum packet_support is_supported;
5762 char *p, *end, *name_end, *value;
5763
5764 /* First separate out this item from the rest of the packet. If
5765 there's another item after this, we overwrite the separator
5766 (terminated strings are much easier to work with). */
5767 p = next;
5768 end = strchr (p, ';');
5769 if (end == NULL)
5770 {
5771 end = p + strlen (p);
5772 next = end;
5773 }
5774 else
5775 {
5776 *end = '\0';
5777 next = end + 1;
5778
5779 if (end == p)
5780 {
5781 warning (_("empty item in \"qSupported\" response"));
5782 continue;
5783 }
5784 }
5785
5786 name_end = strchr (p, '=');
5787 if (name_end)
5788 {
5789 /* This is a name=value entry. */
5790 is_supported = PACKET_ENABLE;
5791 value = name_end + 1;
5792 *name_end = '\0';
5793 }
5794 else
5795 {
5796 value = NULL;
5797 switch (end[-1])
5798 {
5799 case '+':
5800 is_supported = PACKET_ENABLE;
5801 break;
5802
5803 case '-':
5804 is_supported = PACKET_DISABLE;
5805 break;
5806
5807 case '?':
5808 is_supported = PACKET_SUPPORT_UNKNOWN;
5809 break;
5810
5811 default:
5812 warning (_("unrecognized item \"%s\" "
5813 "in \"qSupported\" response"), p);
5814 continue;
5815 }
5816 end[-1] = '\0';
5817 }
5818
5819 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5820 if (strcmp (remote_protocol_features[i].name, p) == 0)
5821 {
5822 const struct protocol_feature *feature;
5823
5824 seen[i] = 1;
5825 feature = &remote_protocol_features[i];
5826 feature->func (this, feature, is_supported, value);
5827 break;
5828 }
5829 }
5830
5831 /* If we increased the packet size, make sure to increase the global
5832 buffer size also. We delay this until after parsing the entire
5833 qSupported packet, because this is the same buffer we were
5834 parsing. */
5835 if (rs->buf.size () < rs->explicit_packet_size)
5836 rs->buf.resize (rs->explicit_packet_size);
5837
5838 /* Handle the defaults for unmentioned features. */
5839 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5840 if (!seen[i])
5841 {
5842 const struct protocol_feature *feature;
5843
5844 feature = &remote_protocol_features[i];
5845 feature->func (this, feature, feature->default_support, NULL);
5846 }
5847 }
5848
5849 /* Serial QUIT handler for the remote serial descriptor.
5850
5851 Defers handling a Ctrl-C until we're done with the current
5852 command/response packet sequence, unless:
5853
5854 - We're setting up the connection. Don't send a remote interrupt
5855 request, as we're not fully synced yet. Quit immediately
5856 instead.
5857
5858 - The target has been resumed in the foreground
5859 (target_terminal::is_ours is false) with a synchronous resume
5860 packet, and we're blocked waiting for the stop reply, thus a
5861 Ctrl-C should be immediately sent to the target.
5862
5863 - We get a second Ctrl-C while still within the same serial read or
5864 write. In that case the serial is seemingly wedged --- offer to
5865 quit/disconnect.
5866
5867 - We see a second Ctrl-C without target response, after having
5868 previously interrupted the target. In that case the target/stub
5869 is probably wedged --- offer to quit/disconnect.
5870 */
5871
5872 void
5873 remote_target::remote_serial_quit_handler ()
5874 {
5875 struct remote_state *rs = get_remote_state ();
5876
5877 if (check_quit_flag ())
5878 {
5879 /* If we're starting up, we're not fully synced yet. Quit
5880 immediately. */
5881 if (rs->starting_up)
5882 quit ();
5883 else if (rs->got_ctrlc_during_io)
5884 {
5885 if (query (_("The target is not responding to GDB commands.\n"
5886 "Stop debugging it? ")))
5887 remote_unpush_and_throw (this);
5888 }
5889 /* If ^C has already been sent once, offer to disconnect. */
5890 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5891 interrupt_query ();
5892 /* All-stop protocol, and blocked waiting for stop reply. Send
5893 an interrupt request. */
5894 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5895 target_interrupt ();
5896 else
5897 rs->got_ctrlc_during_io = 1;
5898 }
5899 }
5900
5901 /* The remote_target that is current while the quit handler is
5902 overridden with remote_serial_quit_handler. */
5903 static remote_target *curr_quit_handler_target;
5904
5905 static void
5906 remote_serial_quit_handler ()
5907 {
5908 curr_quit_handler_target->remote_serial_quit_handler ();
5909 }
5910
5911 /* Remove the remote target from the target stack of each inferior
5912 that is using it. Upper targets depend on it so remove them
5913 first. */
5914
5915 static void
5916 remote_unpush_target (remote_target *target)
5917 {
5918 /* We have to unpush the target from all inferiors, even those that
5919 aren't running. */
5920 scoped_restore_current_inferior restore_current_inferior;
5921
5922 for (inferior *inf : all_inferiors (target))
5923 {
5924 switch_to_inferior_no_thread (inf);
5925 inf->pop_all_targets_at_and_above (process_stratum);
5926 generic_mourn_inferior ();
5927 }
5928
5929 /* Don't rely on target_close doing this when the target is popped
5930 from the last remote inferior above, because something may be
5931 holding a reference to the target higher up on the stack, meaning
5932 target_close won't be called yet. We lost the connection to the
5933 target, so clear these now, otherwise we may later throw
5934 TARGET_CLOSE_ERROR while trying to tell the remote target to
5935 close the file. */
5936 fileio_handles_invalidate_target (target);
5937 }
5938
5939 static void
5940 remote_unpush_and_throw (remote_target *target)
5941 {
5942 remote_unpush_target (target);
5943 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5944 }
5945
5946 void
5947 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5948 {
5949 remote_target *curr_remote = get_current_remote_target ();
5950
5951 if (name == 0)
5952 error (_("To open a remote debug connection, you need to specify what\n"
5953 "serial device is attached to the remote system\n"
5954 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5955
5956 /* If we're connected to a running target, target_preopen will kill it.
5957 Ask this question first, before target_preopen has a chance to kill
5958 anything. */
5959 if (curr_remote != NULL && !target_has_execution ())
5960 {
5961 if (from_tty
5962 && !query (_("Already connected to a remote target. Disconnect? ")))
5963 error (_("Still connected."));
5964 }
5965
5966 /* Here the possibly existing remote target gets unpushed. */
5967 target_preopen (from_tty);
5968
5969 remote_fileio_reset ();
5970 reopen_exec_file ();
5971 reread_symbols (from_tty);
5972
5973 remote_target *remote
5974 = (extended_p ? new extended_remote_target () : new remote_target ());
5975 target_ops_up target_holder (remote);
5976
5977 remote_state *rs = remote->get_remote_state ();
5978
5979 /* See FIXME above. */
5980 if (!target_async_permitted)
5981 rs->wait_forever_enabled_p = true;
5982
5983 rs->remote_desc = remote_serial_open (name);
5984 if (!rs->remote_desc)
5985 perror_with_name (name);
5986
5987 if (baud_rate != -1)
5988 {
5989 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5990 {
5991 /* The requested speed could not be set. Error out to
5992 top level after closing remote_desc. Take care to
5993 set remote_desc to NULL to avoid closing remote_desc
5994 more than once. */
5995 serial_close (rs->remote_desc);
5996 rs->remote_desc = NULL;
5997 perror_with_name (name);
5998 }
5999 }
6000
6001 serial_setparity (rs->remote_desc, serial_parity);
6002 serial_raw (rs->remote_desc);
6003
6004 /* If there is something sitting in the buffer we might take it as a
6005 response to a command, which would be bad. */
6006 serial_flush_input (rs->remote_desc);
6007
6008 if (from_tty)
6009 {
6010 gdb_puts ("Remote debugging using ");
6011 gdb_puts (name);
6012 gdb_puts ("\n");
6013 }
6014
6015 /* Switch to using the remote target now. */
6016 current_inferior ()->push_target (std::move (target_holder));
6017
6018 /* Register extra event sources in the event loop. */
6019 rs->create_async_event_handler ();
6020
6021 rs->notif_state = remote_notif_state_allocate (remote);
6022
6023 /* Reset the target state; these things will be queried either by
6024 remote_query_supported or as they are needed. */
6025 remote->m_features.reset_all_packet_configs_support ();
6026 rs->explicit_packet_size = 0;
6027 rs->noack_mode = 0;
6028 rs->extended = extended_p;
6029 rs->waiting_for_stop_reply = 0;
6030 rs->ctrlc_pending_p = 0;
6031 rs->got_ctrlc_during_io = 0;
6032
6033 rs->general_thread = not_sent_ptid;
6034 rs->continue_thread = not_sent_ptid;
6035 rs->remote_traceframe_number = -1;
6036
6037 rs->last_resume_exec_dir = EXEC_FORWARD;
6038
6039 /* Probe for ability to use "ThreadInfo" query, as required. */
6040 rs->use_threadinfo_query = 1;
6041 rs->use_threadextra_query = 1;
6042
6043 rs->readahead_cache.invalidate ();
6044
6045 if (target_async_permitted)
6046 {
6047 /* FIXME: cagney/1999-09-23: During the initial connection it is
6048 assumed that the target is already ready and able to respond to
6049 requests. Unfortunately remote_start_remote() eventually calls
6050 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
6051 around this. Eventually a mechanism that allows
6052 wait_for_inferior() to expect/get timeouts will be
6053 implemented. */
6054 rs->wait_forever_enabled_p = false;
6055 }
6056
6057 /* First delete any symbols previously loaded from shared libraries. */
6058 no_shared_libraries (NULL, 0);
6059
6060 /* Start the remote connection. If error() or QUIT, discard this
6061 target (we'd otherwise be in an inconsistent state) and then
6062 propogate the error on up the exception chain. This ensures that
6063 the caller doesn't stumble along blindly assuming that the
6064 function succeeded. The CLI doesn't have this problem but other
6065 UI's, such as MI do.
6066
6067 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
6068 this function should return an error indication letting the
6069 caller restore the previous state. Unfortunately the command
6070 ``target remote'' is directly wired to this function making that
6071 impossible. On a positive note, the CLI side of this problem has
6072 been fixed - the function set_cmd_context() makes it possible for
6073 all the ``target ....'' commands to share a common callback
6074 function. See cli-dump.c. */
6075 {
6076
6077 try
6078 {
6079 remote->start_remote (from_tty, extended_p);
6080 }
6081 catch (const gdb_exception &ex)
6082 {
6083 /* Pop the partially set up target - unless something else did
6084 already before throwing the exception. */
6085 if (ex.error != TARGET_CLOSE_ERROR)
6086 remote_unpush_target (remote);
6087 throw;
6088 }
6089 }
6090
6091 remote_btrace_reset (rs);
6092
6093 if (target_async_permitted)
6094 rs->wait_forever_enabled_p = true;
6095 }
6096
6097 /* Determine if WS represents a fork status. */
6098
6099 static bool
6100 is_fork_status (target_waitkind kind)
6101 {
6102 return (kind == TARGET_WAITKIND_FORKED
6103 || kind == TARGET_WAITKIND_VFORKED);
6104 }
6105
6106 /* Return THREAD's pending status if it is a pending fork parent, else
6107 return nullptr. */
6108
6109 static const target_waitstatus *
6110 thread_pending_fork_status (struct thread_info *thread)
6111 {
6112 const target_waitstatus &ws
6113 = (thread->has_pending_waitstatus ()
6114 ? thread->pending_waitstatus ()
6115 : thread->pending_follow);
6116
6117 if (!is_fork_status (ws.kind ()))
6118 return nullptr;
6119
6120 return &ws;
6121 }
6122
6123 /* Detach the specified process. */
6124
6125 void
6126 remote_target::remote_detach_pid (int pid)
6127 {
6128 struct remote_state *rs = get_remote_state ();
6129
6130 /* This should not be necessary, but the handling for D;PID in
6131 GDBserver versions prior to 8.2 incorrectly assumes that the
6132 selected process points to the same process we're detaching,
6133 leading to misbehavior (and possibly GDBserver crashing) when it
6134 does not. Since it's easy and cheap, work around it by forcing
6135 GDBserver to select GDB's current process. */
6136 set_general_process ();
6137
6138 if (m_features.remote_multi_process_p ())
6139 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
6140 else
6141 strcpy (rs->buf.data (), "D");
6142
6143 putpkt (rs->buf);
6144 getpkt (&rs->buf);
6145
6146 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
6147 ;
6148 else if (rs->buf[0] == '\0')
6149 error (_("Remote doesn't know how to detach"));
6150 else
6151 error (_("Can't detach process."));
6152 }
6153
6154 /* This detaches a program to which we previously attached, using
6155 inferior_ptid to identify the process. After this is done, GDB
6156 can be used to debug some other program. We better not have left
6157 any breakpoints in the target program or it'll die when it hits
6158 one. */
6159
6160 void
6161 remote_target::remote_detach_1 (inferior *inf, int from_tty)
6162 {
6163 int pid = inferior_ptid.pid ();
6164 struct remote_state *rs = get_remote_state ();
6165 int is_fork_parent;
6166
6167 if (!target_has_execution ())
6168 error (_("No process to detach from."));
6169
6170 target_announce_detach (from_tty);
6171
6172 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
6173 {
6174 /* If we're in breakpoints-always-inserted mode, or the inferior
6175 is running, we have to remove breakpoints before detaching.
6176 We don't do this in common code instead because not all
6177 targets support removing breakpoints while the target is
6178 running. The remote target / gdbserver does, though. */
6179 remove_breakpoints_inf (current_inferior ());
6180 }
6181
6182 /* Tell the remote target to detach. */
6183 remote_detach_pid (pid);
6184
6185 /* Exit only if this is the only active inferior. */
6186 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
6187 gdb_puts (_("Ending remote debugging.\n"));
6188
6189 /* See if any thread of the inferior we are detaching has a pending fork
6190 status. In that case, we must detach from the child resulting from
6191 that fork. */
6192 for (thread_info *thread : inf->non_exited_threads ())
6193 {
6194 const target_waitstatus *ws = thread_pending_fork_status (thread);
6195
6196 if (ws == nullptr)
6197 continue;
6198
6199 remote_detach_pid (ws->child_ptid ().pid ());
6200 }
6201
6202 /* Check also for any pending fork events in the stop reply queue. */
6203 remote_notif_get_pending_events (&notif_client_stop);
6204 for (stop_reply_up &reply : rs->stop_reply_queue)
6205 {
6206 if (reply->ptid.pid () != pid)
6207 continue;
6208
6209 if (!is_fork_status (reply->ws.kind ()))
6210 continue;
6211
6212 remote_detach_pid (reply->ws.child_ptid ().pid ());
6213 }
6214
6215 thread_info *tp = this->find_thread (inferior_ptid);
6216
6217 /* Check to see if we are detaching a fork parent. Note that if we
6218 are detaching a fork child, tp == NULL. */
6219 is_fork_parent = (tp != NULL
6220 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
6221
6222 /* If doing detach-on-fork, we don't mourn, because that will delete
6223 breakpoints that should be available for the followed inferior. */
6224 if (!is_fork_parent)
6225 {
6226 /* Save the pid as a string before mourning, since that will
6227 unpush the remote target, and we need the string after. */
6228 std::string infpid = target_pid_to_str (ptid_t (pid));
6229
6230 target_mourn_inferior (inferior_ptid);
6231 if (print_inferior_events)
6232 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6233 inf->num, infpid.c_str ());
6234 }
6235 else
6236 {
6237 switch_to_no_thread ();
6238 detach_inferior (current_inferior ());
6239 }
6240 }
6241
6242 void
6243 remote_target::detach (inferior *inf, int from_tty)
6244 {
6245 remote_detach_1 (inf, from_tty);
6246 }
6247
6248 void
6249 extended_remote_target::detach (inferior *inf, int from_tty)
6250 {
6251 remote_detach_1 (inf, from_tty);
6252 }
6253
6254 /* Target follow-fork function for remote targets. On entry, and
6255 at return, the current inferior is the fork parent.
6256
6257 Note that although this is currently only used for extended-remote,
6258 it is named remote_follow_fork in anticipation of using it for the
6259 remote target as well. */
6260
6261 void
6262 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6263 target_waitkind fork_kind, bool follow_child,
6264 bool detach_fork)
6265 {
6266 process_stratum_target::follow_fork (child_inf, child_ptid,
6267 fork_kind, follow_child, detach_fork);
6268
6269 if ((fork_kind == TARGET_WAITKIND_FORKED
6270 && m_features.remote_fork_event_p ())
6271 || (fork_kind == TARGET_WAITKIND_VFORKED
6272 && m_features.remote_vfork_event_p ()))
6273 {
6274 /* When following the parent and detaching the child, we detach
6275 the child here. For the case of following the child and
6276 detaching the parent, the detach is done in the target-
6277 independent follow fork code in infrun.c. We can't use
6278 target_detach when detaching an unfollowed child because
6279 the client side doesn't know anything about the child. */
6280 if (detach_fork && !follow_child)
6281 {
6282 /* Detach the fork child. */
6283 remote_detach_pid (child_ptid.pid ());
6284 }
6285 }
6286 }
6287
6288 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6289 in the program space of the new inferior. */
6290
6291 void
6292 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6293 const char *execd_pathname)
6294 {
6295 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6296
6297 /* We know that this is a target file name, so if it has the "target:"
6298 prefix we strip it off before saving it in the program space. */
6299 if (is_target_filename (execd_pathname))
6300 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6301
6302 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6303 }
6304
6305 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6306
6307 void
6308 remote_target::disconnect (const char *args, int from_tty)
6309 {
6310 if (args)
6311 error (_("Argument given to \"disconnect\" when remotely debugging."));
6312
6313 /* Make sure we unpush even the extended remote targets. Calling
6314 target_mourn_inferior won't unpush, and
6315 remote_target::mourn_inferior won't unpush if there is more than
6316 one inferior left. */
6317 remote_unpush_target (this);
6318
6319 if (from_tty)
6320 gdb_puts ("Ending remote debugging.\n");
6321 }
6322
6323 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6324 be chatty about it. */
6325
6326 void
6327 extended_remote_target::attach (const char *args, int from_tty)
6328 {
6329 struct remote_state *rs = get_remote_state ();
6330 int pid;
6331 char *wait_status = NULL;
6332
6333 pid = parse_pid_to_attach (args);
6334
6335 /* Remote PID can be freely equal to getpid, do not check it here the same
6336 way as in other targets. */
6337
6338 if (m_features.packet_support (PACKET_vAttach) == PACKET_DISABLE)
6339 error (_("This target does not support attaching to a process"));
6340
6341 target_announce_attach (from_tty, pid);
6342
6343 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6344 putpkt (rs->buf);
6345 getpkt (&rs->buf);
6346
6347 switch (m_features.packet_ok (rs->buf, PACKET_vAttach))
6348 {
6349 case PACKET_OK:
6350 if (!target_is_non_stop_p ())
6351 {
6352 /* Save the reply for later. */
6353 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6354 strcpy (wait_status, rs->buf.data ());
6355 }
6356 else if (strcmp (rs->buf.data (), "OK") != 0)
6357 error (_("Attaching to %s failed with: %s"),
6358 target_pid_to_str (ptid_t (pid)).c_str (),
6359 rs->buf.data ());
6360 break;
6361 case PACKET_UNKNOWN:
6362 error (_("This target does not support attaching to a process"));
6363 default:
6364 error (_("Attaching to %s failed"),
6365 target_pid_to_str (ptid_t (pid)).c_str ());
6366 }
6367
6368 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6369
6370 inferior_ptid = ptid_t (pid);
6371
6372 if (target_is_non_stop_p ())
6373 {
6374 /* Get list of threads. */
6375 update_thread_list ();
6376
6377 thread_info *thread = first_thread_of_inferior (current_inferior ());
6378 if (thread != nullptr)
6379 switch_to_thread (thread);
6380
6381 /* Invalidate our notion of the remote current thread. */
6382 record_currthread (rs, minus_one_ptid);
6383 }
6384 else
6385 {
6386 /* Now, if we have thread information, update the main thread's
6387 ptid. */
6388 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6389
6390 /* Add the main thread to the thread list. We add the thread
6391 silently in this case (the final true parameter). */
6392 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
6393
6394 switch_to_thread (thr);
6395 }
6396
6397 /* Next, if the target can specify a description, read it. We do
6398 this before anything involving memory or registers. */
6399 target_find_description ();
6400
6401 if (!target_is_non_stop_p ())
6402 {
6403 /* Use the previously fetched status. */
6404 gdb_assert (wait_status != NULL);
6405
6406 struct notif_event *reply
6407 = remote_notif_parse (this, &notif_client_stop, wait_status);
6408
6409 push_stop_reply ((struct stop_reply *) reply);
6410 }
6411 else
6412 {
6413 gdb_assert (wait_status == NULL);
6414
6415 gdb_assert (target_can_async_p ());
6416 }
6417 }
6418
6419 /* Implementation of the to_post_attach method. */
6420
6421 void
6422 extended_remote_target::post_attach (int pid)
6423 {
6424 /* Get text, data & bss offsets. */
6425 get_offsets ();
6426
6427 /* In certain cases GDB might not have had the chance to start
6428 symbol lookup up until now. This could happen if the debugged
6429 binary is not using shared libraries, the vsyscall page is not
6430 present (on Linux) and the binary itself hadn't changed since the
6431 debugging process was started. */
6432 if (current_program_space->symfile_object_file != NULL)
6433 remote_check_symbols();
6434 }
6435
6436 \f
6437 /* Check for the availability of vCont. This function should also check
6438 the response. */
6439
6440 void
6441 remote_target::remote_vcont_probe ()
6442 {
6443 remote_state *rs = get_remote_state ();
6444 char *buf;
6445
6446 strcpy (rs->buf.data (), "vCont?");
6447 putpkt (rs->buf);
6448 getpkt (&rs->buf);
6449 buf = rs->buf.data ();
6450
6451 /* Make sure that the features we assume are supported. */
6452 if (startswith (buf, "vCont"))
6453 {
6454 char *p = &buf[5];
6455 int support_c, support_C;
6456
6457 rs->supports_vCont.s = 0;
6458 rs->supports_vCont.S = 0;
6459 support_c = 0;
6460 support_C = 0;
6461 rs->supports_vCont.t = 0;
6462 rs->supports_vCont.r = 0;
6463 while (p && *p == ';')
6464 {
6465 p++;
6466 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6467 rs->supports_vCont.s = 1;
6468 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6469 rs->supports_vCont.S = 1;
6470 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6471 support_c = 1;
6472 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6473 support_C = 1;
6474 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6475 rs->supports_vCont.t = 1;
6476 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6477 rs->supports_vCont.r = 1;
6478
6479 p = strchr (p, ';');
6480 }
6481
6482 /* If c, and C are not all supported, we can't use vCont. Clearing
6483 BUF will make packet_ok disable the packet. */
6484 if (!support_c || !support_C)
6485 buf[0] = 0;
6486 }
6487
6488 m_features.packet_ok (rs->buf, PACKET_vCont);
6489 }
6490
6491 /* Helper function for building "vCont" resumptions. Write a
6492 resumption to P. ENDP points to one-passed-the-end of the buffer
6493 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6494 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6495 resumed thread should be single-stepped and/or signalled. If PTID
6496 equals minus_one_ptid, then all threads are resumed; if PTID
6497 represents a process, then all threads of the process are
6498 resumed. */
6499
6500 char *
6501 remote_target::append_resumption (char *p, char *endp,
6502 ptid_t ptid, int step, gdb_signal siggnal)
6503 {
6504 struct remote_state *rs = get_remote_state ();
6505
6506 if (step && siggnal != GDB_SIGNAL_0)
6507 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6508 else if (step
6509 /* GDB is willing to range step. */
6510 && use_range_stepping
6511 /* Target supports range stepping. */
6512 && rs->supports_vCont.r
6513 /* We don't currently support range stepping multiple
6514 threads with a wildcard (though the protocol allows it,
6515 so stubs shouldn't make an active effort to forbid
6516 it). */
6517 && !(m_features.remote_multi_process_p () && ptid.is_pid ()))
6518 {
6519 struct thread_info *tp;
6520
6521 if (ptid == minus_one_ptid)
6522 {
6523 /* If we don't know about the target thread's tid, then
6524 we're resuming magic_null_ptid (see caller). */
6525 tp = this->find_thread (magic_null_ptid);
6526 }
6527 else
6528 tp = this->find_thread (ptid);
6529 gdb_assert (tp != NULL);
6530
6531 if (tp->control.may_range_step)
6532 {
6533 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
6534
6535 p += xsnprintf (p, endp - p, ";r%s,%s",
6536 phex_nz (tp->control.step_range_start,
6537 addr_size),
6538 phex_nz (tp->control.step_range_end,
6539 addr_size));
6540 }
6541 else
6542 p += xsnprintf (p, endp - p, ";s");
6543 }
6544 else if (step)
6545 p += xsnprintf (p, endp - p, ";s");
6546 else if (siggnal != GDB_SIGNAL_0)
6547 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6548 else
6549 p += xsnprintf (p, endp - p, ";c");
6550
6551 if (m_features.remote_multi_process_p () && ptid.is_pid ())
6552 {
6553 ptid_t nptid;
6554
6555 /* All (-1) threads of process. */
6556 nptid = ptid_t (ptid.pid (), -1);
6557
6558 p += xsnprintf (p, endp - p, ":");
6559 p = write_ptid (p, endp, nptid);
6560 }
6561 else if (ptid != minus_one_ptid)
6562 {
6563 p += xsnprintf (p, endp - p, ":");
6564 p = write_ptid (p, endp, ptid);
6565 }
6566
6567 return p;
6568 }
6569
6570 /* Clear the thread's private info on resume. */
6571
6572 static void
6573 resume_clear_thread_private_info (struct thread_info *thread)
6574 {
6575 if (thread->priv != NULL)
6576 {
6577 remote_thread_info *priv = get_remote_thread_info (thread);
6578
6579 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6580 priv->watch_data_address = 0;
6581 }
6582 }
6583
6584 /* Append a vCont continue-with-signal action for threads that have a
6585 non-zero stop signal. */
6586
6587 char *
6588 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6589 ptid_t ptid)
6590 {
6591 for (thread_info *thread : all_non_exited_threads (this, ptid))
6592 if (inferior_ptid != thread->ptid
6593 && thread->stop_signal () != GDB_SIGNAL_0)
6594 {
6595 p = append_resumption (p, endp, thread->ptid,
6596 0, thread->stop_signal ());
6597 thread->set_stop_signal (GDB_SIGNAL_0);
6598 resume_clear_thread_private_info (thread);
6599 }
6600
6601 return p;
6602 }
6603
6604 /* Set the target running, using the packets that use Hc
6605 (c/s/C/S). */
6606
6607 void
6608 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6609 gdb_signal siggnal)
6610 {
6611 struct remote_state *rs = get_remote_state ();
6612 char *buf;
6613
6614 rs->last_sent_signal = siggnal;
6615 rs->last_sent_step = step;
6616
6617 /* The c/s/C/S resume packets use Hc, so set the continue
6618 thread. */
6619 if (ptid == minus_one_ptid)
6620 set_continue_thread (any_thread_ptid);
6621 else
6622 set_continue_thread (ptid);
6623
6624 for (thread_info *thread : all_non_exited_threads (this))
6625 resume_clear_thread_private_info (thread);
6626
6627 buf = rs->buf.data ();
6628 if (::execution_direction == EXEC_REVERSE)
6629 {
6630 /* We don't pass signals to the target in reverse exec mode. */
6631 if (info_verbose && siggnal != GDB_SIGNAL_0)
6632 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6633 siggnal);
6634
6635 if (step && m_features.packet_support (PACKET_bs) == PACKET_DISABLE)
6636 error (_("Remote reverse-step not supported."));
6637 if (!step && m_features.packet_support (PACKET_bc) == PACKET_DISABLE)
6638 error (_("Remote reverse-continue not supported."));
6639
6640 strcpy (buf, step ? "bs" : "bc");
6641 }
6642 else if (siggnal != GDB_SIGNAL_0)
6643 {
6644 buf[0] = step ? 'S' : 'C';
6645 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6646 buf[2] = tohex (((int) siggnal) & 0xf);
6647 buf[3] = '\0';
6648 }
6649 else
6650 strcpy (buf, step ? "s" : "c");
6651
6652 putpkt (buf);
6653 }
6654
6655 /* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6656 STEP, and SIGGNAL have the same meaning as in target_resume. This
6657 function returns non-zero iff it resumes the inferior.
6658
6659 This function issues a strict subset of all possible vCont commands
6660 at the moment. */
6661
6662 int
6663 remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6664 enum gdb_signal siggnal)
6665 {
6666 struct remote_state *rs = get_remote_state ();
6667 char *p;
6668 char *endp;
6669
6670 /* No reverse execution actions defined for vCont. */
6671 if (::execution_direction == EXEC_REVERSE)
6672 return 0;
6673
6674 if (m_features.packet_support (PACKET_vCont) == PACKET_DISABLE)
6675 return 0;
6676
6677 p = rs->buf.data ();
6678 endp = p + get_remote_packet_size ();
6679
6680 /* If we could generate a wider range of packets, we'd have to worry
6681 about overflowing BUF. Should there be a generic
6682 "multi-part-packet" packet? */
6683
6684 p += xsnprintf (p, endp - p, "vCont");
6685
6686 if (scope_ptid == magic_null_ptid)
6687 {
6688 /* MAGIC_NULL_PTID means that we don't have any active threads,
6689 so we don't have any TID numbers the inferior will
6690 understand. Make sure to only send forms that do not specify
6691 a TID. */
6692 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6693 }
6694 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
6695 {
6696 /* Resume all threads (of all processes, or of a single
6697 process), with preference for INFERIOR_PTID. This assumes
6698 inferior_ptid belongs to the set of all threads we are about
6699 to resume. */
6700 if (step || siggnal != GDB_SIGNAL_0)
6701 {
6702 /* Step inferior_ptid, with or without signal. */
6703 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6704 }
6705
6706 /* Also pass down any pending signaled resumption for other
6707 threads not the current. */
6708 p = append_pending_thread_resumptions (p, endp, scope_ptid);
6709
6710 /* And continue others without a signal. */
6711 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
6712 }
6713 else
6714 {
6715 /* Scheduler locking; resume only SCOPE_PTID. */
6716 append_resumption (p, endp, scope_ptid, step, siggnal);
6717 }
6718
6719 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6720 putpkt (rs->buf);
6721
6722 if (target_is_non_stop_p ())
6723 {
6724 /* In non-stop, the stub replies to vCont with "OK". The stop
6725 reply will be reported asynchronously by means of a `%Stop'
6726 notification. */
6727 getpkt (&rs->buf);
6728 if (strcmp (rs->buf.data (), "OK") != 0)
6729 error (_("Unexpected vCont reply in non-stop mode: %s"),
6730 rs->buf.data ());
6731 }
6732
6733 return 1;
6734 }
6735
6736 /* Tell the remote machine to resume. */
6737
6738 void
6739 remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
6740 {
6741 struct remote_state *rs = get_remote_state ();
6742
6743 /* When connected in non-stop mode, the core resumes threads
6744 individually. Resuming remote threads directly in target_resume
6745 would thus result in sending one packet per thread. Instead, to
6746 minimize roundtrip latency, here we just store the resume
6747 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6748 resumption will be done in remote_target::commit_resume, where we'll be
6749 able to do vCont action coalescing. */
6750 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6751 {
6752 remote_thread_info *remote_thr
6753 = get_remote_thread_info (inferior_thread ());
6754
6755 /* We don't expect the core to ask to resume an already resumed (from
6756 its point of view) thread. */
6757 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6758
6759 remote_thr->set_resumed_pending_vcont (step, siggnal);
6760
6761 /* There's actually nothing that says that the core can't
6762 request a wildcard resume in non-stop mode, though. It's
6763 just that we know it doesn't currently, so we don't bother
6764 with it. */
6765 gdb_assert (scope_ptid == inferior_ptid);
6766 return;
6767 }
6768
6769 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6770 (explained in remote-notif.c:handle_notification) so
6771 remote_notif_process is not called. We need find a place where
6772 it is safe to start a 'vNotif' sequence. It is good to do it
6773 before resuming inferior, because inferior was stopped and no RSP
6774 traffic at that moment. */
6775 if (!target_is_non_stop_p ())
6776 remote_notif_process (rs->notif_state, &notif_client_stop);
6777
6778 rs->last_resume_exec_dir = ::execution_direction;
6779
6780 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6781 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
6782 remote_resume_with_hc (scope_ptid, step, siggnal);
6783
6784 /* Update resumed state tracked by the remote target. */
6785 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
6786 get_remote_thread_info (tp)->set_resumed ();
6787
6788 /* We've just told the target to resume. The remote server will
6789 wait for the inferior to stop, and then send a stop reply. In
6790 the mean time, we can't start another command/query ourselves
6791 because the stub wouldn't be ready to process it. This applies
6792 only to the base all-stop protocol, however. In non-stop (which
6793 only supports vCont), the stub replies with an "OK", and is
6794 immediate able to process further serial input. */
6795 if (!target_is_non_stop_p ())
6796 rs->waiting_for_stop_reply = 1;
6797 }
6798
6799 /* Private per-inferior info for target remote processes. */
6800
6801 struct remote_inferior : public private_inferior
6802 {
6803 /* Whether we can send a wildcard vCont for this process. */
6804 bool may_wildcard_vcont = true;
6805 };
6806
6807 /* Get the remote private inferior data associated to INF. */
6808
6809 static remote_inferior *
6810 get_remote_inferior (inferior *inf)
6811 {
6812 if (inf->priv == NULL)
6813 inf->priv.reset (new remote_inferior);
6814
6815 return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
6816 }
6817
6818 /* Class used to track the construction of a vCont packet in the
6819 outgoing packet buffer. This is used to send multiple vCont
6820 packets if we have more actions than would fit a single packet. */
6821
6822 class vcont_builder
6823 {
6824 public:
6825 explicit vcont_builder (remote_target *remote)
6826 : m_remote (remote)
6827 {
6828 restart ();
6829 }
6830
6831 void flush ();
6832 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6833
6834 private:
6835 void restart ();
6836
6837 /* The remote target. */
6838 remote_target *m_remote;
6839
6840 /* Pointer to the first action. P points here if no action has been
6841 appended yet. */
6842 char *m_first_action;
6843
6844 /* Where the next action will be appended. */
6845 char *m_p;
6846
6847 /* The end of the buffer. Must never write past this. */
6848 char *m_endp;
6849 };
6850
6851 /* Prepare the outgoing buffer for a new vCont packet. */
6852
6853 void
6854 vcont_builder::restart ()
6855 {
6856 struct remote_state *rs = m_remote->get_remote_state ();
6857
6858 m_p = rs->buf.data ();
6859 m_endp = m_p + m_remote->get_remote_packet_size ();
6860 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6861 m_first_action = m_p;
6862 }
6863
6864 /* If the vCont packet being built has any action, send it to the
6865 remote end. */
6866
6867 void
6868 vcont_builder::flush ()
6869 {
6870 struct remote_state *rs;
6871
6872 if (m_p == m_first_action)
6873 return;
6874
6875 rs = m_remote->get_remote_state ();
6876 m_remote->putpkt (rs->buf);
6877 m_remote->getpkt (&rs->buf);
6878 if (strcmp (rs->buf.data (), "OK") != 0)
6879 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
6880 }
6881
6882 /* The largest action is range-stepping, with its two addresses. This
6883 is more than sufficient. If a new, bigger action is created, it'll
6884 quickly trigger a failed assertion in append_resumption (and we'll
6885 just bump this). */
6886 #define MAX_ACTION_SIZE 200
6887
6888 /* Append a new vCont action in the outgoing packet being built. If
6889 the action doesn't fit the packet along with previous actions, push
6890 what we've got so far to the remote end and start over a new vCont
6891 packet (with the new action). */
6892
6893 void
6894 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6895 {
6896 char buf[MAX_ACTION_SIZE + 1];
6897
6898 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6899 ptid, step, siggnal);
6900
6901 /* Check whether this new action would fit in the vCont packet along
6902 with previous actions. If not, send what we've got so far and
6903 start a new vCont packet. */
6904 size_t rsize = endp - buf;
6905 if (rsize > m_endp - m_p)
6906 {
6907 flush ();
6908 restart ();
6909
6910 /* Should now fit. */
6911 gdb_assert (rsize <= m_endp - m_p);
6912 }
6913
6914 memcpy (m_p, buf, rsize);
6915 m_p += rsize;
6916 *m_p = '\0';
6917 }
6918
6919 /* to_commit_resume implementation. */
6920
6921 void
6922 remote_target::commit_resumed ()
6923 {
6924 /* If connected in all-stop mode, we'd send the remote resume
6925 request directly from remote_resume. Likewise if
6926 reverse-debugging, as there are no defined vCont actions for
6927 reverse execution. */
6928 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6929 return;
6930
6931 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6932 instead of resuming all threads of each process individually.
6933 However, if any thread of a process must remain halted, we can't
6934 send wildcard resumes and must send one action per thread.
6935
6936 Care must be taken to not resume threads/processes the server
6937 side already told us are stopped, but the core doesn't know about
6938 yet, because the events are still in the vStopped notification
6939 queue. For example:
6940
6941 #1 => vCont s:p1.1;c
6942 #2 <= OK
6943 #3 <= %Stopped T05 p1.1
6944 #4 => vStopped
6945 #5 <= T05 p1.2
6946 #6 => vStopped
6947 #7 <= OK
6948 #8 (infrun handles the stop for p1.1 and continues stepping)
6949 #9 => vCont s:p1.1;c
6950
6951 The last vCont above would resume thread p1.2 by mistake, because
6952 the server has no idea that the event for p1.2 had not been
6953 handled yet.
6954
6955 The server side must similarly ignore resume actions for the
6956 thread that has a pending %Stopped notification (and any other
6957 threads with events pending), until GDB acks the notification
6958 with vStopped. Otherwise, e.g., the following case is
6959 mishandled:
6960
6961 #1 => g (or any other packet)
6962 #2 <= [registers]
6963 #3 <= %Stopped T05 p1.2
6964 #4 => vCont s:p1.1;c
6965 #5 <= OK
6966
6967 Above, the server must not resume thread p1.2. GDB can't know
6968 that p1.2 stopped until it acks the %Stopped notification, and
6969 since from GDB's perspective all threads should be running, it
6970 sends a "c" action.
6971
6972 Finally, special care must also be given to handling fork/vfork
6973 events. A (v)fork event actually tells us that two processes
6974 stopped -- the parent and the child. Until we follow the fork,
6975 we must not resume the child. Therefore, if we have a pending
6976 fork follow, we must not send a global wildcard resume action
6977 (vCont;c). We can still send process-wide wildcards though. */
6978
6979 /* Start by assuming a global wildcard (vCont;c) is possible. */
6980 bool may_global_wildcard_vcont = true;
6981
6982 /* And assume every process is individually wildcard-able too. */
6983 for (inferior *inf : all_non_exited_inferiors (this))
6984 {
6985 remote_inferior *priv = get_remote_inferior (inf);
6986
6987 priv->may_wildcard_vcont = true;
6988 }
6989
6990 /* Check for any pending events (not reported or processed yet) and
6991 disable process and global wildcard resumes appropriately. */
6992 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6993
6994 bool any_pending_vcont_resume = false;
6995
6996 for (thread_info *tp : all_non_exited_threads (this))
6997 {
6998 remote_thread_info *priv = get_remote_thread_info (tp);
6999
7000 /* If a thread of a process is not meant to be resumed, then we
7001 can't wildcard that process. */
7002 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
7003 {
7004 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
7005
7006 /* And if we can't wildcard a process, we can't wildcard
7007 everything either. */
7008 may_global_wildcard_vcont = false;
7009 continue;
7010 }
7011
7012 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
7013 any_pending_vcont_resume = true;
7014
7015 /* If a thread is the parent of an unfollowed fork, then we
7016 can't do a global wildcard, as that would resume the fork
7017 child. */
7018 if (thread_pending_fork_status (tp) != nullptr)
7019 may_global_wildcard_vcont = false;
7020 }
7021
7022 /* We didn't have any resumed thread pending a vCont resume, so nothing to
7023 do. */
7024 if (!any_pending_vcont_resume)
7025 return;
7026
7027 /* Now let's build the vCont packet(s). Actions must be appended
7028 from narrower to wider scopes (thread -> process -> global). If
7029 we end up with too many actions for a single packet vcont_builder
7030 flushes the current vCont packet to the remote side and starts a
7031 new one. */
7032 struct vcont_builder vcont_builder (this);
7033
7034 /* Threads first. */
7035 for (thread_info *tp : all_non_exited_threads (this))
7036 {
7037 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7038
7039 /* If the thread was previously vCont-resumed, no need to send a specific
7040 action for it. If we didn't receive a resume request for it, don't
7041 send an action for it either. */
7042 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
7043 continue;
7044
7045 gdb_assert (!thread_is_in_step_over_chain (tp));
7046
7047 /* We should never be commit-resuming a thread that has a stop reply.
7048 Otherwise, we would end up reporting a stop event for a thread while
7049 it is running on the remote target. */
7050 remote_state *rs = get_remote_state ();
7051 for (const auto &stop_reply : rs->stop_reply_queue)
7052 gdb_assert (stop_reply->ptid != tp->ptid);
7053
7054 const resumed_pending_vcont_info &info
7055 = remote_thr->resumed_pending_vcont_info ();
7056
7057 /* Check if we need to send a specific action for this thread. If not,
7058 it will be included in a wildcard resume instead. */
7059 if (info.step || info.sig != GDB_SIGNAL_0
7060 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
7061 vcont_builder.push_action (tp->ptid, info.step, info.sig);
7062
7063 remote_thr->set_resumed ();
7064 }
7065
7066 /* Now check whether we can send any process-wide wildcard. This is
7067 to avoid sending a global wildcard in the case nothing is
7068 supposed to be resumed. */
7069 bool any_process_wildcard = false;
7070
7071 for (inferior *inf : all_non_exited_inferiors (this))
7072 {
7073 if (get_remote_inferior (inf)->may_wildcard_vcont)
7074 {
7075 any_process_wildcard = true;
7076 break;
7077 }
7078 }
7079
7080 if (any_process_wildcard)
7081 {
7082 /* If all processes are wildcard-able, then send a single "c"
7083 action, otherwise, send an "all (-1) threads of process"
7084 continue action for each running process, if any. */
7085 if (may_global_wildcard_vcont)
7086 {
7087 vcont_builder.push_action (minus_one_ptid,
7088 false, GDB_SIGNAL_0);
7089 }
7090 else
7091 {
7092 for (inferior *inf : all_non_exited_inferiors (this))
7093 {
7094 if (get_remote_inferior (inf)->may_wildcard_vcont)
7095 {
7096 vcont_builder.push_action (ptid_t (inf->pid),
7097 false, GDB_SIGNAL_0);
7098 }
7099 }
7100 }
7101 }
7102
7103 vcont_builder.flush ();
7104 }
7105
7106 /* Implementation of target_has_pending_events. */
7107
7108 bool
7109 remote_target::has_pending_events ()
7110 {
7111 if (target_can_async_p ())
7112 {
7113 remote_state *rs = get_remote_state ();
7114
7115 if (rs->async_event_handler_marked ())
7116 return true;
7117
7118 /* Note that BUFCNT can be negative, indicating sticky
7119 error. */
7120 if (rs->remote_desc->bufcnt != 0)
7121 return true;
7122 }
7123 return false;
7124 }
7125
7126 \f
7127
7128 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
7129 thread, all threads of a remote process, or all threads of all
7130 processes. */
7131
7132 void
7133 remote_target::remote_stop_ns (ptid_t ptid)
7134 {
7135 struct remote_state *rs = get_remote_state ();
7136 char *p = rs->buf.data ();
7137 char *endp = p + get_remote_packet_size ();
7138
7139 /* If any thread that needs to stop was resumed but pending a vCont
7140 resume, generate a phony stop_reply. However, first check
7141 whether the thread wasn't resumed with a signal. Generating a
7142 phony stop in that case would result in losing the signal. */
7143 bool needs_commit = false;
7144 for (thread_info *tp : all_non_exited_threads (this, ptid))
7145 {
7146 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7147
7148 if (remote_thr->get_resume_state ()
7149 == resume_state::RESUMED_PENDING_VCONT)
7150 {
7151 const resumed_pending_vcont_info &info
7152 = remote_thr->resumed_pending_vcont_info ();
7153 if (info.sig != GDB_SIGNAL_0)
7154 {
7155 /* This signal must be forwarded to the inferior. We
7156 could commit-resume just this thread, but its simpler
7157 to just commit-resume everything. */
7158 needs_commit = true;
7159 break;
7160 }
7161 }
7162 }
7163
7164 if (needs_commit)
7165 commit_resumed ();
7166 else
7167 for (thread_info *tp : all_non_exited_threads (this, ptid))
7168 {
7169 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7170
7171 if (remote_thr->get_resume_state ()
7172 == resume_state::RESUMED_PENDING_VCONT)
7173 {
7174 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
7175 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
7176 tp->ptid.lwp (),
7177 pulongest (tp->ptid.tid ()));
7178
7179 /* Check that the thread wasn't resumed with a signal.
7180 Generating a phony stop would result in losing the
7181 signal. */
7182 const resumed_pending_vcont_info &info
7183 = remote_thr->resumed_pending_vcont_info ();
7184 gdb_assert (info.sig == GDB_SIGNAL_0);
7185
7186 stop_reply *sr = new stop_reply ();
7187 sr->ptid = tp->ptid;
7188 sr->rs = rs;
7189 sr->ws.set_stopped (GDB_SIGNAL_0);
7190 sr->arch = tp->inf->arch ();
7191 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7192 sr->watch_data_address = 0;
7193 sr->core = 0;
7194 this->push_stop_reply (sr);
7195
7196 /* Pretend that this thread was actually resumed on the
7197 remote target, then stopped. If we leave it in the
7198 RESUMED_PENDING_VCONT state and the commit_resumed
7199 method is called while the stop reply is still in the
7200 queue, we'll end up reporting a stop event to the core
7201 for that thread while it is running on the remote
7202 target... that would be bad. */
7203 remote_thr->set_resumed ();
7204 }
7205 }
7206
7207 if (!rs->supports_vCont.t)
7208 error (_("Remote server does not support stopping threads"));
7209
7210 if (ptid == minus_one_ptid
7211 || (!m_features.remote_multi_process_p () && ptid.is_pid ()))
7212 p += xsnprintf (p, endp - p, "vCont;t");
7213 else
7214 {
7215 ptid_t nptid;
7216
7217 p += xsnprintf (p, endp - p, "vCont;t:");
7218
7219 if (ptid.is_pid ())
7220 /* All (-1) threads of process. */
7221 nptid = ptid_t (ptid.pid (), -1);
7222 else
7223 {
7224 /* Small optimization: if we already have a stop reply for
7225 this thread, no use in telling the stub we want this
7226 stopped. */
7227 if (peek_stop_reply (ptid))
7228 return;
7229
7230 nptid = ptid;
7231 }
7232
7233 write_ptid (p, endp, nptid);
7234 }
7235
7236 /* In non-stop, we get an immediate OK reply. The stop reply will
7237 come in asynchronously by notification. */
7238 putpkt (rs->buf);
7239 getpkt (&rs->buf);
7240 if (strcmp (rs->buf.data (), "OK") != 0)
7241 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7242 rs->buf.data ());
7243 }
7244
7245 /* All-stop version of target_interrupt. Sends a break or a ^C to
7246 interrupt the remote target. It is undefined which thread of which
7247 process reports the interrupt. */
7248
7249 void
7250 remote_target::remote_interrupt_as ()
7251 {
7252 struct remote_state *rs = get_remote_state ();
7253
7254 rs->ctrlc_pending_p = 1;
7255
7256 /* If the inferior is stopped already, but the core didn't know
7257 about it yet, just ignore the request. The pending stop events
7258 will be collected in remote_wait. */
7259 if (stop_reply_queue_length () > 0)
7260 return;
7261
7262 /* Send interrupt_sequence to remote target. */
7263 send_interrupt_sequence ();
7264 }
7265
7266 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7267 the remote target. It is undefined which thread of which process
7268 reports the interrupt. Throws an error if the packet is not
7269 supported by the server. */
7270
7271 void
7272 remote_target::remote_interrupt_ns ()
7273 {
7274 struct remote_state *rs = get_remote_state ();
7275 char *p = rs->buf.data ();
7276 char *endp = p + get_remote_packet_size ();
7277
7278 xsnprintf (p, endp - p, "vCtrlC");
7279
7280 /* In non-stop, we get an immediate OK reply. The stop reply will
7281 come in asynchronously by notification. */
7282 putpkt (rs->buf);
7283 getpkt (&rs->buf);
7284
7285 switch (m_features.packet_ok (rs->buf, PACKET_vCtrlC))
7286 {
7287 case PACKET_OK:
7288 break;
7289 case PACKET_UNKNOWN:
7290 error (_("No support for interrupting the remote target."));
7291 case PACKET_ERROR:
7292 error (_("Interrupting target failed: %s"), rs->buf.data ());
7293 }
7294 }
7295
7296 /* Implement the to_stop function for the remote targets. */
7297
7298 void
7299 remote_target::stop (ptid_t ptid)
7300 {
7301 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7302
7303 if (target_is_non_stop_p ())
7304 remote_stop_ns (ptid);
7305 else
7306 {
7307 /* We don't currently have a way to transparently pause the
7308 remote target in all-stop mode. Interrupt it instead. */
7309 remote_interrupt_as ();
7310 }
7311 }
7312
7313 /* Implement the to_interrupt function for the remote targets. */
7314
7315 void
7316 remote_target::interrupt ()
7317 {
7318 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7319
7320 if (target_is_non_stop_p ())
7321 remote_interrupt_ns ();
7322 else
7323 remote_interrupt_as ();
7324 }
7325
7326 /* Implement the to_pass_ctrlc function for the remote targets. */
7327
7328 void
7329 remote_target::pass_ctrlc ()
7330 {
7331 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7332
7333 struct remote_state *rs = get_remote_state ();
7334
7335 /* If we're starting up, we're not fully synced yet. Quit
7336 immediately. */
7337 if (rs->starting_up)
7338 quit ();
7339 /* If ^C has already been sent once, offer to disconnect. */
7340 else if (rs->ctrlc_pending_p)
7341 interrupt_query ();
7342 else
7343 target_interrupt ();
7344 }
7345
7346 /* Ask the user what to do when an interrupt is received. */
7347
7348 void
7349 remote_target::interrupt_query ()
7350 {
7351 struct remote_state *rs = get_remote_state ();
7352
7353 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7354 {
7355 if (query (_("The target is not responding to interrupt requests.\n"
7356 "Stop debugging it? ")))
7357 {
7358 remote_unpush_target (this);
7359 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7360 }
7361 }
7362 else
7363 {
7364 if (query (_("Interrupted while waiting for the program.\n"
7365 "Give up waiting? ")))
7366 quit ();
7367 }
7368 }
7369
7370 /* Enable/disable target terminal ownership. Most targets can use
7371 terminal groups to control terminal ownership. Remote targets are
7372 different in that explicit transfer of ownership to/from GDB/target
7373 is required. */
7374
7375 void
7376 remote_target::terminal_inferior ()
7377 {
7378 /* NOTE: At this point we could also register our selves as the
7379 recipient of all input. Any characters typed could then be
7380 passed on down to the target. */
7381 }
7382
7383 void
7384 remote_target::terminal_ours ()
7385 {
7386 }
7387
7388 static void
7389 remote_console_output (const char *msg)
7390 {
7391 const char *p;
7392
7393 for (p = msg; p[0] && p[1]; p += 2)
7394 {
7395 char tb[2];
7396 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7397
7398 tb[0] = c;
7399 tb[1] = 0;
7400 gdb_stdtarg->puts (tb);
7401 }
7402 gdb_stdtarg->flush ();
7403 }
7404
7405 /* Return the length of the stop reply queue. */
7406
7407 int
7408 remote_target::stop_reply_queue_length ()
7409 {
7410 remote_state *rs = get_remote_state ();
7411 return rs->stop_reply_queue.size ();
7412 }
7413
7414 static void
7415 remote_notif_stop_parse (remote_target *remote,
7416 const notif_client *self, const char *buf,
7417 struct notif_event *event)
7418 {
7419 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7420 }
7421
7422 static void
7423 remote_notif_stop_ack (remote_target *remote,
7424 const notif_client *self, const char *buf,
7425 struct notif_event *event)
7426 {
7427 struct stop_reply *stop_reply = (struct stop_reply *) event;
7428
7429 /* acknowledge */
7430 putpkt (remote, self->ack_command);
7431
7432 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7433 the notification. It was left in the queue because we need to
7434 acknowledge it and pull the rest of the notifications out. */
7435 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7436 remote->push_stop_reply (stop_reply);
7437 }
7438
7439 static int
7440 remote_notif_stop_can_get_pending_events (remote_target *remote,
7441 const notif_client *self)
7442 {
7443 /* We can't get pending events in remote_notif_process for
7444 notification stop, and we have to do this in remote_wait_ns
7445 instead. If we fetch all queued events from stub, remote stub
7446 may exit and we have no chance to process them back in
7447 remote_wait_ns. */
7448 remote_state *rs = remote->get_remote_state ();
7449 rs->mark_async_event_handler ();
7450 return 0;
7451 }
7452
7453 stop_reply::~stop_reply ()
7454 {
7455 for (cached_reg_t &reg : regcache)
7456 xfree (reg.data);
7457 }
7458
7459 static notif_event_up
7460 remote_notif_stop_alloc_reply ()
7461 {
7462 return notif_event_up (new struct stop_reply ());
7463 }
7464
7465 /* A client of notification Stop. */
7466
7467 const notif_client notif_client_stop =
7468 {
7469 "Stop",
7470 "vStopped",
7471 remote_notif_stop_parse,
7472 remote_notif_stop_ack,
7473 remote_notif_stop_can_get_pending_events,
7474 remote_notif_stop_alloc_reply,
7475 REMOTE_NOTIF_STOP,
7476 };
7477
7478 /* If CONTEXT contains any fork child threads that have not been
7479 reported yet, remove them from the CONTEXT list. If such a
7480 thread exists it is because we are stopped at a fork catchpoint
7481 and have not yet called follow_fork, which will set up the
7482 host-side data structures for the new process. */
7483
7484 void
7485 remote_target::remove_new_fork_children (threads_listing_context *context)
7486 {
7487 const notif_client *notif = &notif_client_stop;
7488
7489 /* For any threads stopped at a fork event, remove the corresponding
7490 fork child threads from the CONTEXT list. */
7491 for (thread_info *thread : all_non_exited_threads (this))
7492 {
7493 const target_waitstatus *ws = thread_pending_fork_status (thread);
7494
7495 if (ws == nullptr)
7496 continue;
7497
7498 context->remove_thread (ws->child_ptid ());
7499 }
7500
7501 /* Check for any pending fork events (not reported or processed yet)
7502 in process PID and remove those fork child threads from the
7503 CONTEXT list as well. */
7504 remote_notif_get_pending_events (notif);
7505 for (auto &event : get_remote_state ()->stop_reply_queue)
7506 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7507 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7508 context->remove_thread (event->ws.child_ptid ());
7509 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7510 context->remove_thread (event->ptid);
7511 }
7512
7513 /* Check whether any event pending in the vStopped queue would prevent a
7514 global or process wildcard vCont action. Set *may_global_wildcard to
7515 false if we can't do a global wildcard (vCont;c), and clear the event
7516 inferior's may_wildcard_vcont flag if we can't do a process-wide
7517 wildcard resume (vCont;c:pPID.-1). */
7518
7519 void
7520 remote_target::check_pending_events_prevent_wildcard_vcont
7521 (bool *may_global_wildcard)
7522 {
7523 const notif_client *notif = &notif_client_stop;
7524
7525 remote_notif_get_pending_events (notif);
7526 for (auto &event : get_remote_state ()->stop_reply_queue)
7527 {
7528 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7529 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7530 continue;
7531
7532 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7533 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7534 *may_global_wildcard = false;
7535
7536 /* This may be the first time we heard about this process.
7537 Regardless, we must not do a global wildcard resume, otherwise
7538 we'd resume this process too. */
7539 *may_global_wildcard = false;
7540 if (event->ptid != null_ptid)
7541 {
7542 inferior *inf = find_inferior_ptid (this, event->ptid);
7543 if (inf != NULL)
7544 get_remote_inferior (inf)->may_wildcard_vcont = false;
7545 }
7546 }
7547 }
7548
7549 /* Discard all pending stop replies of inferior INF. */
7550
7551 void
7552 remote_target::discard_pending_stop_replies (struct inferior *inf)
7553 {
7554 struct stop_reply *reply;
7555 struct remote_state *rs = get_remote_state ();
7556 struct remote_notif_state *rns = rs->notif_state;
7557
7558 /* This function can be notified when an inferior exists. When the
7559 target is not remote, the notification state is NULL. */
7560 if (rs->remote_desc == NULL)
7561 return;
7562
7563 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7564
7565 /* Discard the in-flight notification. */
7566 if (reply != NULL && reply->ptid.pid () == inf->pid)
7567 {
7568 /* Leave the notification pending, since the server expects that
7569 we acknowledge it with vStopped. But clear its contents, so
7570 that later on when we acknowledge it, we also discard it. */
7571 remote_debug_printf
7572 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7573 reply->ptid.to_string().c_str(),
7574 reply->ws.to_string ().c_str ());
7575 reply->ws.set_ignore ();
7576 }
7577
7578 /* Discard the stop replies we have already pulled with
7579 vStopped. */
7580 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7581 rs->stop_reply_queue.end (),
7582 [=] (const stop_reply_up &event)
7583 {
7584 return event->ptid.pid () == inf->pid;
7585 });
7586 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7587 remote_debug_printf
7588 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7589 (*it)->ptid.to_string().c_str(),
7590 (*it)->ws.to_string ().c_str ());
7591 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7592 }
7593
7594 /* Discard the stop replies for RS in stop_reply_queue. */
7595
7596 void
7597 remote_target::discard_pending_stop_replies_in_queue ()
7598 {
7599 remote_state *rs = get_remote_state ();
7600
7601 /* Discard the stop replies we have already pulled with
7602 vStopped. */
7603 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7604 rs->stop_reply_queue.end (),
7605 [=] (const stop_reply_up &event)
7606 {
7607 return event->rs == rs;
7608 });
7609 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7610 }
7611
7612 /* Remove the first reply in 'stop_reply_queue' which matches
7613 PTID. */
7614
7615 struct stop_reply *
7616 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7617 {
7618 remote_state *rs = get_remote_state ();
7619
7620 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7621 rs->stop_reply_queue.end (),
7622 [=] (const stop_reply_up &event)
7623 {
7624 return event->ptid.matches (ptid);
7625 });
7626 struct stop_reply *result;
7627 if (iter == rs->stop_reply_queue.end ())
7628 result = nullptr;
7629 else
7630 {
7631 result = iter->release ();
7632 rs->stop_reply_queue.erase (iter);
7633 }
7634
7635 if (notif_debug)
7636 gdb_printf (gdb_stdlog,
7637 "notif: discard queued event: 'Stop' in %s\n",
7638 ptid.to_string ().c_str ());
7639
7640 return result;
7641 }
7642
7643 /* Look for a queued stop reply belonging to PTID. If one is found,
7644 remove it from the queue, and return it. Returns NULL if none is
7645 found. If there are still queued events left to process, tell the
7646 event loop to get back to target_wait soon. */
7647
7648 struct stop_reply *
7649 remote_target::queued_stop_reply (ptid_t ptid)
7650 {
7651 remote_state *rs = get_remote_state ();
7652 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7653
7654 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7655 {
7656 /* There's still at least an event left. */
7657 rs->mark_async_event_handler ();
7658 }
7659
7660 return r;
7661 }
7662
7663 /* Push a fully parsed stop reply in the stop reply queue. Since we
7664 know that we now have at least one queued event left to pass to the
7665 core side, tell the event loop to get back to target_wait soon. */
7666
7667 void
7668 remote_target::push_stop_reply (struct stop_reply *new_event)
7669 {
7670 remote_state *rs = get_remote_state ();
7671 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7672
7673 if (notif_debug)
7674 gdb_printf (gdb_stdlog,
7675 "notif: push 'Stop' %s to queue %d\n",
7676 new_event->ptid.to_string ().c_str (),
7677 int (rs->stop_reply_queue.size ()));
7678
7679 /* Mark the pending event queue only if async mode is currently enabled.
7680 If async mode is not currently enabled, then, if it later becomes
7681 enabled, and there are events in this queue, we will mark the event
7682 token at that point, see remote_target::async. */
7683 if (target_is_async_p ())
7684 rs->mark_async_event_handler ();
7685 }
7686
7687 /* Returns true if we have a stop reply for PTID. */
7688
7689 int
7690 remote_target::peek_stop_reply (ptid_t ptid)
7691 {
7692 remote_state *rs = get_remote_state ();
7693 for (auto &event : rs->stop_reply_queue)
7694 if (ptid == event->ptid
7695 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7696 return 1;
7697 return 0;
7698 }
7699
7700 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7701 starting with P and ending with PEND matches PREFIX. */
7702
7703 static int
7704 strprefix (const char *p, const char *pend, const char *prefix)
7705 {
7706 for ( ; p < pend; p++, prefix++)
7707 if (*p != *prefix)
7708 return 0;
7709 return *prefix == '\0';
7710 }
7711
7712 /* Parse the stop reply in BUF. Either the function succeeds, and the
7713 result is stored in EVENT, or throws an error. */
7714
7715 void
7716 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7717 {
7718 remote_arch_state *rsa = NULL;
7719 ULONGEST addr;
7720 const char *p;
7721 int skipregs = 0;
7722
7723 event->ptid = null_ptid;
7724 event->rs = get_remote_state ();
7725 event->ws.set_ignore ();
7726 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7727 event->regcache.clear ();
7728 event->core = -1;
7729
7730 switch (buf[0])
7731 {
7732 case 'T': /* Status with PC, SP, FP, ... */
7733 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7734 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7735 ss = signal number
7736 n... = register number
7737 r... = register contents
7738 */
7739
7740 p = &buf[3]; /* after Txx */
7741 while (*p)
7742 {
7743 const char *p1;
7744 int fieldsize;
7745
7746 p1 = strchr (p, ':');
7747 if (p1 == NULL)
7748 error (_("Malformed packet(a) (missing colon): %s\n\
7749 Packet: '%s'\n"),
7750 p, buf);
7751 if (p == p1)
7752 error (_("Malformed packet(a) (missing register number): %s\n\
7753 Packet: '%s'\n"),
7754 p, buf);
7755
7756 /* Some "registers" are actually extended stop information.
7757 Note if you're adding a new entry here: GDB 7.9 and
7758 earlier assume that all register "numbers" that start
7759 with an hex digit are real register numbers. Make sure
7760 the server only sends such a packet if it knows the
7761 client understands it. */
7762
7763 if (strprefix (p, p1, "thread"))
7764 event->ptid = read_ptid (++p1, &p);
7765 else if (strprefix (p, p1, "syscall_entry"))
7766 {
7767 ULONGEST sysno;
7768
7769 p = unpack_varlen_hex (++p1, &sysno);
7770 event->ws.set_syscall_entry ((int) sysno);
7771 }
7772 else if (strprefix (p, p1, "syscall_return"))
7773 {
7774 ULONGEST sysno;
7775
7776 p = unpack_varlen_hex (++p1, &sysno);
7777 event->ws.set_syscall_return ((int) sysno);
7778 }
7779 else if (strprefix (p, p1, "watch")
7780 || strprefix (p, p1, "rwatch")
7781 || strprefix (p, p1, "awatch"))
7782 {
7783 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7784 p = unpack_varlen_hex (++p1, &addr);
7785 event->watch_data_address = (CORE_ADDR) addr;
7786 }
7787 else if (strprefix (p, p1, "swbreak"))
7788 {
7789 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7790
7791 /* Make sure the stub doesn't forget to indicate support
7792 with qSupported. */
7793 if (m_features.packet_support (PACKET_swbreak_feature)
7794 != PACKET_ENABLE)
7795 error (_("Unexpected swbreak stop reason"));
7796
7797 /* The value part is documented as "must be empty",
7798 though we ignore it, in case we ever decide to make
7799 use of it in a backward compatible way. */
7800 p = strchrnul (p1 + 1, ';');
7801 }
7802 else if (strprefix (p, p1, "hwbreak"))
7803 {
7804 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7805
7806 /* Make sure the stub doesn't forget to indicate support
7807 with qSupported. */
7808 if (m_features.packet_support (PACKET_hwbreak_feature)
7809 != PACKET_ENABLE)
7810 error (_("Unexpected hwbreak stop reason"));
7811
7812 /* See above. */
7813 p = strchrnul (p1 + 1, ';');
7814 }
7815 else if (strprefix (p, p1, "library"))
7816 {
7817 event->ws.set_loaded ();
7818 p = strchrnul (p1 + 1, ';');
7819 }
7820 else if (strprefix (p, p1, "replaylog"))
7821 {
7822 event->ws.set_no_history ();
7823 /* p1 will indicate "begin" or "end", but it makes
7824 no difference for now, so ignore it. */
7825 p = strchrnul (p1 + 1, ';');
7826 }
7827 else if (strprefix (p, p1, "core"))
7828 {
7829 ULONGEST c;
7830
7831 p = unpack_varlen_hex (++p1, &c);
7832 event->core = c;
7833 }
7834 else if (strprefix (p, p1, "fork"))
7835 event->ws.set_forked (read_ptid (++p1, &p));
7836 else if (strprefix (p, p1, "vfork"))
7837 event->ws.set_vforked (read_ptid (++p1, &p));
7838 else if (strprefix (p, p1, "vforkdone"))
7839 {
7840 event->ws.set_vfork_done ();
7841 p = strchrnul (p1 + 1, ';');
7842 }
7843 else if (strprefix (p, p1, "exec"))
7844 {
7845 ULONGEST ignored;
7846 int pathlen;
7847
7848 /* Determine the length of the execd pathname. */
7849 p = unpack_varlen_hex (++p1, &ignored);
7850 pathlen = (p - p1) / 2;
7851
7852 /* Save the pathname for event reporting and for
7853 the next run command. */
7854 gdb::unique_xmalloc_ptr<char> pathname
7855 ((char *) xmalloc (pathlen + 1));
7856 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
7857 pathname.get ()[pathlen] = '\0';
7858
7859 /* This is freed during event handling. */
7860 event->ws.set_execd (std::move (pathname));
7861
7862 /* Skip the registers included in this packet, since
7863 they may be for an architecture different from the
7864 one used by the original program. */
7865 skipregs = 1;
7866 }
7867 else if (strprefix (p, p1, "create"))
7868 {
7869 event->ws.set_thread_created ();
7870 p = strchrnul (p1 + 1, ';');
7871 }
7872 else
7873 {
7874 ULONGEST pnum;
7875 const char *p_temp;
7876
7877 if (skipregs)
7878 {
7879 p = strchrnul (p1 + 1, ';');
7880 p++;
7881 continue;
7882 }
7883
7884 /* Maybe a real ``P'' register number. */
7885 p_temp = unpack_varlen_hex (p, &pnum);
7886 /* If the first invalid character is the colon, we got a
7887 register number. Otherwise, it's an unknown stop
7888 reason. */
7889 if (p_temp == p1)
7890 {
7891 /* If we haven't parsed the event's thread yet, find
7892 it now, in order to find the architecture of the
7893 reported expedited registers. */
7894 if (event->ptid == null_ptid)
7895 {
7896 /* If there is no thread-id information then leave
7897 the event->ptid as null_ptid. Later in
7898 process_stop_reply we will pick a suitable
7899 thread. */
7900 const char *thr = strstr (p1 + 1, ";thread:");
7901 if (thr != NULL)
7902 event->ptid = read_ptid (thr + strlen (";thread:"),
7903 NULL);
7904 }
7905
7906 if (rsa == NULL)
7907 {
7908 inferior *inf
7909 = (event->ptid == null_ptid
7910 ? NULL
7911 : find_inferior_ptid (this, event->ptid));
7912 /* If this is the first time we learn anything
7913 about this process, skip the registers
7914 included in this packet, since we don't yet
7915 know which architecture to use to parse them.
7916 We'll determine the architecture later when
7917 we process the stop reply and retrieve the
7918 target description, via
7919 remote_notice_new_inferior ->
7920 post_create_inferior. */
7921 if (inf == NULL)
7922 {
7923 p = strchrnul (p1 + 1, ';');
7924 p++;
7925 continue;
7926 }
7927
7928 event->arch = inf->arch ();
7929 rsa = event->rs->get_remote_arch_state (event->arch);
7930 }
7931
7932 packet_reg *reg
7933 = packet_reg_from_pnum (event->arch, rsa, pnum);
7934 cached_reg_t cached_reg;
7935
7936 if (reg == NULL)
7937 error (_("Remote sent bad register number %s: %s\n\
7938 Packet: '%s'\n"),
7939 hex_string (pnum), p, buf);
7940
7941 cached_reg.num = reg->regnum;
7942 cached_reg.data = (gdb_byte *)
7943 xmalloc (register_size (event->arch, reg->regnum));
7944
7945 p = p1 + 1;
7946 fieldsize = hex2bin (p, cached_reg.data,
7947 register_size (event->arch, reg->regnum));
7948 p += 2 * fieldsize;
7949 if (fieldsize < register_size (event->arch, reg->regnum))
7950 warning (_("Remote reply is too short: %s"), buf);
7951
7952 event->regcache.push_back (cached_reg);
7953 }
7954 else
7955 {
7956 /* Not a number. Silently skip unknown optional
7957 info. */
7958 p = strchrnul (p1 + 1, ';');
7959 }
7960 }
7961
7962 if (*p != ';')
7963 error (_("Remote register badly formatted: %s\nhere: %s"),
7964 buf, p);
7965 ++p;
7966 }
7967
7968 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
7969 break;
7970
7971 /* fall through */
7972 case 'S': /* Old style status, just signal only. */
7973 {
7974 int sig;
7975
7976 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7977 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7978 event->ws.set_stopped ((enum gdb_signal) sig);
7979 else
7980 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
7981 }
7982 break;
7983 case 'w': /* Thread exited. */
7984 {
7985 ULONGEST value;
7986
7987 p = unpack_varlen_hex (&buf[1], &value);
7988 event->ws.set_thread_exited (value);
7989 if (*p != ';')
7990 error (_("stop reply packet badly formatted: %s"), buf);
7991 event->ptid = read_ptid (++p, NULL);
7992 break;
7993 }
7994 case 'W': /* Target exited. */
7995 case 'X':
7996 {
7997 ULONGEST value;
7998
7999 /* GDB used to accept only 2 hex chars here. Stubs should
8000 only send more if they detect GDB supports multi-process
8001 support. */
8002 p = unpack_varlen_hex (&buf[1], &value);
8003
8004 if (buf[0] == 'W')
8005 {
8006 /* The remote process exited. */
8007 event->ws.set_exited (value);
8008 }
8009 else
8010 {
8011 /* The remote process exited with a signal. */
8012 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
8013 event->ws.set_signalled ((enum gdb_signal) value);
8014 else
8015 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
8016 }
8017
8018 /* If no process is specified, return null_ptid, and let the
8019 caller figure out the right process to use. */
8020 int pid = 0;
8021 if (*p == '\0')
8022 ;
8023 else if (*p == ';')
8024 {
8025 p++;
8026
8027 if (*p == '\0')
8028 ;
8029 else if (startswith (p, "process:"))
8030 {
8031 ULONGEST upid;
8032
8033 p += sizeof ("process:") - 1;
8034 unpack_varlen_hex (p, &upid);
8035 pid = upid;
8036 }
8037 else
8038 error (_("unknown stop reply packet: %s"), buf);
8039 }
8040 else
8041 error (_("unknown stop reply packet: %s"), buf);
8042 event->ptid = ptid_t (pid);
8043 }
8044 break;
8045 case 'N':
8046 event->ws.set_no_resumed ();
8047 event->ptid = minus_one_ptid;
8048 break;
8049 }
8050 }
8051
8052 /* When the stub wants to tell GDB about a new notification reply, it
8053 sends a notification (%Stop, for example). Those can come it at
8054 any time, hence, we have to make sure that any pending
8055 putpkt/getpkt sequence we're making is finished, before querying
8056 the stub for more events with the corresponding ack command
8057 (vStopped, for example). E.g., if we started a vStopped sequence
8058 immediately upon receiving the notification, something like this
8059 could happen:
8060
8061 1.1) --> Hg 1
8062 1.2) <-- OK
8063 1.3) --> g
8064 1.4) <-- %Stop
8065 1.5) --> vStopped
8066 1.6) <-- (registers reply to step #1.3)
8067
8068 Obviously, the reply in step #1.6 would be unexpected to a vStopped
8069 query.
8070
8071 To solve this, whenever we parse a %Stop notification successfully,
8072 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
8073 doing whatever we were doing:
8074
8075 2.1) --> Hg 1
8076 2.2) <-- OK
8077 2.3) --> g
8078 2.4) <-- %Stop
8079 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
8080 2.5) <-- (registers reply to step #2.3)
8081
8082 Eventually after step #2.5, we return to the event loop, which
8083 notices there's an event on the
8084 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
8085 associated callback --- the function below. At this point, we're
8086 always safe to start a vStopped sequence. :
8087
8088 2.6) --> vStopped
8089 2.7) <-- T05 thread:2
8090 2.8) --> vStopped
8091 2.9) --> OK
8092 */
8093
8094 void
8095 remote_target::remote_notif_get_pending_events (const notif_client *nc)
8096 {
8097 struct remote_state *rs = get_remote_state ();
8098
8099 if (rs->notif_state->pending_event[nc->id] != NULL)
8100 {
8101 if (notif_debug)
8102 gdb_printf (gdb_stdlog,
8103 "notif: process: '%s' ack pending event\n",
8104 nc->name);
8105
8106 /* acknowledge */
8107 nc->ack (this, nc, rs->buf.data (),
8108 rs->notif_state->pending_event[nc->id]);
8109 rs->notif_state->pending_event[nc->id] = NULL;
8110
8111 while (1)
8112 {
8113 getpkt (&rs->buf);
8114 if (strcmp (rs->buf.data (), "OK") == 0)
8115 break;
8116 else
8117 remote_notif_ack (this, nc, rs->buf.data ());
8118 }
8119 }
8120 else
8121 {
8122 if (notif_debug)
8123 gdb_printf (gdb_stdlog,
8124 "notif: process: '%s' no pending reply\n",
8125 nc->name);
8126 }
8127 }
8128
8129 /* Wrapper around remote_target::remote_notif_get_pending_events to
8130 avoid having to export the whole remote_target class. */
8131
8132 void
8133 remote_notif_get_pending_events (remote_target *remote, const notif_client *nc)
8134 {
8135 remote->remote_notif_get_pending_events (nc);
8136 }
8137
8138 /* Called from process_stop_reply when the stop packet we are responding
8139 to didn't include a process-id or thread-id. STATUS is the stop event
8140 we are responding to.
8141
8142 It is the task of this function to select a suitable thread (or process)
8143 and return its ptid, this is the thread (or process) we will assume the
8144 stop event came from.
8145
8146 In some cases there isn't really any choice about which thread (or
8147 process) is selected, a basic remote with a single process containing a
8148 single thread might choose not to send any process-id or thread-id in
8149 its stop packets, this function will select and return the one and only
8150 thread.
8151
8152 However, if a target supports multiple threads (or processes) and still
8153 doesn't include a thread-id (or process-id) in its stop packet then
8154 first, this is a badly behaving target, and second, we're going to have
8155 to select a thread (or process) at random and use that. This function
8156 will print a warning to the user if it detects that there is the
8157 possibility that GDB is guessing which thread (or process) to
8158 report.
8159
8160 Note that this is called before GDB fetches the updated thread list from the
8161 target. So it's possible for the stop reply to be ambiguous and for GDB to
8162 not realize it. For example, if there's initially one thread, the target
8163 spawns a second thread, and then sends a stop reply without an id that
8164 concerns the first thread. GDB will assume the stop reply is about the
8165 first thread - the only thread it knows about - without printing a warning.
8166 Anyway, if the remote meant for the stop reply to be about the second thread,
8167 then it would be really broken, because GDB doesn't know about that thread
8168 yet. */
8169
8170 ptid_t
8171 remote_target::select_thread_for_ambiguous_stop_reply
8172 (const target_waitstatus &status)
8173 {
8174 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8175
8176 /* Some stop events apply to all threads in an inferior, while others
8177 only apply to a single thread. */
8178 bool process_wide_stop
8179 = (status.kind () == TARGET_WAITKIND_EXITED
8180 || status.kind () == TARGET_WAITKIND_SIGNALLED);
8181
8182 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
8183
8184 thread_info *first_resumed_thread = nullptr;
8185 bool ambiguous = false;
8186
8187 /* Consider all non-exited threads of the target, find the first resumed
8188 one. */
8189 for (thread_info *thr : all_non_exited_threads (this))
8190 {
8191 remote_thread_info *remote_thr = get_remote_thread_info (thr);
8192
8193 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8194 continue;
8195
8196 if (first_resumed_thread == nullptr)
8197 first_resumed_thread = thr;
8198 else if (!process_wide_stop
8199 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8200 ambiguous = true;
8201 }
8202
8203 gdb_assert (first_resumed_thread != nullptr);
8204
8205 remote_debug_printf ("first resumed thread is %s",
8206 pid_to_str (first_resumed_thread->ptid).c_str ());
8207 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8208
8209 /* Warn if the remote target is sending ambiguous stop replies. */
8210 if (ambiguous)
8211 {
8212 static bool warned = false;
8213
8214 if (!warned)
8215 {
8216 /* If you are seeing this warning then the remote target has
8217 stopped without specifying a thread-id, but the target
8218 does have multiple threads (or inferiors), and so GDB is
8219 having to guess which thread stopped.
8220
8221 Examples of what might cause this are the target sending
8222 and 'S' stop packet, or a 'T' stop packet and not
8223 including a thread-id.
8224
8225 Additionally, the target might send a 'W' or 'X packet
8226 without including a process-id, when the target has
8227 multiple running inferiors. */
8228 if (process_wide_stop)
8229 warning (_("multi-inferior target stopped without "
8230 "sending a process-id, using first "
8231 "non-exited inferior"));
8232 else
8233 warning (_("multi-threaded target stopped without "
8234 "sending a thread-id, using first "
8235 "non-exited thread"));
8236 warned = true;
8237 }
8238 }
8239
8240 /* If this is a stop for all threads then don't use a particular threads
8241 ptid, instead create a new ptid where only the pid field is set. */
8242 if (process_wide_stop)
8243 return ptid_t (first_resumed_thread->ptid.pid ());
8244 else
8245 return first_resumed_thread->ptid;
8246 }
8247
8248 /* Called when it is decided that STOP_REPLY holds the info of the
8249 event that is to be returned to the core. This function always
8250 destroys STOP_REPLY. */
8251
8252 ptid_t
8253 remote_target::process_stop_reply (struct stop_reply *stop_reply,
8254 struct target_waitstatus *status)
8255 {
8256 *status = stop_reply->ws;
8257 ptid_t ptid = stop_reply->ptid;
8258
8259 /* If no thread/process was reported by the stub then select a suitable
8260 thread/process. */
8261 if (ptid == null_ptid)
8262 ptid = select_thread_for_ambiguous_stop_reply (*status);
8263 gdb_assert (ptid != null_ptid);
8264
8265 if (status->kind () != TARGET_WAITKIND_EXITED
8266 && status->kind () != TARGET_WAITKIND_SIGNALLED
8267 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8268 {
8269 /* Expedited registers. */
8270 if (!stop_reply->regcache.empty ())
8271 {
8272 struct regcache *regcache
8273 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
8274
8275 for (cached_reg_t &reg : stop_reply->regcache)
8276 {
8277 regcache->raw_supply (reg.num, reg.data);
8278 xfree (reg.data);
8279 }
8280
8281 stop_reply->regcache.clear ();
8282 }
8283
8284 remote_notice_new_inferior (ptid, false);
8285 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8286 remote_thr->core = stop_reply->core;
8287 remote_thr->stop_reason = stop_reply->stop_reason;
8288 remote_thr->watch_data_address = stop_reply->watch_data_address;
8289
8290 if (target_is_non_stop_p ())
8291 {
8292 /* If the target works in non-stop mode, a stop-reply indicates that
8293 only this thread stopped. */
8294 remote_thr->set_not_resumed ();
8295 }
8296 else
8297 {
8298 /* If the target works in all-stop mode, a stop-reply indicates that
8299 all the target's threads stopped. */
8300 for (thread_info *tp : all_non_exited_threads (this))
8301 get_remote_thread_info (tp)->set_not_resumed ();
8302 }
8303 }
8304
8305 delete stop_reply;
8306 return ptid;
8307 }
8308
8309 /* The non-stop mode version of target_wait. */
8310
8311 ptid_t
8312 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8313 target_wait_flags options)
8314 {
8315 struct remote_state *rs = get_remote_state ();
8316 struct stop_reply *stop_reply;
8317 int ret;
8318 bool is_notif = false;
8319
8320 /* If in non-stop mode, get out of getpkt even if a
8321 notification is received. */
8322
8323 ret = getpkt (&rs->buf, false /* forever */, &is_notif);
8324 while (1)
8325 {
8326 if (ret != -1 && !is_notif)
8327 switch (rs->buf[0])
8328 {
8329 case 'E': /* Error of some sort. */
8330 /* We're out of sync with the target now. Did it continue
8331 or not? We can't tell which thread it was in non-stop,
8332 so just ignore this. */
8333 warning (_("Remote failure reply: %s"), rs->buf.data ());
8334 break;
8335 case 'O': /* Console output. */
8336 remote_console_output (&rs->buf[1]);
8337 break;
8338 default:
8339 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8340 break;
8341 }
8342
8343 /* Acknowledge a pending stop reply that may have arrived in the
8344 mean time. */
8345 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8346 remote_notif_get_pending_events (&notif_client_stop);
8347
8348 /* If indeed we noticed a stop reply, we're done. */
8349 stop_reply = queued_stop_reply (ptid);
8350 if (stop_reply != NULL)
8351 return process_stop_reply (stop_reply, status);
8352
8353 /* Still no event. If we're just polling for an event, then
8354 return to the event loop. */
8355 if (options & TARGET_WNOHANG)
8356 {
8357 status->set_ignore ();
8358 return minus_one_ptid;
8359 }
8360
8361 /* Otherwise do a blocking wait. */
8362 ret = getpkt (&rs->buf, true /* forever */, &is_notif);
8363 }
8364 }
8365
8366 /* Return the first resumed thread. */
8367
8368 static ptid_t
8369 first_remote_resumed_thread (remote_target *target)
8370 {
8371 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8372 if (tp->resumed ())
8373 return tp->ptid;
8374 return null_ptid;
8375 }
8376
8377 /* Wait until the remote machine stops, then return, storing status in
8378 STATUS just as `wait' would. */
8379
8380 ptid_t
8381 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8382 target_wait_flags options)
8383 {
8384 struct remote_state *rs = get_remote_state ();
8385 ptid_t event_ptid = null_ptid;
8386 char *buf;
8387 struct stop_reply *stop_reply;
8388
8389 again:
8390
8391 status->set_ignore ();
8392
8393 stop_reply = queued_stop_reply (ptid);
8394 if (stop_reply != NULL)
8395 {
8396 /* None of the paths that push a stop reply onto the queue should
8397 have set the waiting_for_stop_reply flag. */
8398 gdb_assert (!rs->waiting_for_stop_reply);
8399 event_ptid = process_stop_reply (stop_reply, status);
8400 }
8401 else
8402 {
8403 bool forever = ((options & TARGET_WNOHANG) == 0
8404 && rs->wait_forever_enabled_p);
8405
8406 if (!rs->waiting_for_stop_reply)
8407 {
8408 status->set_no_resumed ();
8409 return minus_one_ptid;
8410 }
8411
8412 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8413 _never_ wait for ever -> test on target_is_async_p().
8414 However, before we do that we need to ensure that the caller
8415 knows how to take the target into/out of async mode. */
8416 bool is_notif;
8417 int ret = getpkt (&rs->buf, forever, &is_notif);
8418
8419 /* GDB gets a notification. Return to core as this event is
8420 not interesting. */
8421 if (ret != -1 && is_notif)
8422 return minus_one_ptid;
8423
8424 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8425 return minus_one_ptid;
8426
8427 buf = rs->buf.data ();
8428
8429 /* Assume that the target has acknowledged Ctrl-C unless we receive
8430 an 'F' or 'O' packet. */
8431 if (buf[0] != 'F' && buf[0] != 'O')
8432 rs->ctrlc_pending_p = 0;
8433
8434 switch (buf[0])
8435 {
8436 case 'E': /* Error of some sort. */
8437 /* We're out of sync with the target now. Did it continue or
8438 not? Not is more likely, so report a stop. */
8439 rs->waiting_for_stop_reply = 0;
8440
8441 warning (_("Remote failure reply: %s"), buf);
8442 status->set_stopped (GDB_SIGNAL_0);
8443 break;
8444 case 'F': /* File-I/O request. */
8445 /* GDB may access the inferior memory while handling the File-I/O
8446 request, but we don't want GDB accessing memory while waiting
8447 for a stop reply. See the comments in putpkt_binary. Set
8448 waiting_for_stop_reply to 0 temporarily. */
8449 rs->waiting_for_stop_reply = 0;
8450 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8451 rs->ctrlc_pending_p = 0;
8452 /* GDB handled the File-I/O request, and the target is running
8453 again. Keep waiting for events. */
8454 rs->waiting_for_stop_reply = 1;
8455 break;
8456 case 'N': case 'T': case 'S': case 'X': case 'W':
8457 {
8458 /* There is a stop reply to handle. */
8459 rs->waiting_for_stop_reply = 0;
8460
8461 stop_reply
8462 = (struct stop_reply *) remote_notif_parse (this,
8463 &notif_client_stop,
8464 rs->buf.data ());
8465
8466 event_ptid = process_stop_reply (stop_reply, status);
8467 break;
8468 }
8469 case 'O': /* Console output. */
8470 remote_console_output (buf + 1);
8471 break;
8472 case '\0':
8473 if (rs->last_sent_signal != GDB_SIGNAL_0)
8474 {
8475 /* Zero length reply means that we tried 'S' or 'C' and the
8476 remote system doesn't support it. */
8477 target_terminal::ours_for_output ();
8478 gdb_printf
8479 ("Can't send signals to this remote system. %s not sent.\n",
8480 gdb_signal_to_name (rs->last_sent_signal));
8481 rs->last_sent_signal = GDB_SIGNAL_0;
8482 target_terminal::inferior ();
8483
8484 strcpy (buf, rs->last_sent_step ? "s" : "c");
8485 putpkt (buf);
8486 break;
8487 }
8488 /* fallthrough */
8489 default:
8490 warning (_("Invalid remote reply: %s"), buf);
8491 break;
8492 }
8493 }
8494
8495 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8496 return minus_one_ptid;
8497 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8498 {
8499 /* Nothing interesting happened. If we're doing a non-blocking
8500 poll, we're done. Otherwise, go back to waiting. */
8501 if (options & TARGET_WNOHANG)
8502 return minus_one_ptid;
8503 else
8504 goto again;
8505 }
8506 else if (status->kind () != TARGET_WAITKIND_EXITED
8507 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8508 {
8509 if (event_ptid != null_ptid)
8510 record_currthread (rs, event_ptid);
8511 else
8512 event_ptid = first_remote_resumed_thread (this);
8513 }
8514 else
8515 {
8516 /* A process exit. Invalidate our notion of current thread. */
8517 record_currthread (rs, minus_one_ptid);
8518 /* It's possible that the packet did not include a pid. */
8519 if (event_ptid == null_ptid)
8520 event_ptid = first_remote_resumed_thread (this);
8521 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8522 if (event_ptid == null_ptid)
8523 event_ptid = magic_null_ptid;
8524 }
8525
8526 return event_ptid;
8527 }
8528
8529 /* Wait until the remote machine stops, then return, storing status in
8530 STATUS just as `wait' would. */
8531
8532 ptid_t
8533 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8534 target_wait_flags options)
8535 {
8536 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8537
8538 remote_state *rs = get_remote_state ();
8539
8540 /* Start by clearing the flag that asks for our wait method to be called,
8541 we'll mark it again at the end if needed. If the target is not in
8542 async mode then the async token should not be marked. */
8543 if (target_is_async_p ())
8544 rs->clear_async_event_handler ();
8545 else
8546 gdb_assert (!rs->async_event_handler_marked ());
8547
8548 ptid_t event_ptid;
8549
8550 if (target_is_non_stop_p ())
8551 event_ptid = wait_ns (ptid, status, options);
8552 else
8553 event_ptid = wait_as (ptid, status, options);
8554
8555 if (target_is_async_p ())
8556 {
8557 /* If there are events left in the queue, or unacknowledged
8558 notifications, then tell the event loop to call us again. */
8559 if (!rs->stop_reply_queue.empty ()
8560 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8561 rs->mark_async_event_handler ();
8562 }
8563
8564 return event_ptid;
8565 }
8566
8567 /* Fetch a single register using a 'p' packet. */
8568
8569 int
8570 remote_target::fetch_register_using_p (struct regcache *regcache,
8571 packet_reg *reg)
8572 {
8573 struct gdbarch *gdbarch = regcache->arch ();
8574 struct remote_state *rs = get_remote_state ();
8575 char *buf, *p;
8576 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8577 int i;
8578
8579 if (m_features.packet_support (PACKET_p) == PACKET_DISABLE)
8580 return 0;
8581
8582 if (reg->pnum == -1)
8583 return 0;
8584
8585 p = rs->buf.data ();
8586 *p++ = 'p';
8587 p += hexnumstr (p, reg->pnum);
8588 *p++ = '\0';
8589 putpkt (rs->buf);
8590 getpkt (&rs->buf);
8591
8592 buf = rs->buf.data ();
8593
8594 switch (m_features.packet_ok (rs->buf, PACKET_p))
8595 {
8596 case PACKET_OK:
8597 break;
8598 case PACKET_UNKNOWN:
8599 return 0;
8600 case PACKET_ERROR:
8601 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8602 gdbarch_register_name (regcache->arch (), reg->regnum),
8603 buf);
8604 }
8605
8606 /* If this register is unfetchable, tell the regcache. */
8607 if (buf[0] == 'x')
8608 {
8609 regcache->raw_supply (reg->regnum, NULL);
8610 return 1;
8611 }
8612
8613 /* Otherwise, parse and supply the value. */
8614 p = buf;
8615 i = 0;
8616 while (p[0] != 0)
8617 {
8618 if (p[1] == 0)
8619 error (_("fetch_register_using_p: early buf termination"));
8620
8621 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8622 p += 2;
8623 }
8624 regcache->raw_supply (reg->regnum, regp);
8625 return 1;
8626 }
8627
8628 /* Fetch the registers included in the target's 'g' packet. */
8629
8630 int
8631 remote_target::send_g_packet ()
8632 {
8633 struct remote_state *rs = get_remote_state ();
8634 int buf_len;
8635
8636 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8637 putpkt (rs->buf);
8638 getpkt (&rs->buf);
8639 if (packet_check_result (rs->buf) == PACKET_ERROR)
8640 error (_("Could not read registers; remote failure reply '%s'"),
8641 rs->buf.data ());
8642
8643 /* We can get out of synch in various cases. If the first character
8644 in the buffer is not a hex character, assume that has happened
8645 and try to fetch another packet to read. */
8646 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8647 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8648 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8649 && rs->buf[0] != 'x') /* New: unavailable register value. */
8650 {
8651 remote_debug_printf ("Bad register packet; fetching a new packet");
8652 getpkt (&rs->buf);
8653 }
8654
8655 buf_len = strlen (rs->buf.data ());
8656
8657 /* Sanity check the received packet. */
8658 if (buf_len % 2 != 0)
8659 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8660
8661 return buf_len / 2;
8662 }
8663
8664 void
8665 remote_target::process_g_packet (struct regcache *regcache)
8666 {
8667 struct gdbarch *gdbarch = regcache->arch ();
8668 struct remote_state *rs = get_remote_state ();
8669 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8670 int i, buf_len;
8671 char *p;
8672 char *regs;
8673
8674 buf_len = strlen (rs->buf.data ());
8675
8676 /* Further sanity checks, with knowledge of the architecture. */
8677 if (buf_len > 2 * rsa->sizeof_g_packet)
8678 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8679 "bytes): %s"),
8680 rsa->sizeof_g_packet, buf_len / 2,
8681 rs->buf.data ());
8682
8683 /* Save the size of the packet sent to us by the target. It is used
8684 as a heuristic when determining the max size of packets that the
8685 target can safely receive. */
8686 if (rsa->actual_register_packet_size == 0)
8687 rsa->actual_register_packet_size = buf_len;
8688
8689 /* If this is smaller than we guessed the 'g' packet would be,
8690 update our records. A 'g' reply that doesn't include a register's
8691 value implies either that the register is not available, or that
8692 the 'p' packet must be used. */
8693 if (buf_len < 2 * rsa->sizeof_g_packet)
8694 {
8695 long sizeof_g_packet = buf_len / 2;
8696
8697 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8698 {
8699 long offset = rsa->regs[i].offset;
8700 long reg_size = register_size (gdbarch, i);
8701
8702 if (rsa->regs[i].pnum == -1)
8703 continue;
8704
8705 if (offset >= sizeof_g_packet)
8706 rsa->regs[i].in_g_packet = 0;
8707 else if (offset + reg_size > sizeof_g_packet)
8708 error (_("Truncated register %d in remote 'g' packet"), i);
8709 else
8710 rsa->regs[i].in_g_packet = 1;
8711 }
8712
8713 /* Looks valid enough, we can assume this is the correct length
8714 for a 'g' packet. It's important not to adjust
8715 rsa->sizeof_g_packet if we have truncated registers otherwise
8716 this "if" won't be run the next time the method is called
8717 with a packet of the same size and one of the internal errors
8718 below will trigger instead. */
8719 rsa->sizeof_g_packet = sizeof_g_packet;
8720 }
8721
8722 regs = (char *) alloca (rsa->sizeof_g_packet);
8723
8724 /* Unimplemented registers read as all bits zero. */
8725 memset (regs, 0, rsa->sizeof_g_packet);
8726
8727 /* Reply describes registers byte by byte, each byte encoded as two
8728 hex characters. Suck them all up, then supply them to the
8729 register cacheing/storage mechanism. */
8730
8731 p = rs->buf.data ();
8732 for (i = 0; i < rsa->sizeof_g_packet; i++)
8733 {
8734 if (p[0] == 0 || p[1] == 0)
8735 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8736 internal_error (_("unexpected end of 'g' packet reply"));
8737
8738 if (p[0] == 'x' && p[1] == 'x')
8739 regs[i] = 0; /* 'x' */
8740 else
8741 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8742 p += 2;
8743 }
8744
8745 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8746 {
8747 struct packet_reg *r = &rsa->regs[i];
8748 long reg_size = register_size (gdbarch, i);
8749
8750 if (r->in_g_packet)
8751 {
8752 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8753 /* This shouldn't happen - we adjusted in_g_packet above. */
8754 internal_error (_("unexpected end of 'g' packet reply"));
8755 else if (rs->buf[r->offset * 2] == 'x')
8756 {
8757 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8758 /* The register isn't available, mark it as such (at
8759 the same time setting the value to zero). */
8760 regcache->raw_supply (r->regnum, NULL);
8761 }
8762 else
8763 regcache->raw_supply (r->regnum, regs + r->offset);
8764 }
8765 }
8766 }
8767
8768 void
8769 remote_target::fetch_registers_using_g (struct regcache *regcache)
8770 {
8771 send_g_packet ();
8772 process_g_packet (regcache);
8773 }
8774
8775 /* Make the remote selected traceframe match GDB's selected
8776 traceframe. */
8777
8778 void
8779 remote_target::set_remote_traceframe ()
8780 {
8781 int newnum;
8782 struct remote_state *rs = get_remote_state ();
8783
8784 if (rs->remote_traceframe_number == get_traceframe_number ())
8785 return;
8786
8787 /* Avoid recursion, remote_trace_find calls us again. */
8788 rs->remote_traceframe_number = get_traceframe_number ();
8789
8790 newnum = target_trace_find (tfind_number,
8791 get_traceframe_number (), 0, 0, NULL);
8792
8793 /* Should not happen. If it does, all bets are off. */
8794 if (newnum != get_traceframe_number ())
8795 warning (_("could not set remote traceframe"));
8796 }
8797
8798 void
8799 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8800 {
8801 struct gdbarch *gdbarch = regcache->arch ();
8802 struct remote_state *rs = get_remote_state ();
8803 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8804 int i;
8805
8806 set_remote_traceframe ();
8807 set_general_thread (regcache->ptid ());
8808
8809 if (regnum >= 0)
8810 {
8811 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8812
8813 gdb_assert (reg != NULL);
8814
8815 /* If this register might be in the 'g' packet, try that first -
8816 we are likely to read more than one register. If this is the
8817 first 'g' packet, we might be overly optimistic about its
8818 contents, so fall back to 'p'. */
8819 if (reg->in_g_packet)
8820 {
8821 fetch_registers_using_g (regcache);
8822 if (reg->in_g_packet)
8823 return;
8824 }
8825
8826 if (fetch_register_using_p (regcache, reg))
8827 return;
8828
8829 /* This register is not available. */
8830 regcache->raw_supply (reg->regnum, NULL);
8831
8832 return;
8833 }
8834
8835 fetch_registers_using_g (regcache);
8836
8837 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8838 if (!rsa->regs[i].in_g_packet)
8839 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8840 {
8841 /* This register is not available. */
8842 regcache->raw_supply (i, NULL);
8843 }
8844 }
8845
8846 /* Prepare to store registers. Since we may send them all (using a
8847 'G' request), we have to read out the ones we don't want to change
8848 first. */
8849
8850 void
8851 remote_target::prepare_to_store (struct regcache *regcache)
8852 {
8853 struct remote_state *rs = get_remote_state ();
8854 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8855 int i;
8856
8857 /* Make sure the entire registers array is valid. */
8858 switch (m_features.packet_support (PACKET_P))
8859 {
8860 case PACKET_DISABLE:
8861 case PACKET_SUPPORT_UNKNOWN:
8862 /* Make sure all the necessary registers are cached. */
8863 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8864 if (rsa->regs[i].in_g_packet)
8865 regcache->raw_update (rsa->regs[i].regnum);
8866 break;
8867 case PACKET_ENABLE:
8868 break;
8869 }
8870 }
8871
8872 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8873 packet was not recognized. */
8874
8875 int
8876 remote_target::store_register_using_P (const struct regcache *regcache,
8877 packet_reg *reg)
8878 {
8879 struct gdbarch *gdbarch = regcache->arch ();
8880 struct remote_state *rs = get_remote_state ();
8881 /* Try storing a single register. */
8882 char *buf = rs->buf.data ();
8883 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8884 char *p;
8885
8886 if (m_features.packet_support (PACKET_P) == PACKET_DISABLE)
8887 return 0;
8888
8889 if (reg->pnum == -1)
8890 return 0;
8891
8892 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8893 p = buf + strlen (buf);
8894 regcache->raw_collect (reg->regnum, regp);
8895 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8896 putpkt (rs->buf);
8897 getpkt (&rs->buf);
8898
8899 switch (m_features.packet_ok (rs->buf, PACKET_P))
8900 {
8901 case PACKET_OK:
8902 return 1;
8903 case PACKET_ERROR:
8904 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8905 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
8906 case PACKET_UNKNOWN:
8907 return 0;
8908 default:
8909 internal_error (_("Bad result from packet_ok"));
8910 }
8911 }
8912
8913 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8914 contents of the register cache buffer. FIXME: ignores errors. */
8915
8916 void
8917 remote_target::store_registers_using_G (const struct regcache *regcache)
8918 {
8919 struct remote_state *rs = get_remote_state ();
8920 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8921 gdb_byte *regs;
8922 char *p;
8923
8924 /* Extract all the registers in the regcache copying them into a
8925 local buffer. */
8926 {
8927 int i;
8928
8929 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8930 memset (regs, 0, rsa->sizeof_g_packet);
8931 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8932 {
8933 struct packet_reg *r = &rsa->regs[i];
8934
8935 if (r->in_g_packet)
8936 regcache->raw_collect (r->regnum, regs + r->offset);
8937 }
8938 }
8939
8940 /* Command describes registers byte by byte,
8941 each byte encoded as two hex characters. */
8942 p = rs->buf.data ();
8943 *p++ = 'G';
8944 bin2hex (regs, p, rsa->sizeof_g_packet);
8945 putpkt (rs->buf);
8946 getpkt (&rs->buf);
8947 if (packet_check_result (rs->buf) == PACKET_ERROR)
8948 error (_("Could not write registers; remote failure reply '%s'"),
8949 rs->buf.data ());
8950 }
8951
8952 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8953 of the register cache buffer. FIXME: ignores errors. */
8954
8955 void
8956 remote_target::store_registers (struct regcache *regcache, int regnum)
8957 {
8958 struct gdbarch *gdbarch = regcache->arch ();
8959 struct remote_state *rs = get_remote_state ();
8960 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8961 int i;
8962
8963 set_remote_traceframe ();
8964 set_general_thread (regcache->ptid ());
8965
8966 if (regnum >= 0)
8967 {
8968 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8969
8970 gdb_assert (reg != NULL);
8971
8972 /* Always prefer to store registers using the 'P' packet if
8973 possible; we often change only a small number of registers.
8974 Sometimes we change a larger number; we'd need help from a
8975 higher layer to know to use 'G'. */
8976 if (store_register_using_P (regcache, reg))
8977 return;
8978
8979 /* For now, don't complain if we have no way to write the
8980 register. GDB loses track of unavailable registers too
8981 easily. Some day, this may be an error. We don't have
8982 any way to read the register, either... */
8983 if (!reg->in_g_packet)
8984 return;
8985
8986 store_registers_using_G (regcache);
8987 return;
8988 }
8989
8990 store_registers_using_G (regcache);
8991
8992 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8993 if (!rsa->regs[i].in_g_packet)
8994 if (!store_register_using_P (regcache, &rsa->regs[i]))
8995 /* See above for why we do not issue an error here. */
8996 continue;
8997 }
8998 \f
8999
9000 /* Return the number of hex digits in num. */
9001
9002 static int
9003 hexnumlen (ULONGEST num)
9004 {
9005 int i;
9006
9007 for (i = 0; num != 0; i++)
9008 num >>= 4;
9009
9010 return std::max (i, 1);
9011 }
9012
9013 /* Set BUF to the minimum number of hex digits representing NUM. */
9014
9015 static int
9016 hexnumstr (char *buf, ULONGEST num)
9017 {
9018 int len = hexnumlen (num);
9019
9020 return hexnumnstr (buf, num, len);
9021 }
9022
9023
9024 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
9025
9026 static int
9027 hexnumnstr (char *buf, ULONGEST num, int width)
9028 {
9029 int i;
9030
9031 buf[width] = '\0';
9032
9033 for (i = width - 1; i >= 0; i--)
9034 {
9035 buf[i] = "0123456789abcdef"[(num & 0xf)];
9036 num >>= 4;
9037 }
9038
9039 return width;
9040 }
9041
9042 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
9043
9044 static CORE_ADDR
9045 remote_address_masked (CORE_ADDR addr)
9046 {
9047 unsigned int address_size = remote_address_size;
9048
9049 /* If "remoteaddresssize" was not set, default to target address size. */
9050 if (!address_size)
9051 address_size = gdbarch_addr_bit (current_inferior ()->arch ());
9052
9053 if (address_size > 0
9054 && address_size < (sizeof (ULONGEST) * 8))
9055 {
9056 /* Only create a mask when that mask can safely be constructed
9057 in a ULONGEST variable. */
9058 ULONGEST mask = 1;
9059
9060 mask = (mask << address_size) - 1;
9061 addr &= mask;
9062 }
9063 return addr;
9064 }
9065
9066 /* Determine whether the remote target supports binary downloading.
9067 This is accomplished by sending a no-op memory write of zero length
9068 to the target at the specified address. It does not suffice to send
9069 the whole packet, since many stubs strip the eighth bit and
9070 subsequently compute a wrong checksum, which causes real havoc with
9071 remote_write_bytes.
9072
9073 NOTE: This can still lose if the serial line is not eight-bit
9074 clean. In cases like this, the user should clear "remote
9075 X-packet". */
9076
9077 void
9078 remote_target::check_binary_download (CORE_ADDR addr)
9079 {
9080 struct remote_state *rs = get_remote_state ();
9081
9082 switch (m_features.packet_support (PACKET_X))
9083 {
9084 case PACKET_DISABLE:
9085 break;
9086 case PACKET_ENABLE:
9087 break;
9088 case PACKET_SUPPORT_UNKNOWN:
9089 {
9090 char *p;
9091
9092 p = rs->buf.data ();
9093 *p++ = 'X';
9094 p += hexnumstr (p, (ULONGEST) addr);
9095 *p++ = ',';
9096 p += hexnumstr (p, (ULONGEST) 0);
9097 *p++ = ':';
9098 *p = '\0';
9099
9100 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9101 getpkt (&rs->buf);
9102
9103 if (rs->buf[0] == '\0')
9104 {
9105 remote_debug_printf ("binary downloading NOT supported by target");
9106 m_features.m_protocol_packets[PACKET_X].support = PACKET_DISABLE;
9107 }
9108 else
9109 {
9110 remote_debug_printf ("binary downloading supported by target");
9111 m_features.m_protocol_packets[PACKET_X].support = PACKET_ENABLE;
9112 }
9113 break;
9114 }
9115 }
9116 }
9117
9118 /* Helper function to resize the payload in order to try to get a good
9119 alignment. We try to write an amount of data such that the next write will
9120 start on an address aligned on REMOTE_ALIGN_WRITES. */
9121
9122 static int
9123 align_for_efficient_write (int todo, CORE_ADDR memaddr)
9124 {
9125 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
9126 }
9127
9128 /* Write memory data directly to the remote machine.
9129 This does not inform the data cache; the data cache uses this.
9130 HEADER is the starting part of the packet.
9131 MEMADDR is the address in the remote memory space.
9132 MYADDR is the address of the buffer in our space.
9133 LEN_UNITS is the number of addressable units to write.
9134 UNIT_SIZE is the length in bytes of an addressable unit.
9135 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9136 should send data as binary ('X'), or hex-encoded ('M').
9137
9138 The function creates packet of the form
9139 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9140
9141 where encoding of <DATA> is terminated by PACKET_FORMAT.
9142
9143 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9144 are omitted.
9145
9146 Return the transferred status, error or OK (an
9147 'enum target_xfer_status' value). Save the number of addressable units
9148 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9149
9150 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9151 exchange between gdb and the stub could look like (?? in place of the
9152 checksum):
9153
9154 -> $m1000,4#??
9155 <- aaaabbbbccccdddd
9156
9157 -> $M1000,3:eeeeffffeeee#??
9158 <- OK
9159
9160 -> $m1000,4#??
9161 <- eeeeffffeeeedddd */
9162
9163 target_xfer_status
9164 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
9165 const gdb_byte *myaddr,
9166 ULONGEST len_units,
9167 int unit_size,
9168 ULONGEST *xfered_len_units,
9169 char packet_format, int use_length)
9170 {
9171 struct remote_state *rs = get_remote_state ();
9172 char *p;
9173 char *plen = NULL;
9174 int plenlen = 0;
9175 int todo_units;
9176 int units_written;
9177 int payload_capacity_bytes;
9178 int payload_length_bytes;
9179
9180 if (packet_format != 'X' && packet_format != 'M')
9181 internal_error (_("remote_write_bytes_aux: bad packet format"));
9182
9183 if (len_units == 0)
9184 return TARGET_XFER_EOF;
9185
9186 payload_capacity_bytes = get_memory_write_packet_size ();
9187
9188 /* The packet buffer will be large enough for the payload;
9189 get_memory_packet_size ensures this. */
9190 rs->buf[0] = '\0';
9191
9192 /* Compute the size of the actual payload by subtracting out the
9193 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9194
9195 payload_capacity_bytes -= strlen ("$,:#NN");
9196 if (!use_length)
9197 /* The comma won't be used. */
9198 payload_capacity_bytes += 1;
9199 payload_capacity_bytes -= strlen (header);
9200 payload_capacity_bytes -= hexnumlen (memaddr);
9201
9202 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9203
9204 strcat (rs->buf.data (), header);
9205 p = rs->buf.data () + strlen (header);
9206
9207 /* Compute a best guess of the number of bytes actually transfered. */
9208 if (packet_format == 'X')
9209 {
9210 /* Best guess at number of bytes that will fit. */
9211 todo_units = std::min (len_units,
9212 (ULONGEST) payload_capacity_bytes / unit_size);
9213 if (use_length)
9214 payload_capacity_bytes -= hexnumlen (todo_units);
9215 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9216 }
9217 else
9218 {
9219 /* Number of bytes that will fit. */
9220 todo_units
9221 = std::min (len_units,
9222 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9223 if (use_length)
9224 payload_capacity_bytes -= hexnumlen (todo_units);
9225 todo_units = std::min (todo_units,
9226 (payload_capacity_bytes / unit_size) / 2);
9227 }
9228
9229 if (todo_units <= 0)
9230 internal_error (_("minimum packet size too small to write data"));
9231
9232 /* If we already need another packet, then try to align the end
9233 of this packet to a useful boundary. */
9234 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9235 todo_units = align_for_efficient_write (todo_units, memaddr);
9236
9237 /* Append "<memaddr>". */
9238 memaddr = remote_address_masked (memaddr);
9239 p += hexnumstr (p, (ULONGEST) memaddr);
9240
9241 if (use_length)
9242 {
9243 /* Append ",". */
9244 *p++ = ',';
9245
9246 /* Append the length and retain its location and size. It may need to be
9247 adjusted once the packet body has been created. */
9248 plen = p;
9249 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9250 p += plenlen;
9251 }
9252
9253 /* Append ":". */
9254 *p++ = ':';
9255 *p = '\0';
9256
9257 /* Append the packet body. */
9258 if (packet_format == 'X')
9259 {
9260 /* Binary mode. Send target system values byte by byte, in
9261 increasing byte addresses. Only escape certain critical
9262 characters. */
9263 payload_length_bytes =
9264 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9265 &units_written, payload_capacity_bytes);
9266
9267 /* If not all TODO units fit, then we'll need another packet. Make
9268 a second try to keep the end of the packet aligned. Don't do
9269 this if the packet is tiny. */
9270 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9271 {
9272 int new_todo_units;
9273
9274 new_todo_units = align_for_efficient_write (units_written, memaddr);
9275
9276 if (new_todo_units != units_written)
9277 payload_length_bytes =
9278 remote_escape_output (myaddr, new_todo_units, unit_size,
9279 (gdb_byte *) p, &units_written,
9280 payload_capacity_bytes);
9281 }
9282
9283 p += payload_length_bytes;
9284 if (use_length && units_written < todo_units)
9285 {
9286 /* Escape chars have filled up the buffer prematurely,
9287 and we have actually sent fewer units than planned.
9288 Fix-up the length field of the packet. Use the same
9289 number of characters as before. */
9290 plen += hexnumnstr (plen, (ULONGEST) units_written,
9291 plenlen);
9292 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9293 }
9294 }
9295 else
9296 {
9297 /* Normal mode: Send target system values byte by byte, in
9298 increasing byte addresses. Each byte is encoded as a two hex
9299 value. */
9300 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9301 units_written = todo_units;
9302 }
9303
9304 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9305 getpkt (&rs->buf);
9306
9307 if (rs->buf[0] == 'E')
9308 return TARGET_XFER_E_IO;
9309
9310 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9311 send fewer units than we'd planned. */
9312 *xfered_len_units = (ULONGEST) units_written;
9313 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9314 }
9315
9316 /* Write memory data directly to the remote machine.
9317 This does not inform the data cache; the data cache uses this.
9318 MEMADDR is the address in the remote memory space.
9319 MYADDR is the address of the buffer in our space.
9320 LEN is the number of bytes.
9321
9322 Return the transferred status, error or OK (an
9323 'enum target_xfer_status' value). Save the number of bytes
9324 transferred in *XFERED_LEN. Only transfer a single packet. */
9325
9326 target_xfer_status
9327 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9328 ULONGEST len, int unit_size,
9329 ULONGEST *xfered_len)
9330 {
9331 const char *packet_format = NULL;
9332
9333 /* Check whether the target supports binary download. */
9334 check_binary_download (memaddr);
9335
9336 switch (m_features.packet_support (PACKET_X))
9337 {
9338 case PACKET_ENABLE:
9339 packet_format = "X";
9340 break;
9341 case PACKET_DISABLE:
9342 packet_format = "M";
9343 break;
9344 case PACKET_SUPPORT_UNKNOWN:
9345 internal_error (_("remote_write_bytes: bad internal state"));
9346 default:
9347 internal_error (_("bad switch"));
9348 }
9349
9350 return remote_write_bytes_aux (packet_format,
9351 memaddr, myaddr, len, unit_size, xfered_len,
9352 packet_format[0], 1);
9353 }
9354
9355 /* Read memory data directly from the remote machine.
9356 This does not use the data cache; the data cache uses this.
9357 MEMADDR is the address in the remote memory space.
9358 MYADDR is the address of the buffer in our space.
9359 LEN_UNITS is the number of addressable memory units to read..
9360 UNIT_SIZE is the length in bytes of an addressable unit.
9361
9362 Return the transferred status, error or OK (an
9363 'enum target_xfer_status' value). Save the number of bytes
9364 transferred in *XFERED_LEN_UNITS.
9365
9366 See the comment of remote_write_bytes_aux for an example of
9367 memory read/write exchange between gdb and the stub. */
9368
9369 target_xfer_status
9370 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9371 ULONGEST len_units,
9372 int unit_size, ULONGEST *xfered_len_units)
9373 {
9374 struct remote_state *rs = get_remote_state ();
9375 int buf_size_bytes; /* Max size of packet output buffer. */
9376 char *p;
9377 int todo_units;
9378 int decoded_bytes;
9379
9380 buf_size_bytes = get_memory_read_packet_size ();
9381 /* The packet buffer will be large enough for the payload;
9382 get_memory_packet_size ensures this. */
9383
9384 /* Number of units that will fit. */
9385 todo_units = std::min (len_units,
9386 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9387
9388 /* Construct "m"<memaddr>","<len>". */
9389 memaddr = remote_address_masked (memaddr);
9390 p = rs->buf.data ();
9391 *p++ = 'm';
9392 p += hexnumstr (p, (ULONGEST) memaddr);
9393 *p++ = ',';
9394 p += hexnumstr (p, (ULONGEST) todo_units);
9395 *p = '\0';
9396 putpkt (rs->buf);
9397 getpkt (&rs->buf);
9398 if (rs->buf[0] == 'E'
9399 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9400 && rs->buf[3] == '\0')
9401 return TARGET_XFER_E_IO;
9402 /* Reply describes memory byte by byte, each byte encoded as two hex
9403 characters. */
9404 p = rs->buf.data ();
9405 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9406 /* Return what we have. Let higher layers handle partial reads. */
9407 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9408 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9409 }
9410
9411 /* Using the set of read-only target sections of remote, read live
9412 read-only memory.
9413
9414 For interface/parameters/return description see target.h,
9415 to_xfer_partial. */
9416
9417 target_xfer_status
9418 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9419 ULONGEST memaddr,
9420 ULONGEST len,
9421 int unit_size,
9422 ULONGEST *xfered_len)
9423 {
9424 const struct target_section *secp;
9425
9426 secp = target_section_by_addr (this, memaddr);
9427 if (secp != NULL
9428 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9429 {
9430 ULONGEST memend = memaddr + len;
9431
9432 const target_section_table *table = target_get_section_table (this);
9433 for (const target_section &p : *table)
9434 {
9435 if (memaddr >= p.addr)
9436 {
9437 if (memend <= p.endaddr)
9438 {
9439 /* Entire transfer is within this section. */
9440 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9441 xfered_len);
9442 }
9443 else if (memaddr >= p.endaddr)
9444 {
9445 /* This section ends before the transfer starts. */
9446 continue;
9447 }
9448 else
9449 {
9450 /* This section overlaps the transfer. Just do half. */
9451 len = p.endaddr - memaddr;
9452 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9453 xfered_len);
9454 }
9455 }
9456 }
9457 }
9458
9459 return TARGET_XFER_EOF;
9460 }
9461
9462 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9463 first if the requested memory is unavailable in traceframe.
9464 Otherwise, fall back to remote_read_bytes_1. */
9465
9466 target_xfer_status
9467 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9468 gdb_byte *myaddr, ULONGEST len, int unit_size,
9469 ULONGEST *xfered_len)
9470 {
9471 if (len == 0)
9472 return TARGET_XFER_EOF;
9473
9474 if (get_traceframe_number () != -1)
9475 {
9476 std::vector<mem_range> available;
9477
9478 /* If we fail to get the set of available memory, then the
9479 target does not support querying traceframe info, and so we
9480 attempt reading from the traceframe anyway (assuming the
9481 target implements the old QTro packet then). */
9482 if (traceframe_available_memory (&available, memaddr, len))
9483 {
9484 if (available.empty () || available[0].start != memaddr)
9485 {
9486 enum target_xfer_status res;
9487
9488 /* Don't read into the traceframe's available
9489 memory. */
9490 if (!available.empty ())
9491 {
9492 LONGEST oldlen = len;
9493
9494 len = available[0].start - memaddr;
9495 gdb_assert (len <= oldlen);
9496 }
9497
9498 /* This goes through the topmost target again. */
9499 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9500 len, unit_size, xfered_len);
9501 if (res == TARGET_XFER_OK)
9502 return TARGET_XFER_OK;
9503 else
9504 {
9505 /* No use trying further, we know some memory starting
9506 at MEMADDR isn't available. */
9507 *xfered_len = len;
9508 return (*xfered_len != 0) ?
9509 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9510 }
9511 }
9512
9513 /* Don't try to read more than how much is available, in
9514 case the target implements the deprecated QTro packet to
9515 cater for older GDBs (the target's knowledge of read-only
9516 sections may be outdated by now). */
9517 len = available[0].length;
9518 }
9519 }
9520
9521 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9522 }
9523
9524 \f
9525
9526 /* Sends a packet with content determined by the printf format string
9527 FORMAT and the remaining arguments, then gets the reply. Returns
9528 whether the packet was a success, a failure, or unknown. */
9529
9530 packet_result
9531 remote_target::remote_send_printf (const char *format, ...)
9532 {
9533 struct remote_state *rs = get_remote_state ();
9534 int max_size = get_remote_packet_size ();
9535 va_list ap;
9536
9537 va_start (ap, format);
9538
9539 rs->buf[0] = '\0';
9540 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9541
9542 va_end (ap);
9543
9544 if (size >= max_size)
9545 internal_error (_("Too long remote packet."));
9546
9547 if (putpkt (rs->buf) < 0)
9548 error (_("Communication problem with target."));
9549
9550 rs->buf[0] = '\0';
9551 getpkt (&rs->buf);
9552
9553 return packet_check_result (rs->buf);
9554 }
9555
9556 /* Flash writing can take quite some time. We'll set
9557 effectively infinite timeout for flash operations.
9558 In future, we'll need to decide on a better approach. */
9559 static const int remote_flash_timeout = 1000;
9560
9561 void
9562 remote_target::flash_erase (ULONGEST address, LONGEST length)
9563 {
9564 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
9565 enum packet_result ret;
9566 scoped_restore restore_timeout
9567 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9568
9569 ret = remote_send_printf ("vFlashErase:%s,%s",
9570 phex (address, addr_size),
9571 phex (length, 4));
9572 switch (ret)
9573 {
9574 case PACKET_UNKNOWN:
9575 error (_("Remote target does not support flash erase"));
9576 case PACKET_ERROR:
9577 error (_("Error erasing flash with vFlashErase packet"));
9578 default:
9579 break;
9580 }
9581 }
9582
9583 target_xfer_status
9584 remote_target::remote_flash_write (ULONGEST address,
9585 ULONGEST length, ULONGEST *xfered_len,
9586 const gdb_byte *data)
9587 {
9588 scoped_restore restore_timeout
9589 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9590 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9591 xfered_len,'X', 0);
9592 }
9593
9594 void
9595 remote_target::flash_done ()
9596 {
9597 int ret;
9598
9599 scoped_restore restore_timeout
9600 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9601
9602 ret = remote_send_printf ("vFlashDone");
9603
9604 switch (ret)
9605 {
9606 case PACKET_UNKNOWN:
9607 error (_("Remote target does not support vFlashDone"));
9608 case PACKET_ERROR:
9609 error (_("Error finishing flash operation"));
9610 default:
9611 break;
9612 }
9613 }
9614
9615 \f
9616 /* Stuff for dealing with the packets which are part of this protocol.
9617 See comment at top of file for details. */
9618
9619 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9620 error to higher layers. Called when a serial error is detected.
9621 The exception message is STRING, followed by a colon and a blank,
9622 the system error message for errno at function entry and final dot
9623 for output compatibility with throw_perror_with_name. */
9624
9625 static void
9626 unpush_and_perror (remote_target *target, const char *string)
9627 {
9628 int saved_errno = errno;
9629
9630 remote_unpush_target (target);
9631 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9632 safe_strerror (saved_errno));
9633 }
9634
9635 /* Read a single character from the remote end. The current quit
9636 handler is overridden to avoid quitting in the middle of packet
9637 sequence, as that would break communication with the remote server.
9638 See remote_serial_quit_handler for more detail. */
9639
9640 int
9641 remote_target::readchar (int timeout)
9642 {
9643 int ch;
9644 struct remote_state *rs = get_remote_state ();
9645
9646 {
9647 scoped_restore restore_quit_target
9648 = make_scoped_restore (&curr_quit_handler_target, this);
9649 scoped_restore restore_quit
9650 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9651
9652 rs->got_ctrlc_during_io = 0;
9653
9654 ch = serial_readchar (rs->remote_desc, timeout);
9655
9656 if (rs->got_ctrlc_during_io)
9657 set_quit_flag ();
9658 }
9659
9660 if (ch >= 0)
9661 return ch;
9662
9663 switch ((enum serial_rc) ch)
9664 {
9665 case SERIAL_EOF:
9666 remote_unpush_target (this);
9667 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9668 /* no return */
9669 case SERIAL_ERROR:
9670 unpush_and_perror (this, _("Remote communication error. "
9671 "Target disconnected"));
9672 /* no return */
9673 case SERIAL_TIMEOUT:
9674 break;
9675 }
9676 return ch;
9677 }
9678
9679 /* Wrapper for serial_write that closes the target and throws if
9680 writing fails. The current quit handler is overridden to avoid
9681 quitting in the middle of packet sequence, as that would break
9682 communication with the remote server. See
9683 remote_serial_quit_handler for more detail. */
9684
9685 void
9686 remote_target::remote_serial_write (const char *str, int len)
9687 {
9688 struct remote_state *rs = get_remote_state ();
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 if (serial_write (rs->remote_desc, str, len))
9698 {
9699 unpush_and_perror (this, _("Remote communication error. "
9700 "Target disconnected"));
9701 }
9702
9703 if (rs->got_ctrlc_during_io)
9704 set_quit_flag ();
9705 }
9706
9707 /* Return a string representing an escaped version of BUF, of len N.
9708 E.g. \n is converted to \\n, \t to \\t, etc. */
9709
9710 static std::string
9711 escape_buffer (const char *buf, int n)
9712 {
9713 string_file stb;
9714
9715 stb.putstrn (buf, n, '\\');
9716 return stb.release ();
9717 }
9718
9719 int
9720 remote_target::putpkt (const char *buf)
9721 {
9722 return putpkt_binary (buf, strlen (buf));
9723 }
9724
9725 /* Wrapper around remote_target::putpkt to avoid exporting
9726 remote_target. */
9727
9728 int
9729 putpkt (remote_target *remote, const char *buf)
9730 {
9731 return remote->putpkt (buf);
9732 }
9733
9734 /* Send a packet to the remote machine, with error checking. The data
9735 of the packet is in BUF. The string in BUF can be at most
9736 get_remote_packet_size () - 5 to account for the $, # and checksum,
9737 and for a possible /0 if we are debugging (remote_debug) and want
9738 to print the sent packet as a string. */
9739
9740 int
9741 remote_target::putpkt_binary (const char *buf, int cnt)
9742 {
9743 struct remote_state *rs = get_remote_state ();
9744 int i;
9745 unsigned char csum = 0;
9746 gdb::def_vector<char> data (cnt + 6);
9747 char *buf2 = data.data ();
9748
9749 int ch;
9750 int tcount = 0;
9751 char *p;
9752
9753 /* Catch cases like trying to read memory or listing threads while
9754 we're waiting for a stop reply. The remote server wouldn't be
9755 ready to handle this request, so we'd hang and timeout. We don't
9756 have to worry about this in synchronous mode, because in that
9757 case it's not possible to issue a command while the target is
9758 running. This is not a problem in non-stop mode, because in that
9759 case, the stub is always ready to process serial input. */
9760 if (!target_is_non_stop_p ()
9761 && target_is_async_p ()
9762 && rs->waiting_for_stop_reply)
9763 {
9764 error (_("Cannot execute this command while the target is running.\n"
9765 "Use the \"interrupt\" command to stop the target\n"
9766 "and then try again."));
9767 }
9768
9769 /* Copy the packet into buffer BUF2, encapsulating it
9770 and giving it a checksum. */
9771
9772 p = buf2;
9773 *p++ = '$';
9774
9775 for (i = 0; i < cnt; i++)
9776 {
9777 csum += buf[i];
9778 *p++ = buf[i];
9779 }
9780 *p++ = '#';
9781 *p++ = tohex ((csum >> 4) & 0xf);
9782 *p++ = tohex (csum & 0xf);
9783
9784 /* Send it over and over until we get a positive ack. */
9785
9786 while (1)
9787 {
9788 if (remote_debug)
9789 {
9790 *p = '\0';
9791
9792 int len = (int) (p - buf2);
9793 int max_chars;
9794
9795 if (remote_packet_max_chars < 0)
9796 max_chars = len;
9797 else
9798 max_chars = remote_packet_max_chars;
9799
9800 std::string str
9801 = escape_buffer (buf2, std::min (len, max_chars));
9802
9803 if (len > max_chars)
9804 remote_debug_printf_nofunc
9805 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9806 len - max_chars);
9807 else
9808 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9809 }
9810 remote_serial_write (buf2, p - buf2);
9811
9812 /* If this is a no acks version of the remote protocol, send the
9813 packet and move on. */
9814 if (rs->noack_mode)
9815 break;
9816
9817 /* Read until either a timeout occurs (-2) or '+' is read.
9818 Handle any notification that arrives in the mean time. */
9819 while (1)
9820 {
9821 ch = readchar (remote_timeout);
9822
9823 switch (ch)
9824 {
9825 case '+':
9826 remote_debug_printf_nofunc ("Received Ack");
9827 return 1;
9828 case '-':
9829 remote_debug_printf_nofunc ("Received Nak");
9830 /* FALLTHROUGH */
9831 case SERIAL_TIMEOUT:
9832 tcount++;
9833 if (tcount > 3)
9834 return 0;
9835 break; /* Retransmit buffer. */
9836 case '$':
9837 {
9838 remote_debug_printf ("Packet instead of Ack, ignoring it");
9839 /* It's probably an old response sent because an ACK
9840 was lost. Gobble up the packet and ack it so it
9841 doesn't get retransmitted when we resend this
9842 packet. */
9843 skip_frame ();
9844 remote_serial_write ("+", 1);
9845 continue; /* Now, go look for +. */
9846 }
9847
9848 case '%':
9849 {
9850 int val;
9851
9852 /* If we got a notification, handle it, and go back to looking
9853 for an ack. */
9854 /* We've found the start of a notification. Now
9855 collect the data. */
9856 val = read_frame (&rs->buf);
9857 if (val >= 0)
9858 {
9859 remote_debug_printf_nofunc
9860 (" Notification received: %s",
9861 escape_buffer (rs->buf.data (), val).c_str ());
9862
9863 handle_notification (rs->notif_state, rs->buf.data ());
9864 /* We're in sync now, rewait for the ack. */
9865 tcount = 0;
9866 }
9867 else
9868 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9869 rs->buf.data ());
9870 continue;
9871 }
9872 /* fall-through */
9873 default:
9874 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9875 rs->buf.data ());
9876 continue;
9877 }
9878 break; /* Here to retransmit. */
9879 }
9880
9881 #if 0
9882 /* This is wrong. If doing a long backtrace, the user should be
9883 able to get out next time we call QUIT, without anything as
9884 violent as interrupt_query. If we want to provide a way out of
9885 here without getting to the next QUIT, it should be based on
9886 hitting ^C twice as in remote_wait. */
9887 if (quit_flag)
9888 {
9889 quit_flag = 0;
9890 interrupt_query ();
9891 }
9892 #endif
9893 }
9894
9895 return 0;
9896 }
9897
9898 /* Come here after finding the start of a frame when we expected an
9899 ack. Do our best to discard the rest of this packet. */
9900
9901 void
9902 remote_target::skip_frame ()
9903 {
9904 int c;
9905
9906 while (1)
9907 {
9908 c = readchar (remote_timeout);
9909 switch (c)
9910 {
9911 case SERIAL_TIMEOUT:
9912 /* Nothing we can do. */
9913 return;
9914 case '#':
9915 /* Discard the two bytes of checksum and stop. */
9916 c = readchar (remote_timeout);
9917 if (c >= 0)
9918 c = readchar (remote_timeout);
9919
9920 return;
9921 case '*': /* Run length encoding. */
9922 /* Discard the repeat count. */
9923 c = readchar (remote_timeout);
9924 if (c < 0)
9925 return;
9926 break;
9927 default:
9928 /* A regular character. */
9929 break;
9930 }
9931 }
9932 }
9933
9934 /* Come here after finding the start of the frame. Collect the rest
9935 into *BUF, verifying the checksum, length, and handling run-length
9936 compression. NUL terminate the buffer. If there is not enough room,
9937 expand *BUF.
9938
9939 Returns -1 on error, number of characters in buffer (ignoring the
9940 trailing NULL) on success. (could be extended to return one of the
9941 SERIAL status indications). */
9942
9943 long
9944 remote_target::read_frame (gdb::char_vector *buf_p)
9945 {
9946 unsigned char csum;
9947 long bc;
9948 int c;
9949 char *buf = buf_p->data ();
9950 struct remote_state *rs = get_remote_state ();
9951
9952 csum = 0;
9953 bc = 0;
9954
9955 while (1)
9956 {
9957 c = readchar (remote_timeout);
9958 switch (c)
9959 {
9960 case SERIAL_TIMEOUT:
9961 remote_debug_printf ("Timeout in mid-packet, retrying");
9962 return -1;
9963
9964 case '$':
9965 remote_debug_printf ("Saw new packet start in middle of old one");
9966 return -1; /* Start a new packet, count retries. */
9967
9968 case '#':
9969 {
9970 unsigned char pktcsum;
9971 int check_0 = 0;
9972 int check_1 = 0;
9973
9974 buf[bc] = '\0';
9975
9976 check_0 = readchar (remote_timeout);
9977 if (check_0 >= 0)
9978 check_1 = readchar (remote_timeout);
9979
9980 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9981 {
9982 remote_debug_printf ("Timeout in checksum, retrying");
9983 return -1;
9984 }
9985 else if (check_0 < 0 || check_1 < 0)
9986 {
9987 remote_debug_printf ("Communication error in checksum");
9988 return -1;
9989 }
9990
9991 /* Don't recompute the checksum; with no ack packets we
9992 don't have any way to indicate a packet retransmission
9993 is necessary. */
9994 if (rs->noack_mode)
9995 return bc;
9996
9997 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9998 if (csum == pktcsum)
9999 return bc;
10000
10001 remote_debug_printf
10002 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
10003 pktcsum, csum, escape_buffer (buf, bc).c_str ());
10004
10005 /* Number of characters in buffer ignoring trailing
10006 NULL. */
10007 return -1;
10008 }
10009 case '*': /* Run length encoding. */
10010 {
10011 int repeat;
10012
10013 csum += c;
10014 c = readchar (remote_timeout);
10015 csum += c;
10016 repeat = c - ' ' + 3; /* Compute repeat count. */
10017
10018 /* The character before ``*'' is repeated. */
10019
10020 if (repeat > 0 && repeat <= 255 && bc > 0)
10021 {
10022 if (bc + repeat - 1 >= buf_p->size () - 1)
10023 {
10024 /* Make some more room in the buffer. */
10025 buf_p->resize (buf_p->size () + repeat);
10026 buf = buf_p->data ();
10027 }
10028
10029 memset (&buf[bc], buf[bc - 1], repeat);
10030 bc += repeat;
10031 continue;
10032 }
10033
10034 buf[bc] = '\0';
10035 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
10036 return -1;
10037 }
10038 default:
10039 if (bc >= buf_p->size () - 1)
10040 {
10041 /* Make some more room in the buffer. */
10042 buf_p->resize (buf_p->size () * 2);
10043 buf = buf_p->data ();
10044 }
10045
10046 buf[bc++] = c;
10047 csum += c;
10048 continue;
10049 }
10050 }
10051 }
10052
10053 /* Set this to the maximum number of seconds to wait instead of waiting forever
10054 in target_wait(). If this timer times out, then it generates an error and
10055 the command is aborted. This replaces most of the need for timeouts in the
10056 GDB test suite, and makes it possible to distinguish between a hung target
10057 and one with slow communications. */
10058
10059 static int watchdog = 0;
10060 static void
10061 show_watchdog (struct ui_file *file, int from_tty,
10062 struct cmd_list_element *c, const char *value)
10063 {
10064 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
10065 }
10066
10067 /* Read a packet from the remote machine, with error checking, and
10068 store it in *BUF. Resize *BUF if necessary to hold the result. If
10069 FOREVER, wait forever rather than timing out; this is used (in
10070 synchronous mode) to wait for a target that is is executing user
10071 code to stop. If FOREVER == false, this function is allowed to time
10072 out gracefully and return an indication of this to the caller.
10073 Otherwise return the number of bytes read. If IS_NOTIF is not
10074 NULL, then consider receiving a notification enough reason to
10075 return to the caller. In this case, *IS_NOTIF is an output boolean
10076 that indicates whether *BUF holds a notification or not (a regular
10077 packet). */
10078
10079 int
10080 remote_target::getpkt (gdb::char_vector *buf, bool forever, bool *is_notif)
10081 {
10082 struct remote_state *rs = get_remote_state ();
10083 int c;
10084 int tries;
10085 int timeout;
10086 int val = -1;
10087
10088 strcpy (buf->data (), "timeout");
10089
10090 if (forever)
10091 timeout = watchdog > 0 ? watchdog : -1;
10092 else if (is_notif != nullptr)
10093 timeout = 0; /* There should already be a char in the buffer. If
10094 not, bail out. */
10095 else
10096 timeout = remote_timeout;
10097
10098 #define MAX_TRIES 3
10099
10100 /* Process any number of notifications, and then return when
10101 we get a packet. */
10102 for (;;)
10103 {
10104 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
10105 times. */
10106 for (tries = 1; tries <= MAX_TRIES; tries++)
10107 {
10108 /* This can loop forever if the remote side sends us
10109 characters continuously, but if it pauses, we'll get
10110 SERIAL_TIMEOUT from readchar because of timeout. Then
10111 we'll count that as a retry.
10112
10113 Note that even when forever is set, we will only wait
10114 forever prior to the start of a packet. After that, we
10115 expect characters to arrive at a brisk pace. They should
10116 show up within remote_timeout intervals. */
10117 do
10118 c = readchar (timeout);
10119 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
10120
10121 if (c == SERIAL_TIMEOUT)
10122 {
10123 if (is_notif != nullptr)
10124 return -1; /* Don't complain, it's normal to not get
10125 anything in this case. */
10126
10127 if (forever) /* Watchdog went off? Kill the target. */
10128 {
10129 remote_unpush_target (this);
10130 throw_error (TARGET_CLOSE_ERROR,
10131 _("Watchdog timeout has expired. "
10132 "Target detached."));
10133 }
10134
10135 remote_debug_printf ("Timed out.");
10136 }
10137 else
10138 {
10139 /* We've found the start of a packet or notification.
10140 Now collect the data. */
10141 val = read_frame (buf);
10142 if (val >= 0)
10143 break;
10144 }
10145
10146 remote_serial_write ("-", 1);
10147 }
10148
10149 if (tries > MAX_TRIES)
10150 {
10151 /* We have tried hard enough, and just can't receive the
10152 packet/notification. Give up. */
10153 gdb_printf (_("Ignoring packet error, continuing...\n"));
10154
10155 /* Skip the ack char if we're in no-ack mode. */
10156 if (!rs->noack_mode)
10157 remote_serial_write ("+", 1);
10158 return -1;
10159 }
10160
10161 /* If we got an ordinary packet, return that to our caller. */
10162 if (c == '$')
10163 {
10164 if (remote_debug)
10165 {
10166 int max_chars;
10167
10168 if (remote_packet_max_chars < 0)
10169 max_chars = val;
10170 else
10171 max_chars = remote_packet_max_chars;
10172
10173 std::string str
10174 = escape_buffer (buf->data (),
10175 std::min (val, max_chars));
10176
10177 if (val > max_chars)
10178 remote_debug_printf_nofunc
10179 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10180 val - max_chars);
10181 else
10182 remote_debug_printf_nofunc ("Packet received: %s",
10183 str.c_str ());
10184 }
10185
10186 /* Skip the ack char if we're in no-ack mode. */
10187 if (!rs->noack_mode)
10188 remote_serial_write ("+", 1);
10189 if (is_notif != NULL)
10190 *is_notif = false;
10191 return val;
10192 }
10193
10194 /* If we got a notification, handle it, and go back to looking
10195 for a packet. */
10196 else
10197 {
10198 gdb_assert (c == '%');
10199
10200 remote_debug_printf_nofunc
10201 (" Notification received: %s",
10202 escape_buffer (buf->data (), val).c_str ());
10203
10204 if (is_notif != NULL)
10205 *is_notif = true;
10206
10207 handle_notification (rs->notif_state, buf->data ());
10208
10209 /* Notifications require no acknowledgement. */
10210
10211 if (is_notif != nullptr)
10212 return val;
10213 }
10214 }
10215 }
10216
10217 /* Kill any new fork children of inferior INF that haven't been
10218 processed by follow_fork. */
10219
10220 void
10221 remote_target::kill_new_fork_children (inferior *inf)
10222 {
10223 remote_state *rs = get_remote_state ();
10224 const notif_client *notif = &notif_client_stop;
10225
10226 /* Kill the fork child threads of any threads in inferior INF that are stopped
10227 at a fork event. */
10228 for (thread_info *thread : inf->non_exited_threads ())
10229 {
10230 const target_waitstatus *ws = thread_pending_fork_status (thread);
10231
10232 if (ws == nullptr)
10233 continue;
10234
10235 int child_pid = ws->child_ptid ().pid ();
10236 int res = remote_vkill (child_pid);
10237
10238 if (res != 0)
10239 error (_("Can't kill fork child process %d"), child_pid);
10240 }
10241
10242 /* Check for any pending fork events (not reported or processed yet)
10243 in inferior INF and kill those fork child threads as well. */
10244 remote_notif_get_pending_events (notif);
10245 for (auto &event : rs->stop_reply_queue)
10246 {
10247 if (event->ptid.pid () != inf->pid)
10248 continue;
10249
10250 if (!is_fork_status (event->ws.kind ()))
10251 continue;
10252
10253 int child_pid = event->ws.child_ptid ().pid ();
10254 int res = remote_vkill (child_pid);
10255
10256 if (res != 0)
10257 error (_("Can't kill fork child process %d"), child_pid);
10258 }
10259 }
10260
10261 \f
10262 /* Target hook to kill the current inferior. */
10263
10264 void
10265 remote_target::kill ()
10266 {
10267 int res = -1;
10268 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10269
10270 gdb_assert (inf != nullptr);
10271
10272 if (m_features.packet_support (PACKET_vKill) != PACKET_DISABLE)
10273 {
10274 /* If we're stopped while forking and we haven't followed yet,
10275 kill the child task. We need to do this before killing the
10276 parent task because if this is a vfork then the parent will
10277 be sleeping. */
10278 kill_new_fork_children (inf);
10279
10280 res = remote_vkill (inf->pid);
10281 if (res == 0)
10282 {
10283 target_mourn_inferior (inferior_ptid);
10284 return;
10285 }
10286 }
10287
10288 /* If we are in 'target remote' mode and we are killing the only
10289 inferior, then we will tell gdbserver to exit and unpush the
10290 target. */
10291 if (res == -1 && !m_features.remote_multi_process_p ()
10292 && number_of_live_inferiors (this) == 1)
10293 {
10294 remote_kill_k ();
10295
10296 /* We've killed the remote end, we get to mourn it. If we are
10297 not in extended mode, mourning the inferior also unpushes
10298 remote_ops from the target stack, which closes the remote
10299 connection. */
10300 target_mourn_inferior (inferior_ptid);
10301
10302 return;
10303 }
10304
10305 error (_("Can't kill process"));
10306 }
10307
10308 /* Send a kill request to the target using the 'vKill' packet. */
10309
10310 int
10311 remote_target::remote_vkill (int pid)
10312 {
10313 if (m_features.packet_support (PACKET_vKill) == PACKET_DISABLE)
10314 return -1;
10315
10316 remote_state *rs = get_remote_state ();
10317
10318 /* Tell the remote target to detach. */
10319 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10320 putpkt (rs->buf);
10321 getpkt (&rs->buf);
10322
10323 switch (m_features.packet_ok (rs->buf, PACKET_vKill))
10324 {
10325 case PACKET_OK:
10326 return 0;
10327 case PACKET_ERROR:
10328 return 1;
10329 case PACKET_UNKNOWN:
10330 return -1;
10331 default:
10332 internal_error (_("Bad result from packet_ok"));
10333 }
10334 }
10335
10336 /* Send a kill request to the target using the 'k' packet. */
10337
10338 void
10339 remote_target::remote_kill_k ()
10340 {
10341 /* Catch errors so the user can quit from gdb even when we
10342 aren't on speaking terms with the remote system. */
10343 try
10344 {
10345 putpkt ("k");
10346 }
10347 catch (const gdb_exception_error &ex)
10348 {
10349 if (ex.error == TARGET_CLOSE_ERROR)
10350 {
10351 /* If we got an (EOF) error that caused the target
10352 to go away, then we're done, that's what we wanted.
10353 "k" is susceptible to cause a premature EOF, given
10354 that the remote server isn't actually required to
10355 reply to "k", and it can happen that it doesn't
10356 even get to reply ACK to the "k". */
10357 return;
10358 }
10359
10360 /* Otherwise, something went wrong. We didn't actually kill
10361 the target. Just propagate the exception, and let the
10362 user or higher layers decide what to do. */
10363 throw;
10364 }
10365 }
10366
10367 void
10368 remote_target::mourn_inferior ()
10369 {
10370 struct remote_state *rs = get_remote_state ();
10371
10372 /* We're no longer interested in notification events of an inferior
10373 that exited or was killed/detached. */
10374 discard_pending_stop_replies (current_inferior ());
10375
10376 /* In 'target remote' mode with one inferior, we close the connection. */
10377 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10378 {
10379 remote_unpush_target (this);
10380 return;
10381 }
10382
10383 /* In case we got here due to an error, but we're going to stay
10384 connected. */
10385 rs->waiting_for_stop_reply = 0;
10386
10387 /* If the current general thread belonged to the process we just
10388 detached from or has exited, the remote side current general
10389 thread becomes undefined. Considering a case like this:
10390
10391 - We just got here due to a detach.
10392 - The process that we're detaching from happens to immediately
10393 report a global breakpoint being hit in non-stop mode, in the
10394 same thread we had selected before.
10395 - GDB attaches to this process again.
10396 - This event happens to be the next event we handle.
10397
10398 GDB would consider that the current general thread didn't need to
10399 be set on the stub side (with Hg), since for all it knew,
10400 GENERAL_THREAD hadn't changed.
10401
10402 Notice that although in all-stop mode, the remote server always
10403 sets the current thread to the thread reporting the stop event,
10404 that doesn't happen in non-stop mode; in non-stop, the stub *must
10405 not* change the current thread when reporting a breakpoint hit,
10406 due to the decoupling of event reporting and event handling.
10407
10408 To keep things simple, we always invalidate our notion of the
10409 current thread. */
10410 record_currthread (rs, minus_one_ptid);
10411
10412 /* Call common code to mark the inferior as not running. */
10413 generic_mourn_inferior ();
10414 }
10415
10416 bool
10417 extended_remote_target::supports_disable_randomization ()
10418 {
10419 return (m_features.packet_support (PACKET_QDisableRandomization)
10420 == PACKET_ENABLE);
10421 }
10422
10423 void
10424 remote_target::extended_remote_disable_randomization (int val)
10425 {
10426 struct remote_state *rs = get_remote_state ();
10427 char *reply;
10428
10429 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10430 "QDisableRandomization:%x", val);
10431 putpkt (rs->buf);
10432 reply = remote_get_noisy_reply ();
10433 if (*reply == '\0')
10434 error (_("Target does not support QDisableRandomization."));
10435 if (strcmp (reply, "OK") != 0)
10436 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10437 }
10438
10439 int
10440 remote_target::extended_remote_run (const std::string &args)
10441 {
10442 struct remote_state *rs = get_remote_state ();
10443 int len;
10444 const char *remote_exec_file = get_remote_exec_file ();
10445
10446 /* If the user has disabled vRun support, or we have detected that
10447 support is not available, do not try it. */
10448 if (m_features.packet_support (PACKET_vRun) == PACKET_DISABLE)
10449 return -1;
10450
10451 strcpy (rs->buf.data (), "vRun;");
10452 len = strlen (rs->buf.data ());
10453
10454 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10455 error (_("Remote file name too long for run packet"));
10456 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10457 strlen (remote_exec_file));
10458
10459 if (!args.empty ())
10460 {
10461 int i;
10462
10463 gdb_argv argv (args.c_str ());
10464 for (i = 0; argv[i] != NULL; i++)
10465 {
10466 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10467 error (_("Argument list too long for run packet"));
10468 rs->buf[len++] = ';';
10469 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10470 strlen (argv[i]));
10471 }
10472 }
10473
10474 rs->buf[len++] = '\0';
10475
10476 putpkt (rs->buf);
10477 getpkt (&rs->buf);
10478
10479 switch (m_features.packet_ok (rs->buf, PACKET_vRun))
10480 {
10481 case PACKET_OK:
10482 /* We have a wait response. All is well. */
10483 return 0;
10484 case PACKET_UNKNOWN:
10485 return -1;
10486 case PACKET_ERROR:
10487 if (remote_exec_file[0] == '\0')
10488 error (_("Running the default executable on the remote target failed; "
10489 "try \"set remote exec-file\"?"));
10490 else
10491 error (_("Running \"%s\" on the remote target failed"),
10492 remote_exec_file);
10493 default:
10494 gdb_assert_not_reached ("bad switch");
10495 }
10496 }
10497
10498 /* Helper function to send set/unset environment packets. ACTION is
10499 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10500 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10501 sent. */
10502
10503 void
10504 remote_target::send_environment_packet (const char *action,
10505 const char *packet,
10506 const char *value)
10507 {
10508 remote_state *rs = get_remote_state ();
10509
10510 /* Convert the environment variable to an hex string, which
10511 is the best format to be transmitted over the wire. */
10512 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10513 strlen (value));
10514
10515 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10516 "%s:%s", packet, encoded_value.c_str ());
10517
10518 putpkt (rs->buf);
10519 getpkt (&rs->buf);
10520 if (strcmp (rs->buf.data (), "OK") != 0)
10521 warning (_("Unable to %s environment variable '%s' on remote."),
10522 action, value);
10523 }
10524
10525 /* Helper function to handle the QEnvironment* packets. */
10526
10527 void
10528 remote_target::extended_remote_environment_support ()
10529 {
10530 remote_state *rs = get_remote_state ();
10531
10532 if (m_features.packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10533 {
10534 putpkt ("QEnvironmentReset");
10535 getpkt (&rs->buf);
10536 if (strcmp (rs->buf.data (), "OK") != 0)
10537 warning (_("Unable to reset environment on remote."));
10538 }
10539
10540 gdb_environ *e = &current_inferior ()->environment;
10541
10542 if (m_features.packet_support (PACKET_QEnvironmentHexEncoded)
10543 != PACKET_DISABLE)
10544 {
10545 for (const std::string &el : e->user_set_env ())
10546 send_environment_packet ("set", "QEnvironmentHexEncoded",
10547 el.c_str ());
10548 }
10549
10550
10551 if (m_features.packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10552 for (const std::string &el : e->user_unset_env ())
10553 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10554 }
10555
10556 /* Helper function to set the current working directory for the
10557 inferior in the remote target. */
10558
10559 void
10560 remote_target::extended_remote_set_inferior_cwd ()
10561 {
10562 if (m_features.packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10563 {
10564 const std::string &inferior_cwd = current_inferior ()->cwd ();
10565 remote_state *rs = get_remote_state ();
10566
10567 if (!inferior_cwd.empty ())
10568 {
10569 std::string hexpath
10570 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10571 inferior_cwd.size ());
10572
10573 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10574 "QSetWorkingDir:%s", hexpath.c_str ());
10575 }
10576 else
10577 {
10578 /* An empty inferior_cwd means that the user wants us to
10579 reset the remote server's inferior's cwd. */
10580 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10581 "QSetWorkingDir:");
10582 }
10583
10584 putpkt (rs->buf);
10585 getpkt (&rs->buf);
10586 if (m_features.packet_ok (rs->buf, PACKET_QSetWorkingDir) != PACKET_OK)
10587 error (_("\
10588 Remote replied unexpectedly while setting the inferior's working\n\
10589 directory: %s"),
10590 rs->buf.data ());
10591
10592 }
10593 }
10594
10595 /* In the extended protocol we want to be able to do things like
10596 "run" and have them basically work as expected. So we need
10597 a special create_inferior function. We support changing the
10598 executable file and the command line arguments, but not the
10599 environment. */
10600
10601 void
10602 extended_remote_target::create_inferior (const char *exec_file,
10603 const std::string &args,
10604 char **env, int from_tty)
10605 {
10606 int run_worked;
10607 char *stop_reply;
10608 struct remote_state *rs = get_remote_state ();
10609 const char *remote_exec_file = get_remote_exec_file ();
10610
10611 /* If running asynchronously, register the target file descriptor
10612 with the event loop. */
10613 if (target_can_async_p ())
10614 target_async (true);
10615
10616 /* Disable address space randomization if requested (and supported). */
10617 if (supports_disable_randomization ())
10618 extended_remote_disable_randomization (disable_randomization);
10619
10620 /* If startup-with-shell is on, we inform gdbserver to start the
10621 remote inferior using a shell. */
10622 if (m_features.packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10623 {
10624 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10625 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10626 putpkt (rs->buf);
10627 getpkt (&rs->buf);
10628 if (strcmp (rs->buf.data (), "OK") != 0)
10629 error (_("\
10630 Remote replied unexpectedly while setting startup-with-shell: %s"),
10631 rs->buf.data ());
10632 }
10633
10634 extended_remote_environment_support ();
10635
10636 extended_remote_set_inferior_cwd ();
10637
10638 /* Now restart the remote server. */
10639 run_worked = extended_remote_run (args) != -1;
10640 if (!run_worked)
10641 {
10642 /* vRun was not supported. Fail if we need it to do what the
10643 user requested. */
10644 if (remote_exec_file[0])
10645 error (_("Remote target does not support \"set remote exec-file\""));
10646 if (!args.empty ())
10647 error (_("Remote target does not support \"set args\" or run ARGS"));
10648
10649 /* Fall back to "R". */
10650 extended_remote_restart ();
10651 }
10652
10653 /* vRun's success return is a stop reply. */
10654 stop_reply = run_worked ? rs->buf.data () : NULL;
10655 add_current_inferior_and_thread (stop_reply);
10656
10657 /* Get updated offsets, if the stub uses qOffsets. */
10658 get_offsets ();
10659 }
10660 \f
10661
10662 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10663 the list of conditions (in agent expression bytecode format), if any, the
10664 target needs to evaluate. The output is placed into the packet buffer
10665 started from BUF and ended at BUF_END. */
10666
10667 static int
10668 remote_add_target_side_condition (struct gdbarch *gdbarch,
10669 struct bp_target_info *bp_tgt, char *buf,
10670 char *buf_end)
10671 {
10672 if (bp_tgt->conditions.empty ())
10673 return 0;
10674
10675 buf += strlen (buf);
10676 xsnprintf (buf, buf_end - buf, "%s", ";");
10677 buf++;
10678
10679 /* Send conditions to the target. */
10680 for (agent_expr *aexpr : bp_tgt->conditions)
10681 {
10682 xsnprintf (buf, buf_end - buf, "X%x,", (int) aexpr->buf.size ());
10683 buf += strlen (buf);
10684 for (int i = 0; i < aexpr->buf.size (); ++i)
10685 buf = pack_hex_byte (buf, aexpr->buf[i]);
10686 *buf = '\0';
10687 }
10688 return 0;
10689 }
10690
10691 static void
10692 remote_add_target_side_commands (struct gdbarch *gdbarch,
10693 struct bp_target_info *bp_tgt, char *buf)
10694 {
10695 if (bp_tgt->tcommands.empty ())
10696 return;
10697
10698 buf += strlen (buf);
10699
10700 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10701 buf += strlen (buf);
10702
10703 /* Concatenate all the agent expressions that are commands into the
10704 cmds parameter. */
10705 for (agent_expr *aexpr : bp_tgt->tcommands)
10706 {
10707 sprintf (buf, "X%x,", (int) aexpr->buf.size ());
10708 buf += strlen (buf);
10709 for (int i = 0; i < aexpr->buf.size (); ++i)
10710 buf = pack_hex_byte (buf, aexpr->buf[i]);
10711 *buf = '\0';
10712 }
10713 }
10714
10715 /* Insert a breakpoint. On targets that have software breakpoint
10716 support, we ask the remote target to do the work; on targets
10717 which don't, we insert a traditional memory breakpoint. */
10718
10719 int
10720 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10721 struct bp_target_info *bp_tgt)
10722 {
10723 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10724 If it succeeds, then set the support to PACKET_ENABLE. If it
10725 fails, and the user has explicitly requested the Z support then
10726 report an error, otherwise, mark it disabled and go on. */
10727
10728 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
10729 {
10730 CORE_ADDR addr = bp_tgt->reqstd_address;
10731 struct remote_state *rs;
10732 char *p, *endbuf;
10733
10734 /* Make sure the remote is pointing at the right process, if
10735 necessary. */
10736 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10737 set_general_process ();
10738
10739 rs = get_remote_state ();
10740 p = rs->buf.data ();
10741 endbuf = p + get_remote_packet_size ();
10742
10743 *(p++) = 'Z';
10744 *(p++) = '0';
10745 *(p++) = ',';
10746 addr = (ULONGEST) remote_address_masked (addr);
10747 p += hexnumstr (p, addr);
10748 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10749
10750 if (supports_evaluation_of_breakpoint_conditions ())
10751 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10752
10753 if (can_run_breakpoint_commands ())
10754 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10755
10756 putpkt (rs->buf);
10757 getpkt (&rs->buf);
10758
10759 switch (m_features.packet_ok (rs->buf, PACKET_Z0))
10760 {
10761 case PACKET_ERROR:
10762 return -1;
10763 case PACKET_OK:
10764 return 0;
10765 case PACKET_UNKNOWN:
10766 break;
10767 }
10768 }
10769
10770 /* If this breakpoint has target-side commands but this stub doesn't
10771 support Z0 packets, throw error. */
10772 if (!bp_tgt->tcommands.empty ())
10773 throw_error (NOT_SUPPORTED_ERROR, _("\
10774 Target doesn't support breakpoints that have target side commands."));
10775
10776 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10777 }
10778
10779 int
10780 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10781 struct bp_target_info *bp_tgt,
10782 enum remove_bp_reason reason)
10783 {
10784 CORE_ADDR addr = bp_tgt->placed_address;
10785 struct remote_state *rs = get_remote_state ();
10786
10787 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
10788 {
10789 char *p = rs->buf.data ();
10790 char *endbuf = p + get_remote_packet_size ();
10791
10792 /* Make sure the remote is pointing at the right process, if
10793 necessary. */
10794 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10795 set_general_process ();
10796
10797 *(p++) = 'z';
10798 *(p++) = '0';
10799 *(p++) = ',';
10800
10801 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10802 p += hexnumstr (p, addr);
10803 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10804
10805 putpkt (rs->buf);
10806 getpkt (&rs->buf);
10807
10808 return (rs->buf[0] == 'E');
10809 }
10810
10811 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10812 }
10813
10814 static enum Z_packet_type
10815 watchpoint_to_Z_packet (int type)
10816 {
10817 switch (type)
10818 {
10819 case hw_write:
10820 return Z_PACKET_WRITE_WP;
10821 break;
10822 case hw_read:
10823 return Z_PACKET_READ_WP;
10824 break;
10825 case hw_access:
10826 return Z_PACKET_ACCESS_WP;
10827 break;
10828 default:
10829 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
10830 }
10831 }
10832
10833 int
10834 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10835 enum target_hw_bp_type type, struct expression *cond)
10836 {
10837 struct remote_state *rs = get_remote_state ();
10838 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10839 char *p;
10840 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10841
10842 if (m_features.packet_support ((to_underlying (PACKET_Z0)
10843 + to_underlying (packet))) == PACKET_DISABLE)
10844 return 1;
10845
10846 /* Make sure the remote is pointing at the right process, if
10847 necessary. */
10848 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10849 set_general_process ();
10850
10851 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10852 p = strchr (rs->buf.data (), '\0');
10853 addr = remote_address_masked (addr);
10854 p += hexnumstr (p, (ULONGEST) addr);
10855 xsnprintf (p, endbuf - p, ",%x", len);
10856
10857 putpkt (rs->buf);
10858 getpkt (&rs->buf);
10859
10860 switch (m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
10861 + to_underlying (packet))))
10862 {
10863 case PACKET_ERROR:
10864 return -1;
10865 case PACKET_UNKNOWN:
10866 return 1;
10867 case PACKET_OK:
10868 return 0;
10869 }
10870 internal_error (_("remote_insert_watchpoint: reached end of function"));
10871 }
10872
10873 bool
10874 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10875 CORE_ADDR start, int length)
10876 {
10877 CORE_ADDR diff = remote_address_masked (addr - start);
10878
10879 return diff < length;
10880 }
10881
10882
10883 int
10884 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10885 enum target_hw_bp_type type, struct expression *cond)
10886 {
10887 struct remote_state *rs = get_remote_state ();
10888 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10889 char *p;
10890 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10891
10892 if (m_features.packet_support ((to_underlying (PACKET_Z0)
10893 + to_underlying (packet))) == PACKET_DISABLE)
10894 return -1;
10895
10896 /* Make sure the remote is pointing at the right process, if
10897 necessary. */
10898 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10899 set_general_process ();
10900
10901 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10902 p = strchr (rs->buf.data (), '\0');
10903 addr = remote_address_masked (addr);
10904 p += hexnumstr (p, (ULONGEST) addr);
10905 xsnprintf (p, endbuf - p, ",%x", len);
10906 putpkt (rs->buf);
10907 getpkt (&rs->buf);
10908
10909 switch (m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
10910 + to_underlying (packet))))
10911 {
10912 case PACKET_ERROR:
10913 case PACKET_UNKNOWN:
10914 return -1;
10915 case PACKET_OK:
10916 return 0;
10917 }
10918 internal_error (_("remote_remove_watchpoint: reached end of function"));
10919 }
10920
10921
10922 static int remote_hw_watchpoint_limit = -1;
10923 static int remote_hw_watchpoint_length_limit = -1;
10924 static int remote_hw_breakpoint_limit = -1;
10925
10926 int
10927 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10928 {
10929 if (remote_hw_watchpoint_length_limit == 0)
10930 return 0;
10931 else if (remote_hw_watchpoint_length_limit < 0)
10932 return 1;
10933 else if (len <= remote_hw_watchpoint_length_limit)
10934 return 1;
10935 else
10936 return 0;
10937 }
10938
10939 int
10940 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10941 {
10942 if (type == bp_hardware_breakpoint)
10943 {
10944 if (remote_hw_breakpoint_limit == 0)
10945 return 0;
10946 else if (remote_hw_breakpoint_limit < 0)
10947 return 1;
10948 else if (cnt <= remote_hw_breakpoint_limit)
10949 return 1;
10950 }
10951 else
10952 {
10953 if (remote_hw_watchpoint_limit == 0)
10954 return 0;
10955 else if (remote_hw_watchpoint_limit < 0)
10956 return 1;
10957 else if (ot)
10958 return -1;
10959 else if (cnt <= remote_hw_watchpoint_limit)
10960 return 1;
10961 }
10962 return -1;
10963 }
10964
10965 /* The to_stopped_by_sw_breakpoint method of target remote. */
10966
10967 bool
10968 remote_target::stopped_by_sw_breakpoint ()
10969 {
10970 struct thread_info *thread = inferior_thread ();
10971
10972 return (thread->priv != NULL
10973 && (get_remote_thread_info (thread)->stop_reason
10974 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10975 }
10976
10977 /* The to_supports_stopped_by_sw_breakpoint method of target
10978 remote. */
10979
10980 bool
10981 remote_target::supports_stopped_by_sw_breakpoint ()
10982 {
10983 return (m_features.packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10984 }
10985
10986 /* The to_stopped_by_hw_breakpoint method of target remote. */
10987
10988 bool
10989 remote_target::stopped_by_hw_breakpoint ()
10990 {
10991 struct thread_info *thread = inferior_thread ();
10992
10993 return (thread->priv != NULL
10994 && (get_remote_thread_info (thread)->stop_reason
10995 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10996 }
10997
10998 /* The to_supports_stopped_by_hw_breakpoint method of target
10999 remote. */
11000
11001 bool
11002 remote_target::supports_stopped_by_hw_breakpoint ()
11003 {
11004 return (m_features.packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
11005 }
11006
11007 bool
11008 remote_target::stopped_by_watchpoint ()
11009 {
11010 struct thread_info *thread = inferior_thread ();
11011
11012 return (thread->priv != NULL
11013 && (get_remote_thread_info (thread)->stop_reason
11014 == TARGET_STOPPED_BY_WATCHPOINT));
11015 }
11016
11017 bool
11018 remote_target::stopped_data_address (CORE_ADDR *addr_p)
11019 {
11020 struct thread_info *thread = inferior_thread ();
11021
11022 if (thread->priv != NULL
11023 && (get_remote_thread_info (thread)->stop_reason
11024 == TARGET_STOPPED_BY_WATCHPOINT))
11025 {
11026 *addr_p = get_remote_thread_info (thread)->watch_data_address;
11027 return true;
11028 }
11029
11030 return false;
11031 }
11032
11033
11034 int
11035 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
11036 struct bp_target_info *bp_tgt)
11037 {
11038 CORE_ADDR addr = bp_tgt->reqstd_address;
11039 struct remote_state *rs;
11040 char *p, *endbuf;
11041 char *message;
11042
11043 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11044 return -1;
11045
11046 /* Make sure the remote is pointing at the right process, if
11047 necessary. */
11048 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11049 set_general_process ();
11050
11051 rs = get_remote_state ();
11052 p = rs->buf.data ();
11053 endbuf = p + get_remote_packet_size ();
11054
11055 *(p++) = 'Z';
11056 *(p++) = '1';
11057 *(p++) = ',';
11058
11059 addr = remote_address_masked (addr);
11060 p += hexnumstr (p, (ULONGEST) addr);
11061 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11062
11063 if (supports_evaluation_of_breakpoint_conditions ())
11064 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
11065
11066 if (can_run_breakpoint_commands ())
11067 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11068
11069 putpkt (rs->buf);
11070 getpkt (&rs->buf);
11071
11072 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
11073 {
11074 case PACKET_ERROR:
11075 if (rs->buf[1] == '.')
11076 {
11077 message = strchr (&rs->buf[2], '.');
11078 if (message)
11079 error (_("Remote failure reply: %s"), message + 1);
11080 }
11081 return -1;
11082 case PACKET_UNKNOWN:
11083 return -1;
11084 case PACKET_OK:
11085 return 0;
11086 }
11087 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
11088 }
11089
11090
11091 int
11092 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
11093 struct bp_target_info *bp_tgt)
11094 {
11095 CORE_ADDR addr;
11096 struct remote_state *rs = get_remote_state ();
11097 char *p = rs->buf.data ();
11098 char *endbuf = p + get_remote_packet_size ();
11099
11100 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11101 return -1;
11102
11103 /* Make sure the remote is pointing at the right process, if
11104 necessary. */
11105 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11106 set_general_process ();
11107
11108 *(p++) = 'z';
11109 *(p++) = '1';
11110 *(p++) = ',';
11111
11112 addr = remote_address_masked (bp_tgt->placed_address);
11113 p += hexnumstr (p, (ULONGEST) addr);
11114 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11115
11116 putpkt (rs->buf);
11117 getpkt (&rs->buf);
11118
11119 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
11120 {
11121 case PACKET_ERROR:
11122 case PACKET_UNKNOWN:
11123 return -1;
11124 case PACKET_OK:
11125 return 0;
11126 }
11127 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
11128 }
11129
11130 /* Verify memory using the "qCRC:" request. */
11131
11132 int
11133 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
11134 {
11135 struct remote_state *rs = get_remote_state ();
11136 unsigned long host_crc, target_crc;
11137 char *tmp;
11138
11139 /* It doesn't make sense to use qCRC if the remote target is
11140 connected but not running. */
11141 if (target_has_execution ()
11142 && m_features.packet_support (PACKET_qCRC) != PACKET_DISABLE)
11143 {
11144 enum packet_result result;
11145
11146 /* Make sure the remote is pointing at the right process. */
11147 set_general_process ();
11148
11149 /* FIXME: assumes lma can fit into long. */
11150 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
11151 (long) lma, (long) size);
11152 putpkt (rs->buf);
11153
11154 /* Be clever; compute the host_crc before waiting for target
11155 reply. */
11156 host_crc = xcrc32 (data, size, 0xffffffff);
11157
11158 getpkt (&rs->buf);
11159
11160 result = m_features.packet_ok (rs->buf, PACKET_qCRC);
11161 if (result == PACKET_ERROR)
11162 return -1;
11163 else if (result == PACKET_OK)
11164 {
11165 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11166 target_crc = target_crc * 16 + fromhex (*tmp);
11167
11168 return (host_crc == target_crc);
11169 }
11170 }
11171
11172 return simple_verify_memory (this, data, lma, size);
11173 }
11174
11175 /* compare-sections command
11176
11177 With no arguments, compares each loadable section in the exec bfd
11178 with the same memory range on the target, and reports mismatches.
11179 Useful for verifying the image on the target against the exec file. */
11180
11181 static void
11182 compare_sections_command (const char *args, int from_tty)
11183 {
11184 asection *s;
11185 const char *sectname;
11186 bfd_size_type size;
11187 bfd_vma lma;
11188 int matched = 0;
11189 int mismatched = 0;
11190 int res;
11191 int read_only = 0;
11192
11193 if (!current_program_space->exec_bfd ())
11194 error (_("command cannot be used without an exec file"));
11195
11196 if (args != NULL && strcmp (args, "-r") == 0)
11197 {
11198 read_only = 1;
11199 args = NULL;
11200 }
11201
11202 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11203 {
11204 if (!(s->flags & SEC_LOAD))
11205 continue; /* Skip non-loadable section. */
11206
11207 if (read_only && (s->flags & SEC_READONLY) == 0)
11208 continue; /* Skip writeable sections */
11209
11210 size = bfd_section_size (s);
11211 if (size == 0)
11212 continue; /* Skip zero-length section. */
11213
11214 sectname = bfd_section_name (s);
11215 if (args && strcmp (args, sectname) != 0)
11216 continue; /* Not the section selected by user. */
11217
11218 matched = 1; /* Do this section. */
11219 lma = s->lma;
11220
11221 gdb::byte_vector sectdata (size);
11222 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11223 sectdata.data (), 0, size);
11224
11225 res = target_verify_memory (sectdata.data (), lma, size);
11226
11227 if (res == -1)
11228 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11229 paddress (current_inferior ()->arch (), lma),
11230 paddress (current_inferior ()->arch (), lma + size));
11231
11232 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11233 paddress (current_inferior ()->arch (), lma),
11234 paddress (current_inferior ()->arch (), lma + size));
11235 if (res)
11236 gdb_printf ("matched.\n");
11237 else
11238 {
11239 gdb_printf ("MIS-MATCHED!\n");
11240 mismatched++;
11241 }
11242 }
11243 if (mismatched > 0)
11244 warning (_("One or more sections of the target image does "
11245 "not match the loaded file"));
11246 if (args && !matched)
11247 gdb_printf (_("No loaded section named '%s'.\n"), args);
11248 }
11249
11250 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11251 into remote target. The number of bytes written to the remote
11252 target is returned, or -1 for error. */
11253
11254 target_xfer_status
11255 remote_target::remote_write_qxfer (const char *object_name,
11256 const char *annex, const gdb_byte *writebuf,
11257 ULONGEST offset, LONGEST len,
11258 ULONGEST *xfered_len,
11259 const unsigned int which_packet)
11260 {
11261 int i, buf_len;
11262 ULONGEST n;
11263 struct remote_state *rs = get_remote_state ();
11264 int max_size = get_memory_write_packet_size ();
11265
11266 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11267 return TARGET_XFER_E_IO;
11268
11269 /* Insert header. */
11270 i = snprintf (rs->buf.data (), max_size,
11271 "qXfer:%s:write:%s:%s:",
11272 object_name, annex ? annex : "",
11273 phex_nz (offset, sizeof offset));
11274 max_size -= (i + 1);
11275
11276 /* Escape as much data as fits into rs->buf. */
11277 buf_len = remote_escape_output
11278 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11279
11280 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11281 || getpkt (&rs->buf) < 0
11282 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
11283 return TARGET_XFER_E_IO;
11284
11285 unpack_varlen_hex (rs->buf.data (), &n);
11286
11287 *xfered_len = n;
11288 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11289 }
11290
11291 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11292 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11293 number of bytes read is returned, or 0 for EOF, or -1 for error.
11294 The number of bytes read may be less than LEN without indicating an
11295 EOF. PACKET is checked and updated to indicate whether the remote
11296 target supports this object. */
11297
11298 target_xfer_status
11299 remote_target::remote_read_qxfer (const char *object_name,
11300 const char *annex,
11301 gdb_byte *readbuf, ULONGEST offset,
11302 LONGEST len,
11303 ULONGEST *xfered_len,
11304 const unsigned int which_packet)
11305 {
11306 struct remote_state *rs = get_remote_state ();
11307 LONGEST i, n, packet_len;
11308
11309 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11310 return TARGET_XFER_E_IO;
11311
11312 /* Check whether we've cached an end-of-object packet that matches
11313 this request. */
11314 if (rs->finished_object)
11315 {
11316 if (strcmp (object_name, rs->finished_object) == 0
11317 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11318 && offset == rs->finished_offset)
11319 return TARGET_XFER_EOF;
11320
11321
11322 /* Otherwise, we're now reading something different. Discard
11323 the cache. */
11324 xfree (rs->finished_object);
11325 xfree (rs->finished_annex);
11326 rs->finished_object = NULL;
11327 rs->finished_annex = NULL;
11328 }
11329
11330 /* Request only enough to fit in a single packet. The actual data
11331 may not, since we don't know how much of it will need to be escaped;
11332 the target is free to respond with slightly less data. We subtract
11333 five to account for the response type and the protocol frame. */
11334 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11335 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11336 "qXfer:%s:read:%s:%s,%s",
11337 object_name, annex ? annex : "",
11338 phex_nz (offset, sizeof offset),
11339 phex_nz (n, sizeof n));
11340 i = putpkt (rs->buf);
11341 if (i < 0)
11342 return TARGET_XFER_E_IO;
11343
11344 rs->buf[0] = '\0';
11345 packet_len = getpkt (&rs->buf);
11346 if (packet_len < 0
11347 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
11348 return TARGET_XFER_E_IO;
11349
11350 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11351 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11352
11353 /* 'm' means there is (or at least might be) more data after this
11354 batch. That does not make sense unless there's at least one byte
11355 of data in this reply. */
11356 if (rs->buf[0] == 'm' && packet_len == 1)
11357 error (_("Remote qXfer reply contained no data."));
11358
11359 /* Got some data. */
11360 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11361 packet_len - 1, readbuf, n);
11362
11363 /* 'l' is an EOF marker, possibly including a final block of data,
11364 or possibly empty. If we have the final block of a non-empty
11365 object, record this fact to bypass a subsequent partial read. */
11366 if (rs->buf[0] == 'l' && offset + i > 0)
11367 {
11368 rs->finished_object = xstrdup (object_name);
11369 rs->finished_annex = xstrdup (annex ? annex : "");
11370 rs->finished_offset = offset + i;
11371 }
11372
11373 if (i == 0)
11374 return TARGET_XFER_EOF;
11375 else
11376 {
11377 *xfered_len = i;
11378 return TARGET_XFER_OK;
11379 }
11380 }
11381
11382 enum target_xfer_status
11383 remote_target::xfer_partial (enum target_object object,
11384 const char *annex, gdb_byte *readbuf,
11385 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11386 ULONGEST *xfered_len)
11387 {
11388 struct remote_state *rs;
11389 int i;
11390 char *p2;
11391 char query_type;
11392 int unit_size
11393 = gdbarch_addressable_memory_unit_size (current_inferior ()->arch ());
11394
11395 set_remote_traceframe ();
11396 set_general_thread (inferior_ptid);
11397
11398 rs = get_remote_state ();
11399
11400 /* Handle memory using the standard memory routines. */
11401 if (object == TARGET_OBJECT_MEMORY)
11402 {
11403 /* If the remote target is connected but not running, we should
11404 pass this request down to a lower stratum (e.g. the executable
11405 file). */
11406 if (!target_has_execution ())
11407 return TARGET_XFER_EOF;
11408
11409 if (writebuf != NULL)
11410 return remote_write_bytes (offset, writebuf, len, unit_size,
11411 xfered_len);
11412 else
11413 return remote_read_bytes (offset, readbuf, len, unit_size,
11414 xfered_len);
11415 }
11416
11417 /* Handle extra signal info using qxfer packets. */
11418 if (object == TARGET_OBJECT_SIGNAL_INFO)
11419 {
11420 if (readbuf)
11421 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11422 xfered_len, PACKET_qXfer_siginfo_read);
11423 else
11424 return remote_write_qxfer ("siginfo", annex, writebuf, offset, len,
11425 xfered_len, PACKET_qXfer_siginfo_write);
11426 }
11427
11428 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11429 {
11430 if (readbuf)
11431 return remote_read_qxfer ("statictrace", annex,
11432 readbuf, offset, len, xfered_len,
11433 PACKET_qXfer_statictrace_read);
11434 else
11435 return TARGET_XFER_E_IO;
11436 }
11437
11438 /* Only handle flash writes. */
11439 if (writebuf != NULL)
11440 {
11441 switch (object)
11442 {
11443 case TARGET_OBJECT_FLASH:
11444 return remote_flash_write (offset, len, xfered_len,
11445 writebuf);
11446
11447 default:
11448 return TARGET_XFER_E_IO;
11449 }
11450 }
11451
11452 /* Map pre-existing objects onto letters. DO NOT do this for new
11453 objects!!! Instead specify new query packets. */
11454 switch (object)
11455 {
11456 case TARGET_OBJECT_AVR:
11457 query_type = 'R';
11458 break;
11459
11460 case TARGET_OBJECT_AUXV:
11461 gdb_assert (annex == NULL);
11462 return remote_read_qxfer
11463 ("auxv", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_auxv);
11464
11465 case TARGET_OBJECT_AVAILABLE_FEATURES:
11466 return remote_read_qxfer
11467 ("features", annex, readbuf, offset, len, xfered_len,
11468 PACKET_qXfer_features);
11469
11470 case TARGET_OBJECT_LIBRARIES:
11471 return remote_read_qxfer
11472 ("libraries", annex, readbuf, offset, len, xfered_len,
11473 PACKET_qXfer_libraries);
11474
11475 case TARGET_OBJECT_LIBRARIES_SVR4:
11476 return remote_read_qxfer
11477 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11478 PACKET_qXfer_libraries_svr4);
11479
11480 case TARGET_OBJECT_MEMORY_MAP:
11481 gdb_assert (annex == NULL);
11482 return remote_read_qxfer
11483 ("memory-map", annex, readbuf, offset, len, xfered_len,
11484 PACKET_qXfer_memory_map);
11485
11486 case TARGET_OBJECT_OSDATA:
11487 /* Should only get here if we're connected. */
11488 gdb_assert (rs->remote_desc);
11489 return remote_read_qxfer
11490 ("osdata", annex, readbuf, offset, len, xfered_len,
11491 PACKET_qXfer_osdata);
11492
11493 case TARGET_OBJECT_THREADS:
11494 gdb_assert (annex == NULL);
11495 return remote_read_qxfer
11496 ("threads", annex, readbuf, offset, len, xfered_len,
11497 PACKET_qXfer_threads);
11498
11499 case TARGET_OBJECT_TRACEFRAME_INFO:
11500 gdb_assert (annex == NULL);
11501 return remote_read_qxfer
11502 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11503 PACKET_qXfer_traceframe_info);
11504
11505 case TARGET_OBJECT_FDPIC:
11506 return remote_read_qxfer
11507 ("fdpic", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_fdpic);
11508
11509 case TARGET_OBJECT_OPENVMS_UIB:
11510 return remote_read_qxfer
11511 ("uib", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_uib);
11512
11513 case TARGET_OBJECT_BTRACE:
11514 return remote_read_qxfer
11515 ("btrace", annex, readbuf, offset, len, xfered_len,
11516 PACKET_qXfer_btrace);
11517
11518 case TARGET_OBJECT_BTRACE_CONF:
11519 return remote_read_qxfer
11520 ("btrace-conf", annex, readbuf, offset, len, xfered_len,
11521 PACKET_qXfer_btrace_conf);
11522
11523 case TARGET_OBJECT_EXEC_FILE:
11524 return remote_read_qxfer
11525 ("exec-file", annex, readbuf, offset, len, xfered_len,
11526 PACKET_qXfer_exec_file);
11527
11528 default:
11529 return TARGET_XFER_E_IO;
11530 }
11531
11532 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11533 large enough let the caller deal with it. */
11534 if (len < get_remote_packet_size ())
11535 return TARGET_XFER_E_IO;
11536 len = get_remote_packet_size ();
11537
11538 /* Except for querying the minimum buffer size, target must be open. */
11539 if (!rs->remote_desc)
11540 error (_("remote query is only available after target open"));
11541
11542 gdb_assert (annex != NULL);
11543 gdb_assert (readbuf != NULL);
11544
11545 p2 = rs->buf.data ();
11546 *p2++ = 'q';
11547 *p2++ = query_type;
11548
11549 /* We used one buffer char for the remote protocol q command and
11550 another for the query type. As the remote protocol encapsulation
11551 uses 4 chars plus one extra in case we are debugging
11552 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11553 string. */
11554 i = 0;
11555 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11556 {
11557 /* Bad caller may have sent forbidden characters. */
11558 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11559 *p2++ = annex[i];
11560 i++;
11561 }
11562 *p2 = '\0';
11563 gdb_assert (annex[i] == '\0');
11564
11565 i = putpkt (rs->buf);
11566 if (i < 0)
11567 return TARGET_XFER_E_IO;
11568
11569 getpkt (&rs->buf);
11570 strcpy ((char *) readbuf, rs->buf.data ());
11571
11572 *xfered_len = strlen ((char *) readbuf);
11573 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11574 }
11575
11576 /* Implementation of to_get_memory_xfer_limit. */
11577
11578 ULONGEST
11579 remote_target::get_memory_xfer_limit ()
11580 {
11581 return get_memory_write_packet_size ();
11582 }
11583
11584 int
11585 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11586 const gdb_byte *pattern, ULONGEST pattern_len,
11587 CORE_ADDR *found_addrp)
11588 {
11589 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
11590 struct remote_state *rs = get_remote_state ();
11591 int max_size = get_memory_write_packet_size ();
11592
11593 /* Number of packet bytes used to encode the pattern;
11594 this could be more than PATTERN_LEN due to escape characters. */
11595 int escaped_pattern_len;
11596 /* Amount of pattern that was encodable in the packet. */
11597 int used_pattern_len;
11598 int i;
11599 int found;
11600 ULONGEST found_addr;
11601
11602 auto read_memory = [this] (CORE_ADDR addr, gdb_byte *result, size_t len)
11603 {
11604 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11605 == len);
11606 };
11607
11608 /* Don't go to the target if we don't have to. This is done before
11609 checking packet_support to avoid the possibility that a success for this
11610 edge case means the facility works in general. */
11611 if (pattern_len > search_space_len)
11612 return 0;
11613 if (pattern_len == 0)
11614 {
11615 *found_addrp = start_addr;
11616 return 1;
11617 }
11618
11619 /* If we already know the packet isn't supported, fall back to the simple
11620 way of searching memory. */
11621
11622 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11623 {
11624 /* Target doesn't provided special support, fall back and use the
11625 standard support (copy memory and do the search here). */
11626 return simple_search_memory (read_memory, start_addr, search_space_len,
11627 pattern, pattern_len, found_addrp);
11628 }
11629
11630 /* Make sure the remote is pointing at the right process. */
11631 set_general_process ();
11632
11633 /* Insert header. */
11634 i = snprintf (rs->buf.data (), max_size,
11635 "qSearch:memory:%s;%s;",
11636 phex_nz (start_addr, addr_size),
11637 phex_nz (search_space_len, sizeof (search_space_len)));
11638 max_size -= (i + 1);
11639
11640 /* Escape as much data as fits into rs->buf. */
11641 escaped_pattern_len =
11642 remote_escape_output (pattern, pattern_len, 1,
11643 (gdb_byte *) rs->buf.data () + i,
11644 &used_pattern_len, max_size);
11645
11646 /* Bail if the pattern is too large. */
11647 if (used_pattern_len != pattern_len)
11648 error (_("Pattern is too large to transmit to remote target."));
11649
11650 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11651 || getpkt (&rs->buf) < 0
11652 || m_features.packet_ok (rs->buf, PACKET_qSearch_memory) != PACKET_OK)
11653 {
11654 /* The request may not have worked because the command is not
11655 supported. If so, fall back to the simple way. */
11656 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11657 {
11658 return simple_search_memory (read_memory, start_addr, search_space_len,
11659 pattern, pattern_len, found_addrp);
11660 }
11661 return -1;
11662 }
11663
11664 if (rs->buf[0] == '0')
11665 found = 0;
11666 else if (rs->buf[0] == '1')
11667 {
11668 found = 1;
11669 if (rs->buf[1] != ',')
11670 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11671 unpack_varlen_hex (&rs->buf[2], &found_addr);
11672 *found_addrp = found_addr;
11673 }
11674 else
11675 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11676
11677 return found;
11678 }
11679
11680 void
11681 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11682 {
11683 struct remote_state *rs = get_remote_state ();
11684 char *p = rs->buf.data ();
11685
11686 if (!rs->remote_desc)
11687 error (_("remote rcmd is only available after target open"));
11688
11689 /* Send a NULL command across as an empty command. */
11690 if (command == NULL)
11691 command = "";
11692
11693 /* The query prefix. */
11694 strcpy (rs->buf.data (), "qRcmd,");
11695 p = strchr (rs->buf.data (), '\0');
11696
11697 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11698 > get_remote_packet_size ())
11699 error (_("\"monitor\" command ``%s'' is too long."), command);
11700
11701 /* Encode the actual command. */
11702 bin2hex ((const gdb_byte *) command, p, strlen (command));
11703
11704 if (putpkt (rs->buf) < 0)
11705 error (_("Communication problem with target."));
11706
11707 /* get/display the response */
11708 while (1)
11709 {
11710 char *buf;
11711
11712 /* XXX - see also remote_get_noisy_reply(). */
11713 QUIT; /* Allow user to bail out with ^C. */
11714 rs->buf[0] = '\0';
11715 if (getpkt (&rs->buf) == -1)
11716 {
11717 /* Timeout. Continue to (try to) read responses.
11718 This is better than stopping with an error, assuming the stub
11719 is still executing the (long) monitor command.
11720 If needed, the user can interrupt gdb using C-c, obtaining
11721 an effect similar to stop on timeout. */
11722 continue;
11723 }
11724 buf = rs->buf.data ();
11725 if (buf[0] == '\0')
11726 error (_("Target does not support this command."));
11727 if (buf[0] == 'O' && buf[1] != 'K')
11728 {
11729 remote_console_output (buf + 1); /* 'O' message from stub. */
11730 continue;
11731 }
11732 if (strcmp (buf, "OK") == 0)
11733 break;
11734 if (strlen (buf) == 3 && buf[0] == 'E'
11735 && isxdigit (buf[1]) && isxdigit (buf[2]))
11736 {
11737 error (_("Protocol error with Rcmd"));
11738 }
11739 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11740 {
11741 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11742
11743 gdb_putc (c, outbuf);
11744 }
11745 break;
11746 }
11747 }
11748
11749 std::vector<mem_region>
11750 remote_target::memory_map ()
11751 {
11752 std::vector<mem_region> result;
11753 gdb::optional<gdb::char_vector> text
11754 = target_read_stralloc (current_inferior ()->top_target (),
11755 TARGET_OBJECT_MEMORY_MAP, NULL);
11756
11757 if (text)
11758 result = parse_memory_map (text->data ());
11759
11760 return result;
11761 }
11762
11763 /* Set of callbacks used to implement the 'maint packet' command. */
11764
11765 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
11766 {
11767 /* Called before the packet is sent. BUF is the packet content before
11768 the protocol specific prefix, suffix, and escaping is added. */
11769
11770 void sending (gdb::array_view<const char> &buf) override
11771 {
11772 gdb_puts ("sending: ");
11773 print_packet (buf);
11774 gdb_puts ("\n");
11775 }
11776
11777 /* Called with BUF, the reply from the remote target. */
11778
11779 void received (gdb::array_view<const char> &buf) override
11780 {
11781 gdb_puts ("received: \"");
11782 print_packet (buf);
11783 gdb_puts ("\"\n");
11784 }
11785
11786 private:
11787
11788 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11789 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11790
11791 static void
11792 print_packet (gdb::array_view<const char> &buf)
11793 {
11794 string_file stb;
11795
11796 for (int i = 0; i < buf.size (); ++i)
11797 {
11798 gdb_byte c = buf[i];
11799 if (isprint (c))
11800 gdb_putc (c, &stb);
11801 else
11802 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
11803 }
11804
11805 gdb_puts (stb.string ().c_str ());
11806 }
11807 };
11808
11809 /* See remote.h. */
11810
11811 void
11812 send_remote_packet (gdb::array_view<const char> &buf,
11813 send_remote_packet_callbacks *callbacks)
11814 {
11815 if (buf.size () == 0 || buf.data ()[0] == '\0')
11816 error (_("a remote packet must not be empty"));
11817
11818 remote_target *remote = get_current_remote_target ();
11819 if (remote == nullptr)
11820 error (_("packets can only be sent to a remote target"));
11821
11822 callbacks->sending (buf);
11823
11824 remote->putpkt_binary (buf.data (), buf.size ());
11825 remote_state *rs = remote->get_remote_state ();
11826 int bytes = remote->getpkt (&rs->buf);
11827
11828 if (bytes < 0)
11829 error (_("error while fetching packet from remote target"));
11830
11831 gdb::array_view<const char> view (&rs->buf[0], bytes);
11832 callbacks->received (view);
11833 }
11834
11835 /* Entry point for the 'maint packet' command. */
11836
11837 static void
11838 cli_packet_command (const char *args, int from_tty)
11839 {
11840 cli_packet_command_callbacks cb;
11841 gdb::array_view<const char> view
11842 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11843 send_remote_packet (view, &cb);
11844 }
11845
11846 #if 0
11847 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11848
11849 static void display_thread_info (struct gdb_ext_thread_info *info);
11850
11851 static void threadset_test_cmd (char *cmd, int tty);
11852
11853 static void threadalive_test (char *cmd, int tty);
11854
11855 static void threadlist_test_cmd (char *cmd, int tty);
11856
11857 int get_and_display_threadinfo (threadref *ref);
11858
11859 static void threadinfo_test_cmd (char *cmd, int tty);
11860
11861 static int thread_display_step (threadref *ref, void *context);
11862
11863 static void threadlist_update_test_cmd (char *cmd, int tty);
11864
11865 static void init_remote_threadtests (void);
11866
11867 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11868
11869 static void
11870 threadset_test_cmd (const char *cmd, int tty)
11871 {
11872 int sample_thread = SAMPLE_THREAD;
11873
11874 gdb_printf (_("Remote threadset test\n"));
11875 set_general_thread (sample_thread);
11876 }
11877
11878
11879 static void
11880 threadalive_test (const char *cmd, int tty)
11881 {
11882 int sample_thread = SAMPLE_THREAD;
11883 int pid = inferior_ptid.pid ();
11884 ptid_t ptid = ptid_t (pid, sample_thread, 0);
11885
11886 if (remote_thread_alive (ptid))
11887 gdb_printf ("PASS: Thread alive test\n");
11888 else
11889 gdb_printf ("FAIL: Thread alive test\n");
11890 }
11891
11892 void output_threadid (char *title, threadref *ref);
11893
11894 void
11895 output_threadid (char *title, threadref *ref)
11896 {
11897 char hexid[20];
11898
11899 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
11900 hexid[16] = 0;
11901 gdb_printf ("%s %s\n", title, (&hexid[0]));
11902 }
11903
11904 static void
11905 threadlist_test_cmd (const char *cmd, int tty)
11906 {
11907 int startflag = 1;
11908 threadref nextthread;
11909 int done, result_count;
11910 threadref threadlist[3];
11911
11912 gdb_printf ("Remote Threadlist test\n");
11913 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11914 &result_count, &threadlist[0]))
11915 gdb_printf ("FAIL: threadlist test\n");
11916 else
11917 {
11918 threadref *scan = threadlist;
11919 threadref *limit = scan + result_count;
11920
11921 while (scan < limit)
11922 output_threadid (" thread ", scan++);
11923 }
11924 }
11925
11926 void
11927 display_thread_info (struct gdb_ext_thread_info *info)
11928 {
11929 output_threadid ("Threadid: ", &info->threadid);
11930 gdb_printf ("Name: %s\n ", info->shortname);
11931 gdb_printf ("State: %s\n", info->display);
11932 gdb_printf ("other: %s\n\n", info->more_display);
11933 }
11934
11935 int
11936 get_and_display_threadinfo (threadref *ref)
11937 {
11938 int result;
11939 int set;
11940 struct gdb_ext_thread_info threadinfo;
11941
11942 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11943 | TAG_MOREDISPLAY | TAG_DISPLAY;
11944 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11945 display_thread_info (&threadinfo);
11946 return result;
11947 }
11948
11949 static void
11950 threadinfo_test_cmd (const char *cmd, int tty)
11951 {
11952 int athread = SAMPLE_THREAD;
11953 threadref thread;
11954 int set;
11955
11956 int_to_threadref (&thread, athread);
11957 gdb_printf ("Remote Threadinfo test\n");
11958 if (!get_and_display_threadinfo (&thread))
11959 gdb_printf ("FAIL cannot get thread info\n");
11960 }
11961
11962 static int
11963 thread_display_step (threadref *ref, void *context)
11964 {
11965 /* output_threadid(" threadstep ",ref); *//* simple test */
11966 return get_and_display_threadinfo (ref);
11967 }
11968
11969 static void
11970 threadlist_update_test_cmd (const char *cmd, int tty)
11971 {
11972 gdb_printf ("Remote Threadlist update test\n");
11973 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11974 }
11975
11976 static void
11977 init_remote_threadtests (void)
11978 {
11979 add_com ("tlist", class_obscure, threadlist_test_cmd,
11980 _("Fetch and print the remote list of "
11981 "thread identifiers, one pkt only."));
11982 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11983 _("Fetch and display info about one thread."));
11984 add_com ("tset", class_obscure, threadset_test_cmd,
11985 _("Test setting to a different thread."));
11986 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11987 _("Iterate through updating all remote thread info."));
11988 add_com ("talive", class_obscure, threadalive_test,
11989 _("Remote thread alive test."));
11990 }
11991
11992 #endif /* 0 */
11993
11994 /* Convert a thread ID to a string. */
11995
11996 std::string
11997 remote_target::pid_to_str (ptid_t ptid)
11998 {
11999 if (ptid == null_ptid)
12000 return normal_pid_to_str (ptid);
12001 else if (ptid.is_pid ())
12002 {
12003 /* Printing an inferior target id. */
12004
12005 /* When multi-process extensions are off, there's no way in the
12006 remote protocol to know the remote process id, if there's any
12007 at all. There's one exception --- when we're connected with
12008 target extended-remote, and we manually attached to a process
12009 with "attach PID". We don't record anywhere a flag that
12010 allows us to distinguish that case from the case of
12011 connecting with extended-remote and the stub already being
12012 attached to a process, and reporting yes to qAttached, hence
12013 no smart special casing here. */
12014 if (!m_features.remote_multi_process_p ())
12015 return "Remote target";
12016
12017 return normal_pid_to_str (ptid);
12018 }
12019 else
12020 {
12021 if (magic_null_ptid == ptid)
12022 return "Thread <main>";
12023 else if (m_features.remote_multi_process_p ())
12024 if (ptid.lwp () == 0)
12025 return normal_pid_to_str (ptid);
12026 else
12027 return string_printf ("Thread %d.%ld",
12028 ptid.pid (), ptid.lwp ());
12029 else
12030 return string_printf ("Thread %ld", ptid.lwp ());
12031 }
12032 }
12033
12034 /* Get the address of the thread local variable in OBJFILE which is
12035 stored at OFFSET within the thread local storage for thread PTID. */
12036
12037 CORE_ADDR
12038 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
12039 CORE_ADDR offset)
12040 {
12041 if (m_features.packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
12042 {
12043 struct remote_state *rs = get_remote_state ();
12044 char *p = rs->buf.data ();
12045 char *endp = p + get_remote_packet_size ();
12046 enum packet_result result;
12047
12048 strcpy (p, "qGetTLSAddr:");
12049 p += strlen (p);
12050 p = write_ptid (p, endp, ptid);
12051 *p++ = ',';
12052 p += hexnumstr (p, offset);
12053 *p++ = ',';
12054 p += hexnumstr (p, lm);
12055 *p++ = '\0';
12056
12057 putpkt (rs->buf);
12058 getpkt (&rs->buf);
12059 result = m_features.packet_ok (rs->buf, PACKET_qGetTLSAddr);
12060 if (result == PACKET_OK)
12061 {
12062 ULONGEST addr;
12063
12064 unpack_varlen_hex (rs->buf.data (), &addr);
12065 return addr;
12066 }
12067 else if (result == PACKET_UNKNOWN)
12068 throw_error (TLS_GENERIC_ERROR,
12069 _("Remote target doesn't support qGetTLSAddr packet"));
12070 else
12071 throw_error (TLS_GENERIC_ERROR,
12072 _("Remote target failed to process qGetTLSAddr request"));
12073 }
12074 else
12075 throw_error (TLS_GENERIC_ERROR,
12076 _("TLS not supported or disabled on this target"));
12077 /* Not reached. */
12078 return 0;
12079 }
12080
12081 /* Provide thread local base, i.e. Thread Information Block address.
12082 Returns 1 if ptid is found and thread_local_base is non zero. */
12083
12084 bool
12085 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
12086 {
12087 if (m_features.packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
12088 {
12089 struct remote_state *rs = get_remote_state ();
12090 char *p = rs->buf.data ();
12091 char *endp = p + get_remote_packet_size ();
12092 enum packet_result result;
12093
12094 strcpy (p, "qGetTIBAddr:");
12095 p += strlen (p);
12096 p = write_ptid (p, endp, ptid);
12097 *p++ = '\0';
12098
12099 putpkt (rs->buf);
12100 getpkt (&rs->buf);
12101 result = m_features.packet_ok (rs->buf, PACKET_qGetTIBAddr);
12102 if (result == PACKET_OK)
12103 {
12104 ULONGEST val;
12105 unpack_varlen_hex (rs->buf.data (), &val);
12106 if (addr)
12107 *addr = (CORE_ADDR) val;
12108 return true;
12109 }
12110 else if (result == PACKET_UNKNOWN)
12111 error (_("Remote target doesn't support qGetTIBAddr packet"));
12112 else
12113 error (_("Remote target failed to process qGetTIBAddr request"));
12114 }
12115 else
12116 error (_("qGetTIBAddr not supported or disabled on this target"));
12117 /* Not reached. */
12118 return false;
12119 }
12120
12121 /* Support for inferring a target description based on the current
12122 architecture and the size of a 'g' packet. While the 'g' packet
12123 can have any size (since optional registers can be left off the
12124 end), some sizes are easily recognizable given knowledge of the
12125 approximate architecture. */
12126
12127 struct remote_g_packet_guess
12128 {
12129 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
12130 : bytes (bytes_),
12131 tdesc (tdesc_)
12132 {
12133 }
12134
12135 int bytes;
12136 const struct target_desc *tdesc;
12137 };
12138
12139 struct remote_g_packet_data
12140 {
12141 std::vector<remote_g_packet_guess> guesses;
12142 };
12143
12144 static const registry<gdbarch>::key<struct remote_g_packet_data>
12145 remote_g_packet_data_handle;
12146
12147 static struct remote_g_packet_data *
12148 get_g_packet_data (struct gdbarch *gdbarch)
12149 {
12150 struct remote_g_packet_data *data
12151 = remote_g_packet_data_handle.get (gdbarch);
12152 if (data == nullptr)
12153 data = remote_g_packet_data_handle.emplace (gdbarch);
12154 return data;
12155 }
12156
12157 void
12158 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12159 const struct target_desc *tdesc)
12160 {
12161 struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
12162
12163 gdb_assert (tdesc != NULL);
12164
12165 for (const remote_g_packet_guess &guess : data->guesses)
12166 if (guess.bytes == bytes)
12167 internal_error (_("Duplicate g packet description added for size %d"),
12168 bytes);
12169
12170 data->guesses.emplace_back (bytes, tdesc);
12171 }
12172
12173 /* Return true if remote_read_description would do anything on this target
12174 and architecture, false otherwise. */
12175
12176 static bool
12177 remote_read_description_p (struct target_ops *target)
12178 {
12179 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
12180
12181 return !data->guesses.empty ();
12182 }
12183
12184 const struct target_desc *
12185 remote_target::read_description ()
12186 {
12187 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
12188
12189 /* Do not try this during initial connection, when we do not know
12190 whether there is a running but stopped thread. */
12191 if (!target_has_execution () || inferior_ptid == null_ptid)
12192 return beneath ()->read_description ();
12193
12194 if (!data->guesses.empty ())
12195 {
12196 int bytes = send_g_packet ();
12197
12198 for (const remote_g_packet_guess &guess : data->guesses)
12199 if (guess.bytes == bytes)
12200 return guess.tdesc;
12201
12202 /* We discard the g packet. A minor optimization would be to
12203 hold on to it, and fill the register cache once we have selected
12204 an architecture, but it's too tricky to do safely. */
12205 }
12206
12207 return beneath ()->read_description ();
12208 }
12209
12210 /* Remote file transfer support. This is host-initiated I/O, not
12211 target-initiated; for target-initiated, see remote-fileio.c. */
12212
12213 /* If *LEFT is at least the length of STRING, copy STRING to
12214 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12215 decrease *LEFT. Otherwise raise an error. */
12216
12217 static void
12218 remote_buffer_add_string (char **buffer, int *left, const char *string)
12219 {
12220 int len = strlen (string);
12221
12222 if (len > *left)
12223 error (_("Packet too long for target."));
12224
12225 memcpy (*buffer, string, len);
12226 *buffer += len;
12227 *left -= len;
12228
12229 /* NUL-terminate the buffer as a convenience, if there is
12230 room. */
12231 if (*left)
12232 **buffer = '\0';
12233 }
12234
12235 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12236 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12237 decrease *LEFT. Otherwise raise an error. */
12238
12239 static void
12240 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12241 int len)
12242 {
12243 if (2 * len > *left)
12244 error (_("Packet too long for target."));
12245
12246 bin2hex (bytes, *buffer, len);
12247 *buffer += 2 * len;
12248 *left -= 2 * len;
12249
12250 /* NUL-terminate the buffer as a convenience, if there is
12251 room. */
12252 if (*left)
12253 **buffer = '\0';
12254 }
12255
12256 /* If *LEFT is large enough, convert VALUE to hex and add it 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_int (char **buffer, int *left, ULONGEST value)
12262 {
12263 int len = hexnumlen (value);
12264
12265 if (len > *left)
12266 error (_("Packet too long for target."));
12267
12268 hexnumstr (*buffer, value);
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 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12279 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
12280 was included, and *ATTACHMENT to point to the start of the annex
12281 if any. The length of the packet isn't needed here; there may
12282 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12283
12284 Return 0 if the packet could be parsed, -1 if it could not. If
12285 -1 is returned, the other variables may not be initialized. */
12286
12287 static int
12288 remote_hostio_parse_result (const char *buffer, int *retcode,
12289 fileio_error *remote_errno, const char **attachment)
12290 {
12291 char *p, *p2;
12292
12293 *remote_errno = FILEIO_SUCCESS;
12294 *attachment = NULL;
12295
12296 if (buffer[0] != 'F')
12297 return -1;
12298
12299 errno = 0;
12300 *retcode = strtol (&buffer[1], &p, 16);
12301 if (errno != 0 || p == &buffer[1])
12302 return -1;
12303
12304 /* Check for ",errno". */
12305 if (*p == ',')
12306 {
12307 errno = 0;
12308 *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
12309 if (errno != 0 || p + 1 == p2)
12310 return -1;
12311 p = p2;
12312 }
12313
12314 /* Check for ";attachment". If there is no attachment, the
12315 packet should end here. */
12316 if (*p == ';')
12317 {
12318 *attachment = p + 1;
12319 return 0;
12320 }
12321 else if (*p == '\0')
12322 return 0;
12323 else
12324 return -1;
12325 }
12326
12327 /* Send a prepared I/O packet to the target and read its response.
12328 The prepared packet is in the global RS->BUF before this function
12329 is called, and the answer is there when we return.
12330
12331 COMMAND_BYTES is the length of the request to send, which may include
12332 binary data. WHICH_PACKET is the packet configuration to check
12333 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12334 is set to the error number and -1 is returned. Otherwise the value
12335 returned by the function is returned.
12336
12337 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12338 attachment is expected; an error will be reported if there's a
12339 mismatch. If one is found, *ATTACHMENT will be set to point into
12340 the packet buffer and *ATTACHMENT_LEN will be set to the
12341 attachment's length. */
12342
12343 int
12344 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12345 fileio_error *remote_errno, const char **attachment,
12346 int *attachment_len)
12347 {
12348 struct remote_state *rs = get_remote_state ();
12349 int ret, bytes_read;
12350 const char *attachment_tmp;
12351
12352 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
12353 {
12354 *remote_errno = FILEIO_ENOSYS;
12355 return -1;
12356 }
12357
12358 putpkt_binary (rs->buf.data (), command_bytes);
12359 bytes_read = getpkt (&rs->buf);
12360
12361 /* If it timed out, something is wrong. Don't try to parse the
12362 buffer. */
12363 if (bytes_read < 0)
12364 {
12365 *remote_errno = FILEIO_EINVAL;
12366 return -1;
12367 }
12368
12369 switch (m_features.packet_ok (rs->buf, which_packet))
12370 {
12371 case PACKET_ERROR:
12372 *remote_errno = FILEIO_EINVAL;
12373 return -1;
12374 case PACKET_UNKNOWN:
12375 *remote_errno = FILEIO_ENOSYS;
12376 return -1;
12377 case PACKET_OK:
12378 break;
12379 }
12380
12381 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12382 &attachment_tmp))
12383 {
12384 *remote_errno = FILEIO_EINVAL;
12385 return -1;
12386 }
12387
12388 /* Make sure we saw an attachment if and only if we expected one. */
12389 if ((attachment_tmp == NULL && attachment != NULL)
12390 || (attachment_tmp != NULL && attachment == NULL))
12391 {
12392 *remote_errno = FILEIO_EINVAL;
12393 return -1;
12394 }
12395
12396 /* If an attachment was found, it must point into the packet buffer;
12397 work out how many bytes there were. */
12398 if (attachment_tmp != NULL)
12399 {
12400 *attachment = attachment_tmp;
12401 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12402 }
12403
12404 return ret;
12405 }
12406
12407 /* See declaration.h. */
12408
12409 void
12410 readahead_cache::invalidate ()
12411 {
12412 this->fd = -1;
12413 }
12414
12415 /* See declaration.h. */
12416
12417 void
12418 readahead_cache::invalidate_fd (int fd)
12419 {
12420 if (this->fd == fd)
12421 this->fd = -1;
12422 }
12423
12424 /* Set the filesystem remote_hostio functions that take FILENAME
12425 arguments will use. Return 0 on success, or -1 if an error
12426 occurs (and set *REMOTE_ERRNO). */
12427
12428 int
12429 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12430 fileio_error *remote_errno)
12431 {
12432 struct remote_state *rs = get_remote_state ();
12433 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12434 char *p = rs->buf.data ();
12435 int left = get_remote_packet_size () - 1;
12436 char arg[9];
12437 int ret;
12438
12439 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12440 return 0;
12441
12442 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12443 return 0;
12444
12445 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12446
12447 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12448 remote_buffer_add_string (&p, &left, arg);
12449
12450 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12451 remote_errno, NULL, NULL);
12452
12453 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12454 return 0;
12455
12456 if (ret == 0)
12457 rs->fs_pid = required_pid;
12458
12459 return ret;
12460 }
12461
12462 /* Implementation of to_fileio_open. */
12463
12464 int
12465 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12466 int flags, int mode, int warn_if_slow,
12467 fileio_error *remote_errno)
12468 {
12469 struct remote_state *rs = get_remote_state ();
12470 char *p = rs->buf.data ();
12471 int left = get_remote_packet_size () - 1;
12472
12473 if (warn_if_slow)
12474 {
12475 static int warning_issued = 0;
12476
12477 gdb_printf (_("Reading %s from remote target...\n"),
12478 filename);
12479
12480 if (!warning_issued)
12481 {
12482 warning (_("File transfers from remote targets can be slow."
12483 " Use \"set sysroot\" to access files locally"
12484 " instead."));
12485 warning_issued = 1;
12486 }
12487 }
12488
12489 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12490 return -1;
12491
12492 remote_buffer_add_string (&p, &left, "vFile:open:");
12493
12494 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12495 strlen (filename));
12496 remote_buffer_add_string (&p, &left, ",");
12497
12498 remote_buffer_add_int (&p, &left, flags);
12499 remote_buffer_add_string (&p, &left, ",");
12500
12501 remote_buffer_add_int (&p, &left, mode);
12502
12503 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12504 remote_errno, NULL, NULL);
12505 }
12506
12507 int
12508 remote_target::fileio_open (struct inferior *inf, const char *filename,
12509 int flags, int mode, int warn_if_slow,
12510 fileio_error *remote_errno)
12511 {
12512 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12513 remote_errno);
12514 }
12515
12516 /* Implementation of to_fileio_pwrite. */
12517
12518 int
12519 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12520 ULONGEST offset, fileio_error *remote_errno)
12521 {
12522 struct remote_state *rs = get_remote_state ();
12523 char *p = rs->buf.data ();
12524 int left = get_remote_packet_size ();
12525 int out_len;
12526
12527 rs->readahead_cache.invalidate_fd (fd);
12528
12529 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12530
12531 remote_buffer_add_int (&p, &left, fd);
12532 remote_buffer_add_string (&p, &left, ",");
12533
12534 remote_buffer_add_int (&p, &left, offset);
12535 remote_buffer_add_string (&p, &left, ",");
12536
12537 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12538 (get_remote_packet_size ()
12539 - (p - rs->buf.data ())));
12540
12541 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12542 remote_errno, NULL, NULL);
12543 }
12544
12545 int
12546 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12547 ULONGEST offset, fileio_error *remote_errno)
12548 {
12549 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12550 }
12551
12552 /* Helper for the implementation of to_fileio_pread. Read the file
12553 from the remote side with vFile:pread. */
12554
12555 int
12556 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12557 ULONGEST offset, fileio_error *remote_errno)
12558 {
12559 struct remote_state *rs = get_remote_state ();
12560 char *p = rs->buf.data ();
12561 const char *attachment;
12562 int left = get_remote_packet_size ();
12563 int ret, attachment_len;
12564 int read_len;
12565
12566 remote_buffer_add_string (&p, &left, "vFile:pread:");
12567
12568 remote_buffer_add_int (&p, &left, fd);
12569 remote_buffer_add_string (&p, &left, ",");
12570
12571 remote_buffer_add_int (&p, &left, len);
12572 remote_buffer_add_string (&p, &left, ",");
12573
12574 remote_buffer_add_int (&p, &left, offset);
12575
12576 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12577 remote_errno, &attachment,
12578 &attachment_len);
12579
12580 if (ret < 0)
12581 return ret;
12582
12583 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12584 read_buf, len);
12585 if (read_len != ret)
12586 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12587
12588 return ret;
12589 }
12590
12591 /* See declaration.h. */
12592
12593 int
12594 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12595 ULONGEST offset)
12596 {
12597 if (this->fd == fd
12598 && this->offset <= offset
12599 && offset < this->offset + this->buf.size ())
12600 {
12601 ULONGEST max = this->offset + this->buf.size ();
12602
12603 if (offset + len > max)
12604 len = max - offset;
12605
12606 memcpy (read_buf, &this->buf[offset - this->offset], len);
12607 return len;
12608 }
12609
12610 return 0;
12611 }
12612
12613 /* Implementation of to_fileio_pread. */
12614
12615 int
12616 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12617 ULONGEST offset, fileio_error *remote_errno)
12618 {
12619 int ret;
12620 struct remote_state *rs = get_remote_state ();
12621 readahead_cache *cache = &rs->readahead_cache;
12622
12623 ret = cache->pread (fd, read_buf, len, offset);
12624 if (ret > 0)
12625 {
12626 cache->hit_count++;
12627
12628 remote_debug_printf ("readahead cache hit %s",
12629 pulongest (cache->hit_count));
12630 return ret;
12631 }
12632
12633 cache->miss_count++;
12634
12635 remote_debug_printf ("readahead cache miss %s",
12636 pulongest (cache->miss_count));
12637
12638 cache->fd = fd;
12639 cache->offset = offset;
12640 cache->buf.resize (get_remote_packet_size ());
12641
12642 ret = remote_hostio_pread_vFile (cache->fd, &cache->buf[0],
12643 cache->buf.size (),
12644 cache->offset, remote_errno);
12645 if (ret <= 0)
12646 {
12647 cache->invalidate_fd (fd);
12648 return ret;
12649 }
12650
12651 cache->buf.resize (ret);
12652 return cache->pread (fd, read_buf, len, offset);
12653 }
12654
12655 int
12656 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12657 ULONGEST offset, fileio_error *remote_errno)
12658 {
12659 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12660 }
12661
12662 /* Implementation of to_fileio_close. */
12663
12664 int
12665 remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
12666 {
12667 struct remote_state *rs = get_remote_state ();
12668 char *p = rs->buf.data ();
12669 int left = get_remote_packet_size () - 1;
12670
12671 rs->readahead_cache.invalidate_fd (fd);
12672
12673 remote_buffer_add_string (&p, &left, "vFile:close:");
12674
12675 remote_buffer_add_int (&p, &left, fd);
12676
12677 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12678 remote_errno, NULL, NULL);
12679 }
12680
12681 int
12682 remote_target::fileio_close (int fd, fileio_error *remote_errno)
12683 {
12684 return remote_hostio_close (fd, remote_errno);
12685 }
12686
12687 /* Implementation of to_fileio_unlink. */
12688
12689 int
12690 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12691 fileio_error *remote_errno)
12692 {
12693 struct remote_state *rs = get_remote_state ();
12694 char *p = rs->buf.data ();
12695 int left = get_remote_packet_size () - 1;
12696
12697 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12698 return -1;
12699
12700 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12701
12702 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12703 strlen (filename));
12704
12705 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12706 remote_errno, NULL, NULL);
12707 }
12708
12709 int
12710 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12711 fileio_error *remote_errno)
12712 {
12713 return remote_hostio_unlink (inf, filename, remote_errno);
12714 }
12715
12716 /* Implementation of to_fileio_readlink. */
12717
12718 gdb::optional<std::string>
12719 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12720 fileio_error *remote_errno)
12721 {
12722 struct remote_state *rs = get_remote_state ();
12723 char *p = rs->buf.data ();
12724 const char *attachment;
12725 int left = get_remote_packet_size ();
12726 int len, attachment_len;
12727 int read_len;
12728
12729 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12730 return {};
12731
12732 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12733
12734 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12735 strlen (filename));
12736
12737 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12738 remote_errno, &attachment,
12739 &attachment_len);
12740
12741 if (len < 0)
12742 return {};
12743
12744 std::string ret (len, '\0');
12745
12746 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12747 (gdb_byte *) &ret[0], len);
12748 if (read_len != len)
12749 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12750
12751 return ret;
12752 }
12753
12754 /* Implementation of to_fileio_fstat. */
12755
12756 int
12757 remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
12758 {
12759 struct remote_state *rs = get_remote_state ();
12760 char *p = rs->buf.data ();
12761 int left = get_remote_packet_size ();
12762 int attachment_len, ret;
12763 const char *attachment;
12764 struct fio_stat fst;
12765 int read_len;
12766
12767 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12768
12769 remote_buffer_add_int (&p, &left, fd);
12770
12771 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12772 remote_errno, &attachment,
12773 &attachment_len);
12774 if (ret < 0)
12775 {
12776 if (*remote_errno != FILEIO_ENOSYS)
12777 return ret;
12778
12779 /* Strictly we should return -1, ENOSYS here, but when
12780 "set sysroot remote:" was implemented in August 2008
12781 BFD's need for a stat function was sidestepped with
12782 this hack. This was not remedied until March 2015
12783 so we retain the previous behavior to avoid breaking
12784 compatibility.
12785
12786 Note that the memset is a March 2015 addition; older
12787 GDBs set st_size *and nothing else* so the structure
12788 would have garbage in all other fields. This might
12789 break something but retaining the previous behavior
12790 here would be just too wrong. */
12791
12792 memset (st, 0, sizeof (struct stat));
12793 st->st_size = INT_MAX;
12794 return 0;
12795 }
12796
12797 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12798 (gdb_byte *) &fst, sizeof (fst));
12799
12800 if (read_len != ret)
12801 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12802
12803 if (read_len != sizeof (fst))
12804 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12805 read_len, (int) sizeof (fst));
12806
12807 remote_fileio_to_host_stat (&fst, st);
12808
12809 return 0;
12810 }
12811
12812 /* Implementation of to_filesystem_is_local. */
12813
12814 bool
12815 remote_target::filesystem_is_local ()
12816 {
12817 /* Valgrind GDB presents itself as a remote target but works
12818 on the local filesystem: it does not implement remote get
12819 and users are not expected to set a sysroot. To handle
12820 this case we treat the remote filesystem as local if the
12821 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12822 does not support vFile:open. */
12823 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
12824 {
12825 packet_support ps = m_features.packet_support (PACKET_vFile_open);
12826
12827 if (ps == PACKET_SUPPORT_UNKNOWN)
12828 {
12829 int fd;
12830 fileio_error remote_errno;
12831
12832 /* Try opening a file to probe support. The supplied
12833 filename is irrelevant, we only care about whether
12834 the stub recognizes the packet or not. */
12835 fd = remote_hostio_open (NULL, "just probing",
12836 FILEIO_O_RDONLY, 0700, 0,
12837 &remote_errno);
12838
12839 if (fd >= 0)
12840 remote_hostio_close (fd, &remote_errno);
12841
12842 ps = m_features.packet_support (PACKET_vFile_open);
12843 }
12844
12845 if (ps == PACKET_DISABLE)
12846 {
12847 static int warning_issued = 0;
12848
12849 if (!warning_issued)
12850 {
12851 warning (_("remote target does not support file"
12852 " transfer, attempting to access files"
12853 " from local filesystem."));
12854 warning_issued = 1;
12855 }
12856
12857 return true;
12858 }
12859 }
12860
12861 return false;
12862 }
12863
12864 static char *
12865 remote_hostio_error (fileio_error errnum)
12866 {
12867 int host_error = fileio_error_to_host (errnum);
12868
12869 if (host_error == -1)
12870 error (_("Unknown remote I/O error %d"), errnum);
12871 else
12872 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12873 }
12874
12875 /* A RAII wrapper around a remote file descriptor. */
12876
12877 class scoped_remote_fd
12878 {
12879 public:
12880 scoped_remote_fd (remote_target *remote, int fd)
12881 : m_remote (remote), m_fd (fd)
12882 {
12883 }
12884
12885 ~scoped_remote_fd ()
12886 {
12887 if (m_fd != -1)
12888 {
12889 try
12890 {
12891 fileio_error remote_errno;
12892 m_remote->remote_hostio_close (m_fd, &remote_errno);
12893 }
12894 catch (...)
12895 {
12896 /* Swallow exception before it escapes the dtor. If
12897 something goes wrong, likely the connection is gone,
12898 and there's nothing else that can be done. */
12899 }
12900 }
12901 }
12902
12903 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12904
12905 /* Release ownership of the file descriptor, and return it. */
12906 ATTRIBUTE_UNUSED_RESULT int release () noexcept
12907 {
12908 int fd = m_fd;
12909 m_fd = -1;
12910 return fd;
12911 }
12912
12913 /* Return the owned file descriptor. */
12914 int get () const noexcept
12915 {
12916 return m_fd;
12917 }
12918
12919 private:
12920 /* The remote target. */
12921 remote_target *m_remote;
12922
12923 /* The owned remote I/O file descriptor. */
12924 int m_fd;
12925 };
12926
12927 void
12928 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12929 {
12930 remote_target *remote = get_current_remote_target ();
12931
12932 if (remote == nullptr)
12933 error (_("command can only be used with remote target"));
12934
12935 remote->remote_file_put (local_file, remote_file, from_tty);
12936 }
12937
12938 void
12939 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12940 int from_tty)
12941 {
12942 int retcode, bytes, io_size;
12943 fileio_error remote_errno;
12944 int bytes_in_buffer;
12945 int saw_eof;
12946 ULONGEST offset;
12947
12948 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12949 if (file == NULL)
12950 perror_with_name (local_file);
12951
12952 scoped_remote_fd fd
12953 (this, remote_hostio_open (NULL,
12954 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12955 | FILEIO_O_TRUNC),
12956 0700, 0, &remote_errno));
12957 if (fd.get () == -1)
12958 remote_hostio_error (remote_errno);
12959
12960 /* Send up to this many bytes at once. They won't all fit in the
12961 remote packet limit, so we'll transfer slightly fewer. */
12962 io_size = get_remote_packet_size ();
12963 gdb::byte_vector buffer (io_size);
12964
12965 bytes_in_buffer = 0;
12966 saw_eof = 0;
12967 offset = 0;
12968 while (bytes_in_buffer || !saw_eof)
12969 {
12970 if (!saw_eof)
12971 {
12972 bytes = fread (buffer.data () + bytes_in_buffer, 1,
12973 io_size - bytes_in_buffer,
12974 file.get ());
12975 if (bytes == 0)
12976 {
12977 if (ferror (file.get ()))
12978 error (_("Error reading %s."), local_file);
12979 else
12980 {
12981 /* EOF. Unless there is something still in the
12982 buffer from the last iteration, we are done. */
12983 saw_eof = 1;
12984 if (bytes_in_buffer == 0)
12985 break;
12986 }
12987 }
12988 }
12989 else
12990 bytes = 0;
12991
12992 bytes += bytes_in_buffer;
12993 bytes_in_buffer = 0;
12994
12995 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12996 offset, &remote_errno);
12997
12998 if (retcode < 0)
12999 remote_hostio_error (remote_errno);
13000 else if (retcode == 0)
13001 error (_("Remote write of %d bytes returned 0!"), bytes);
13002 else if (retcode < bytes)
13003 {
13004 /* Short write. Save the rest of the read data for the next
13005 write. */
13006 bytes_in_buffer = bytes - retcode;
13007 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
13008 }
13009
13010 offset += retcode;
13011 }
13012
13013 if (remote_hostio_close (fd.release (), &remote_errno))
13014 remote_hostio_error (remote_errno);
13015
13016 if (from_tty)
13017 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
13018 }
13019
13020 void
13021 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
13022 {
13023 remote_target *remote = get_current_remote_target ();
13024
13025 if (remote == nullptr)
13026 error (_("command can only be used with remote target"));
13027
13028 remote->remote_file_get (remote_file, local_file, from_tty);
13029 }
13030
13031 void
13032 remote_target::remote_file_get (const char *remote_file, const char *local_file,
13033 int from_tty)
13034 {
13035 fileio_error remote_errno;
13036 int bytes, io_size;
13037 ULONGEST offset;
13038
13039 scoped_remote_fd fd
13040 (this, remote_hostio_open (NULL,
13041 remote_file, FILEIO_O_RDONLY, 0, 0,
13042 &remote_errno));
13043 if (fd.get () == -1)
13044 remote_hostio_error (remote_errno);
13045
13046 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
13047 if (file == NULL)
13048 perror_with_name (local_file);
13049
13050 /* Send up to this many bytes at once. They won't all fit in the
13051 remote packet limit, so we'll transfer slightly fewer. */
13052 io_size = get_remote_packet_size ();
13053 gdb::byte_vector buffer (io_size);
13054
13055 offset = 0;
13056 while (1)
13057 {
13058 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
13059 &remote_errno);
13060 if (bytes == 0)
13061 /* Success, but no bytes, means end-of-file. */
13062 break;
13063 if (bytes == -1)
13064 remote_hostio_error (remote_errno);
13065
13066 offset += bytes;
13067
13068 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
13069 if (bytes == 0)
13070 perror_with_name (local_file);
13071 }
13072
13073 if (remote_hostio_close (fd.release (), &remote_errno))
13074 remote_hostio_error (remote_errno);
13075
13076 if (from_tty)
13077 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
13078 }
13079
13080 void
13081 remote_file_delete (const char *remote_file, int from_tty)
13082 {
13083 remote_target *remote = get_current_remote_target ();
13084
13085 if (remote == nullptr)
13086 error (_("command can only be used with remote target"));
13087
13088 remote->remote_file_delete (remote_file, from_tty);
13089 }
13090
13091 void
13092 remote_target::remote_file_delete (const char *remote_file, int from_tty)
13093 {
13094 int retcode;
13095 fileio_error remote_errno;
13096
13097 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
13098 if (retcode == -1)
13099 remote_hostio_error (remote_errno);
13100
13101 if (from_tty)
13102 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
13103 }
13104
13105 static void
13106 remote_put_command (const char *args, int from_tty)
13107 {
13108 if (args == NULL)
13109 error_no_arg (_("file to put"));
13110
13111 gdb_argv argv (args);
13112 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13113 error (_("Invalid parameters to remote put"));
13114
13115 remote_file_put (argv[0], argv[1], from_tty);
13116 }
13117
13118 static void
13119 remote_get_command (const char *args, int from_tty)
13120 {
13121 if (args == NULL)
13122 error_no_arg (_("file to get"));
13123
13124 gdb_argv argv (args);
13125 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13126 error (_("Invalid parameters to remote get"));
13127
13128 remote_file_get (argv[0], argv[1], from_tty);
13129 }
13130
13131 static void
13132 remote_delete_command (const char *args, int from_tty)
13133 {
13134 if (args == NULL)
13135 error_no_arg (_("file to delete"));
13136
13137 gdb_argv argv (args);
13138 if (argv[0] == NULL || argv[1] != NULL)
13139 error (_("Invalid parameters to remote delete"));
13140
13141 remote_file_delete (argv[0], from_tty);
13142 }
13143
13144 bool
13145 remote_target::can_execute_reverse ()
13146 {
13147 if (m_features.packet_support (PACKET_bs) == PACKET_ENABLE
13148 || m_features.packet_support (PACKET_bc) == PACKET_ENABLE)
13149 return true;
13150 else
13151 return false;
13152 }
13153
13154 bool
13155 remote_target::supports_non_stop ()
13156 {
13157 return true;
13158 }
13159
13160 bool
13161 remote_target::supports_disable_randomization ()
13162 {
13163 /* Only supported in extended mode. */
13164 return false;
13165 }
13166
13167 bool
13168 remote_target::supports_multi_process ()
13169 {
13170 return m_features.remote_multi_process_p ();
13171 }
13172
13173 int
13174 remote_target::remote_supports_cond_tracepoints ()
13175 {
13176 return (m_features.packet_support (PACKET_ConditionalTracepoints)
13177 == PACKET_ENABLE);
13178 }
13179
13180 bool
13181 remote_target::supports_evaluation_of_breakpoint_conditions ()
13182 {
13183 return (m_features.packet_support (PACKET_ConditionalBreakpoints)
13184 == PACKET_ENABLE);
13185 }
13186
13187 int
13188 remote_target::remote_supports_fast_tracepoints ()
13189 {
13190 return m_features.packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13191 }
13192
13193 int
13194 remote_target::remote_supports_static_tracepoints ()
13195 {
13196 return m_features.packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13197 }
13198
13199 int
13200 remote_target::remote_supports_install_in_trace ()
13201 {
13202 return m_features.packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13203 }
13204
13205 bool
13206 remote_target::supports_enable_disable_tracepoint ()
13207 {
13208 return (m_features.packet_support (PACKET_EnableDisableTracepoints_feature)
13209 == PACKET_ENABLE);
13210 }
13211
13212 bool
13213 remote_target::supports_string_tracing ()
13214 {
13215 return m_features.packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13216 }
13217
13218 bool
13219 remote_target::can_run_breakpoint_commands ()
13220 {
13221 return m_features.packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13222 }
13223
13224 void
13225 remote_target::trace_init ()
13226 {
13227 struct remote_state *rs = get_remote_state ();
13228
13229 putpkt ("QTinit");
13230 remote_get_noisy_reply ();
13231 if (strcmp (rs->buf.data (), "OK") != 0)
13232 error (_("Target does not support this command."));
13233 }
13234
13235 /* Recursive routine to walk through command list including loops, and
13236 download packets for each command. */
13237
13238 void
13239 remote_target::remote_download_command_source (int num, ULONGEST addr,
13240 struct command_line *cmds)
13241 {
13242 struct remote_state *rs = get_remote_state ();
13243 struct command_line *cmd;
13244
13245 for (cmd = cmds; cmd; cmd = cmd->next)
13246 {
13247 QUIT; /* Allow user to bail out with ^C. */
13248 strcpy (rs->buf.data (), "QTDPsrc:");
13249 encode_source_string (num, addr, "cmd", cmd->line,
13250 rs->buf.data () + strlen (rs->buf.data ()),
13251 rs->buf.size () - strlen (rs->buf.data ()));
13252 putpkt (rs->buf);
13253 remote_get_noisy_reply ();
13254 if (strcmp (rs->buf.data (), "OK"))
13255 warning (_("Target does not support source download."));
13256
13257 if (cmd->control_type == while_control
13258 || cmd->control_type == while_stepping_control)
13259 {
13260 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13261
13262 QUIT; /* Allow user to bail out with ^C. */
13263 strcpy (rs->buf.data (), "QTDPsrc:");
13264 encode_source_string (num, addr, "cmd", "end",
13265 rs->buf.data () + strlen (rs->buf.data ()),
13266 rs->buf.size () - strlen (rs->buf.data ()));
13267 putpkt (rs->buf);
13268 remote_get_noisy_reply ();
13269 if (strcmp (rs->buf.data (), "OK"))
13270 warning (_("Target does not support source download."));
13271 }
13272 }
13273 }
13274
13275 void
13276 remote_target::download_tracepoint (struct bp_location *loc)
13277 {
13278 CORE_ADDR tpaddr;
13279 char addrbuf[40];
13280 std::vector<std::string> tdp_actions;
13281 std::vector<std::string> stepping_actions;
13282 char *pkt;
13283 struct breakpoint *b = loc->owner;
13284 tracepoint *t = gdb::checked_static_cast<tracepoint *> (b);
13285 struct remote_state *rs = get_remote_state ();
13286 int ret;
13287 const char *err_msg = _("Tracepoint packet too large for target.");
13288 size_t size_left;
13289
13290 /* We use a buffer other than rs->buf because we'll build strings
13291 across multiple statements, and other statements in between could
13292 modify rs->buf. */
13293 gdb::char_vector buf (get_remote_packet_size ());
13294
13295 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13296
13297 tpaddr = loc->address;
13298 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13299 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13300 b->number, addrbuf, /* address */
13301 (b->enable_state == bp_enabled ? 'E' : 'D'),
13302 t->step_count, t->pass_count);
13303
13304 if (ret < 0 || ret >= buf.size ())
13305 error ("%s", err_msg);
13306
13307 /* Fast tracepoints are mostly handled by the target, but we can
13308 tell the target how big of an instruction block should be moved
13309 around. */
13310 if (b->type == bp_fast_tracepoint)
13311 {
13312 /* Only test for support at download time; we may not know
13313 target capabilities at definition time. */
13314 if (remote_supports_fast_tracepoints ())
13315 {
13316 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13317 NULL))
13318 {
13319 size_left = buf.size () - strlen (buf.data ());
13320 ret = snprintf (buf.data () + strlen (buf.data ()),
13321 size_left, ":F%x",
13322 gdb_insn_length (loc->gdbarch, tpaddr));
13323
13324 if (ret < 0 || ret >= size_left)
13325 error ("%s", err_msg);
13326 }
13327 else
13328 /* If it passed validation at definition but fails now,
13329 something is very wrong. */
13330 internal_error (_("Fast tracepoint not valid during download"));
13331 }
13332 else
13333 /* Fast tracepoints are functionally identical to regular
13334 tracepoints, so don't take lack of support as a reason to
13335 give up on the trace run. */
13336 warning (_("Target does not support fast tracepoints, "
13337 "downloading %d as regular tracepoint"), b->number);
13338 }
13339 else if (b->type == bp_static_tracepoint
13340 || b->type == bp_static_marker_tracepoint)
13341 {
13342 /* Only test for support at download time; we may not know
13343 target capabilities at definition time. */
13344 if (remote_supports_static_tracepoints ())
13345 {
13346 struct static_tracepoint_marker marker;
13347
13348 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13349 {
13350 size_left = buf.size () - strlen (buf.data ());
13351 ret = snprintf (buf.data () + strlen (buf.data ()),
13352 size_left, ":S");
13353
13354 if (ret < 0 || ret >= size_left)
13355 error ("%s", err_msg);
13356 }
13357 else
13358 error (_("Static tracepoint not valid during download"));
13359 }
13360 else
13361 /* Fast tracepoints are functionally identical to regular
13362 tracepoints, so don't take lack of support as a reason
13363 to give up on the trace run. */
13364 error (_("Target does not support static tracepoints"));
13365 }
13366 /* If the tracepoint has a conditional, make it into an agent
13367 expression and append to the definition. */
13368 if (loc->cond)
13369 {
13370 /* Only test support at download time, we may not know target
13371 capabilities at definition time. */
13372 if (remote_supports_cond_tracepoints ())
13373 {
13374 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13375 loc->cond.get ());
13376
13377 size_left = buf.size () - strlen (buf.data ());
13378
13379 ret = snprintf (buf.data () + strlen (buf.data ()),
13380 size_left, ":X%x,", (int) aexpr->buf.size ());
13381
13382 if (ret < 0 || ret >= size_left)
13383 error ("%s", err_msg);
13384
13385 size_left = buf.size () - strlen (buf.data ());
13386
13387 /* Two bytes to encode each aexpr byte, plus the terminating
13388 null byte. */
13389 if (aexpr->buf.size () * 2 + 1 > size_left)
13390 error ("%s", err_msg);
13391
13392 pkt = buf.data () + strlen (buf.data ());
13393
13394 for (int ndx = 0; ndx < aexpr->buf.size (); ++ndx)
13395 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13396 *pkt = '\0';
13397 }
13398 else
13399 warning (_("Target does not support conditional tracepoints, "
13400 "ignoring tp %d cond"), b->number);
13401 }
13402
13403 if (b->commands || !default_collect.empty ())
13404 {
13405 size_left = buf.size () - strlen (buf.data ());
13406
13407 ret = snprintf (buf.data () + strlen (buf.data ()),
13408 size_left, "-");
13409
13410 if (ret < 0 || ret >= size_left)
13411 error ("%s", err_msg);
13412 }
13413
13414 putpkt (buf.data ());
13415 remote_get_noisy_reply ();
13416 if (strcmp (rs->buf.data (), "OK"))
13417 error (_("Target does not support tracepoints."));
13418
13419 /* do_single_steps (t); */
13420 for (auto action_it = tdp_actions.begin ();
13421 action_it != tdp_actions.end (); action_it++)
13422 {
13423 QUIT; /* Allow user to bail out with ^C. */
13424
13425 bool has_more = ((action_it + 1) != tdp_actions.end ()
13426 || !stepping_actions.empty ());
13427
13428 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13429 b->number, addrbuf, /* address */
13430 action_it->c_str (),
13431 has_more ? '-' : 0);
13432
13433 if (ret < 0 || ret >= buf.size ())
13434 error ("%s", err_msg);
13435
13436 putpkt (buf.data ());
13437 remote_get_noisy_reply ();
13438 if (strcmp (rs->buf.data (), "OK"))
13439 error (_("Error on target while setting tracepoints."));
13440 }
13441
13442 for (auto action_it = stepping_actions.begin ();
13443 action_it != stepping_actions.end (); action_it++)
13444 {
13445 QUIT; /* Allow user to bail out with ^C. */
13446
13447 bool is_first = action_it == stepping_actions.begin ();
13448 bool has_more = (action_it + 1) != stepping_actions.end ();
13449
13450 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13451 b->number, addrbuf, /* address */
13452 is_first ? "S" : "",
13453 action_it->c_str (),
13454 has_more ? "-" : "");
13455
13456 if (ret < 0 || ret >= buf.size ())
13457 error ("%s", err_msg);
13458
13459 putpkt (buf.data ());
13460 remote_get_noisy_reply ();
13461 if (strcmp (rs->buf.data (), "OK"))
13462 error (_("Error on target while setting tracepoints."));
13463 }
13464
13465 if (m_features.packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13466 {
13467 if (b->locspec != nullptr)
13468 {
13469 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13470
13471 if (ret < 0 || ret >= buf.size ())
13472 error ("%s", err_msg);
13473
13474 const char *str = b->locspec->to_string ();
13475 encode_source_string (b->number, loc->address, "at", str,
13476 buf.data () + strlen (buf.data ()),
13477 buf.size () - strlen (buf.data ()));
13478 putpkt (buf.data ());
13479 remote_get_noisy_reply ();
13480 if (strcmp (rs->buf.data (), "OK"))
13481 warning (_("Target does not support source download."));
13482 }
13483 if (b->cond_string)
13484 {
13485 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13486
13487 if (ret < 0 || ret >= buf.size ())
13488 error ("%s", err_msg);
13489
13490 encode_source_string (b->number, loc->address,
13491 "cond", b->cond_string.get (),
13492 buf.data () + strlen (buf.data ()),
13493 buf.size () - strlen (buf.data ()));
13494 putpkt (buf.data ());
13495 remote_get_noisy_reply ();
13496 if (strcmp (rs->buf.data (), "OK"))
13497 warning (_("Target does not support source download."));
13498 }
13499 remote_download_command_source (b->number, loc->address,
13500 breakpoint_commands (b));
13501 }
13502 }
13503
13504 bool
13505 remote_target::can_download_tracepoint ()
13506 {
13507 struct remote_state *rs = get_remote_state ();
13508 struct trace_status *ts;
13509 int status;
13510
13511 /* Don't try to install tracepoints until we've relocated our
13512 symbols, and fetched and merged the target's tracepoint list with
13513 ours. */
13514 if (rs->starting_up)
13515 return false;
13516
13517 ts = current_trace_status ();
13518 status = get_trace_status (ts);
13519
13520 if (status == -1 || !ts->running_known || !ts->running)
13521 return false;
13522
13523 /* If we are in a tracing experiment, but remote stub doesn't support
13524 installing tracepoint in trace, we have to return. */
13525 if (!remote_supports_install_in_trace ())
13526 return false;
13527
13528 return true;
13529 }
13530
13531
13532 void
13533 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13534 {
13535 struct remote_state *rs = get_remote_state ();
13536 char *p;
13537
13538 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13539 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13540 tsv.builtin);
13541 p = rs->buf.data () + strlen (rs->buf.data ());
13542 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13543 >= get_remote_packet_size ())
13544 error (_("Trace state variable name too long for tsv definition packet"));
13545 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13546 *p++ = '\0';
13547 putpkt (rs->buf);
13548 remote_get_noisy_reply ();
13549 if (rs->buf[0] == '\0')
13550 error (_("Target does not support this command."));
13551 if (strcmp (rs->buf.data (), "OK") != 0)
13552 error (_("Error on target while downloading trace state variable."));
13553 }
13554
13555 void
13556 remote_target::enable_tracepoint (struct bp_location *location)
13557 {
13558 struct remote_state *rs = get_remote_state ();
13559
13560 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13561 location->owner->number,
13562 phex (location->address, sizeof (CORE_ADDR)));
13563 putpkt (rs->buf);
13564 remote_get_noisy_reply ();
13565 if (rs->buf[0] == '\0')
13566 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13567 if (strcmp (rs->buf.data (), "OK") != 0)
13568 error (_("Error on target while enabling tracepoint."));
13569 }
13570
13571 void
13572 remote_target::disable_tracepoint (struct bp_location *location)
13573 {
13574 struct remote_state *rs = get_remote_state ();
13575
13576 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13577 location->owner->number,
13578 phex (location->address, sizeof (CORE_ADDR)));
13579 putpkt (rs->buf);
13580 remote_get_noisy_reply ();
13581 if (rs->buf[0] == '\0')
13582 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13583 if (strcmp (rs->buf.data (), "OK") != 0)
13584 error (_("Error on target while disabling tracepoint."));
13585 }
13586
13587 void
13588 remote_target::trace_set_readonly_regions ()
13589 {
13590 asection *s;
13591 bfd_size_type size;
13592 bfd_vma vma;
13593 int anysecs = 0;
13594 int offset = 0;
13595 bfd *abfd = current_program_space->exec_bfd ();
13596
13597 if (!abfd)
13598 return; /* No information to give. */
13599
13600 struct remote_state *rs = get_remote_state ();
13601
13602 strcpy (rs->buf.data (), "QTro");
13603 offset = strlen (rs->buf.data ());
13604 for (s = abfd->sections; s; s = s->next)
13605 {
13606 char tmp1[40], tmp2[40];
13607 int sec_length;
13608
13609 if ((s->flags & SEC_LOAD) == 0
13610 /* || (s->flags & SEC_CODE) == 0 */
13611 || (s->flags & SEC_READONLY) == 0)
13612 continue;
13613
13614 anysecs = 1;
13615 vma = bfd_section_vma (s);
13616 size = bfd_section_size (s);
13617 bfd_sprintf_vma (abfd, tmp1, vma);
13618 bfd_sprintf_vma (abfd, tmp2, vma + size);
13619 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13620 if (offset + sec_length + 1 > rs->buf.size ())
13621 {
13622 if (m_features.packet_support (PACKET_qXfer_traceframe_info)
13623 != PACKET_ENABLE)
13624 warning (_("\
13625 Too many sections for read-only sections definition packet."));
13626 break;
13627 }
13628 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13629 tmp1, tmp2);
13630 offset += sec_length;
13631 }
13632 if (anysecs)
13633 {
13634 putpkt (rs->buf);
13635 getpkt (&rs->buf);
13636 }
13637 }
13638
13639 void
13640 remote_target::trace_start ()
13641 {
13642 struct remote_state *rs = get_remote_state ();
13643
13644 putpkt ("QTStart");
13645 remote_get_noisy_reply ();
13646 if (rs->buf[0] == '\0')
13647 error (_("Target does not support this command."));
13648 if (strcmp (rs->buf.data (), "OK") != 0)
13649 error (_("Bogus reply from target: %s"), rs->buf.data ());
13650 }
13651
13652 int
13653 remote_target::get_trace_status (struct trace_status *ts)
13654 {
13655 /* Initialize it just to avoid a GCC false warning. */
13656 char *p = NULL;
13657 enum packet_result result;
13658 struct remote_state *rs = get_remote_state ();
13659
13660 if (m_features.packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13661 return -1;
13662
13663 /* FIXME we need to get register block size some other way. */
13664 trace_regblock_size
13665 = rs->get_remote_arch_state (current_inferior ()->arch ())->sizeof_g_packet;
13666
13667 putpkt ("qTStatus");
13668
13669 try
13670 {
13671 p = remote_get_noisy_reply ();
13672 }
13673 catch (const gdb_exception_error &ex)
13674 {
13675 if (ex.error != TARGET_CLOSE_ERROR)
13676 {
13677 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13678 return -1;
13679 }
13680 throw;
13681 }
13682
13683 result = m_features.packet_ok (p, PACKET_qTStatus);
13684
13685 /* If the remote target doesn't do tracing, flag it. */
13686 if (result == PACKET_UNKNOWN)
13687 return -1;
13688
13689 /* We're working with a live target. */
13690 ts->filename = NULL;
13691
13692 if (*p++ != 'T')
13693 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13694
13695 /* Function 'parse_trace_status' sets default value of each field of
13696 'ts' at first, so we don't have to do it here. */
13697 parse_trace_status (p, ts);
13698
13699 return ts->running;
13700 }
13701
13702 void
13703 remote_target::get_tracepoint_status (tracepoint *tp,
13704 struct uploaded_tp *utp)
13705 {
13706 struct remote_state *rs = get_remote_state ();
13707 char *reply;
13708 size_t size = get_remote_packet_size ();
13709
13710 if (tp)
13711 {
13712 tp->hit_count = 0;
13713 tp->traceframe_usage = 0;
13714 for (bp_location &loc : tp->locations ())
13715 {
13716 /* If the tracepoint was never downloaded, don't go asking for
13717 any status. */
13718 if (tp->number_on_target == 0)
13719 continue;
13720 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13721 phex_nz (loc.address, 0));
13722 putpkt (rs->buf);
13723 reply = remote_get_noisy_reply ();
13724 if (reply && *reply)
13725 {
13726 if (*reply == 'V')
13727 parse_tracepoint_status (reply + 1, tp, utp);
13728 }
13729 }
13730 }
13731 else if (utp)
13732 {
13733 utp->hit_count = 0;
13734 utp->traceframe_usage = 0;
13735 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13736 phex_nz (utp->addr, 0));
13737 putpkt (rs->buf);
13738 reply = remote_get_noisy_reply ();
13739 if (reply && *reply)
13740 {
13741 if (*reply == 'V')
13742 parse_tracepoint_status (reply + 1, tp, utp);
13743 }
13744 }
13745 }
13746
13747 void
13748 remote_target::trace_stop ()
13749 {
13750 struct remote_state *rs = get_remote_state ();
13751
13752 putpkt ("QTStop");
13753 remote_get_noisy_reply ();
13754 if (rs->buf[0] == '\0')
13755 error (_("Target does not support this command."));
13756 if (strcmp (rs->buf.data (), "OK") != 0)
13757 error (_("Bogus reply from target: %s"), rs->buf.data ());
13758 }
13759
13760 int
13761 remote_target::trace_find (enum trace_find_type type, int num,
13762 CORE_ADDR addr1, CORE_ADDR addr2,
13763 int *tpp)
13764 {
13765 struct remote_state *rs = get_remote_state ();
13766 char *endbuf = rs->buf.data () + get_remote_packet_size ();
13767 char *p, *reply;
13768 int target_frameno = -1, target_tracept = -1;
13769
13770 /* Lookups other than by absolute frame number depend on the current
13771 trace selected, so make sure it is correct on the remote end
13772 first. */
13773 if (type != tfind_number)
13774 set_remote_traceframe ();
13775
13776 p = rs->buf.data ();
13777 strcpy (p, "QTFrame:");
13778 p = strchr (p, '\0');
13779 switch (type)
13780 {
13781 case tfind_number:
13782 xsnprintf (p, endbuf - p, "%x", num);
13783 break;
13784 case tfind_pc:
13785 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13786 break;
13787 case tfind_tp:
13788 xsnprintf (p, endbuf - p, "tdp:%x", num);
13789 break;
13790 case tfind_range:
13791 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13792 phex_nz (addr2, 0));
13793 break;
13794 case tfind_outside:
13795 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13796 phex_nz (addr2, 0));
13797 break;
13798 default:
13799 error (_("Unknown trace find type %d"), type);
13800 }
13801
13802 putpkt (rs->buf);
13803 reply = remote_get_noisy_reply ();
13804 if (*reply == '\0')
13805 error (_("Target does not support this command."));
13806
13807 while (reply && *reply)
13808 switch (*reply)
13809 {
13810 case 'F':
13811 p = ++reply;
13812 target_frameno = (int) strtol (p, &reply, 16);
13813 if (reply == p)
13814 error (_("Unable to parse trace frame number"));
13815 /* Don't update our remote traceframe number cache on failure
13816 to select a remote traceframe. */
13817 if (target_frameno == -1)
13818 return -1;
13819 break;
13820 case 'T':
13821 p = ++reply;
13822 target_tracept = (int) strtol (p, &reply, 16);
13823 if (reply == p)
13824 error (_("Unable to parse tracepoint number"));
13825 break;
13826 case 'O': /* "OK"? */
13827 if (reply[1] == 'K' && reply[2] == '\0')
13828 reply += 2;
13829 else
13830 error (_("Bogus reply from target: %s"), reply);
13831 break;
13832 default:
13833 error (_("Bogus reply from target: %s"), reply);
13834 }
13835 if (tpp)
13836 *tpp = target_tracept;
13837
13838 rs->remote_traceframe_number = target_frameno;
13839 return target_frameno;
13840 }
13841
13842 bool
13843 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13844 {
13845 struct remote_state *rs = get_remote_state ();
13846 char *reply;
13847 ULONGEST uval;
13848
13849 set_remote_traceframe ();
13850
13851 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
13852 putpkt (rs->buf);
13853 reply = remote_get_noisy_reply ();
13854 if (reply && *reply)
13855 {
13856 if (*reply == 'V')
13857 {
13858 unpack_varlen_hex (reply + 1, &uval);
13859 *val = (LONGEST) uval;
13860 return true;
13861 }
13862 }
13863 return false;
13864 }
13865
13866 int
13867 remote_target::save_trace_data (const char *filename)
13868 {
13869 struct remote_state *rs = get_remote_state ();
13870 char *p, *reply;
13871
13872 p = rs->buf.data ();
13873 strcpy (p, "QTSave:");
13874 p += strlen (p);
13875 if ((p - rs->buf.data ()) + strlen (filename) * 2
13876 >= get_remote_packet_size ())
13877 error (_("Remote file name too long for trace save packet"));
13878 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13879 *p++ = '\0';
13880 putpkt (rs->buf);
13881 reply = remote_get_noisy_reply ();
13882 if (*reply == '\0')
13883 error (_("Target does not support this command."));
13884 if (strcmp (reply, "OK") != 0)
13885 error (_("Bogus reply from target: %s"), reply);
13886 return 0;
13887 }
13888
13889 /* This is basically a memory transfer, but needs to be its own packet
13890 because we don't know how the target actually organizes its trace
13891 memory, plus we want to be able to ask for as much as possible, but
13892 not be unhappy if we don't get as much as we ask for. */
13893
13894 LONGEST
13895 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13896 {
13897 struct remote_state *rs = get_remote_state ();
13898 char *reply;
13899 char *p;
13900 int rslt;
13901
13902 p = rs->buf.data ();
13903 strcpy (p, "qTBuffer:");
13904 p += strlen (p);
13905 p += hexnumstr (p, offset);
13906 *p++ = ',';
13907 p += hexnumstr (p, len);
13908 *p++ = '\0';
13909
13910 putpkt (rs->buf);
13911 reply = remote_get_noisy_reply ();
13912 if (reply && *reply)
13913 {
13914 /* 'l' by itself means we're at the end of the buffer and
13915 there is nothing more to get. */
13916 if (*reply == 'l')
13917 return 0;
13918
13919 /* Convert the reply into binary. Limit the number of bytes to
13920 convert according to our passed-in buffer size, rather than
13921 what was returned in the packet; if the target is
13922 unexpectedly generous and gives us a bigger reply than we
13923 asked for, we don't want to crash. */
13924 rslt = hex2bin (reply, buf, len);
13925 return rslt;
13926 }
13927
13928 /* Something went wrong, flag as an error. */
13929 return -1;
13930 }
13931
13932 void
13933 remote_target::set_disconnected_tracing (int val)
13934 {
13935 struct remote_state *rs = get_remote_state ();
13936
13937 if (m_features.packet_support (PACKET_DisconnectedTracing_feature)
13938 == PACKET_ENABLE)
13939 {
13940 char *reply;
13941
13942 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13943 "QTDisconnected:%x", val);
13944 putpkt (rs->buf);
13945 reply = remote_get_noisy_reply ();
13946 if (*reply == '\0')
13947 error (_("Target does not support this command."));
13948 if (strcmp (reply, "OK") != 0)
13949 error (_("Bogus reply from target: %s"), reply);
13950 }
13951 else if (val)
13952 warning (_("Target does not support disconnected tracing."));
13953 }
13954
13955 int
13956 remote_target::core_of_thread (ptid_t ptid)
13957 {
13958 thread_info *info = this->find_thread (ptid);
13959
13960 if (info != NULL && info->priv != NULL)
13961 return get_remote_thread_info (info)->core;
13962
13963 return -1;
13964 }
13965
13966 void
13967 remote_target::set_circular_trace_buffer (int val)
13968 {
13969 struct remote_state *rs = get_remote_state ();
13970 char *reply;
13971
13972 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13973 "QTBuffer:circular:%x", val);
13974 putpkt (rs->buf);
13975 reply = remote_get_noisy_reply ();
13976 if (*reply == '\0')
13977 error (_("Target does not support this command."));
13978 if (strcmp (reply, "OK") != 0)
13979 error (_("Bogus reply from target: %s"), reply);
13980 }
13981
13982 traceframe_info_up
13983 remote_target::traceframe_info ()
13984 {
13985 gdb::optional<gdb::char_vector> text
13986 = target_read_stralloc (current_inferior ()->top_target (),
13987 TARGET_OBJECT_TRACEFRAME_INFO,
13988 NULL);
13989 if (text)
13990 return parse_traceframe_info (text->data ());
13991
13992 return NULL;
13993 }
13994
13995 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13996 instruction on which a fast tracepoint may be placed. Returns -1
13997 if the packet is not supported, and 0 if the minimum instruction
13998 length is unknown. */
13999
14000 int
14001 remote_target::get_min_fast_tracepoint_insn_len ()
14002 {
14003 struct remote_state *rs = get_remote_state ();
14004 char *reply;
14005
14006 /* If we're not debugging a process yet, the IPA can't be
14007 loaded. */
14008 if (!target_has_execution ())
14009 return 0;
14010
14011 /* Make sure the remote is pointing at the right process. */
14012 set_general_process ();
14013
14014 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
14015 putpkt (rs->buf);
14016 reply = remote_get_noisy_reply ();
14017 if (*reply == '\0')
14018 return -1;
14019 else
14020 {
14021 ULONGEST min_insn_len;
14022
14023 unpack_varlen_hex (reply, &min_insn_len);
14024
14025 return (int) min_insn_len;
14026 }
14027 }
14028
14029 void
14030 remote_target::set_trace_buffer_size (LONGEST val)
14031 {
14032 if (m_features.packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
14033 {
14034 struct remote_state *rs = get_remote_state ();
14035 char *buf = rs->buf.data ();
14036 char *endbuf = buf + get_remote_packet_size ();
14037 enum packet_result result;
14038
14039 gdb_assert (val >= 0 || val == -1);
14040 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
14041 /* Send -1 as literal "-1" to avoid host size dependency. */
14042 if (val < 0)
14043 {
14044 *buf++ = '-';
14045 buf += hexnumstr (buf, (ULONGEST) -val);
14046 }
14047 else
14048 buf += hexnumstr (buf, (ULONGEST) val);
14049
14050 putpkt (rs->buf);
14051 remote_get_noisy_reply ();
14052 result = m_features.packet_ok (rs->buf, PACKET_QTBuffer_size);
14053
14054 if (result != PACKET_OK)
14055 warning (_("Bogus reply from target: %s"), rs->buf.data ());
14056 }
14057 }
14058
14059 bool
14060 remote_target::set_trace_notes (const char *user, const char *notes,
14061 const char *stop_notes)
14062 {
14063 struct remote_state *rs = get_remote_state ();
14064 char *reply;
14065 char *buf = rs->buf.data ();
14066 char *endbuf = buf + get_remote_packet_size ();
14067 int nbytes;
14068
14069 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
14070 if (user)
14071 {
14072 buf += xsnprintf (buf, endbuf - buf, "user:");
14073 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
14074 buf += 2 * nbytes;
14075 *buf++ = ';';
14076 }
14077 if (notes)
14078 {
14079 buf += xsnprintf (buf, endbuf - buf, "notes:");
14080 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
14081 buf += 2 * nbytes;
14082 *buf++ = ';';
14083 }
14084 if (stop_notes)
14085 {
14086 buf += xsnprintf (buf, endbuf - buf, "tstop:");
14087 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
14088 buf += 2 * nbytes;
14089 *buf++ = ';';
14090 }
14091 /* Ensure the buffer is terminated. */
14092 *buf = '\0';
14093
14094 putpkt (rs->buf);
14095 reply = remote_get_noisy_reply ();
14096 if (*reply == '\0')
14097 return false;
14098
14099 if (strcmp (reply, "OK") != 0)
14100 error (_("Bogus reply from target: %s"), reply);
14101
14102 return true;
14103 }
14104
14105 bool
14106 remote_target::use_agent (bool use)
14107 {
14108 if (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE)
14109 {
14110 struct remote_state *rs = get_remote_state ();
14111
14112 /* If the stub supports QAgent. */
14113 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
14114 putpkt (rs->buf);
14115 getpkt (&rs->buf);
14116
14117 if (strcmp (rs->buf.data (), "OK") == 0)
14118 {
14119 ::use_agent = use;
14120 return true;
14121 }
14122 }
14123
14124 return false;
14125 }
14126
14127 bool
14128 remote_target::can_use_agent ()
14129 {
14130 return (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE);
14131 }
14132
14133 #if defined (HAVE_LIBEXPAT)
14134
14135 /* Check the btrace document version. */
14136
14137 static void
14138 check_xml_btrace_version (struct gdb_xml_parser *parser,
14139 const struct gdb_xml_element *element,
14140 void *user_data,
14141 std::vector<gdb_xml_value> &attributes)
14142 {
14143 const char *version
14144 = (const char *) xml_find_attribute (attributes, "version")->value.get ();
14145
14146 if (strcmp (version, "1.0") != 0)
14147 gdb_xml_error (parser, _("Unsupported btrace version: \"%s\""), version);
14148 }
14149
14150 /* Parse a btrace "block" xml record. */
14151
14152 static void
14153 parse_xml_btrace_block (struct gdb_xml_parser *parser,
14154 const struct gdb_xml_element *element,
14155 void *user_data,
14156 std::vector<gdb_xml_value> &attributes)
14157 {
14158 struct btrace_data *btrace;
14159 ULONGEST *begin, *end;
14160
14161 btrace = (struct btrace_data *) user_data;
14162
14163 switch (btrace->format)
14164 {
14165 case BTRACE_FORMAT_BTS:
14166 break;
14167
14168 case BTRACE_FORMAT_NONE:
14169 btrace->format = BTRACE_FORMAT_BTS;
14170 btrace->variant.bts.blocks = new std::vector<btrace_block>;
14171 break;
14172
14173 default:
14174 gdb_xml_error (parser, _("Btrace format error."));
14175 }
14176
14177 begin = (ULONGEST *) xml_find_attribute (attributes, "begin")->value.get ();
14178 end = (ULONGEST *) xml_find_attribute (attributes, "end")->value.get ();
14179 btrace->variant.bts.blocks->emplace_back (*begin, *end);
14180 }
14181
14182 /* Parse a "raw" xml record. */
14183
14184 static void
14185 parse_xml_raw (struct gdb_xml_parser *parser, const char *body_text,
14186 gdb_byte **pdata, size_t *psize)
14187 {
14188 gdb_byte *bin;
14189 size_t len, size;
14190
14191 len = strlen (body_text);
14192 if (len % 2 != 0)
14193 gdb_xml_error (parser, _("Bad raw data size."));
14194
14195 size = len / 2;
14196
14197 gdb::unique_xmalloc_ptr<gdb_byte> data ((gdb_byte *) xmalloc (size));
14198 bin = data.get ();
14199
14200 /* We use hex encoding - see gdbsupport/rsp-low.h. */
14201 while (len > 0)
14202 {
14203 char hi, lo;
14204
14205 hi = *body_text++;
14206 lo = *body_text++;
14207
14208 if (hi == 0 || lo == 0)
14209 gdb_xml_error (parser, _("Bad hex encoding."));
14210
14211 *bin++ = fromhex (hi) * 16 + fromhex (lo);
14212 len -= 2;
14213 }
14214
14215 *pdata = data.release ();
14216 *psize = size;
14217 }
14218
14219 /* Parse a btrace pt-config "cpu" xml record. */
14220
14221 static void
14222 parse_xml_btrace_pt_config_cpu (struct gdb_xml_parser *parser,
14223 const struct gdb_xml_element *element,
14224 void *user_data,
14225 std::vector<gdb_xml_value> &attributes)
14226 {
14227 struct btrace_data *btrace;
14228 const char *vendor;
14229 ULONGEST *family, *model, *stepping;
14230
14231 vendor
14232 = (const char *) xml_find_attribute (attributes, "vendor")->value.get ();
14233 family
14234 = (ULONGEST *) xml_find_attribute (attributes, "family")->value.get ();
14235 model
14236 = (ULONGEST *) xml_find_attribute (attributes, "model")->value.get ();
14237 stepping
14238 = (ULONGEST *) xml_find_attribute (attributes, "stepping")->value.get ();
14239
14240 btrace = (struct btrace_data *) user_data;
14241
14242 if (strcmp (vendor, "GenuineIntel") == 0)
14243 btrace->variant.pt.config.cpu.vendor = CV_INTEL;
14244
14245 btrace->variant.pt.config.cpu.family = *family;
14246 btrace->variant.pt.config.cpu.model = *model;
14247 btrace->variant.pt.config.cpu.stepping = *stepping;
14248 }
14249
14250 /* Parse a btrace pt "raw" xml record. */
14251
14252 static void
14253 parse_xml_btrace_pt_raw (struct gdb_xml_parser *parser,
14254 const struct gdb_xml_element *element,
14255 void *user_data, const char *body_text)
14256 {
14257 struct btrace_data *btrace;
14258
14259 btrace = (struct btrace_data *) user_data;
14260 parse_xml_raw (parser, body_text, &btrace->variant.pt.data,
14261 &btrace->variant.pt.size);
14262 }
14263
14264 /* Parse a btrace "pt" xml record. */
14265
14266 static void
14267 parse_xml_btrace_pt (struct gdb_xml_parser *parser,
14268 const struct gdb_xml_element *element,
14269 void *user_data,
14270 std::vector<gdb_xml_value> &attributes)
14271 {
14272 struct btrace_data *btrace;
14273
14274 btrace = (struct btrace_data *) user_data;
14275 btrace->format = BTRACE_FORMAT_PT;
14276 btrace->variant.pt.config.cpu.vendor = CV_UNKNOWN;
14277 btrace->variant.pt.data = NULL;
14278 btrace->variant.pt.size = 0;
14279 }
14280
14281 static const struct gdb_xml_attribute block_attributes[] = {
14282 { "begin", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14283 { "end", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14284 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14285 };
14286
14287 static const struct gdb_xml_attribute btrace_pt_config_cpu_attributes[] = {
14288 { "vendor", GDB_XML_AF_NONE, NULL, NULL },
14289 { "family", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14290 { "model", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14291 { "stepping", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14292 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14293 };
14294
14295 static const struct gdb_xml_element btrace_pt_config_children[] = {
14296 { "cpu", btrace_pt_config_cpu_attributes, NULL, GDB_XML_EF_OPTIONAL,
14297 parse_xml_btrace_pt_config_cpu, NULL },
14298 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14299 };
14300
14301 static const struct gdb_xml_element btrace_pt_children[] = {
14302 { "pt-config", NULL, btrace_pt_config_children, GDB_XML_EF_OPTIONAL, NULL,
14303 NULL },
14304 { "raw", NULL, NULL, GDB_XML_EF_OPTIONAL, NULL, parse_xml_btrace_pt_raw },
14305 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14306 };
14307
14308 static const struct gdb_xml_attribute btrace_attributes[] = {
14309 { "version", GDB_XML_AF_NONE, NULL, NULL },
14310 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14311 };
14312
14313 static const struct gdb_xml_element btrace_children[] = {
14314 { "block", block_attributes, NULL,
14315 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL, parse_xml_btrace_block, NULL },
14316 { "pt", NULL, btrace_pt_children, GDB_XML_EF_OPTIONAL, parse_xml_btrace_pt,
14317 NULL },
14318 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14319 };
14320
14321 static const struct gdb_xml_element btrace_elements[] = {
14322 { "btrace", btrace_attributes, btrace_children, GDB_XML_EF_NONE,
14323 check_xml_btrace_version, NULL },
14324 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14325 };
14326
14327 #endif /* defined (HAVE_LIBEXPAT) */
14328
14329 /* Parse a branch trace xml document XML into DATA. */
14330
14331 static void
14332 parse_xml_btrace (struct btrace_data *btrace, const char *buffer)
14333 {
14334 #if defined (HAVE_LIBEXPAT)
14335
14336 int errcode;
14337 btrace_data result;
14338 result.format = BTRACE_FORMAT_NONE;
14339
14340 errcode = gdb_xml_parse_quick (_("btrace"), "btrace.dtd", btrace_elements,
14341 buffer, &result);
14342 if (errcode != 0)
14343 error (_("Error parsing branch trace."));
14344
14345 /* Keep parse results. */
14346 *btrace = std::move (result);
14347
14348 #else /* !defined (HAVE_LIBEXPAT) */
14349
14350 error (_("Cannot process branch trace. XML support was disabled at "
14351 "compile time."));
14352
14353 #endif /* !defined (HAVE_LIBEXPAT) */
14354 }
14355
14356 #if defined (HAVE_LIBEXPAT)
14357
14358 /* Parse a btrace-conf "bts" xml record. */
14359
14360 static void
14361 parse_xml_btrace_conf_bts (struct gdb_xml_parser *parser,
14362 const struct gdb_xml_element *element,
14363 void *user_data,
14364 std::vector<gdb_xml_value> &attributes)
14365 {
14366 struct btrace_config *conf;
14367 struct gdb_xml_value *size;
14368
14369 conf = (struct btrace_config *) user_data;
14370 conf->format = BTRACE_FORMAT_BTS;
14371 conf->bts.size = 0;
14372
14373 size = xml_find_attribute (attributes, "size");
14374 if (size != NULL)
14375 conf->bts.size = (unsigned int) *(ULONGEST *) size->value.get ();
14376 }
14377
14378 /* Parse a btrace-conf "pt" xml record. */
14379
14380 static void
14381 parse_xml_btrace_conf_pt (struct gdb_xml_parser *parser,
14382 const struct gdb_xml_element *element,
14383 void *user_data,
14384 std::vector<gdb_xml_value> &attributes)
14385 {
14386 struct btrace_config *conf;
14387 struct gdb_xml_value *size;
14388
14389 conf = (struct btrace_config *) user_data;
14390 conf->format = BTRACE_FORMAT_PT;
14391 conf->pt.size = 0;
14392
14393 size = xml_find_attribute (attributes, "size");
14394 if (size != NULL)
14395 conf->pt.size = (unsigned int) *(ULONGEST *) size->value.get ();
14396 }
14397
14398 static const struct gdb_xml_attribute btrace_conf_pt_attributes[] = {
14399 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14400 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14401 };
14402
14403 static const struct gdb_xml_attribute btrace_conf_bts_attributes[] = {
14404 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14405 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14406 };
14407
14408 static const struct gdb_xml_element btrace_conf_children[] = {
14409 { "bts", btrace_conf_bts_attributes, NULL, GDB_XML_EF_OPTIONAL,
14410 parse_xml_btrace_conf_bts, NULL },
14411 { "pt", btrace_conf_pt_attributes, NULL, GDB_XML_EF_OPTIONAL,
14412 parse_xml_btrace_conf_pt, NULL },
14413 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14414 };
14415
14416 static const struct gdb_xml_attribute btrace_conf_attributes[] = {
14417 { "version", GDB_XML_AF_NONE, NULL, NULL },
14418 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14419 };
14420
14421 static const struct gdb_xml_element btrace_conf_elements[] = {
14422 { "btrace-conf", btrace_conf_attributes, btrace_conf_children,
14423 GDB_XML_EF_NONE, NULL, NULL },
14424 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14425 };
14426
14427 #endif /* defined (HAVE_LIBEXPAT) */
14428
14429 /* Parse a branch trace configuration xml document XML into CONF. */
14430
14431 static void
14432 parse_xml_btrace_conf (struct btrace_config *conf, const char *xml)
14433 {
14434 #if defined (HAVE_LIBEXPAT)
14435
14436 int errcode;
14437 errcode = gdb_xml_parse_quick (_("btrace-conf"), "btrace-conf.dtd",
14438 btrace_conf_elements, xml, conf);
14439 if (errcode != 0)
14440 error (_("Error parsing branch trace configuration."));
14441
14442 #else /* !defined (HAVE_LIBEXPAT) */
14443
14444 error (_("Cannot process the branch trace configuration. XML support "
14445 "was disabled at compile time."));
14446
14447 #endif /* !defined (HAVE_LIBEXPAT) */
14448 }
14449
14450 /* Reset our idea of our target's btrace configuration. */
14451
14452 static void
14453 remote_btrace_reset (remote_state *rs)
14454 {
14455 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14456 }
14457
14458 /* Synchronize the configuration with the target. */
14459
14460 void
14461 remote_target::btrace_sync_conf (const btrace_config *conf)
14462 {
14463 struct remote_state *rs;
14464 char *buf, *pos, *endbuf;
14465
14466 rs = get_remote_state ();
14467 buf = rs->buf.data ();
14468 endbuf = buf + get_remote_packet_size ();
14469
14470 if (m_features.packet_support (PACKET_Qbtrace_conf_bts_size) == PACKET_ENABLE
14471 && conf->bts.size != rs->btrace_config.bts.size)
14472 {
14473 pos = buf;
14474 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14475 packets_descriptions[PACKET_Qbtrace_conf_bts_size].name,
14476 conf->bts.size);
14477
14478 putpkt (buf);
14479 getpkt (&rs->buf);
14480
14481 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_bts_size)
14482 == PACKET_ERROR)
14483 {
14484 if (buf[0] == 'E' && buf[1] == '.')
14485 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14486 else
14487 error (_("Failed to configure the BTS buffer size."));
14488 }
14489
14490 rs->btrace_config.bts.size = conf->bts.size;
14491 }
14492
14493 if (m_features.packet_support (PACKET_Qbtrace_conf_pt_size) == PACKET_ENABLE
14494 && conf->pt.size != rs->btrace_config.pt.size)
14495 {
14496 pos = buf;
14497 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14498 packets_descriptions[PACKET_Qbtrace_conf_pt_size].name,
14499 conf->pt.size);
14500
14501 putpkt (buf);
14502 getpkt (&rs->buf);
14503
14504 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_size)
14505 == PACKET_ERROR)
14506 {
14507 if (buf[0] == 'E' && buf[1] == '.')
14508 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14509 else
14510 error (_("Failed to configure the trace buffer size."));
14511 }
14512
14513 rs->btrace_config.pt.size = conf->pt.size;
14514 }
14515 }
14516
14517 /* Read TP's btrace configuration from the target and store it into CONF. */
14518
14519 static void
14520 btrace_read_config (thread_info *tp, btrace_config *conf)
14521 {
14522 /* target_read_stralloc relies on INFERIOR_PTID. */
14523 scoped_restore_current_thread restore_thread;
14524 switch_to_thread (tp);
14525
14526 gdb::optional<gdb::char_vector> xml
14527 = target_read_stralloc (current_inferior ()->top_target (),
14528 TARGET_OBJECT_BTRACE_CONF, "");
14529 if (xml)
14530 parse_xml_btrace_conf (conf, xml->data ());
14531 }
14532
14533 /* Maybe reopen target btrace. */
14534
14535 void
14536 remote_target::remote_btrace_maybe_reopen ()
14537 {
14538 struct remote_state *rs = get_remote_state ();
14539 int btrace_target_pushed = 0;
14540 #if !defined (HAVE_LIBIPT)
14541 int warned = 0;
14542 #endif
14543
14544 /* Don't bother walking the entirety of the remote thread list when
14545 we know the feature isn't supported by the remote. */
14546 if (m_features.packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14547 return;
14548
14549 for (thread_info *tp : all_non_exited_threads (this))
14550 {
14551 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14552 btrace_read_config (tp, &rs->btrace_config);
14553
14554 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14555 continue;
14556
14557 #if !defined (HAVE_LIBIPT)
14558 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14559 {
14560 if (!warned)
14561 {
14562 warned = 1;
14563 warning (_("Target is recording using Intel Processor Trace "
14564 "but support was disabled at compile time."));
14565 }
14566
14567 continue;
14568 }
14569 #endif /* !defined (HAVE_LIBIPT) */
14570
14571 /* Push target, once, but before anything else happens. This way our
14572 changes to the threads will be cleaned up by unpushing the target
14573 in case btrace_read_config () throws. */
14574 if (!btrace_target_pushed)
14575 {
14576 btrace_target_pushed = 1;
14577 record_btrace_push_target ();
14578 gdb_printf (_("Target is recording using %s.\n"),
14579 btrace_format_string (rs->btrace_config.format));
14580 }
14581
14582 tp->btrace.target
14583 = new btrace_target_info { tp->ptid, rs->btrace_config };
14584 }
14585 }
14586
14587 /* Enable branch tracing. */
14588
14589 struct btrace_target_info *
14590 remote_target::enable_btrace (thread_info *tp,
14591 const struct btrace_config *conf)
14592 {
14593 struct packet_config *packet = NULL;
14594 struct remote_state *rs = get_remote_state ();
14595 char *buf = rs->buf.data ();
14596 char *endbuf = buf + get_remote_packet_size ();
14597
14598 unsigned int which_packet;
14599 switch (conf->format)
14600 {
14601 case BTRACE_FORMAT_BTS:
14602 which_packet = PACKET_Qbtrace_bts;
14603 break;
14604 case BTRACE_FORMAT_PT:
14605 which_packet = PACKET_Qbtrace_pt;
14606 break;
14607 default:
14608 internal_error (_("Bad branch btrace format: %u."),
14609 (unsigned int) conf->format);
14610 }
14611
14612 packet = &m_features.m_protocol_packets[which_packet];
14613 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14614 error (_("Target does not support branch tracing."));
14615
14616 btrace_sync_conf (conf);
14617
14618 ptid_t ptid = tp->ptid;
14619 set_general_thread (ptid);
14620
14621 buf += xsnprintf (buf, endbuf - buf, "%s",
14622 packets_descriptions[which_packet].name);
14623 putpkt (rs->buf);
14624 getpkt (&rs->buf);
14625
14626 if (m_features.packet_ok (rs->buf, which_packet) == PACKET_ERROR)
14627 {
14628 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14629 error (_("Could not enable branch tracing for %s: %s"),
14630 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14631 else
14632 error (_("Could not enable branch tracing for %s."),
14633 target_pid_to_str (ptid).c_str ());
14634 }
14635
14636 btrace_target_info *tinfo = new btrace_target_info { ptid };
14637
14638 /* If we fail to read the configuration, we lose some information, but the
14639 tracing itself is not impacted. */
14640 try
14641 {
14642 btrace_read_config (tp, &tinfo->conf);
14643 }
14644 catch (const gdb_exception_error &err)
14645 {
14646 if (err.message != NULL)
14647 warning ("%s", err.what ());
14648 }
14649
14650 return tinfo;
14651 }
14652
14653 /* Disable branch tracing. */
14654
14655 void
14656 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14657 {
14658 struct remote_state *rs = get_remote_state ();
14659 char *buf = rs->buf.data ();
14660 char *endbuf = buf + get_remote_packet_size ();
14661
14662 if (m_features.packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
14663 error (_("Target does not support branch tracing."));
14664
14665 set_general_thread (tinfo->ptid);
14666
14667 buf += xsnprintf (buf, endbuf - buf, "%s",
14668 packets_descriptions[PACKET_Qbtrace_off].name);
14669 putpkt (rs->buf);
14670 getpkt (&rs->buf);
14671
14672 if (m_features.packet_ok (rs->buf, PACKET_Qbtrace_off) == PACKET_ERROR)
14673 {
14674 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14675 error (_("Could not disable branch tracing for %s: %s"),
14676 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14677 else
14678 error (_("Could not disable branch tracing for %s."),
14679 target_pid_to_str (tinfo->ptid).c_str ());
14680 }
14681
14682 delete tinfo;
14683 }
14684
14685 /* Teardown branch tracing. */
14686
14687 void
14688 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14689 {
14690 /* We must not talk to the target during teardown. */
14691 delete tinfo;
14692 }
14693
14694 /* Read the branch trace. */
14695
14696 enum btrace_error
14697 remote_target::read_btrace (struct btrace_data *btrace,
14698 struct btrace_target_info *tinfo,
14699 enum btrace_read_type type)
14700 {
14701 const char *annex;
14702
14703 if (m_features.packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
14704 error (_("Target does not support branch tracing."));
14705
14706 #if !defined(HAVE_LIBEXPAT)
14707 error (_("Cannot process branch tracing result. XML parsing not supported."));
14708 #endif
14709
14710 switch (type)
14711 {
14712 case BTRACE_READ_ALL:
14713 annex = "all";
14714 break;
14715 case BTRACE_READ_NEW:
14716 annex = "new";
14717 break;
14718 case BTRACE_READ_DELTA:
14719 annex = "delta";
14720 break;
14721 default:
14722 internal_error (_("Bad branch tracing read type: %u."),
14723 (unsigned int) type);
14724 }
14725
14726 gdb::optional<gdb::char_vector> xml
14727 = target_read_stralloc (current_inferior ()->top_target (),
14728 TARGET_OBJECT_BTRACE, annex);
14729 if (!xml)
14730 return BTRACE_ERR_UNKNOWN;
14731
14732 parse_xml_btrace (btrace, xml->data ());
14733
14734 return BTRACE_ERR_NONE;
14735 }
14736
14737 const struct btrace_config *
14738 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14739 {
14740 return &tinfo->conf;
14741 }
14742
14743 bool
14744 remote_target::augmented_libraries_svr4_read ()
14745 {
14746 return
14747 (m_features.packet_support (PACKET_augmented_libraries_svr4_read_feature)
14748 == PACKET_ENABLE);
14749 }
14750
14751 /* Implementation of to_load. */
14752
14753 void
14754 remote_target::load (const char *name, int from_tty)
14755 {
14756 generic_load (name, from_tty);
14757 }
14758
14759 /* Accepts an integer PID; returns a string representing a file that
14760 can be opened on the remote side to get the symbols for the child
14761 process. Returns NULL if the operation is not supported. */
14762
14763 const char *
14764 remote_target::pid_to_exec_file (int pid)
14765 {
14766 static gdb::optional<gdb::char_vector> filename;
14767 char *annex = NULL;
14768
14769 if (m_features.packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14770 return NULL;
14771
14772 inferior *inf = find_inferior_pid (this, pid);
14773 if (inf == NULL)
14774 internal_error (_("not currently attached to process %d"), pid);
14775
14776 if (!inf->fake_pid_p)
14777 {
14778 const int annex_size = 9;
14779
14780 annex = (char *) alloca (annex_size);
14781 xsnprintf (annex, annex_size, "%x", pid);
14782 }
14783
14784 filename = target_read_stralloc (current_inferior ()->top_target (),
14785 TARGET_OBJECT_EXEC_FILE, annex);
14786
14787 return filename ? filename->data () : nullptr;
14788 }
14789
14790 /* Implement the to_can_do_single_step target_ops method. */
14791
14792 int
14793 remote_target::can_do_single_step ()
14794 {
14795 /* We can only tell whether target supports single step or not by
14796 supported s and S vCont actions if the stub supports vContSupported
14797 feature. If the stub doesn't support vContSupported feature,
14798 we have conservatively to think target doesn't supports single
14799 step. */
14800 if (m_features.packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14801 {
14802 struct remote_state *rs = get_remote_state ();
14803
14804 return rs->supports_vCont.s && rs->supports_vCont.S;
14805 }
14806 else
14807 return 0;
14808 }
14809
14810 /* Implementation of the to_execution_direction method for the remote
14811 target. */
14812
14813 enum exec_direction_kind
14814 remote_target::execution_direction ()
14815 {
14816 struct remote_state *rs = get_remote_state ();
14817
14818 return rs->last_resume_exec_dir;
14819 }
14820
14821 /* Return pointer to the thread_info struct which corresponds to
14822 THREAD_HANDLE (having length HANDLE_LEN). */
14823
14824 thread_info *
14825 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14826 int handle_len,
14827 inferior *inf)
14828 {
14829 for (thread_info *tp : all_non_exited_threads (this))
14830 {
14831 remote_thread_info *priv = get_remote_thread_info (tp);
14832
14833 if (tp->inf == inf && priv != NULL)
14834 {
14835 if (handle_len != priv->thread_handle.size ())
14836 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14837 handle_len, priv->thread_handle.size ());
14838 if (memcmp (thread_handle, priv->thread_handle.data (),
14839 handle_len) == 0)
14840 return tp;
14841 }
14842 }
14843
14844 return NULL;
14845 }
14846
14847 gdb::array_view<const gdb_byte>
14848 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14849 {
14850 remote_thread_info *priv = get_remote_thread_info (tp);
14851 return priv->thread_handle;
14852 }
14853
14854 bool
14855 remote_target::can_async_p ()
14856 {
14857 /* This flag should be checked in the common target.c code. */
14858 gdb_assert (target_async_permitted);
14859
14860 /* We're async whenever the serial device can. */
14861 struct remote_state *rs = get_remote_state ();
14862 return serial_can_async_p (rs->remote_desc);
14863 }
14864
14865 bool
14866 remote_target::is_async_p ()
14867 {
14868 /* We're async whenever the serial device is. */
14869 struct remote_state *rs = get_remote_state ();
14870 return serial_is_async_p (rs->remote_desc);
14871 }
14872
14873 /* Pass the SERIAL event on and up to the client. One day this code
14874 will be able to delay notifying the client of an event until the
14875 point where an entire packet has been received. */
14876
14877 static serial_event_ftype remote_async_serial_handler;
14878
14879 static void
14880 remote_async_serial_handler (struct serial *scb, void *context)
14881 {
14882 /* Don't propogate error information up to the client. Instead let
14883 the client find out about the error by querying the target. */
14884 inferior_event_handler (INF_REG_EVENT);
14885 }
14886
14887 int
14888 remote_target::async_wait_fd ()
14889 {
14890 struct remote_state *rs = get_remote_state ();
14891 return rs->remote_desc->fd;
14892 }
14893
14894 void
14895 remote_target::async (bool enable)
14896 {
14897 struct remote_state *rs = get_remote_state ();
14898
14899 if (enable)
14900 {
14901 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14902
14903 /* If there are pending events in the stop reply queue tell the
14904 event loop to process them. */
14905 if (!rs->stop_reply_queue.empty ())
14906 rs->mark_async_event_handler ();
14907
14908 /* For simplicity, below we clear the pending events token
14909 without remembering whether it is marked, so here we always
14910 mark it. If there's actually no pending notification to
14911 process, this ends up being a no-op (other than a spurious
14912 event-loop wakeup). */
14913 if (target_is_non_stop_p ())
14914 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14915 }
14916 else
14917 {
14918 serial_async (rs->remote_desc, NULL, NULL);
14919 /* If the core is disabling async, it doesn't want to be
14920 disturbed with target events. Clear all async event sources
14921 too. */
14922 rs->clear_async_event_handler ();
14923
14924 if (target_is_non_stop_p ())
14925 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14926 }
14927 }
14928
14929 /* Implementation of the to_thread_events method. */
14930
14931 void
14932 remote_target::thread_events (int enable)
14933 {
14934 struct remote_state *rs = get_remote_state ();
14935 size_t size = get_remote_packet_size ();
14936
14937 if (m_features.packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14938 return;
14939
14940 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
14941 putpkt (rs->buf);
14942 getpkt (&rs->buf);
14943
14944 switch (m_features.packet_ok (rs->buf, PACKET_QThreadEvents))
14945 {
14946 case PACKET_OK:
14947 if (strcmp (rs->buf.data (), "OK") != 0)
14948 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
14949 break;
14950 case PACKET_ERROR:
14951 warning (_("Remote failure reply: %s"), rs->buf.data ());
14952 break;
14953 case PACKET_UNKNOWN:
14954 break;
14955 }
14956 }
14957
14958 static void
14959 show_remote_cmd (const char *args, int from_tty)
14960 {
14961 /* We can't just use cmd_show_list here, because we want to skip
14962 the redundant "show remote Z-packet" and the legacy aliases. */
14963 struct cmd_list_element *list = remote_show_cmdlist;
14964 struct ui_out *uiout = current_uiout;
14965
14966 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14967 for (; list != NULL; list = list->next)
14968 if (strcmp (list->name, "Z-packet") == 0)
14969 continue;
14970 else if (list->type == not_set_cmd)
14971 /* Alias commands are exactly like the original, except they
14972 don't have the normal type. */
14973 continue;
14974 else
14975 {
14976 ui_out_emit_tuple option_emitter (uiout, "option");
14977
14978 uiout->field_string ("name", list->name);
14979 uiout->text (": ");
14980 if (list->type == show_cmd)
14981 do_show_command (NULL, from_tty, list);
14982 else
14983 cmd_func (list, NULL, from_tty);
14984 }
14985 }
14986
14987 /* Some change happened in PSPACE's objfile list (obfiles added or removed),
14988 offer all inferiors using that program space a change to look up symbols. */
14989
14990 static void
14991 remote_objfile_changed_check_symbols (program_space *pspace)
14992 {
14993 /* The affected program space is possibly shared by multiple inferiors.
14994 Consider sending a qSymbol packet for each of the inferiors using that
14995 program space. */
14996 for (inferior *inf : all_inferiors ())
14997 {
14998 if (inf->pspace != pspace)
14999 continue;
15000
15001 /* Check whether the inferior's process target is a remote target. */
15002 remote_target *remote = as_remote_target (inf->process_target ());
15003 if (remote == nullptr)
15004 continue;
15005
15006 /* When we are attaching or handling a fork child and the shared library
15007 subsystem reads the list of loaded libraries, we receive new objfile
15008 events in between each found library. The libraries are read in an
15009 undefined order, so if we gave the remote side a chance to look up
15010 symbols between each objfile, we might give it an inconsistent picture
15011 of the inferior. It could appear that a library A appears loaded but
15012 a library B does not, even though library A requires library B. That
15013 would present a state that couldn't normally exist in the inferior.
15014
15015 So, skip these events, we'll give the remote a chance to look up
15016 symbols once all the loaded libraries and their symbols are known to
15017 GDB. */
15018 if (inf->in_initial_library_scan)
15019 continue;
15020
15021 if (!remote->has_execution (inf))
15022 continue;
15023
15024 /* Need to switch to a specific thread, because remote_check_symbols will
15025 set the general thread using INFERIOR_PTID.
15026
15027 It's possible to have inferiors with no thread here, because we are
15028 called very early in the connection process, while the inferior is
15029 being set up, before threads are added. Just skip it, start_remote_1
15030 also calls remote_check_symbols when it's done setting things up. */
15031 thread_info *thread = any_thread_of_inferior (inf);
15032 if (thread != nullptr)
15033 {
15034 scoped_restore_current_thread restore_thread;
15035 switch_to_thread (thread);
15036 remote->remote_check_symbols ();
15037 }
15038 }
15039 }
15040
15041 /* Function to be called whenever a new objfile (shlib) is detected. */
15042
15043 static void
15044 remote_new_objfile (struct objfile *objfile)
15045 {
15046 remote_objfile_changed_check_symbols (objfile->pspace);
15047 }
15048
15049 /* Pull all the tracepoints defined on the target and create local
15050 data structures representing them. We don't want to create real
15051 tracepoints yet, we don't want to mess up the user's existing
15052 collection. */
15053
15054 int
15055 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
15056 {
15057 struct remote_state *rs = get_remote_state ();
15058 char *p;
15059
15060 /* Ask for a first packet of tracepoint definition. */
15061 putpkt ("qTfP");
15062 getpkt (&rs->buf);
15063 p = rs->buf.data ();
15064 while (*p && *p != 'l')
15065 {
15066 parse_tracepoint_definition (p, utpp);
15067 /* Ask for another packet of tracepoint definition. */
15068 putpkt ("qTsP");
15069 getpkt (&rs->buf);
15070 p = rs->buf.data ();
15071 }
15072 return 0;
15073 }
15074
15075 int
15076 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
15077 {
15078 struct remote_state *rs = get_remote_state ();
15079 char *p;
15080
15081 /* Ask for a first packet of variable definition. */
15082 putpkt ("qTfV");
15083 getpkt (&rs->buf);
15084 p = rs->buf.data ();
15085 while (*p && *p != 'l')
15086 {
15087 parse_tsv_definition (p, utsvp);
15088 /* Ask for another packet of variable definition. */
15089 putpkt ("qTsV");
15090 getpkt (&rs->buf);
15091 p = rs->buf.data ();
15092 }
15093 return 0;
15094 }
15095
15096 /* The "set/show range-stepping" show hook. */
15097
15098 static void
15099 show_range_stepping (struct ui_file *file, int from_tty,
15100 struct cmd_list_element *c,
15101 const char *value)
15102 {
15103 gdb_printf (file,
15104 _("Debugger's willingness to use range stepping "
15105 "is %s.\n"), value);
15106 }
15107
15108 /* Return true if the vCont;r action is supported by the remote
15109 stub. */
15110
15111 bool
15112 remote_target::vcont_r_supported ()
15113 {
15114 return (m_features.packet_support (PACKET_vCont) == PACKET_ENABLE
15115 && get_remote_state ()->supports_vCont.r);
15116 }
15117
15118 /* The "set/show range-stepping" set hook. */
15119
15120 static void
15121 set_range_stepping (const char *ignore_args, int from_tty,
15122 struct cmd_list_element *c)
15123 {
15124 /* When enabling, check whether range stepping is actually supported
15125 by the target, and warn if not. */
15126 if (use_range_stepping)
15127 {
15128 remote_target *remote = get_current_remote_target ();
15129 if (remote == NULL
15130 || !remote->vcont_r_supported ())
15131 warning (_("Range stepping is not supported by the current target"));
15132 }
15133 }
15134
15135 static void
15136 show_remote_debug (struct ui_file *file, int from_tty,
15137 struct cmd_list_element *c, const char *value)
15138 {
15139 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
15140 value);
15141 }
15142
15143 static void
15144 show_remote_timeout (struct ui_file *file, int from_tty,
15145 struct cmd_list_element *c, const char *value)
15146 {
15147 gdb_printf (file,
15148 _("Timeout limit to wait for target to respond is %s.\n"),
15149 value);
15150 }
15151
15152 /* Implement the "supports_memory_tagging" target_ops method. */
15153
15154 bool
15155 remote_target::supports_memory_tagging ()
15156 {
15157 return m_features.remote_memory_tagging_p ();
15158 }
15159
15160 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
15161
15162 static void
15163 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15164 size_t len, int type)
15165 {
15166 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15167
15168 std::string request = string_printf ("qMemTags:%s,%s:%s",
15169 phex_nz (address, addr_size),
15170 phex_nz (len, sizeof (len)),
15171 phex_nz (type, sizeof (type)));
15172
15173 strcpy (packet.data (), request.c_str ());
15174 }
15175
15176 /* Parse the qMemTags packet reply into TAGS.
15177
15178 Return true if successful, false otherwise. */
15179
15180 static bool
15181 parse_fetch_memtags_reply (const gdb::char_vector &reply,
15182 gdb::byte_vector &tags)
15183 {
15184 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
15185 return false;
15186
15187 /* Copy the tag data. */
15188 tags = hex2bin (reply.data () + 1);
15189
15190 return true;
15191 }
15192
15193 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
15194
15195 static void
15196 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15197 size_t len, int type,
15198 const gdb::byte_vector &tags)
15199 {
15200 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15201
15202 /* Put together the main packet, address and length. */
15203 std::string request = string_printf ("QMemTags:%s,%s:%s:",
15204 phex_nz (address, addr_size),
15205 phex_nz (len, sizeof (len)),
15206 phex_nz (type, sizeof (type)));
15207 request += bin2hex (tags.data (), tags.size ());
15208
15209 /* Check if we have exceeded the maximum packet size. */
15210 if (packet.size () < request.length ())
15211 error (_("Contents too big for packet QMemTags."));
15212
15213 strcpy (packet.data (), request.c_str ());
15214 }
15215
15216 /* Implement the "fetch_memtags" target_ops method. */
15217
15218 bool
15219 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
15220 gdb::byte_vector &tags, int type)
15221 {
15222 /* Make sure the qMemTags packet is supported. */
15223 if (!m_features.remote_memory_tagging_p ())
15224 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
15225
15226 struct remote_state *rs = get_remote_state ();
15227
15228 create_fetch_memtags_request (rs->buf, address, len, type);
15229
15230 putpkt (rs->buf);
15231 getpkt (&rs->buf);
15232
15233 return parse_fetch_memtags_reply (rs->buf, tags);
15234 }
15235
15236 /* Implement the "store_memtags" target_ops method. */
15237
15238 bool
15239 remote_target::store_memtags (CORE_ADDR address, size_t len,
15240 const gdb::byte_vector &tags, int type)
15241 {
15242 /* Make sure the QMemTags packet is supported. */
15243 if (!m_features.remote_memory_tagging_p ())
15244 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
15245
15246 struct remote_state *rs = get_remote_state ();
15247
15248 create_store_memtags_request (rs->buf, address, len, type, tags);
15249
15250 putpkt (rs->buf);
15251 getpkt (&rs->buf);
15252
15253 /* Verify if the request was successful. */
15254 return packet_check_result (rs->buf.data ()) == PACKET_OK;
15255 }
15256
15257 /* Return true if remote target T is non-stop. */
15258
15259 bool
15260 remote_target_is_non_stop_p (remote_target *t)
15261 {
15262 scoped_restore_current_thread restore_thread;
15263 switch_to_target_no_thread (t);
15264
15265 return target_is_non_stop_p ();
15266 }
15267
15268 #if GDB_SELF_TEST
15269
15270 namespace selftests {
15271
15272 static void
15273 test_memory_tagging_functions ()
15274 {
15275 remote_target remote;
15276
15277 struct packet_config *config
15278 = &remote.m_features.m_protocol_packets[PACKET_memory_tagging_feature];
15279
15280 scoped_restore restore_memtag_support_
15281 = make_scoped_restore (&config->support);
15282
15283 /* Test memory tagging packet support. */
15284 config->support = PACKET_SUPPORT_UNKNOWN;
15285 SELF_CHECK (remote.supports_memory_tagging () == false);
15286 config->support = PACKET_DISABLE;
15287 SELF_CHECK (remote.supports_memory_tagging () == false);
15288 config->support = PACKET_ENABLE;
15289 SELF_CHECK (remote.supports_memory_tagging () == true);
15290
15291 /* Setup testing. */
15292 gdb::char_vector packet;
15293 gdb::byte_vector tags, bv;
15294 std::string expected, reply;
15295 packet.resize (32000);
15296
15297 /* Test creating a qMemTags request. */
15298
15299 expected = "qMemTags:0,0:0";
15300 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
15301 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15302
15303 expected = "qMemTags:deadbeef,10:1";
15304 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
15305 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15306
15307 /* Test parsing a qMemTags reply. */
15308
15309 /* Error reply, tags vector unmodified. */
15310 reply = "E00";
15311 strcpy (packet.data (), reply.c_str ());
15312 tags.resize (0);
15313 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
15314 SELF_CHECK (tags.size () == 0);
15315
15316 /* Valid reply, tags vector updated. */
15317 tags.resize (0);
15318 bv.resize (0);
15319
15320 for (int i = 0; i < 5; i++)
15321 bv.push_back (i);
15322
15323 reply = "m" + bin2hex (bv.data (), bv.size ());
15324 strcpy (packet.data (), reply.c_str ());
15325
15326 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
15327 SELF_CHECK (tags.size () == 5);
15328
15329 for (int i = 0; i < 5; i++)
15330 SELF_CHECK (tags[i] == i);
15331
15332 /* Test creating a QMemTags request. */
15333
15334 /* Empty tag data. */
15335 tags.resize (0);
15336 expected = "QMemTags:0,0:0:";
15337 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
15338 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15339 expected.length ()) == 0);
15340
15341 /* Non-empty tag data. */
15342 tags.resize (0);
15343 for (int i = 0; i < 5; i++)
15344 tags.push_back (i);
15345 expected = "QMemTags:deadbeef,ff:1:0001020304";
15346 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
15347 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15348 expected.length ()) == 0);
15349 }
15350
15351 } // namespace selftests
15352 #endif /* GDB_SELF_TEST */
15353
15354 void _initialize_remote ();
15355 void
15356 _initialize_remote ()
15357 {
15358 add_target (remote_target_info, remote_target::open);
15359 add_target (extended_remote_target_info, extended_remote_target::open);
15360
15361 /* Hook into new objfile notification. */
15362 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
15363 gdb::observers::all_objfiles_removed.attach
15364 (remote_objfile_changed_check_symbols, "remote");
15365
15366 #if 0
15367 init_remote_threadtests ();
15368 #endif
15369
15370 /* set/show remote ... */
15371
15372 add_basic_prefix_cmd ("remote", class_maintenance, _("\
15373 Remote protocol specific variables.\n\
15374 Configure various remote-protocol specific variables such as\n\
15375 the packets being used."),
15376 &remote_set_cmdlist,
15377 0 /* allow-unknown */, &setlist);
15378 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
15379 Remote protocol specific variables.\n\
15380 Configure various remote-protocol specific variables such as\n\
15381 the packets being used."),
15382 &remote_show_cmdlist,
15383 0 /* allow-unknown */, &showlist);
15384
15385 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
15386 Compare section data on target to the exec file.\n\
15387 Argument is a single section name (default: all loaded sections).\n\
15388 To compare only read-only loaded sections, specify the -r option."),
15389 &cmdlist);
15390
15391 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
15392 Send an arbitrary packet to a remote target.\n\
15393 maintenance packet TEXT\n\
15394 If GDB is talking to an inferior via the GDB serial protocol, then\n\
15395 this command sends the string TEXT to the inferior, and displays the\n\
15396 response packet. GDB supplies the initial `$' character, and the\n\
15397 terminating `#' character and checksum."),
15398 &maintenancelist);
15399
15400 set_show_commands remotebreak_cmds
15401 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
15402 Set whether to send break if interrupted."), _("\
15403 Show whether to send break if interrupted."), _("\
15404 If set, a break, instead of a cntrl-c, is sent to the remote target."),
15405 set_remotebreak, show_remotebreak,
15406 &setlist, &showlist);
15407 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
15408 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
15409
15410 add_setshow_enum_cmd ("interrupt-sequence", class_support,
15411 interrupt_sequence_modes, &interrupt_sequence_mode,
15412 _("\
15413 Set interrupt sequence to remote target."), _("\
15414 Show interrupt sequence to remote target."), _("\
15415 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
15416 NULL, show_interrupt_sequence,
15417 &remote_set_cmdlist,
15418 &remote_show_cmdlist);
15419
15420 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
15421 &interrupt_on_connect, _("\
15422 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15423 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15424 If set, interrupt sequence is sent to remote target."),
15425 NULL, NULL,
15426 &remote_set_cmdlist, &remote_show_cmdlist);
15427
15428 /* Install commands for configuring memory read/write packets. */
15429
15430 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
15431 Set the maximum number of bytes per memory write packet (deprecated)."),
15432 &setlist);
15433 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
15434 Show the maximum number of bytes per memory write packet (deprecated)."),
15435 &showlist);
15436 add_cmd ("memory-write-packet-size", no_class,
15437 set_memory_write_packet_size, _("\
15438 Set the maximum number of bytes per memory-write packet.\n\
15439 Specify the number of bytes in a packet or 0 (zero) for the\n\
15440 default packet size. The actual limit is further reduced\n\
15441 dependent on the target. Specify \"fixed\" to disable the\n\
15442 further restriction and \"limit\" to enable that restriction."),
15443 &remote_set_cmdlist);
15444 add_cmd ("memory-read-packet-size", no_class,
15445 set_memory_read_packet_size, _("\
15446 Set the maximum number of bytes per memory-read packet.\n\
15447 Specify the number of bytes in a packet or 0 (zero) for the\n\
15448 default packet size. The actual limit is further reduced\n\
15449 dependent on the target. Specify \"fixed\" to disable the\n\
15450 further restriction and \"limit\" to enable that restriction."),
15451 &remote_set_cmdlist);
15452 add_cmd ("memory-write-packet-size", no_class,
15453 show_memory_write_packet_size,
15454 _("Show the maximum number of bytes per memory-write packet."),
15455 &remote_show_cmdlist);
15456 add_cmd ("memory-read-packet-size", no_class,
15457 show_memory_read_packet_size,
15458 _("Show the maximum number of bytes per memory-read packet."),
15459 &remote_show_cmdlist);
15460
15461 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
15462 &remote_hw_watchpoint_limit, _("\
15463 Set the maximum number of target hardware watchpoints."), _("\
15464 Show the maximum number of target hardware watchpoints."), _("\
15465 Specify \"unlimited\" for unlimited hardware watchpoints."),
15466 NULL, show_hardware_watchpoint_limit,
15467 &remote_set_cmdlist,
15468 &remote_show_cmdlist);
15469 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15470 no_class,
15471 &remote_hw_watchpoint_length_limit, _("\
15472 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15473 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15474 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15475 NULL, show_hardware_watchpoint_length_limit,
15476 &remote_set_cmdlist, &remote_show_cmdlist);
15477 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
15478 &remote_hw_breakpoint_limit, _("\
15479 Set the maximum number of target hardware breakpoints."), _("\
15480 Show the maximum number of target hardware breakpoints."), _("\
15481 Specify \"unlimited\" for unlimited hardware breakpoints."),
15482 NULL, show_hardware_breakpoint_limit,
15483 &remote_set_cmdlist, &remote_show_cmdlist);
15484
15485 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15486 &remote_address_size, _("\
15487 Set the maximum size of the address (in bits) in a memory packet."), _("\
15488 Show the maximum size of the address (in bits) in a memory packet."), NULL,
15489 NULL,
15490 NULL, /* FIXME: i18n: */
15491 &setlist, &showlist);
15492
15493 init_all_packet_configs ();
15494
15495 add_packet_config_cmd (PACKET_X, "X", "binary-download", 1);
15496
15497 add_packet_config_cmd (PACKET_vCont, "vCont", "verbose-resume", 0);
15498
15499 add_packet_config_cmd (PACKET_QPassSignals, "QPassSignals", "pass-signals",
15500 0);
15501
15502 add_packet_config_cmd (PACKET_QCatchSyscalls, "QCatchSyscalls",
15503 "catch-syscalls", 0);
15504
15505 add_packet_config_cmd (PACKET_QProgramSignals, "QProgramSignals",
15506 "program-signals", 0);
15507
15508 add_packet_config_cmd (PACKET_QSetWorkingDir, "QSetWorkingDir",
15509 "set-working-dir", 0);
15510
15511 add_packet_config_cmd (PACKET_QStartupWithShell, "QStartupWithShell",
15512 "startup-with-shell", 0);
15513
15514 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded,"QEnvironmentHexEncoded",
15515 "environment-hex-encoded", 0);
15516
15517 add_packet_config_cmd (PACKET_QEnvironmentReset, "QEnvironmentReset",
15518 "environment-reset", 0);
15519
15520 add_packet_config_cmd (PACKET_QEnvironmentUnset, "QEnvironmentUnset",
15521 "environment-unset", 0);
15522
15523 add_packet_config_cmd (PACKET_qSymbol, "qSymbol", "symbol-lookup", 0);
15524
15525 add_packet_config_cmd (PACKET_P, "P", "set-register", 1);
15526
15527 add_packet_config_cmd (PACKET_p, "p", "fetch-register", 1);
15528
15529 add_packet_config_cmd (PACKET_Z0, "Z0", "software-breakpoint", 0);
15530
15531 add_packet_config_cmd (PACKET_Z1, "Z1", "hardware-breakpoint", 0);
15532
15533 add_packet_config_cmd (PACKET_Z2, "Z2", "write-watchpoint", 0);
15534
15535 add_packet_config_cmd (PACKET_Z3, "Z3", "read-watchpoint", 0);
15536
15537 add_packet_config_cmd (PACKET_Z4, "Z4", "access-watchpoint", 0);
15538
15539 add_packet_config_cmd (PACKET_qXfer_auxv, "qXfer:auxv:read",
15540 "read-aux-vector", 0);
15541
15542 add_packet_config_cmd (PACKET_qXfer_exec_file, "qXfer:exec-file:read",
15543 "pid-to-exec-file", 0);
15544
15545 add_packet_config_cmd (PACKET_qXfer_features,
15546 "qXfer:features:read", "target-features", 0);
15547
15548 add_packet_config_cmd (PACKET_qXfer_libraries, "qXfer:libraries:read",
15549 "library-info", 0);
15550
15551 add_packet_config_cmd (PACKET_qXfer_libraries_svr4,
15552 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15553
15554 add_packet_config_cmd (PACKET_qXfer_memory_map, "qXfer:memory-map:read",
15555 "memory-map", 0);
15556
15557 add_packet_config_cmd (PACKET_qXfer_osdata, "qXfer:osdata:read", "osdata", 0);
15558
15559 add_packet_config_cmd (PACKET_qXfer_threads, "qXfer:threads:read", "threads",
15560 0);
15561
15562 add_packet_config_cmd (PACKET_qXfer_siginfo_read, "qXfer:siginfo:read",
15563 "read-siginfo-object", 0);
15564
15565 add_packet_config_cmd (PACKET_qXfer_siginfo_write, "qXfer:siginfo:write",
15566 "write-siginfo-object", 0);
15567
15568 add_packet_config_cmd (PACKET_qXfer_traceframe_info,
15569 "qXfer:traceframe-info:read", "traceframe-info", 0);
15570
15571 add_packet_config_cmd (PACKET_qXfer_uib, "qXfer:uib:read",
15572 "unwind-info-block", 0);
15573
15574 add_packet_config_cmd (PACKET_qGetTLSAddr, "qGetTLSAddr",
15575 "get-thread-local-storage-address", 0);
15576
15577 add_packet_config_cmd (PACKET_qGetTIBAddr, "qGetTIBAddr",
15578 "get-thread-information-block-address", 0);
15579
15580 add_packet_config_cmd (PACKET_bc, "bc", "reverse-continue", 0);
15581
15582 add_packet_config_cmd (PACKET_bs, "bs", "reverse-step", 0);
15583
15584 add_packet_config_cmd (PACKET_qSupported, "qSupported", "supported-packets",
15585 0);
15586
15587 add_packet_config_cmd (PACKET_qSearch_memory, "qSearch:memory",
15588 "search-memory", 0);
15589
15590 add_packet_config_cmd (PACKET_qTStatus, "qTStatus", "trace-status", 0);
15591
15592 add_packet_config_cmd (PACKET_vFile_setfs, "vFile:setfs", "hostio-setfs", 0);
15593
15594 add_packet_config_cmd (PACKET_vFile_open, "vFile:open", "hostio-open", 0);
15595
15596 add_packet_config_cmd (PACKET_vFile_pread, "vFile:pread", "hostio-pread", 0);
15597
15598 add_packet_config_cmd (PACKET_vFile_pwrite, "vFile:pwrite", "hostio-pwrite",
15599 0);
15600
15601 add_packet_config_cmd (PACKET_vFile_close, "vFile:close", "hostio-close", 0);
15602
15603 add_packet_config_cmd (PACKET_vFile_unlink, "vFile:unlink", "hostio-unlink",
15604 0);
15605
15606 add_packet_config_cmd (PACKET_vFile_readlink, "vFile:readlink",
15607 "hostio-readlink", 0);
15608
15609 add_packet_config_cmd (PACKET_vFile_fstat, "vFile:fstat", "hostio-fstat", 0);
15610
15611 add_packet_config_cmd (PACKET_vAttach, "vAttach", "attach", 0);
15612
15613 add_packet_config_cmd (PACKET_vRun, "vRun", "run", 0);
15614
15615 add_packet_config_cmd (PACKET_QStartNoAckMode, "QStartNoAckMode", "noack", 0);
15616
15617 add_packet_config_cmd (PACKET_vKill, "vKill", "kill", 0);
15618
15619 add_packet_config_cmd (PACKET_qAttached, "qAttached", "query-attached", 0);
15620
15621 add_packet_config_cmd (PACKET_ConditionalTracepoints,
15622 "ConditionalTracepoints", "conditional-tracepoints",
15623 0);
15624
15625 add_packet_config_cmd (PACKET_ConditionalBreakpoints,
15626 "ConditionalBreakpoints", "conditional-breakpoints",
15627 0);
15628
15629 add_packet_config_cmd (PACKET_BreakpointCommands, "BreakpointCommands",
15630 "breakpoint-commands", 0);
15631
15632 add_packet_config_cmd (PACKET_FastTracepoints, "FastTracepoints",
15633 "fast-tracepoints", 0);
15634
15635 add_packet_config_cmd (PACKET_TracepointSource, "TracepointSource",
15636 "TracepointSource", 0);
15637
15638 add_packet_config_cmd (PACKET_QAllow, "QAllow", "allow", 0);
15639
15640 add_packet_config_cmd (PACKET_StaticTracepoints, "StaticTracepoints",
15641 "static-tracepoints", 0);
15642
15643 add_packet_config_cmd (PACKET_InstallInTrace, "InstallInTrace",
15644 "install-in-trace", 0);
15645
15646 add_packet_config_cmd (PACKET_qXfer_statictrace_read,
15647 "qXfer:statictrace:read", "read-sdata-object", 0);
15648
15649 add_packet_config_cmd (PACKET_qXfer_fdpic, "qXfer:fdpic:read",
15650 "read-fdpic-loadmap", 0);
15651
15652 add_packet_config_cmd (PACKET_QDisableRandomization, "QDisableRandomization",
15653 "disable-randomization", 0);
15654
15655 add_packet_config_cmd (PACKET_QAgent, "QAgent", "agent", 0);
15656
15657 add_packet_config_cmd (PACKET_QTBuffer_size, "QTBuffer:size",
15658 "trace-buffer-size", 0);
15659
15660 add_packet_config_cmd (PACKET_Qbtrace_off, "Qbtrace:off", "disable-btrace",
15661 0);
15662
15663 add_packet_config_cmd (PACKET_Qbtrace_bts, "Qbtrace:bts", "enable-btrace-bts",
15664 0);
15665
15666 add_packet_config_cmd (PACKET_Qbtrace_pt, "Qbtrace:pt", "enable-btrace-pt",
15667 0);
15668
15669 add_packet_config_cmd (PACKET_qXfer_btrace, "qXfer:btrace", "read-btrace", 0);
15670
15671 add_packet_config_cmd (PACKET_qXfer_btrace_conf, "qXfer:btrace-conf",
15672 "read-btrace-conf", 0);
15673
15674 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size, "Qbtrace-conf:bts:size",
15675 "btrace-conf-bts-size", 0);
15676
15677 add_packet_config_cmd (PACKET_multiprocess_feature, "multiprocess-feature",
15678 "multiprocess-feature", 0);
15679
15680 add_packet_config_cmd (PACKET_swbreak_feature, "swbreak-feature",
15681 "swbreak-feature", 0);
15682
15683 add_packet_config_cmd (PACKET_hwbreak_feature, "hwbreak-feature",
15684 "hwbreak-feature", 0);
15685
15686 add_packet_config_cmd (PACKET_fork_event_feature, "fork-event-feature",
15687 "fork-event-feature", 0);
15688
15689 add_packet_config_cmd (PACKET_vfork_event_feature, "vfork-event-feature",
15690 "vfork-event-feature", 0);
15691
15692 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size, "Qbtrace-conf:pt:size",
15693 "btrace-conf-pt-size", 0);
15694
15695 add_packet_config_cmd (PACKET_vContSupported, "vContSupported",
15696 "verbose-resume-supported", 0);
15697
15698 add_packet_config_cmd (PACKET_exec_event_feature, "exec-event-feature",
15699 "exec-event-feature", 0);
15700
15701 add_packet_config_cmd (PACKET_vCtrlC, "vCtrlC", "ctrl-c", 0);
15702
15703 add_packet_config_cmd (PACKET_QThreadEvents, "QThreadEvents", "thread-events",
15704 0);
15705
15706 add_packet_config_cmd (PACKET_no_resumed, "N stop reply",
15707 "no-resumed-stop-reply", 0);
15708
15709 add_packet_config_cmd (PACKET_memory_tagging_feature,
15710 "memory-tagging-feature", "memory-tagging-feature", 0);
15711
15712 /* Assert that we've registered "set remote foo-packet" commands
15713 for all packet configs. */
15714 {
15715 int i;
15716
15717 for (i = 0; i < PACKET_MAX; i++)
15718 {
15719 /* Ideally all configs would have a command associated. Some
15720 still don't though. */
15721 int excepted;
15722
15723 switch (i)
15724 {
15725 case PACKET_QNonStop:
15726 case PACKET_EnableDisableTracepoints_feature:
15727 case PACKET_tracenz_feature:
15728 case PACKET_DisconnectedTracing_feature:
15729 case PACKET_augmented_libraries_svr4_read_feature:
15730 case PACKET_qCRC:
15731 /* Additions to this list need to be well justified:
15732 pre-existing packets are OK; new packets are not. */
15733 excepted = 1;
15734 break;
15735 default:
15736 excepted = 0;
15737 break;
15738 }
15739
15740 /* This catches both forgetting to add a config command, and
15741 forgetting to remove a packet from the exception list. */
15742 gdb_assert (excepted == (packets_descriptions[i].name == NULL));
15743 }
15744 }
15745
15746 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15747 Z sub-packet has its own set and show commands, but users may
15748 have sets to this variable in their .gdbinit files (or in their
15749 documentation). */
15750 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
15751 &remote_Z_packet_detect, _("\
15752 Set use of remote protocol `Z' packets."), _("\
15753 Show use of remote protocol `Z' packets."), _("\
15754 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
15755 packets."),
15756 set_remote_protocol_Z_packet_cmd,
15757 show_remote_protocol_Z_packet_cmd,
15758 /* FIXME: i18n: Use of remote protocol
15759 `Z' packets is %s. */
15760 &remote_set_cmdlist, &remote_show_cmdlist);
15761
15762 add_basic_prefix_cmd ("remote", class_files, _("\
15763 Manipulate files on the remote system.\n\
15764 Transfer files to and from the remote target system."),
15765 &remote_cmdlist,
15766 0 /* allow-unknown */, &cmdlist);
15767
15768 add_cmd ("put", class_files, remote_put_command,
15769 _("Copy a local file to the remote system."),
15770 &remote_cmdlist);
15771
15772 add_cmd ("get", class_files, remote_get_command,
15773 _("Copy a remote file to the local system."),
15774 &remote_cmdlist);
15775
15776 add_cmd ("delete", class_files, remote_delete_command,
15777 _("Delete a remote file."),
15778 &remote_cmdlist);
15779
15780 add_setshow_string_noescape_cmd ("exec-file", class_files,
15781 &remote_exec_file_var, _("\
15782 Set the remote pathname for \"run\"."), _("\
15783 Show the remote pathname for \"run\"."), NULL,
15784 set_remote_exec_file,
15785 show_remote_exec_file,
15786 &remote_set_cmdlist,
15787 &remote_show_cmdlist);
15788
15789 add_setshow_boolean_cmd ("range-stepping", class_run,
15790 &use_range_stepping, _("\
15791 Enable or disable range stepping."), _("\
15792 Show whether target-assisted range stepping is enabled."), _("\
15793 If on, and the target supports it, when stepping a source line, GDB\n\
15794 tells the target to step the corresponding range of addresses itself instead\n\
15795 of issuing multiple single-steps. This speeds up source level\n\
15796 stepping. If off, GDB always issues single-steps, even if range\n\
15797 stepping is supported by the target. The default is on."),
15798 set_range_stepping,
15799 show_range_stepping,
15800 &setlist,
15801 &showlist);
15802
15803 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15804 Set watchdog timer."), _("\
15805 Show watchdog timer."), _("\
15806 When non-zero, this timeout is used instead of waiting forever for a target\n\
15807 to finish a low-level step or continue operation. If the specified amount\n\
15808 of time passes without a response from the target, an error occurs."),
15809 NULL,
15810 show_watchdog,
15811 &setlist, &showlist);
15812
15813 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15814 &remote_packet_max_chars, _("\
15815 Set the maximum number of characters to display for each remote packet."), _("\
15816 Show the maximum number of characters to display for each remote packet."), _("\
15817 Specify \"unlimited\" to display all the characters."),
15818 NULL, show_remote_packet_max_chars,
15819 &setdebuglist, &showdebuglist);
15820
15821 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15822 _("Set debugging of remote protocol."),
15823 _("Show debugging of remote protocol."),
15824 _("\
15825 When enabled, each packet sent or received with the remote target\n\
15826 is displayed."),
15827 NULL,
15828 show_remote_debug,
15829 &setdebuglist, &showdebuglist);
15830
15831 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15832 &remote_timeout, _("\
15833 Set timeout limit to wait for target to respond."), _("\
15834 Show timeout limit to wait for target to respond."), _("\
15835 This value is used to set the time limit for gdb to wait for a response\n\
15836 from the target."),
15837 NULL,
15838 show_remote_timeout,
15839 &setlist, &showlist);
15840
15841 /* Eventually initialize fileio. See fileio.c */
15842 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
15843
15844 #if GDB_SELF_TEST
15845 selftests::register_test ("remote_memory_tagging",
15846 selftests::test_memory_tagging_functions);
15847 #endif
15848 }