]> Git Repo - binutils.git/blob - gdb/remote.c
gdb-add-index.sh: Remove use of non posix 'local'
[binutils.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3    Copyright (C) 1988-2021 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 "gdb-stabs.h"
34 #include "gdbthread.h"
35 #include "remote.h"
36 #include "remote-notif.h"
37 #include "regcache.h"
38 #include "value.h"
39 #include "observable.h"
40 #include "solib.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
44 #include "gdb_bfd.h"
45 #include "gdbsupport/filestuff.h"
46 #include "gdbsupport/rsp-low.h"
47 #include "disasm.h"
48 #include "location.h"
49
50 #include "gdbsupport/gdb_sys_time.h"
51
52 #include "gdbsupport/event-loop.h"
53 #include "event-top.h"
54 #include "inf-loop.h"
55
56 #include <signal.h>
57 #include "serial.h"
58
59 #include "gdbcore.h"
60
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
63 #include <sys/stat.h>
64 #include "xml-support.h"
65
66 #include "memory-map.h"
67
68 #include "tracepoint.h"
69 #include "ax.h"
70 #include "ax-gdb.h"
71 #include "gdbsupport/agent.h"
72 #include "btrace.h"
73 #include "record-btrace.h"
74 #include <algorithm>
75 #include "gdbsupport/scoped_restore.h"
76 #include "gdbsupport/environ.h"
77 #include "gdbsupport/byte-vector.h"
78 #include "gdbsupport/search.h"
79 #include <algorithm>
80 #include <unordered_map>
81 #include "async-event.h"
82 #include "gdbsupport/selftest.h"
83
84 /* The remote target.  */
85
86 static const char remote_doc[] = N_("\
87 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
88 Specify the serial device it is connected to\n\
89 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
90
91 /* See remote.h  */
92
93 bool remote_debug = false;
94
95 #define OPAQUETHREADBYTES 8
96
97 /* a 64 bit opaque identifier */
98 typedef unsigned char threadref[OPAQUETHREADBYTES];
99
100 struct gdb_ext_thread_info;
101 struct threads_listing_context;
102 typedef int (*rmt_thread_action) (threadref *ref, void *context);
103 struct protocol_feature;
104 struct packet_reg;
105
106 struct stop_reply;
107 typedef std::unique_ptr<stop_reply> stop_reply_up;
108
109 /* Generic configuration support for packets the stub optionally
110    supports.  Allows the user to specify the use of the packet as well
111    as allowing GDB to auto-detect support in the remote stub.  */
112
113 enum packet_support
114   {
115     PACKET_SUPPORT_UNKNOWN = 0,
116     PACKET_ENABLE,
117     PACKET_DISABLE
118   };
119
120 /* Analyze a packet's return value and update the packet config
121    accordingly.  */
122
123 enum packet_result
124 {
125   PACKET_ERROR,
126   PACKET_OK,
127   PACKET_UNKNOWN
128 };
129
130 struct threads_listing_context;
131
132 /* Stub vCont actions support.
133
134    Each field is a boolean flag indicating whether the stub reports
135    support for the corresponding action.  */
136
137 struct vCont_action_support
138 {
139   /* vCont;t */
140   bool t = false;
141
142   /* vCont;r */
143   bool r = false;
144
145   /* vCont;s */
146   bool s = false;
147
148   /* vCont;S */
149   bool S = false;
150 };
151
152 /* About this many threadids fit in a packet.  */
153
154 #define MAXTHREADLISTRESULTS 32
155
156 /* Data for the vFile:pread readahead cache.  */
157
158 struct readahead_cache
159 {
160   /* Invalidate the readahead cache.  */
161   void invalidate ();
162
163   /* Invalidate the readahead cache if it is holding data for FD.  */
164   void invalidate_fd (int fd);
165
166   /* Serve pread from the readahead cache.  Returns number of bytes
167      read, or 0 if the request can't be served from the cache.  */
168   int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
169
170   /* The file descriptor for the file that is being cached.  -1 if the
171      cache is invalid.  */
172   int fd = -1;
173
174   /* The offset into the file that the cache buffer corresponds
175      to.  */
176   ULONGEST offset = 0;
177
178   /* The buffer holding the cache contents.  */
179   gdb_byte *buf = nullptr;
180   /* The buffer's size.  We try to read as much as fits into a packet
181      at a time.  */
182   size_t bufsize = 0;
183
184   /* Cache hit and miss counters.  */
185   ULONGEST hit_count = 0;
186   ULONGEST miss_count = 0;
187 };
188
189 /* Description of the remote protocol for a given architecture.  */
190
191 struct packet_reg
192 {
193   long offset; /* Offset into G packet.  */
194   long regnum; /* GDB's internal register number.  */
195   LONGEST pnum; /* Remote protocol register number.  */
196   int in_g_packet; /* Always part of G packet.  */
197   /* long size in bytes;  == register_size (target_gdbarch (), regnum);
198      at present.  */
199   /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
200      at present.  */
201 };
202
203 struct remote_arch_state
204 {
205   explicit remote_arch_state (struct gdbarch *gdbarch);
206
207   /* Description of the remote protocol registers.  */
208   long sizeof_g_packet;
209
210   /* Description of the remote protocol registers indexed by REGNUM
211      (making an array gdbarch_num_regs in size).  */
212   std::unique_ptr<packet_reg[]> regs;
213
214   /* This is the size (in chars) of the first response to the ``g''
215      packet.  It is used as a heuristic when determining the maximum
216      size of memory-read and memory-write packets.  A target will
217      typically only reserve a buffer large enough to hold the ``g''
218      packet.  The size does not include packet overhead (headers and
219      trailers).  */
220   long actual_register_packet_size;
221
222   /* This is the maximum size (in chars) of a non read/write packet.
223      It is also used as a cap on the size of read/write packets.  */
224   long remote_packet_size;
225 };
226
227 /* Description of the remote protocol state for the currently
228    connected target.  This is per-target state, and independent of the
229    selected architecture.  */
230
231 class remote_state
232 {
233 public:
234
235   remote_state ();
236   ~remote_state ();
237
238   /* Get the remote arch state for GDBARCH.  */
239   struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
240
241 public: /* data */
242
243   /* A buffer to use for incoming packets, and its current size.  The
244      buffer is grown dynamically for larger incoming packets.
245      Outgoing packets may also be constructed in this buffer.
246      The size of the buffer is always at least REMOTE_PACKET_SIZE;
247      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
248      packets.  */
249   gdb::char_vector buf;
250
251   /* True if we're going through initial connection setup (finding out
252      about the remote side's threads, relocating symbols, etc.).  */
253   bool starting_up = false;
254
255   /* If we negotiated packet size explicitly (and thus can bypass
256      heuristics for the largest packet size that will not overflow
257      a buffer in the stub), this will be set to that packet size.
258      Otherwise zero, meaning to use the guessed size.  */
259   long explicit_packet_size = 0;
260
261   /* remote_wait is normally called when the target is running and
262      waits for a stop reply packet.  But sometimes we need to call it
263      when the target is already stopped.  We can send a "?" packet
264      and have remote_wait read the response.  Or, if we already have
265      the response, we can stash it in BUF and tell remote_wait to
266      skip calling getpkt.  This flag is set when BUF contains a
267      stop reply packet and the target is not waiting.  */
268   int cached_wait_status = 0;
269
270   /* True, if in no ack mode.  That is, neither GDB nor the stub will
271      expect acks from each other.  The connection is assumed to be
272      reliable.  */
273   bool noack_mode = false;
274
275   /* True if we're connected in extended remote mode.  */
276   bool extended = false;
277
278   /* True if we resumed the target and we're waiting for the target to
279      stop.  In the mean time, we can't start another command/query.
280      The remote server wouldn't be ready to process it, so we'd
281      timeout waiting for a reply that would never come and eventually
282      we'd close the connection.  This can happen in asynchronous mode
283      because we allow GDB commands while the target is running.  */
284   bool waiting_for_stop_reply = false;
285
286   /* The status of the stub support for the various vCont actions.  */
287   vCont_action_support supports_vCont;
288   /* Whether vCont support was probed already.  This is a workaround
289      until packet_support is per-connection.  */
290   bool supports_vCont_probed;
291
292   /* True if the user has pressed Ctrl-C, but the target hasn't
293      responded to that.  */
294   bool ctrlc_pending_p = false;
295
296   /* True if we saw a Ctrl-C while reading or writing from/to the
297      remote descriptor.  At that point it is not safe to send a remote
298      interrupt packet, so we instead remember we saw the Ctrl-C and
299      process it once we're done with sending/receiving the current
300      packet, which should be shortly.  If however that takes too long,
301      and the user presses Ctrl-C again, we offer to disconnect.  */
302   bool got_ctrlc_during_io = false;
303
304   /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
305      remote_open knows that we don't have a file open when the program
306      starts.  */
307   struct serial *remote_desc = nullptr;
308
309   /* These are the threads which we last sent to the remote system.  The
310      TID member will be -1 for all or -2 for not sent yet.  */
311   ptid_t general_thread = null_ptid;
312   ptid_t continue_thread = null_ptid;
313
314   /* This is the traceframe which we last selected on the remote system.
315      It will be -1 if no traceframe is selected.  */
316   int remote_traceframe_number = -1;
317
318   char *last_pass_packet = nullptr;
319
320   /* The last QProgramSignals packet sent to the target.  We bypass
321      sending a new program signals list down to the target if the new
322      packet is exactly the same as the last we sent.  IOW, we only let
323      the target know about program signals list changes.  */
324   char *last_program_signals_packet = nullptr;
325
326   gdb_signal last_sent_signal = GDB_SIGNAL_0;
327
328   bool last_sent_step = false;
329
330   /* The execution direction of the last resume we got.  */
331   exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
332
333   char *finished_object = nullptr;
334   char *finished_annex = nullptr;
335   ULONGEST finished_offset = 0;
336
337   /* Should we try the 'ThreadInfo' query packet?
338
339      This variable (NOT available to the user: auto-detect only!)
340      determines whether GDB will use the new, simpler "ThreadInfo"
341      query or the older, more complex syntax for thread queries.
342      This is an auto-detect variable (set to true at each connect,
343      and set to false when the target fails to recognize it).  */
344   bool use_threadinfo_query = false;
345   bool use_threadextra_query = false;
346
347   threadref echo_nextthread {};
348   threadref nextthread {};
349   threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
350
351   /* The state of remote notification.  */
352   struct remote_notif_state *notif_state = nullptr;
353
354   /* The branch trace configuration.  */
355   struct btrace_config btrace_config {};
356
357   /* The argument to the last "vFile:setfs:" packet we sent, used
358      to avoid sending repeated unnecessary "vFile:setfs:" packets.
359      Initialized to -1 to indicate that no "vFile:setfs:" packet
360      has yet been sent.  */
361   int fs_pid = -1;
362
363   /* A readahead cache for vFile:pread.  Often, reading a binary
364      involves a sequence of small reads.  E.g., when parsing an ELF
365      file.  A readahead cache helps mostly the case of remote
366      debugging on a connection with higher latency, due to the
367      request/reply nature of the RSP.  We only cache data for a single
368      file descriptor at a time.  */
369   struct readahead_cache readahead_cache;
370
371   /* The list of already fetched and acknowledged stop events.  This
372      queue is used for notification Stop, and other notifications
373      don't need queue for their events, because the notification
374      events of Stop can't be consumed immediately, so that events
375      should be queued first, and be consumed by remote_wait_{ns,as}
376      one per time.  Other notifications can consume their events
377      immediately, so queue is not needed for them.  */
378   std::vector<stop_reply_up> stop_reply_queue;
379
380   /* Asynchronous signal handle registered as event loop source for
381      when we have pending events ready to be passed to the core.  */
382   struct async_event_handler *remote_async_inferior_event_token = nullptr;
383
384   /* FIXME: cagney/1999-09-23: Even though getpkt was called with
385      ``forever'' still use the normal timeout mechanism.  This is
386      currently used by the ASYNC code to guarentee that target reads
387      during the initial connect always time-out.  Once getpkt has been
388      modified to return a timeout indication and, in turn
389      remote_wait()/wait_for_inferior() have gained a timeout parameter
390      this can go away.  */
391   int wait_forever_enabled_p = 1;
392
393 private:
394   /* Mapping of remote protocol data for each gdbarch.  Usually there
395      is only one entry here, though we may see more with stubs that
396      support multi-process.  */
397   std::unordered_map<struct gdbarch *, remote_arch_state>
398     m_arch_states;
399 };
400
401 static const target_info remote_target_info = {
402   "remote",
403   N_("Remote serial target in gdb-specific protocol"),
404   remote_doc
405 };
406
407 class remote_target : public process_stratum_target
408 {
409 public:
410   remote_target () = default;
411   ~remote_target () override;
412
413   const target_info &info () const override
414   { return remote_target_info; }
415
416   const char *connection_string () override;
417
418   thread_control_capabilities get_thread_control_capabilities () override
419   { return tc_schedlock; }
420
421   /* Open a remote connection.  */
422   static void open (const char *, int);
423
424   void close () override;
425
426   void detach (inferior *, int) override;
427   void disconnect (const char *, int) override;
428
429   void commit_resumed () override;
430   void resume (ptid_t, int, enum gdb_signal) override;
431   ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
432   bool has_pending_events () override;
433
434   void fetch_registers (struct regcache *, int) override;
435   void store_registers (struct regcache *, int) override;
436   void prepare_to_store (struct regcache *) override;
437
438   void files_info () override;
439
440   int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
441
442   int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
443                          enum remove_bp_reason) override;
444
445
446   bool stopped_by_sw_breakpoint () override;
447   bool supports_stopped_by_sw_breakpoint () override;
448
449   bool stopped_by_hw_breakpoint () override;
450
451   bool supports_stopped_by_hw_breakpoint () override;
452
453   bool stopped_by_watchpoint () override;
454
455   bool stopped_data_address (CORE_ADDR *) override;
456
457   bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
458
459   int can_use_hw_breakpoint (enum bptype, int, int) override;
460
461   int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
462
463   int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
464
465   int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
466
467   int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
468                          struct expression *) override;
469
470   int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
471                          struct expression *) override;
472
473   void kill () override;
474
475   void load (const char *, int) override;
476
477   void mourn_inferior () override;
478
479   void pass_signals (gdb::array_view<const unsigned char>) override;
480
481   int set_syscall_catchpoint (int, bool, int,
482                               gdb::array_view<const int>) override;
483
484   void program_signals (gdb::array_view<const unsigned char>) override;
485
486   bool thread_alive (ptid_t ptid) override;
487
488   const char *thread_name (struct thread_info *) override;
489
490   void update_thread_list () override;
491
492   std::string pid_to_str (ptid_t) override;
493
494   const char *extra_thread_info (struct thread_info *) override;
495
496   ptid_t get_ada_task_ptid (long lwp, long thread) override;
497
498   thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
499                                              int handle_len,
500                                              inferior *inf) override;
501
502   gdb::byte_vector thread_info_to_thread_handle (struct thread_info *tp)
503                                                  override;
504
505   void stop (ptid_t) override;
506
507   void interrupt () override;
508
509   void pass_ctrlc () override;
510
511   enum target_xfer_status xfer_partial (enum target_object object,
512                                         const char *annex,
513                                         gdb_byte *readbuf,
514                                         const gdb_byte *writebuf,
515                                         ULONGEST offset, ULONGEST len,
516                                         ULONGEST *xfered_len) override;
517
518   ULONGEST get_memory_xfer_limit () override;
519
520   void rcmd (const char *command, struct ui_file *output) override;
521
522   char *pid_to_exec_file (int pid) override;
523
524   void log_command (const char *cmd) override
525   {
526     serial_log_command (this, cmd);
527   }
528
529   CORE_ADDR get_thread_local_address (ptid_t ptid,
530                                       CORE_ADDR load_module_addr,
531                                       CORE_ADDR offset) override;
532
533   bool can_execute_reverse () override;
534
535   std::vector<mem_region> memory_map () override;
536
537   void flash_erase (ULONGEST address, LONGEST length) override;
538
539   void flash_done () override;
540
541   const struct target_desc *read_description () override;
542
543   int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
544                      const gdb_byte *pattern, ULONGEST pattern_len,
545                      CORE_ADDR *found_addrp) override;
546
547   bool can_async_p () override;
548
549   bool is_async_p () override;
550
551   void async (int) override;
552
553   int async_wait_fd () override;
554
555   void thread_events (int) override;
556
557   int can_do_single_step () override;
558
559   void terminal_inferior () override;
560
561   void terminal_ours () override;
562
563   bool supports_non_stop () override;
564
565   bool supports_multi_process () override;
566
567   bool supports_disable_randomization () override;
568
569   bool filesystem_is_local () override;
570
571
572   int fileio_open (struct inferior *inf, const char *filename,
573                    int flags, int mode, int warn_if_slow,
574                    int *target_errno) override;
575
576   int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
577                      ULONGEST offset, int *target_errno) override;
578
579   int fileio_pread (int fd, gdb_byte *read_buf, int len,
580                     ULONGEST offset, int *target_errno) override;
581
582   int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
583
584   int fileio_close (int fd, int *target_errno) override;
585
586   int fileio_unlink (struct inferior *inf,
587                      const char *filename,
588                      int *target_errno) override;
589
590   gdb::optional<std::string>
591     fileio_readlink (struct inferior *inf,
592                      const char *filename,
593                      int *target_errno) override;
594
595   bool supports_enable_disable_tracepoint () override;
596
597   bool supports_string_tracing () override;
598
599   bool supports_evaluation_of_breakpoint_conditions () override;
600
601   bool can_run_breakpoint_commands () override;
602
603   void trace_init () override;
604
605   void download_tracepoint (struct bp_location *location) override;
606
607   bool can_download_tracepoint () override;
608
609   void download_trace_state_variable (const trace_state_variable &tsv) override;
610
611   void enable_tracepoint (struct bp_location *location) override;
612
613   void disable_tracepoint (struct bp_location *location) override;
614
615   void trace_set_readonly_regions () override;
616
617   void trace_start () override;
618
619   int get_trace_status (struct trace_status *ts) override;
620
621   void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
622     override;
623
624   void trace_stop () override;
625
626   int trace_find (enum trace_find_type type, int num,
627                   CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
628
629   bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
630
631   int save_trace_data (const char *filename) override;
632
633   int upload_tracepoints (struct uploaded_tp **utpp) override;
634
635   int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
636
637   LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
638
639   int get_min_fast_tracepoint_insn_len () override;
640
641   void set_disconnected_tracing (int val) override;
642
643   void set_circular_trace_buffer (int val) override;
644
645   void set_trace_buffer_size (LONGEST val) override;
646
647   bool set_trace_notes (const char *user, const char *notes,
648                         const char *stopnotes) override;
649
650   int core_of_thread (ptid_t ptid) override;
651
652   int verify_memory (const gdb_byte *data,
653                      CORE_ADDR memaddr, ULONGEST size) override;
654
655
656   bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
657
658   void set_permissions () override;
659
660   bool static_tracepoint_marker_at (CORE_ADDR,
661                                     struct static_tracepoint_marker *marker)
662     override;
663
664   std::vector<static_tracepoint_marker>
665     static_tracepoint_markers_by_strid (const char *id) override;
666
667   traceframe_info_up traceframe_info () override;
668
669   bool use_agent (bool use) override;
670   bool can_use_agent () override;
671
672   struct btrace_target_info *enable_btrace (ptid_t ptid,
673                                             const struct btrace_config *conf) override;
674
675   void disable_btrace (struct btrace_target_info *tinfo) override;
676
677   void teardown_btrace (struct btrace_target_info *tinfo) override;
678
679   enum btrace_error read_btrace (struct btrace_data *data,
680                                  struct btrace_target_info *btinfo,
681                                  enum btrace_read_type type) override;
682
683   const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
684   bool augmented_libraries_svr4_read () override;
685   bool follow_fork (bool, bool) override;
686   void follow_exec (struct inferior *, const char *) override;
687   int insert_fork_catchpoint (int) override;
688   int remove_fork_catchpoint (int) override;
689   int insert_vfork_catchpoint (int) override;
690   int remove_vfork_catchpoint (int) override;
691   int insert_exec_catchpoint (int) override;
692   int remove_exec_catchpoint (int) override;
693   enum exec_direction_kind execution_direction () override;
694
695   bool supports_memory_tagging () override;
696
697   bool fetch_memtags (CORE_ADDR address, size_t len,
698                       gdb::byte_vector &tags, int type) override;
699
700   bool store_memtags (CORE_ADDR address, size_t len,
701                       const gdb::byte_vector &tags, int type) override;
702
703 public: /* Remote specific methods.  */
704
705   void remote_download_command_source (int num, ULONGEST addr,
706                                        struct command_line *cmds);
707
708   void remote_file_put (const char *local_file, const char *remote_file,
709                         int from_tty);
710   void remote_file_get (const char *remote_file, const char *local_file,
711                         int from_tty);
712   void remote_file_delete (const char *remote_file, int from_tty);
713
714   int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
715                            ULONGEST offset, int *remote_errno);
716   int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
717                             ULONGEST offset, int *remote_errno);
718   int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
719                                  ULONGEST offset, int *remote_errno);
720
721   int remote_hostio_send_command (int command_bytes, int which_packet,
722                                   int *remote_errno, const char **attachment,
723                                   int *attachment_len);
724   int remote_hostio_set_filesystem (struct inferior *inf,
725                                     int *remote_errno);
726   /* We should get rid of this and use fileio_open directly.  */
727   int remote_hostio_open (struct inferior *inf, const char *filename,
728                           int flags, int mode, int warn_if_slow,
729                           int *remote_errno);
730   int remote_hostio_close (int fd, int *remote_errno);
731
732   int remote_hostio_unlink (inferior *inf, const char *filename,
733                             int *remote_errno);
734
735   struct remote_state *get_remote_state ();
736
737   long get_remote_packet_size (void);
738   long get_memory_packet_size (struct memory_packet_config *config);
739
740   long get_memory_write_packet_size ();
741   long get_memory_read_packet_size ();
742
743   char *append_pending_thread_resumptions (char *p, char *endp,
744                                            ptid_t ptid);
745   static void open_1 (const char *name, int from_tty, int extended_p);
746   void start_remote (int from_tty, int extended_p);
747   void remote_detach_1 (struct inferior *inf, int from_tty);
748
749   char *append_resumption (char *p, char *endp,
750                            ptid_t ptid, int step, gdb_signal siggnal);
751   int remote_resume_with_vcont (ptid_t ptid, int step,
752                                 gdb_signal siggnal);
753
754   thread_info *add_current_inferior_and_thread (const char *wait_status);
755
756   ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
757                   target_wait_flags options);
758   ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
759                   target_wait_flags options);
760
761   ptid_t process_stop_reply (struct stop_reply *stop_reply,
762                              target_waitstatus *status);
763
764   ptid_t select_thread_for_ambiguous_stop_reply
765     (const struct target_waitstatus *status);
766
767   void remote_notice_new_inferior (ptid_t currthread, int executing);
768
769   void process_initial_stop_replies (int from_tty);
770
771   thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing);
772
773   void btrace_sync_conf (const btrace_config *conf);
774
775   void remote_btrace_maybe_reopen ();
776
777   void remove_new_fork_children (threads_listing_context *context);
778   void kill_new_fork_children (int pid);
779   void discard_pending_stop_replies (struct inferior *inf);
780   int stop_reply_queue_length ();
781
782   void check_pending_events_prevent_wildcard_vcont
783     (int *may_global_wildcard_vcont);
784
785   void discard_pending_stop_replies_in_queue ();
786   struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
787   struct stop_reply *queued_stop_reply (ptid_t ptid);
788   int peek_stop_reply (ptid_t ptid);
789   void remote_parse_stop_reply (const char *buf, stop_reply *event);
790
791   void remote_stop_ns (ptid_t ptid);
792   void remote_interrupt_as ();
793   void remote_interrupt_ns ();
794
795   char *remote_get_noisy_reply ();
796   int remote_query_attached (int pid);
797   inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
798                                  int try_open_exec);
799
800   ptid_t remote_current_thread (ptid_t oldpid);
801   ptid_t get_current_thread (const char *wait_status);
802
803   void set_thread (ptid_t ptid, int gen);
804   void set_general_thread (ptid_t ptid);
805   void set_continue_thread (ptid_t ptid);
806   void set_general_process ();
807
808   char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
809
810   int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
811                                           gdb_ext_thread_info *info);
812   int remote_get_threadinfo (threadref *threadid, int fieldset,
813                              gdb_ext_thread_info *info);
814
815   int parse_threadlist_response (const char *pkt, int result_limit,
816                                  threadref *original_echo,
817                                  threadref *resultlist,
818                                  int *doneflag);
819   int remote_get_threadlist (int startflag, threadref *nextthread,
820                              int result_limit, int *done, int *result_count,
821                              threadref *threadlist);
822
823   int remote_threadlist_iterator (rmt_thread_action stepfunction,
824                                   void *context, int looplimit);
825
826   int remote_get_threads_with_ql (threads_listing_context *context);
827   int remote_get_threads_with_qxfer (threads_listing_context *context);
828   int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
829
830   void extended_remote_restart ();
831
832   void get_offsets ();
833
834   void remote_check_symbols ();
835
836   void remote_supported_packet (const struct protocol_feature *feature,
837                                 enum packet_support support,
838                                 const char *argument);
839
840   void remote_query_supported ();
841
842   void remote_packet_size (const protocol_feature *feature,
843                            packet_support support, const char *value);
844
845   void remote_serial_quit_handler ();
846
847   void remote_detach_pid (int pid);
848
849   void remote_vcont_probe ();
850
851   void remote_resume_with_hc (ptid_t ptid, int step,
852                               gdb_signal siggnal);
853
854   void send_interrupt_sequence ();
855   void interrupt_query ();
856
857   void remote_notif_get_pending_events (notif_client *nc);
858
859   int fetch_register_using_p (struct regcache *regcache,
860                               packet_reg *reg);
861   int send_g_packet ();
862   void process_g_packet (struct regcache *regcache);
863   void fetch_registers_using_g (struct regcache *regcache);
864   int store_register_using_P (const struct regcache *regcache,
865                               packet_reg *reg);
866   void store_registers_using_G (const struct regcache *regcache);
867
868   void set_remote_traceframe ();
869
870   void check_binary_download (CORE_ADDR addr);
871
872   target_xfer_status remote_write_bytes_aux (const char *header,
873                                              CORE_ADDR memaddr,
874                                              const gdb_byte *myaddr,
875                                              ULONGEST len_units,
876                                              int unit_size,
877                                              ULONGEST *xfered_len_units,
878                                              char packet_format,
879                                              int use_length);
880
881   target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
882                                          const gdb_byte *myaddr, ULONGEST len,
883                                          int unit_size, ULONGEST *xfered_len);
884
885   target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
886                                           ULONGEST len_units,
887                                           int unit_size, ULONGEST *xfered_len_units);
888
889   target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
890                                                         ULONGEST memaddr,
891                                                         ULONGEST len,
892                                                         int unit_size,
893                                                         ULONGEST *xfered_len);
894
895   target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
896                                         gdb_byte *myaddr, ULONGEST len,
897                                         int unit_size,
898                                         ULONGEST *xfered_len);
899
900   packet_result remote_send_printf (const char *format, ...)
901     ATTRIBUTE_PRINTF (2, 3);
902
903   target_xfer_status remote_flash_write (ULONGEST address,
904                                          ULONGEST length, ULONGEST *xfered_len,
905                                          const gdb_byte *data);
906
907   int readchar (int timeout);
908
909   void remote_serial_write (const char *str, int len);
910
911   int putpkt (const char *buf);
912   int putpkt_binary (const char *buf, int cnt);
913
914   int putpkt (const gdb::char_vector &buf)
915   {
916     return putpkt (buf.data ());
917   }
918
919   void skip_frame ();
920   long read_frame (gdb::char_vector *buf_p);
921   void getpkt (gdb::char_vector *buf, int forever);
922   int getpkt_or_notif_sane_1 (gdb::char_vector *buf, int forever,
923                               int expecting_notif, int *is_notif);
924   int getpkt_sane (gdb::char_vector *buf, int forever);
925   int getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
926                             int *is_notif);
927   int remote_vkill (int pid);
928   void remote_kill_k ();
929
930   void extended_remote_disable_randomization (int val);
931   int extended_remote_run (const std::string &args);
932
933   void send_environment_packet (const char *action,
934                                 const char *packet,
935                                 const char *value);
936
937   void extended_remote_environment_support ();
938   void extended_remote_set_inferior_cwd ();
939
940   target_xfer_status remote_write_qxfer (const char *object_name,
941                                          const char *annex,
942                                          const gdb_byte *writebuf,
943                                          ULONGEST offset, LONGEST len,
944                                          ULONGEST *xfered_len,
945                                          struct packet_config *packet);
946
947   target_xfer_status remote_read_qxfer (const char *object_name,
948                                         const char *annex,
949                                         gdb_byte *readbuf, ULONGEST offset,
950                                         LONGEST len,
951                                         ULONGEST *xfered_len,
952                                         struct packet_config *packet);
953
954   void push_stop_reply (struct stop_reply *new_event);
955
956   bool vcont_r_supported ();
957
958   void packet_command (const char *args, int from_tty);
959
960 private: /* data fields */
961
962   /* The remote state.  Don't reference this directly.  Use the
963      get_remote_state method instead.  */
964   remote_state m_remote_state;
965 };
966
967 static const target_info extended_remote_target_info = {
968   "extended-remote",
969   N_("Extended remote serial target in gdb-specific protocol"),
970   remote_doc
971 };
972
973 /* Set up the extended remote target by extending the standard remote
974    target and adding to it.  */
975
976 class extended_remote_target final : public remote_target
977 {
978 public:
979   const target_info &info () const override
980   { return extended_remote_target_info; }
981
982   /* Open an extended-remote connection.  */
983   static void open (const char *, int);
984
985   bool can_create_inferior () override { return true; }
986   void create_inferior (const char *, const std::string &,
987                         char **, int) override;
988
989   void detach (inferior *, int) override;
990
991   bool can_attach () override { return true; }
992   void attach (const char *, int) override;
993
994   void post_attach (int) override;
995   bool supports_disable_randomization () override;
996 };
997
998 /* Per-program-space data key.  */
999 static const struct program_space_key<char, gdb::xfree_deleter<char>>
1000   remote_pspace_data;
1001
1002 /* The variable registered as the control variable used by the
1003    remote exec-file commands.  While the remote exec-file setting is
1004    per-program-space, the set/show machinery uses this as the 
1005    location of the remote exec-file value.  */
1006 static char *remote_exec_file_var;
1007
1008 /* The size to align memory write packets, when practical.  The protocol
1009    does not guarantee any alignment, and gdb will generate short
1010    writes and unaligned writes, but even as a best-effort attempt this
1011    can improve bulk transfers.  For instance, if a write is misaligned
1012    relative to the target's data bus, the stub may need to make an extra
1013    round trip fetching data from the target.  This doesn't make a
1014    huge difference, but it's easy to do, so we try to be helpful.
1015
1016    The alignment chosen is arbitrary; usually data bus width is
1017    important here, not the possibly larger cache line size.  */
1018 enum { REMOTE_ALIGN_WRITES = 16 };
1019
1020 /* Prototypes for local functions.  */
1021
1022 static int hexnumlen (ULONGEST num);
1023
1024 static int stubhex (int ch);
1025
1026 static int hexnumstr (char *, ULONGEST);
1027
1028 static int hexnumnstr (char *, ULONGEST, int);
1029
1030 static CORE_ADDR remote_address_masked (CORE_ADDR);
1031
1032 static void print_packet (const char *);
1033
1034 static int stub_unpack_int (const char *buff, int fieldlength);
1035
1036 struct packet_config;
1037
1038 static void show_packet_config_cmd (struct packet_config *config);
1039
1040 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1041                                              int from_tty,
1042                                              struct cmd_list_element *c,
1043                                              const char *value);
1044
1045 static ptid_t read_ptid (const char *buf, const char **obuf);
1046
1047 static void remote_async_inferior_event_handler (gdb_client_data);
1048
1049 static bool remote_read_description_p (struct target_ops *target);
1050
1051 static void remote_console_output (const char *msg);
1052
1053 static void remote_btrace_reset (remote_state *rs);
1054
1055 static void remote_unpush_and_throw (remote_target *target);
1056
1057 /* For "remote".  */
1058
1059 static struct cmd_list_element *remote_cmdlist;
1060
1061 /* For "set remote" and "show remote".  */
1062
1063 static struct cmd_list_element *remote_set_cmdlist;
1064 static struct cmd_list_element *remote_show_cmdlist;
1065
1066 /* Controls whether GDB is willing to use range stepping.  */
1067
1068 static bool use_range_stepping = true;
1069
1070 /* From the remote target's point of view, each thread is in one of these three
1071    states.  */
1072 enum class resume_state
1073 {
1074   /* Not resumed - we haven't been asked to resume this thread.  */
1075   NOT_RESUMED,
1076
1077   /* We have been asked to resume this thread, but haven't sent a vCont action
1078      for it yet.  We'll need to consider it next time commit_resume is
1079      called.  */
1080   RESUMED_PENDING_VCONT,
1081
1082   /* We have been asked to resume this thread, and we have sent a vCont action
1083      for it.  */
1084   RESUMED,
1085 };
1086
1087 /* Information about a thread's pending vCont-resume.  Used when a thread is in
1088    the remote_resume_state::RESUMED_PENDING_VCONT state.  remote_target::resume
1089    stores this information which is then picked up by
1090    remote_target::commit_resume to know which is the proper action for this
1091    thread to include in the vCont packet.  */
1092 struct resumed_pending_vcont_info
1093 {
1094   /* True if the last resume call for this thread was a step request, false
1095      if a continue request.  */
1096   bool step;
1097
1098   /* The signal specified in the last resume call for this thread.  */
1099   gdb_signal sig;
1100 };
1101
1102 /* Private data that we'll store in (struct thread_info)->priv.  */
1103 struct remote_thread_info : public private_thread_info
1104 {
1105   std::string extra;
1106   std::string name;
1107   int core = -1;
1108
1109   /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1110      sequence of bytes.  */
1111   gdb::byte_vector thread_handle;
1112
1113   /* Whether the target stopped for a breakpoint/watchpoint.  */
1114   enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1115
1116   /* This is set to the data address of the access causing the target
1117      to stop for a watchpoint.  */
1118   CORE_ADDR watch_data_address = 0;
1119
1120   /* Get the thread's resume state.  */
1121   enum resume_state get_resume_state () const
1122   {
1123     return m_resume_state;
1124   }
1125
1126   /* Put the thread in the NOT_RESUMED state.  */
1127   void set_not_resumed ()
1128   {
1129     m_resume_state = resume_state::NOT_RESUMED;
1130   }
1131
1132   /* Put the thread in the RESUMED_PENDING_VCONT state.  */
1133   void set_resumed_pending_vcont (bool step, gdb_signal sig)
1134   {
1135     m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1136     m_resumed_pending_vcont_info.step = step;
1137     m_resumed_pending_vcont_info.sig = sig;
1138   }
1139
1140   /* Get the information this thread's pending vCont-resumption.
1141
1142      Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1143      state.  */
1144   const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1145   {
1146     gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1147
1148     return m_resumed_pending_vcont_info;
1149   }
1150
1151   /* Put the thread in the VCONT_RESUMED state.  */
1152   void set_resumed ()
1153   {
1154     m_resume_state = resume_state::RESUMED;
1155   }
1156
1157 private:
1158   /* Resume state for this thread.  This is used to implement vCont action
1159      coalescing (only when the target operates in non-stop mode).
1160
1161      remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1162      which notes that this thread must be considered in the next commit_resume
1163      call.
1164
1165      remote_target::commit_resume sends a vCont packet with actions for the
1166      threads in the RESUMED_PENDING_VCONT state and moves them to the
1167      VCONT_RESUMED state.
1168
1169      When reporting a stop to the core for a thread, that thread is moved back
1170      to the NOT_RESUMED state.  */
1171   enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1172
1173   /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state.  */
1174   struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1175 };
1176
1177 remote_state::remote_state ()
1178   : buf (400)
1179 {
1180 }
1181
1182 remote_state::~remote_state ()
1183 {
1184   xfree (this->last_pass_packet);
1185   xfree (this->last_program_signals_packet);
1186   xfree (this->finished_object);
1187   xfree (this->finished_annex);
1188 }
1189
1190 /* Utility: generate error from an incoming stub packet.  */
1191 static void
1192 trace_error (char *buf)
1193 {
1194   if (*buf++ != 'E')
1195     return;                     /* not an error msg */
1196   switch (*buf)
1197     {
1198     case '1':                   /* malformed packet error */
1199       if (*++buf == '0')        /*   general case: */
1200         error (_("remote.c: error in outgoing packet."));
1201       else
1202         error (_("remote.c: error in outgoing packet at field #%ld."),
1203                strtol (buf, NULL, 16));
1204     default:
1205       error (_("Target returns error code '%s'."), buf);
1206     }
1207 }
1208
1209 /* Utility: wait for reply from stub, while accepting "O" packets.  */
1210
1211 char *
1212 remote_target::remote_get_noisy_reply ()
1213 {
1214   struct remote_state *rs = get_remote_state ();
1215
1216   do                            /* Loop on reply from remote stub.  */
1217     {
1218       char *buf;
1219
1220       QUIT;                     /* Allow user to bail out with ^C.  */
1221       getpkt (&rs->buf, 0);
1222       buf = rs->buf.data ();
1223       if (buf[0] == 'E')
1224         trace_error (buf);
1225       else if (startswith (buf, "qRelocInsn:"))
1226         {
1227           ULONGEST ul;
1228           CORE_ADDR from, to, org_to;
1229           const char *p, *pp;
1230           int adjusted_size = 0;
1231           int relocated = 0;
1232
1233           p = buf + strlen ("qRelocInsn:");
1234           pp = unpack_varlen_hex (p, &ul);
1235           if (*pp != ';')
1236             error (_("invalid qRelocInsn packet: %s"), buf);
1237           from = ul;
1238
1239           p = pp + 1;
1240           unpack_varlen_hex (p, &ul);
1241           to = ul;
1242
1243           org_to = to;
1244
1245           try
1246             {
1247               gdbarch_relocate_instruction (target_gdbarch (), &to, from);
1248               relocated = 1;
1249             }
1250           catch (const gdb_exception &ex)
1251             {
1252               if (ex.error == MEMORY_ERROR)
1253                 {
1254                   /* Propagate memory errors silently back to the
1255                      target.  The stub may have limited the range of
1256                      addresses we can write to, for example.  */
1257                 }
1258               else
1259                 {
1260                   /* Something unexpectedly bad happened.  Be verbose
1261                      so we can tell what, and propagate the error back
1262                      to the stub, so it doesn't get stuck waiting for
1263                      a response.  */
1264                   exception_fprintf (gdb_stderr, ex,
1265                                      _("warning: relocating instruction: "));
1266                 }
1267               putpkt ("E01");
1268             }
1269
1270           if (relocated)
1271             {
1272               adjusted_size = to - org_to;
1273
1274               xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1275               putpkt (buf);
1276             }
1277         }
1278       else if (buf[0] == 'O' && buf[1] != 'K')
1279         remote_console_output (buf + 1);        /* 'O' message from stub */
1280       else
1281         return buf;             /* Here's the actual reply.  */
1282     }
1283   while (1);
1284 }
1285
1286 struct remote_arch_state *
1287 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1288 {
1289   remote_arch_state *rsa;
1290
1291   auto it = this->m_arch_states.find (gdbarch);
1292   if (it == this->m_arch_states.end ())
1293     {
1294       auto p = this->m_arch_states.emplace (std::piecewise_construct,
1295                                             std::forward_as_tuple (gdbarch),
1296                                             std::forward_as_tuple (gdbarch));
1297       rsa = &p.first->second;
1298
1299       /* Make sure that the packet buffer is plenty big enough for
1300          this architecture.  */
1301       if (this->buf.size () < rsa->remote_packet_size)
1302         this->buf.resize (2 * rsa->remote_packet_size);
1303     }
1304   else
1305     rsa = &it->second;
1306
1307   return rsa;
1308 }
1309
1310 /* Fetch the global remote target state.  */
1311
1312 remote_state *
1313 remote_target::get_remote_state ()
1314 {
1315   /* Make sure that the remote architecture state has been
1316      initialized, because doing so might reallocate rs->buf.  Any
1317      function which calls getpkt also needs to be mindful of changes
1318      to rs->buf, but this call limits the number of places which run
1319      into trouble.  */
1320   m_remote_state.get_remote_arch_state (target_gdbarch ());
1321
1322   return &m_remote_state;
1323 }
1324
1325 /* Fetch the remote exec-file from the current program space.  */
1326
1327 static const char *
1328 get_remote_exec_file (void)
1329 {
1330   char *remote_exec_file;
1331
1332   remote_exec_file = remote_pspace_data.get (current_program_space);
1333   if (remote_exec_file == NULL)
1334     return "";
1335
1336   return remote_exec_file;
1337 }
1338
1339 /* Set the remote exec file for PSPACE.  */
1340
1341 static void
1342 set_pspace_remote_exec_file (struct program_space *pspace,
1343                              const char *remote_exec_file)
1344 {
1345   char *old_file = remote_pspace_data.get (pspace);
1346
1347   xfree (old_file);
1348   remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1349 }
1350
1351 /* The "set/show remote exec-file" set command hook.  */
1352
1353 static void
1354 set_remote_exec_file (const char *ignored, int from_tty,
1355                       struct cmd_list_element *c)
1356 {
1357   gdb_assert (remote_exec_file_var != NULL);
1358   set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
1359 }
1360
1361 /* The "set/show remote exec-file" show command hook.  */
1362
1363 static void
1364 show_remote_exec_file (struct ui_file *file, int from_tty,
1365                        struct cmd_list_element *cmd, const char *value)
1366 {
1367   fprintf_filtered (file, "%s\n", get_remote_exec_file ());
1368 }
1369
1370 static int
1371 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1372 {
1373   int regnum, num_remote_regs, offset;
1374   struct packet_reg **remote_regs;
1375
1376   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1377     {
1378       struct packet_reg *r = &regs[regnum];
1379
1380       if (register_size (gdbarch, regnum) == 0)
1381         /* Do not try to fetch zero-sized (placeholder) registers.  */
1382         r->pnum = -1;
1383       else
1384         r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1385
1386       r->regnum = regnum;
1387     }
1388
1389   /* Define the g/G packet format as the contents of each register
1390      with a remote protocol number, in order of ascending protocol
1391      number.  */
1392
1393   remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1394   for (num_remote_regs = 0, regnum = 0;
1395        regnum < gdbarch_num_regs (gdbarch);
1396        regnum++)
1397     if (regs[regnum].pnum != -1)
1398       remote_regs[num_remote_regs++] = &regs[regnum];
1399
1400   std::sort (remote_regs, remote_regs + num_remote_regs,
1401              [] (const packet_reg *a, const packet_reg *b)
1402               { return a->pnum < b->pnum; });
1403
1404   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1405     {
1406       remote_regs[regnum]->in_g_packet = 1;
1407       remote_regs[regnum]->offset = offset;
1408       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1409     }
1410
1411   return offset;
1412 }
1413
1414 /* Given the architecture described by GDBARCH, return the remote
1415    protocol register's number and the register's offset in the g/G
1416    packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1417    If the target does not have a mapping for REGNUM, return false,
1418    otherwise, return true.  */
1419
1420 int
1421 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1422                                    int *pnum, int *poffset)
1423 {
1424   gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1425
1426   std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1427
1428   map_regcache_remote_table (gdbarch, regs.data ());
1429
1430   *pnum = regs[regnum].pnum;
1431   *poffset = regs[regnum].offset;
1432
1433   return *pnum != -1;
1434 }
1435
1436 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1437 {
1438   /* Use the architecture to build a regnum<->pnum table, which will be
1439      1:1 unless a feature set specifies otherwise.  */
1440   this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1441
1442   /* Record the maximum possible size of the g packet - it may turn out
1443      to be smaller.  */
1444   this->sizeof_g_packet
1445     = map_regcache_remote_table (gdbarch, this->regs.get ());
1446
1447   /* Default maximum number of characters in a packet body.  Many
1448      remote stubs have a hardwired buffer size of 400 bytes
1449      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
1450      as the maximum packet-size to ensure that the packet and an extra
1451      NUL character can always fit in the buffer.  This stops GDB
1452      trashing stubs that try to squeeze an extra NUL into what is
1453      already a full buffer (As of 1999-12-04 that was most stubs).  */
1454   this->remote_packet_size = 400 - 1;
1455
1456   /* This one is filled in when a ``g'' packet is received.  */
1457   this->actual_register_packet_size = 0;
1458
1459   /* Should rsa->sizeof_g_packet needs more space than the
1460      default, adjust the size accordingly.  Remember that each byte is
1461      encoded as two characters.  32 is the overhead for the packet
1462      header / footer.  NOTE: cagney/1999-10-26: I suspect that 8
1463      (``$NN:G...#NN'') is a better guess, the below has been padded a
1464      little.  */
1465   if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1466     this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1467 }
1468
1469 /* Get a pointer to the current remote target.  If not connected to a
1470    remote target, return NULL.  */
1471
1472 static remote_target *
1473 get_current_remote_target ()
1474 {
1475   target_ops *proc_target = current_inferior ()->process_target ();
1476   return dynamic_cast<remote_target *> (proc_target);
1477 }
1478
1479 /* Return the current allowed size of a remote packet.  This is
1480    inferred from the current architecture, and should be used to
1481    limit the length of outgoing packets.  */
1482 long
1483 remote_target::get_remote_packet_size ()
1484 {
1485   struct remote_state *rs = get_remote_state ();
1486   remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1487
1488   if (rs->explicit_packet_size)
1489     return rs->explicit_packet_size;
1490
1491   return rsa->remote_packet_size;
1492 }
1493
1494 static struct packet_reg *
1495 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1496                         long regnum)
1497 {
1498   if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1499     return NULL;
1500   else
1501     {
1502       struct packet_reg *r = &rsa->regs[regnum];
1503
1504       gdb_assert (r->regnum == regnum);
1505       return r;
1506     }
1507 }
1508
1509 static struct packet_reg *
1510 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1511                       LONGEST pnum)
1512 {
1513   int i;
1514
1515   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1516     {
1517       struct packet_reg *r = &rsa->regs[i];
1518
1519       if (r->pnum == pnum)
1520         return r;
1521     }
1522   return NULL;
1523 }
1524
1525 /* Allow the user to specify what sequence to send to the remote
1526    when he requests a program interruption: Although ^C is usually
1527    what remote systems expect (this is the default, here), it is
1528    sometimes preferable to send a break.  On other systems such
1529    as the Linux kernel, a break followed by g, which is Magic SysRq g
1530    is required in order to interrupt the execution.  */
1531 const char interrupt_sequence_control_c[] = "Ctrl-C";
1532 const char interrupt_sequence_break[] = "BREAK";
1533 const char interrupt_sequence_break_g[] = "BREAK-g";
1534 static const char *const interrupt_sequence_modes[] =
1535   {
1536     interrupt_sequence_control_c,
1537     interrupt_sequence_break,
1538     interrupt_sequence_break_g,
1539     NULL
1540   };
1541 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1542
1543 static void
1544 show_interrupt_sequence (struct ui_file *file, int from_tty,
1545                          struct cmd_list_element *c,
1546                          const char *value)
1547 {
1548   if (interrupt_sequence_mode == interrupt_sequence_control_c)
1549     fprintf_filtered (file,
1550                       _("Send the ASCII ETX character (Ctrl-c) "
1551                         "to the remote target to interrupt the "
1552                         "execution of the program.\n"));
1553   else if (interrupt_sequence_mode == interrupt_sequence_break)
1554     fprintf_filtered (file,
1555                       _("send a break signal to the remote target "
1556                         "to interrupt the execution of the program.\n"));
1557   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1558     fprintf_filtered (file,
1559                       _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1560                         "the remote target to interrupt the execution "
1561                         "of Linux kernel.\n"));
1562   else
1563     internal_error (__FILE__, __LINE__,
1564                     _("Invalid value for interrupt_sequence_mode: %s."),
1565                     interrupt_sequence_mode);
1566 }
1567
1568 /* This boolean variable specifies whether interrupt_sequence is sent
1569    to the remote target when gdb connects to it.
1570    This is mostly needed when you debug the Linux kernel: The Linux kernel
1571    expects BREAK g which is Magic SysRq g for connecting gdb.  */
1572 static bool interrupt_on_connect = false;
1573
1574 /* This variable is used to implement the "set/show remotebreak" commands.
1575    Since these commands are now deprecated in favor of "set/show remote
1576    interrupt-sequence", it no longer has any effect on the code.  */
1577 static bool remote_break;
1578
1579 static void
1580 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1581 {
1582   if (remote_break)
1583     interrupt_sequence_mode = interrupt_sequence_break;
1584   else
1585     interrupt_sequence_mode = interrupt_sequence_control_c;
1586 }
1587
1588 static void
1589 show_remotebreak (struct ui_file *file, int from_tty,
1590                   struct cmd_list_element *c,
1591                   const char *value)
1592 {
1593 }
1594
1595 /* This variable sets the number of bits in an address that are to be
1596    sent in a memory ("M" or "m") packet.  Normally, after stripping
1597    leading zeros, the entire address would be sent.  This variable
1598    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
1599    initial implementation of remote.c restricted the address sent in
1600    memory packets to ``host::sizeof long'' bytes - (typically 32
1601    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
1602    address was never sent.  Since fixing this bug may cause a break in
1603    some remote targets this variable is principally provided to
1604    facilitate backward compatibility.  */
1605
1606 static unsigned int remote_address_size;
1607
1608 \f
1609 /* User configurable variables for the number of characters in a
1610    memory read/write packet.  MIN (rsa->remote_packet_size,
1611    rsa->sizeof_g_packet) is the default.  Some targets need smaller
1612    values (fifo overruns, et.al.) and some users need larger values
1613    (speed up transfers).  The variables ``preferred_*'' (the user
1614    request), ``current_*'' (what was actually set) and ``forced_*''
1615    (Positive - a soft limit, negative - a hard limit).  */
1616
1617 struct memory_packet_config
1618 {
1619   const char *name;
1620   long size;
1621   int fixed_p;
1622 };
1623
1624 /* The default max memory-write-packet-size, when the setting is
1625    "fixed".  The 16k is historical.  (It came from older GDB's using
1626    alloca for buffers and the knowledge (folklore?) that some hosts
1627    don't cope very well with large alloca calls.)  */
1628 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1629
1630 /* The minimum remote packet size for memory transfers.  Ensures we
1631    can write at least one byte.  */
1632 #define MIN_MEMORY_PACKET_SIZE 20
1633
1634 /* Get the memory packet size, assuming it is fixed.  */
1635
1636 static long
1637 get_fixed_memory_packet_size (struct memory_packet_config *config)
1638 {
1639   gdb_assert (config->fixed_p);
1640
1641   if (config->size <= 0)
1642     return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1643   else
1644     return config->size;
1645 }
1646
1647 /* Compute the current size of a read/write packet.  Since this makes
1648    use of ``actual_register_packet_size'' the computation is dynamic.  */
1649
1650 long
1651 remote_target::get_memory_packet_size (struct memory_packet_config *config)
1652 {
1653   struct remote_state *rs = get_remote_state ();
1654   remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1655
1656   long what_they_get;
1657   if (config->fixed_p)
1658     what_they_get = get_fixed_memory_packet_size (config);
1659   else
1660     {
1661       what_they_get = get_remote_packet_size ();
1662       /* Limit the packet to the size specified by the user.  */
1663       if (config->size > 0
1664           && what_they_get > config->size)
1665         what_they_get = config->size;
1666
1667       /* Limit it to the size of the targets ``g'' response unless we have
1668          permission from the stub to use a larger packet size.  */
1669       if (rs->explicit_packet_size == 0
1670           && rsa->actual_register_packet_size > 0
1671           && what_they_get > rsa->actual_register_packet_size)
1672         what_they_get = rsa->actual_register_packet_size;
1673     }
1674   if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1675     what_they_get = MIN_MEMORY_PACKET_SIZE;
1676
1677   /* Make sure there is room in the global buffer for this packet
1678      (including its trailing NUL byte).  */
1679   if (rs->buf.size () < what_they_get + 1)
1680     rs->buf.resize (2 * what_they_get);
1681
1682   return what_they_get;
1683 }
1684
1685 /* Update the size of a read/write packet.  If they user wants
1686    something really big then do a sanity check.  */
1687
1688 static void
1689 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1690 {
1691   int fixed_p = config->fixed_p;
1692   long size = config->size;
1693
1694   if (args == NULL)
1695     error (_("Argument required (integer, `fixed' or `limited')."));
1696   else if (strcmp (args, "hard") == 0
1697       || strcmp (args, "fixed") == 0)
1698     fixed_p = 1;
1699   else if (strcmp (args, "soft") == 0
1700            || strcmp (args, "limit") == 0)
1701     fixed_p = 0;
1702   else
1703     {
1704       char *end;
1705
1706       size = strtoul (args, &end, 0);
1707       if (args == end)
1708         error (_("Invalid %s (bad syntax)."), config->name);
1709
1710       /* Instead of explicitly capping the size of a packet to or
1711          disallowing it, the user is allowed to set the size to
1712          something arbitrarily large.  */
1713     }
1714
1715   /* Extra checks?  */
1716   if (fixed_p && !config->fixed_p)
1717     {
1718       /* So that the query shows the correct value.  */
1719       long query_size = (size <= 0
1720                          ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1721                          : size);
1722
1723       if (! query (_("The target may not be able to correctly handle a %s\n"
1724                    "of %ld bytes. Change the packet size? "),
1725                    config->name, query_size))
1726         error (_("Packet size not changed."));
1727     }
1728   /* Update the config.  */
1729   config->fixed_p = fixed_p;
1730   config->size = size;
1731 }
1732
1733 static void
1734 show_memory_packet_size (struct memory_packet_config *config)
1735 {
1736   if (config->size == 0)
1737     printf_filtered (_("The %s is 0 (default). "), config->name);
1738   else
1739     printf_filtered (_("The %s is %ld. "), config->name, config->size);
1740   if (config->fixed_p)
1741     printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1742                      get_fixed_memory_packet_size (config));
1743   else
1744     {
1745       remote_target *remote = get_current_remote_target ();
1746
1747       if (remote != NULL)
1748         printf_filtered (_("Packets are limited to %ld bytes.\n"),
1749                          remote->get_memory_packet_size (config));
1750       else
1751         puts_filtered ("The actual limit will be further reduced "
1752                        "dependent on the target.\n");
1753     }
1754 }
1755
1756 /* FIXME: needs to be per-remote-target.  */
1757 static struct memory_packet_config memory_write_packet_config =
1758 {
1759   "memory-write-packet-size",
1760 };
1761
1762 static void
1763 set_memory_write_packet_size (const char *args, int from_tty)
1764 {
1765   set_memory_packet_size (args, &memory_write_packet_config);
1766 }
1767
1768 static void
1769 show_memory_write_packet_size (const char *args, int from_tty)
1770 {
1771   show_memory_packet_size (&memory_write_packet_config);
1772 }
1773
1774 /* Show the number of hardware watchpoints that can be used.  */
1775
1776 static void
1777 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
1778                                 struct cmd_list_element *c,
1779                                 const char *value)
1780 {
1781   fprintf_filtered (file, _("The maximum number of target hardware "
1782                             "watchpoints is %s.\n"), value);
1783 }
1784
1785 /* Show the length limit (in bytes) for hardware watchpoints.  */
1786
1787 static void
1788 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
1789                                        struct cmd_list_element *c,
1790                                        const char *value)
1791 {
1792   fprintf_filtered (file, _("The maximum length (in bytes) of a target "
1793                             "hardware watchpoint is %s.\n"), value);
1794 }
1795
1796 /* Show the number of hardware breakpoints that can be used.  */
1797
1798 static void
1799 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
1800                                 struct cmd_list_element *c,
1801                                 const char *value)
1802 {
1803   fprintf_filtered (file, _("The maximum number of target hardware "
1804                             "breakpoints is %s.\n"), value);
1805 }
1806
1807 /* Controls the maximum number of characters to display in the debug output
1808    for each remote packet.  The remaining characters are omitted.  */
1809
1810 static int remote_packet_max_chars = 512;
1811
1812 /* Show the maximum number of characters to display for each remote packet
1813    when remote debugging is enabled.  */
1814
1815 static void
1816 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
1817                               struct cmd_list_element *c,
1818                               const char *value)
1819 {
1820   fprintf_filtered (file, _("Number of remote packet characters to "
1821                             "display is %s.\n"), value);
1822 }
1823
1824 long
1825 remote_target::get_memory_write_packet_size ()
1826 {
1827   return get_memory_packet_size (&memory_write_packet_config);
1828 }
1829
1830 /* FIXME: needs to be per-remote-target.  */
1831 static struct memory_packet_config memory_read_packet_config =
1832 {
1833   "memory-read-packet-size",
1834 };
1835
1836 static void
1837 set_memory_read_packet_size (const char *args, int from_tty)
1838 {
1839   set_memory_packet_size (args, &memory_read_packet_config);
1840 }
1841
1842 static void
1843 show_memory_read_packet_size (const char *args, int from_tty)
1844 {
1845   show_memory_packet_size (&memory_read_packet_config);
1846 }
1847
1848 long
1849 remote_target::get_memory_read_packet_size ()
1850 {
1851   long size = get_memory_packet_size (&memory_read_packet_config);
1852
1853   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1854      extra buffer size argument before the memory read size can be
1855      increased beyond this.  */
1856   if (size > get_remote_packet_size ())
1857     size = get_remote_packet_size ();
1858   return size;
1859 }
1860
1861 \f
1862
1863 struct packet_config
1864   {
1865     const char *name;
1866     const char *title;
1867
1868     /* If auto, GDB auto-detects support for this packet or feature,
1869        either through qSupported, or by trying the packet and looking
1870        at the response.  If true, GDB assumes the target supports this
1871        packet.  If false, the packet is disabled.  Configs that don't
1872        have an associated command always have this set to auto.  */
1873     enum auto_boolean detect;
1874
1875     /* Does the target support this packet?  */
1876     enum packet_support support;
1877   };
1878
1879 static enum packet_support packet_config_support (struct packet_config *config);
1880 static enum packet_support packet_support (int packet);
1881
1882 static void
1883 show_packet_config_cmd (struct packet_config *config)
1884 {
1885   const char *support = "internal-error";
1886
1887   switch (packet_config_support (config))
1888     {
1889     case PACKET_ENABLE:
1890       support = "enabled";
1891       break;
1892     case PACKET_DISABLE:
1893       support = "disabled";
1894       break;
1895     case PACKET_SUPPORT_UNKNOWN:
1896       support = "unknown";
1897       break;
1898     }
1899   switch (config->detect)
1900     {
1901     case AUTO_BOOLEAN_AUTO:
1902       printf_filtered (_("Support for the `%s' packet "
1903                          "is auto-detected, currently %s.\n"),
1904                        config->name, support);
1905       break;
1906     case AUTO_BOOLEAN_TRUE:
1907     case AUTO_BOOLEAN_FALSE:
1908       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1909                        config->name, support);
1910       break;
1911     }
1912 }
1913
1914 static void
1915 add_packet_config_cmd (struct packet_config *config, const char *name,
1916                        const char *title, int legacy)
1917 {
1918   char *set_doc;
1919   char *show_doc;
1920   char *cmd_name;
1921
1922   config->name = name;
1923   config->title = title;
1924   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
1925                         name, title);
1926   show_doc = xstrprintf ("Show current use of remote "
1927                          "protocol `%s' (%s) packet.",
1928                          name, title);
1929   /* set/show TITLE-packet {auto,on,off} */
1930   cmd_name = xstrprintf ("%s-packet", title);
1931   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1932                                 &config->detect, set_doc,
1933                                 show_doc, NULL, /* help_doc */
1934                                 NULL,
1935                                 show_remote_protocol_packet_cmd,
1936                                 &remote_set_cmdlist, &remote_show_cmdlist);
1937   /* The command code copies the documentation strings.  */
1938   xfree (set_doc);
1939   xfree (show_doc);
1940   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
1941   if (legacy)
1942     {
1943       char *legacy_name;
1944
1945       legacy_name = xstrprintf ("%s-packet", name);
1946       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1947                      &remote_set_cmdlist);
1948       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1949                      &remote_show_cmdlist);
1950     }
1951 }
1952
1953 static enum packet_result
1954 packet_check_result (const char *buf)
1955 {
1956   if (buf[0] != '\0')
1957     {
1958       /* The stub recognized the packet request.  Check that the
1959          operation succeeded.  */
1960       if (buf[0] == 'E'
1961           && isxdigit (buf[1]) && isxdigit (buf[2])
1962           && buf[3] == '\0')
1963         /* "Enn"  - definitely an error.  */
1964         return PACKET_ERROR;
1965
1966       /* Always treat "E." as an error.  This will be used for
1967          more verbose error messages, such as E.memtypes.  */
1968       if (buf[0] == 'E' && buf[1] == '.')
1969         return PACKET_ERROR;
1970
1971       /* The packet may or may not be OK.  Just assume it is.  */
1972       return PACKET_OK;
1973     }
1974   else
1975     /* The stub does not support the packet.  */
1976     return PACKET_UNKNOWN;
1977 }
1978
1979 static enum packet_result
1980 packet_check_result (const gdb::char_vector &buf)
1981 {
1982   return packet_check_result (buf.data ());
1983 }
1984
1985 static enum packet_result
1986 packet_ok (const char *buf, struct packet_config *config)
1987 {
1988   enum packet_result result;
1989
1990   if (config->detect != AUTO_BOOLEAN_TRUE
1991       && config->support == PACKET_DISABLE)
1992     internal_error (__FILE__, __LINE__,
1993                     _("packet_ok: attempt to use a disabled packet"));
1994
1995   result = packet_check_result (buf);
1996   switch (result)
1997     {
1998     case PACKET_OK:
1999     case PACKET_ERROR:
2000       /* The stub recognized the packet request.  */
2001       if (config->support == PACKET_SUPPORT_UNKNOWN)
2002         {
2003           remote_debug_printf ("Packet %s (%s) is supported",
2004                                config->name, config->title);
2005           config->support = PACKET_ENABLE;
2006         }
2007       break;
2008     case PACKET_UNKNOWN:
2009       /* The stub does not support the packet.  */
2010       if (config->detect == AUTO_BOOLEAN_AUTO
2011           && config->support == PACKET_ENABLE)
2012         {
2013           /* If the stub previously indicated that the packet was
2014              supported then there is a protocol error.  */
2015           error (_("Protocol error: %s (%s) conflicting enabled responses."),
2016                  config->name, config->title);
2017         }
2018       else if (config->detect == AUTO_BOOLEAN_TRUE)
2019         {
2020           /* The user set it wrong.  */
2021           error (_("Enabled packet %s (%s) not recognized by stub"),
2022                  config->name, config->title);
2023         }
2024
2025       remote_debug_printf ("Packet %s (%s) is NOT supported",
2026                            config->name, config->title);
2027       config->support = PACKET_DISABLE;
2028       break;
2029     }
2030
2031   return result;
2032 }
2033
2034 static enum packet_result
2035 packet_ok (const gdb::char_vector &buf, struct packet_config *config)
2036 {
2037   return packet_ok (buf.data (), config);
2038 }
2039
2040 enum {
2041   PACKET_vCont = 0,
2042   PACKET_X,
2043   PACKET_qSymbol,
2044   PACKET_P,
2045   PACKET_p,
2046   PACKET_Z0,
2047   PACKET_Z1,
2048   PACKET_Z2,
2049   PACKET_Z3,
2050   PACKET_Z4,
2051   PACKET_vFile_setfs,
2052   PACKET_vFile_open,
2053   PACKET_vFile_pread,
2054   PACKET_vFile_pwrite,
2055   PACKET_vFile_close,
2056   PACKET_vFile_unlink,
2057   PACKET_vFile_readlink,
2058   PACKET_vFile_fstat,
2059   PACKET_qXfer_auxv,
2060   PACKET_qXfer_features,
2061   PACKET_qXfer_exec_file,
2062   PACKET_qXfer_libraries,
2063   PACKET_qXfer_libraries_svr4,
2064   PACKET_qXfer_memory_map,
2065   PACKET_qXfer_osdata,
2066   PACKET_qXfer_threads,
2067   PACKET_qXfer_statictrace_read,
2068   PACKET_qXfer_traceframe_info,
2069   PACKET_qXfer_uib,
2070   PACKET_qGetTIBAddr,
2071   PACKET_qGetTLSAddr,
2072   PACKET_qSupported,
2073   PACKET_qTStatus,
2074   PACKET_QPassSignals,
2075   PACKET_QCatchSyscalls,
2076   PACKET_QProgramSignals,
2077   PACKET_QSetWorkingDir,
2078   PACKET_QStartupWithShell,
2079   PACKET_QEnvironmentHexEncoded,
2080   PACKET_QEnvironmentReset,
2081   PACKET_QEnvironmentUnset,
2082   PACKET_qCRC,
2083   PACKET_qSearch_memory,
2084   PACKET_vAttach,
2085   PACKET_vRun,
2086   PACKET_QStartNoAckMode,
2087   PACKET_vKill,
2088   PACKET_qXfer_siginfo_read,
2089   PACKET_qXfer_siginfo_write,
2090   PACKET_qAttached,
2091
2092   /* Support for conditional tracepoints.  */
2093   PACKET_ConditionalTracepoints,
2094
2095   /* Support for target-side breakpoint conditions.  */
2096   PACKET_ConditionalBreakpoints,
2097
2098   /* Support for target-side breakpoint commands.  */
2099   PACKET_BreakpointCommands,
2100
2101   /* Support for fast tracepoints.  */
2102   PACKET_FastTracepoints,
2103
2104   /* Support for static tracepoints.  */
2105   PACKET_StaticTracepoints,
2106
2107   /* Support for installing tracepoints while a trace experiment is
2108      running.  */
2109   PACKET_InstallInTrace,
2110
2111   PACKET_bc,
2112   PACKET_bs,
2113   PACKET_TracepointSource,
2114   PACKET_QAllow,
2115   PACKET_qXfer_fdpic,
2116   PACKET_QDisableRandomization,
2117   PACKET_QAgent,
2118   PACKET_QTBuffer_size,
2119   PACKET_Qbtrace_off,
2120   PACKET_Qbtrace_bts,
2121   PACKET_Qbtrace_pt,
2122   PACKET_qXfer_btrace,
2123
2124   /* Support for the QNonStop packet.  */
2125   PACKET_QNonStop,
2126
2127   /* Support for the QThreadEvents packet.  */
2128   PACKET_QThreadEvents,
2129
2130   /* Support for multi-process extensions.  */
2131   PACKET_multiprocess_feature,
2132
2133   /* Support for enabling and disabling tracepoints while a trace
2134      experiment is running.  */
2135   PACKET_EnableDisableTracepoints_feature,
2136
2137   /* Support for collecting strings using the tracenz bytecode.  */
2138   PACKET_tracenz_feature,
2139
2140   /* Support for continuing to run a trace experiment while GDB is
2141      disconnected.  */
2142   PACKET_DisconnectedTracing_feature,
2143
2144   /* Support for qXfer:libraries-svr4:read with a non-empty annex.  */
2145   PACKET_augmented_libraries_svr4_read_feature,
2146
2147   /* Support for the qXfer:btrace-conf:read packet.  */
2148   PACKET_qXfer_btrace_conf,
2149
2150   /* Support for the Qbtrace-conf:bts:size packet.  */
2151   PACKET_Qbtrace_conf_bts_size,
2152
2153   /* Support for swbreak+ feature.  */
2154   PACKET_swbreak_feature,
2155
2156   /* Support for hwbreak+ feature.  */
2157   PACKET_hwbreak_feature,
2158
2159   /* Support for fork events.  */
2160   PACKET_fork_event_feature,
2161
2162   /* Support for vfork events.  */
2163   PACKET_vfork_event_feature,
2164
2165   /* Support for the Qbtrace-conf:pt:size packet.  */
2166   PACKET_Qbtrace_conf_pt_size,
2167
2168   /* Support for exec events.  */
2169   PACKET_exec_event_feature,
2170
2171   /* Support for query supported vCont actions.  */
2172   PACKET_vContSupported,
2173
2174   /* Support remote CTRL-C.  */
2175   PACKET_vCtrlC,
2176
2177   /* Support TARGET_WAITKIND_NO_RESUMED.  */
2178   PACKET_no_resumed,
2179
2180   /* Support for memory tagging, allocation tag fetch/store
2181      packets and the tag violation stop replies.  */
2182   PACKET_memory_tagging_feature,
2183
2184   PACKET_MAX
2185 };
2186
2187 /* FIXME: needs to be per-remote-target.  Ignoring this for now,
2188    assuming all remote targets are the same server (thus all support
2189    the same packets).  */
2190 static struct packet_config remote_protocol_packets[PACKET_MAX];
2191
2192 /* Returns the packet's corresponding "set remote foo-packet" command
2193    state.  See struct packet_config for more details.  */
2194
2195 static enum auto_boolean
2196 packet_set_cmd_state (int packet)
2197 {
2198   return remote_protocol_packets[packet].detect;
2199 }
2200
2201 /* Returns whether a given packet or feature is supported.  This takes
2202    into account the state of the corresponding "set remote foo-packet"
2203    command, which may be used to bypass auto-detection.  */
2204
2205 static enum packet_support
2206 packet_config_support (struct packet_config *config)
2207 {
2208   switch (config->detect)
2209     {
2210     case AUTO_BOOLEAN_TRUE:
2211       return PACKET_ENABLE;
2212     case AUTO_BOOLEAN_FALSE:
2213       return PACKET_DISABLE;
2214     case AUTO_BOOLEAN_AUTO:
2215       return config->support;
2216     default:
2217       gdb_assert_not_reached (_("bad switch"));
2218     }
2219 }
2220
2221 /* Same as packet_config_support, but takes the packet's enum value as
2222    argument.  */
2223
2224 static enum packet_support
2225 packet_support (int packet)
2226 {
2227   struct packet_config *config = &remote_protocol_packets[packet];
2228
2229   return packet_config_support (config);
2230 }
2231
2232 static void
2233 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2234                                  struct cmd_list_element *c,
2235                                  const char *value)
2236 {
2237   struct packet_config *packet;
2238
2239   for (packet = remote_protocol_packets;
2240        packet < &remote_protocol_packets[PACKET_MAX];
2241        packet++)
2242     {
2243       if (&packet->detect == c->var)
2244         {
2245           show_packet_config_cmd (packet);
2246           return;
2247         }
2248     }
2249   internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
2250                   c->name);
2251 }
2252
2253 /* Should we try one of the 'Z' requests?  */
2254
2255 enum Z_packet_type
2256 {
2257   Z_PACKET_SOFTWARE_BP,
2258   Z_PACKET_HARDWARE_BP,
2259   Z_PACKET_WRITE_WP,
2260   Z_PACKET_READ_WP,
2261   Z_PACKET_ACCESS_WP,
2262   NR_Z_PACKET_TYPES
2263 };
2264
2265 /* For compatibility with older distributions.  Provide a ``set remote
2266    Z-packet ...'' command that updates all the Z packet types.  */
2267
2268 static enum auto_boolean remote_Z_packet_detect;
2269
2270 static void
2271 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2272                                   struct cmd_list_element *c)
2273 {
2274   int i;
2275
2276   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2277     remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2278 }
2279
2280 static void
2281 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2282                                    struct cmd_list_element *c,
2283                                    const char *value)
2284 {
2285   int i;
2286
2287   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2288     {
2289       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
2290     }
2291 }
2292
2293 /* Returns true if the multi-process extensions are in effect.  */
2294
2295 static int
2296 remote_multi_process_p (struct remote_state *rs)
2297 {
2298   return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2299 }
2300
2301 /* Returns true if fork events are supported.  */
2302
2303 static int
2304 remote_fork_event_p (struct remote_state *rs)
2305 {
2306   return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2307 }
2308
2309 /* Returns true if vfork events are supported.  */
2310
2311 static int
2312 remote_vfork_event_p (struct remote_state *rs)
2313 {
2314   return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2315 }
2316
2317 /* Returns true if exec events are supported.  */
2318
2319 static int
2320 remote_exec_event_p (struct remote_state *rs)
2321 {
2322   return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2323 }
2324
2325 /* Returns true if memory tagging is supported, false otherwise.  */
2326
2327 static bool
2328 remote_memory_tagging_p ()
2329 {
2330   return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE;
2331 }
2332
2333 /* Insert fork catchpoint target routine.  If fork events are enabled
2334    then return success, nothing more to do.  */
2335
2336 int
2337 remote_target::insert_fork_catchpoint (int pid)
2338 {
2339   struct remote_state *rs = get_remote_state ();
2340
2341   return !remote_fork_event_p (rs);
2342 }
2343
2344 /* Remove fork catchpoint target routine.  Nothing to do, just
2345    return success.  */
2346
2347 int
2348 remote_target::remove_fork_catchpoint (int pid)
2349 {
2350   return 0;
2351 }
2352
2353 /* Insert vfork catchpoint target routine.  If vfork events are enabled
2354    then return success, nothing more to do.  */
2355
2356 int
2357 remote_target::insert_vfork_catchpoint (int pid)
2358 {
2359   struct remote_state *rs = get_remote_state ();
2360
2361   return !remote_vfork_event_p (rs);
2362 }
2363
2364 /* Remove vfork catchpoint target routine.  Nothing to do, just
2365    return success.  */
2366
2367 int
2368 remote_target::remove_vfork_catchpoint (int pid)
2369 {
2370   return 0;
2371 }
2372
2373 /* Insert exec catchpoint target routine.  If exec events are
2374    enabled, just return success.  */
2375
2376 int
2377 remote_target::insert_exec_catchpoint (int pid)
2378 {
2379   struct remote_state *rs = get_remote_state ();
2380
2381   return !remote_exec_event_p (rs);
2382 }
2383
2384 /* Remove exec catchpoint target routine.  Nothing to do, just
2385    return success.  */
2386
2387 int
2388 remote_target::remove_exec_catchpoint (int pid)
2389 {
2390   return 0;
2391 }
2392
2393 \f
2394
2395 /* Take advantage of the fact that the TID field is not used, to tag
2396    special ptids with it set to != 0.  */
2397 static const ptid_t magic_null_ptid (42000, -1, 1);
2398 static const ptid_t not_sent_ptid (42000, -2, 1);
2399 static const ptid_t any_thread_ptid (42000, 0, 1);
2400
2401 /* Find out if the stub attached to PID (and hence GDB should offer to
2402    detach instead of killing it when bailing out).  */
2403
2404 int
2405 remote_target::remote_query_attached (int pid)
2406 {
2407   struct remote_state *rs = get_remote_state ();
2408   size_t size = get_remote_packet_size ();
2409
2410   if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2411     return 0;
2412
2413   if (remote_multi_process_p (rs))
2414     xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2415   else
2416     xsnprintf (rs->buf.data (), size, "qAttached");
2417
2418   putpkt (rs->buf);
2419   getpkt (&rs->buf, 0);
2420
2421   switch (packet_ok (rs->buf,
2422                      &remote_protocol_packets[PACKET_qAttached]))
2423     {
2424     case PACKET_OK:
2425       if (strcmp (rs->buf.data (), "1") == 0)
2426         return 1;
2427       break;
2428     case PACKET_ERROR:
2429       warning (_("Remote failure reply: %s"), rs->buf.data ());
2430       break;
2431     case PACKET_UNKNOWN:
2432       break;
2433     }
2434
2435   return 0;
2436 }
2437
2438 /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
2439    has been invented by GDB, instead of reported by the target.  Since
2440    we can be connected to a remote system before before knowing about
2441    any inferior, mark the target with execution when we find the first
2442    inferior.  If ATTACHED is 1, then we had just attached to this
2443    inferior.  If it is 0, then we just created this inferior.  If it
2444    is -1, then try querying the remote stub to find out if it had
2445    attached to the inferior or not.  If TRY_OPEN_EXEC is true then
2446    attempt to open this inferior's executable as the main executable
2447    if no main executable is open already.  */
2448
2449 inferior *
2450 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2451                                     int try_open_exec)
2452 {
2453   struct inferior *inf;
2454
2455   /* Check whether this process we're learning about is to be
2456      considered attached, or if is to be considered to have been
2457      spawned by the stub.  */
2458   if (attached == -1)
2459     attached = remote_query_attached (pid);
2460
2461   if (gdbarch_has_global_solist (target_gdbarch ()))
2462     {
2463       /* If the target shares code across all inferiors, then every
2464          attach adds a new inferior.  */
2465       inf = add_inferior (pid);
2466
2467       /* ... and every inferior is bound to the same program space.
2468          However, each inferior may still have its own address
2469          space.  */
2470       inf->aspace = maybe_new_address_space ();
2471       inf->pspace = current_program_space;
2472     }
2473   else
2474     {
2475       /* In the traditional debugging scenario, there's a 1-1 match
2476          between program/address spaces.  We simply bind the inferior
2477          to the program space's address space.  */
2478       inf = current_inferior ();
2479
2480       /* However, if the current inferior is already bound to a
2481          process, find some other empty inferior.  */
2482       if (inf->pid != 0)
2483         {
2484           inf = nullptr;
2485           for (inferior *it : all_inferiors ())
2486             if (it->pid == 0)
2487               {
2488                 inf = it;
2489                 break;
2490               }
2491         }
2492       if (inf == nullptr)
2493         {
2494           /* Since all inferiors were already bound to a process, add
2495              a new inferior.  */
2496           inf = add_inferior_with_spaces ();
2497         }
2498       switch_to_inferior_no_thread (inf);
2499       inf->push_target (this);
2500       inferior_appeared (inf, pid);
2501     }
2502
2503   inf->attach_flag = attached;
2504   inf->fake_pid_p = fake_pid_p;
2505
2506   /* If no main executable is currently open then attempt to
2507      open the file that was executed to create this inferior.  */
2508   if (try_open_exec && get_exec_file (0) == NULL)
2509     exec_file_locate_attach (pid, 0, 1);
2510
2511   /* Check for exec file mismatch, and let the user solve it.  */
2512   validate_exec_file (1);
2513
2514   return inf;
2515 }
2516
2517 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2518 static remote_thread_info *get_remote_thread_info (remote_target *target,
2519                                                    ptid_t ptid);
2520
2521 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
2522    according to RUNNING.  */
2523
2524 thread_info *
2525 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing)
2526 {
2527   struct remote_state *rs = get_remote_state ();
2528   struct thread_info *thread;
2529
2530   /* GDB historically didn't pull threads in the initial connection
2531      setup.  If the remote target doesn't even have a concept of
2532      threads (e.g., a bare-metal target), even if internally we
2533      consider that a single-threaded target, mentioning a new thread
2534      might be confusing to the user.  Be silent then, preserving the
2535      age old behavior.  */
2536   if (rs->starting_up)
2537     thread = add_thread_silent (this, ptid);
2538   else
2539     thread = add_thread (this, ptid);
2540
2541   /* We start by assuming threads are resumed.  That state then gets updated
2542      when we process a matching stop reply.  */
2543   get_remote_thread_info (thread)->set_resumed ();
2544
2545   set_executing (this, ptid, executing);
2546   set_running (this, ptid, running);
2547
2548   return thread;
2549 }
2550
2551 /* Come here when we learn about a thread id from the remote target.
2552    It may be the first time we hear about such thread, so take the
2553    opportunity to add it to GDB's thread list.  In case this is the
2554    first time we're noticing its corresponding inferior, add it to
2555    GDB's inferior list as well.  EXECUTING indicates whether the
2556    thread is (internally) executing or stopped.  */
2557
2558 void
2559 remote_target::remote_notice_new_inferior (ptid_t currthread, int executing)
2560 {
2561   /* In non-stop mode, we assume new found threads are (externally)
2562      running until proven otherwise with a stop reply.  In all-stop,
2563      we can only get here if all threads are stopped.  */
2564   int running = target_is_non_stop_p () ? 1 : 0;
2565
2566   /* If this is a new thread, add it to GDB's thread list.
2567      If we leave it up to WFI to do this, bad things will happen.  */
2568
2569   thread_info *tp = find_thread_ptid (this, currthread);
2570   if (tp != NULL && tp->state == THREAD_EXITED)
2571     {
2572       /* We're seeing an event on a thread id we knew had exited.
2573          This has to be a new thread reusing the old id.  Add it.  */
2574       remote_add_thread (currthread, running, executing);
2575       return;
2576     }
2577
2578   if (!in_thread_list (this, currthread))
2579     {
2580       struct inferior *inf = NULL;
2581       int pid = currthread.pid ();
2582
2583       if (inferior_ptid.is_pid ()
2584           && pid == inferior_ptid.pid ())
2585         {
2586           /* inferior_ptid has no thread member yet.  This can happen
2587              with the vAttach -> remote_wait,"TAAthread:" path if the
2588              stub doesn't support qC.  This is the first stop reported
2589              after an attach, so this is the main thread.  Update the
2590              ptid in the thread list.  */
2591           if (in_thread_list (this, ptid_t (pid)))
2592             thread_change_ptid (this, inferior_ptid, currthread);
2593           else
2594             {
2595               thread_info *thr
2596                 = remote_add_thread (currthread, running, executing);
2597               switch_to_thread (thr);
2598             }
2599           return;
2600         }
2601
2602       if (magic_null_ptid == inferior_ptid)
2603         {
2604           /* inferior_ptid is not set yet.  This can happen with the
2605              vRun -> remote_wait,"TAAthread:" path if the stub
2606              doesn't support qC.  This is the first stop reported
2607              after an attach, so this is the main thread.  Update the
2608              ptid in the thread list.  */
2609           thread_change_ptid (this, inferior_ptid, currthread);
2610           return;
2611         }
2612
2613       /* When connecting to a target remote, or to a target
2614          extended-remote which already was debugging an inferior, we
2615          may not know about it yet.  Add it before adding its child
2616          thread, so notifications are emitted in a sensible order.  */
2617       if (find_inferior_pid (this, currthread.pid ()) == NULL)
2618         {
2619           struct remote_state *rs = get_remote_state ();
2620           bool fake_pid_p = !remote_multi_process_p (rs);
2621
2622           inf = remote_add_inferior (fake_pid_p,
2623                                      currthread.pid (), -1, 1);
2624         }
2625
2626       /* This is really a new thread.  Add it.  */
2627       thread_info *new_thr
2628         = remote_add_thread (currthread, running, executing);
2629
2630       /* If we found a new inferior, let the common code do whatever
2631          it needs to with it (e.g., read shared libraries, insert
2632          breakpoints), unless we're just setting up an all-stop
2633          connection.  */
2634       if (inf != NULL)
2635         {
2636           struct remote_state *rs = get_remote_state ();
2637
2638           if (!rs->starting_up)
2639             notice_new_inferior (new_thr, executing, 0);
2640         }
2641     }
2642 }
2643
2644 /* Return THREAD's private thread data, creating it if necessary.  */
2645
2646 static remote_thread_info *
2647 get_remote_thread_info (thread_info *thread)
2648 {
2649   gdb_assert (thread != NULL);
2650
2651   if (thread->priv == NULL)
2652     thread->priv.reset (new remote_thread_info);
2653
2654   return static_cast<remote_thread_info *> (thread->priv.get ());
2655 }
2656
2657 /* Return PTID's private thread data, creating it if necessary.  */
2658
2659 static remote_thread_info *
2660 get_remote_thread_info (remote_target *target, ptid_t ptid)
2661 {
2662   thread_info *thr = find_thread_ptid (target, ptid);
2663   return get_remote_thread_info (thr);
2664 }
2665
2666 /* Call this function as a result of
2667    1) A halt indication (T packet) containing a thread id
2668    2) A direct query of currthread
2669    3) Successful execution of set thread */
2670
2671 static void
2672 record_currthread (struct remote_state *rs, ptid_t currthread)
2673 {
2674   rs->general_thread = currthread;
2675 }
2676
2677 /* If 'QPassSignals' is supported, tell the remote stub what signals
2678    it can simply pass through to the inferior without reporting.  */
2679
2680 void
2681 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2682 {
2683   if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2684     {
2685       char *pass_packet, *p;
2686       int count = 0;
2687       struct remote_state *rs = get_remote_state ();
2688
2689       gdb_assert (pass_signals.size () < 256);
2690       for (size_t i = 0; i < pass_signals.size (); i++)
2691         {
2692           if (pass_signals[i])
2693             count++;
2694         }
2695       pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2696       strcpy (pass_packet, "QPassSignals:");
2697       p = pass_packet + strlen (pass_packet);
2698       for (size_t i = 0; i < pass_signals.size (); i++)
2699         {
2700           if (pass_signals[i])
2701             {
2702               if (i >= 16)
2703                 *p++ = tohex (i >> 4);
2704               *p++ = tohex (i & 15);
2705               if (count)
2706                 *p++ = ';';
2707               else
2708                 break;
2709               count--;
2710             }
2711         }
2712       *p = 0;
2713       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2714         {
2715           putpkt (pass_packet);
2716           getpkt (&rs->buf, 0);
2717           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2718           xfree (rs->last_pass_packet);
2719           rs->last_pass_packet = pass_packet;
2720         }
2721       else
2722         xfree (pass_packet);
2723     }
2724 }
2725
2726 /* If 'QCatchSyscalls' is supported, tell the remote stub
2727    to report syscalls to GDB.  */
2728
2729 int
2730 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2731                                        gdb::array_view<const int> syscall_counts)
2732 {
2733   const char *catch_packet;
2734   enum packet_result result;
2735   int n_sysno = 0;
2736
2737   if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2738     {
2739       /* Not supported.  */
2740       return 1;
2741     }
2742
2743   if (needed && any_count == 0)
2744     {
2745       /* Count how many syscalls are to be caught.  */
2746       for (size_t i = 0; i < syscall_counts.size (); i++)
2747         {
2748           if (syscall_counts[i] != 0)
2749             n_sysno++;
2750         }
2751     }
2752
2753   remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
2754                        pid, needed, any_count, n_sysno);
2755
2756   std::string built_packet;
2757   if (needed)
2758     {
2759       /* Prepare a packet with the sysno list, assuming max 8+1
2760          characters for a sysno.  If the resulting packet size is too
2761          big, fallback on the non-selective packet.  */
2762       const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2763       built_packet.reserve (maxpktsz);
2764       built_packet = "QCatchSyscalls:1";
2765       if (any_count == 0)
2766         {
2767           /* Add in each syscall to be caught.  */
2768           for (size_t i = 0; i < syscall_counts.size (); i++)
2769             {
2770               if (syscall_counts[i] != 0)
2771                 string_appendf (built_packet, ";%zx", i);
2772             }
2773         }
2774       if (built_packet.size () > get_remote_packet_size ())
2775         {
2776           /* catch_packet too big.  Fallback to less efficient
2777              non selective mode, with GDB doing the filtering.  */
2778           catch_packet = "QCatchSyscalls:1";
2779         }
2780       else
2781         catch_packet = built_packet.c_str ();
2782     }
2783   else
2784     catch_packet = "QCatchSyscalls:0";
2785
2786   struct remote_state *rs = get_remote_state ();
2787
2788   putpkt (catch_packet);
2789   getpkt (&rs->buf, 0);
2790   result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2791   if (result == PACKET_OK)
2792     return 0;
2793   else
2794     return -1;
2795 }
2796
2797 /* If 'QProgramSignals' is supported, tell the remote stub what
2798    signals it should pass through to the inferior when detaching.  */
2799
2800 void
2801 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
2802 {
2803   if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2804     {
2805       char *packet, *p;
2806       int count = 0;
2807       struct remote_state *rs = get_remote_state ();
2808
2809       gdb_assert (signals.size () < 256);
2810       for (size_t i = 0; i < signals.size (); i++)
2811         {
2812           if (signals[i])
2813             count++;
2814         }
2815       packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2816       strcpy (packet, "QProgramSignals:");
2817       p = packet + strlen (packet);
2818       for (size_t i = 0; i < signals.size (); i++)
2819         {
2820           if (signal_pass_state (i))
2821             {
2822               if (i >= 16)
2823                 *p++ = tohex (i >> 4);
2824               *p++ = tohex (i & 15);
2825               if (count)
2826                 *p++ = ';';
2827               else
2828                 break;
2829               count--;
2830             }
2831         }
2832       *p = 0;
2833       if (!rs->last_program_signals_packet
2834           || strcmp (rs->last_program_signals_packet, packet) != 0)
2835         {
2836           putpkt (packet);
2837           getpkt (&rs->buf, 0);
2838           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2839           xfree (rs->last_program_signals_packet);
2840           rs->last_program_signals_packet = packet;
2841         }
2842       else
2843         xfree (packet);
2844     }
2845 }
2846
2847 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
2848    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2849    thread.  If GEN is set, set the general thread, if not, then set
2850    the step/continue thread.  */
2851 void
2852 remote_target::set_thread (ptid_t ptid, int gen)
2853 {
2854   struct remote_state *rs = get_remote_state ();
2855   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2856   char *buf = rs->buf.data ();
2857   char *endbuf = buf + get_remote_packet_size ();
2858
2859   if (state == ptid)
2860     return;
2861
2862   *buf++ = 'H';
2863   *buf++ = gen ? 'g' : 'c';
2864   if (ptid == magic_null_ptid)
2865     xsnprintf (buf, endbuf - buf, "0");
2866   else if (ptid == any_thread_ptid)
2867     xsnprintf (buf, endbuf - buf, "0");
2868   else if (ptid == minus_one_ptid)
2869     xsnprintf (buf, endbuf - buf, "-1");
2870   else
2871     write_ptid (buf, endbuf, ptid);
2872   putpkt (rs->buf);
2873   getpkt (&rs->buf, 0);
2874   if (gen)
2875     rs->general_thread = ptid;
2876   else
2877     rs->continue_thread = ptid;
2878 }
2879
2880 void
2881 remote_target::set_general_thread (ptid_t ptid)
2882 {
2883   set_thread (ptid, 1);
2884 }
2885
2886 void
2887 remote_target::set_continue_thread (ptid_t ptid)
2888 {
2889   set_thread (ptid, 0);
2890 }
2891
2892 /* Change the remote current process.  Which thread within the process
2893    ends up selected isn't important, as long as it is the same process
2894    as what INFERIOR_PTID points to.
2895
2896    This comes from that fact that there is no explicit notion of
2897    "selected process" in the protocol.  The selected process for
2898    general operations is the process the selected general thread
2899    belongs to.  */
2900
2901 void
2902 remote_target::set_general_process ()
2903 {
2904   struct remote_state *rs = get_remote_state ();
2905
2906   /* If the remote can't handle multiple processes, don't bother.  */
2907   if (!remote_multi_process_p (rs))
2908     return;
2909
2910   /* We only need to change the remote current thread if it's pointing
2911      at some other process.  */
2912   if (rs->general_thread.pid () != inferior_ptid.pid ())
2913     set_general_thread (inferior_ptid);
2914 }
2915
2916 \f
2917 /* Return nonzero if this is the main thread that we made up ourselves
2918    to model non-threaded targets as single-threaded.  */
2919
2920 static int
2921 remote_thread_always_alive (ptid_t ptid)
2922 {
2923   if (ptid == magic_null_ptid)
2924     /* The main thread is always alive.  */
2925     return 1;
2926
2927   if (ptid.pid () != 0 && ptid.lwp () == 0)
2928     /* The main thread is always alive.  This can happen after a
2929        vAttach, if the remote side doesn't support
2930        multi-threading.  */
2931     return 1;
2932
2933   return 0;
2934 }
2935
2936 /* Return nonzero if the thread PTID is still alive on the remote
2937    system.  */
2938
2939 bool
2940 remote_target::thread_alive (ptid_t ptid)
2941 {
2942   struct remote_state *rs = get_remote_state ();
2943   char *p, *endp;
2944
2945   /* Check if this is a thread that we made up ourselves to model
2946      non-threaded targets as single-threaded.  */
2947   if (remote_thread_always_alive (ptid))
2948     return 1;
2949
2950   p = rs->buf.data ();
2951   endp = p + get_remote_packet_size ();
2952
2953   *p++ = 'T';
2954   write_ptid (p, endp, ptid);
2955
2956   putpkt (rs->buf);
2957   getpkt (&rs->buf, 0);
2958   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2959 }
2960
2961 /* Return a pointer to a thread name if we know it and NULL otherwise.
2962    The thread_info object owns the memory for the name.  */
2963
2964 const char *
2965 remote_target::thread_name (struct thread_info *info)
2966 {
2967   if (info->priv != NULL)
2968     {
2969       const std::string &name = get_remote_thread_info (info)->name;
2970       return !name.empty () ? name.c_str () : NULL;
2971     }
2972
2973   return NULL;
2974 }
2975
2976 /* About these extended threadlist and threadinfo packets.  They are
2977    variable length packets but, the fields within them are often fixed
2978    length.  They are redundant enough to send over UDP as is the
2979    remote protocol in general.  There is a matching unit test module
2980    in libstub.  */
2981
2982 /* WARNING: This threadref data structure comes from the remote O.S.,
2983    libstub protocol encoding, and remote.c.  It is not particularly
2984    changable.  */
2985
2986 /* Right now, the internal structure is int. We want it to be bigger.
2987    Plan to fix this.  */
2988
2989 typedef int gdb_threadref;      /* Internal GDB thread reference.  */
2990
2991 /* gdb_ext_thread_info is an internal GDB data structure which is
2992    equivalent to the reply of the remote threadinfo packet.  */
2993
2994 struct gdb_ext_thread_info
2995   {
2996     threadref threadid;         /* External form of thread reference.  */
2997     int active;                 /* Has state interesting to GDB?
2998                                    regs, stack.  */
2999     char display[256];          /* Brief state display, name,
3000                                    blocked/suspended.  */
3001     char shortname[32];         /* To be used to name threads.  */
3002     char more_display[256];     /* Long info, statistics, queue depth,
3003                                    whatever.  */
3004   };
3005
3006 /* The volume of remote transfers can be limited by submitting
3007    a mask containing bits specifying the desired information.
3008    Use a union of these values as the 'selection' parameter to
3009    get_thread_info.  FIXME: Make these TAG names more thread specific.  */
3010
3011 #define TAG_THREADID 1
3012 #define TAG_EXISTS 2
3013 #define TAG_DISPLAY 4
3014 #define TAG_THREADNAME 8
3015 #define TAG_MOREDISPLAY 16
3016
3017 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3018
3019 static const char *unpack_nibble (const char *buf, int *val);
3020
3021 static const char *unpack_byte (const char *buf, int *value);
3022
3023 static char *pack_int (char *buf, int value);
3024
3025 static const char *unpack_int (const char *buf, int *value);
3026
3027 static const char *unpack_string (const char *src, char *dest, int length);
3028
3029 static char *pack_threadid (char *pkt, threadref *id);
3030
3031 static const char *unpack_threadid (const char *inbuf, threadref *id);
3032
3033 void int_to_threadref (threadref *id, int value);
3034
3035 static int threadref_to_int (threadref *ref);
3036
3037 static void copy_threadref (threadref *dest, threadref *src);
3038
3039 static int threadmatch (threadref *dest, threadref *src);
3040
3041 static char *pack_threadinfo_request (char *pkt, int mode,
3042                                       threadref *id);
3043
3044 static char *pack_threadlist_request (char *pkt, int startflag,
3045                                       int threadcount,
3046                                       threadref *nextthread);
3047
3048 static int remote_newthread_step (threadref *ref, void *context);
3049
3050
3051 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
3052    buffer we're allowed to write to.  Returns
3053    BUF+CHARACTERS_WRITTEN.  */
3054
3055 char *
3056 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3057 {
3058   int pid, tid;
3059   struct remote_state *rs = get_remote_state ();
3060
3061   if (remote_multi_process_p (rs))
3062     {
3063       pid = ptid.pid ();
3064       if (pid < 0)
3065         buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3066       else
3067         buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3068     }
3069   tid = ptid.lwp ();
3070   if (tid < 0)
3071     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3072   else
3073     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3074
3075   return buf;
3076 }
3077
3078 /* Extract a PTID from BUF.  If non-null, OBUF is set to one past the
3079    last parsed char.  Returns null_ptid if no thread id is found, and
3080    throws an error if the thread id has an invalid format.  */
3081
3082 static ptid_t
3083 read_ptid (const char *buf, const char **obuf)
3084 {
3085   const char *p = buf;
3086   const char *pp;
3087   ULONGEST pid = 0, tid = 0;
3088
3089   if (*p == 'p')
3090     {
3091       /* Multi-process ptid.  */
3092       pp = unpack_varlen_hex (p + 1, &pid);
3093       if (*pp != '.')
3094         error (_("invalid remote ptid: %s"), p);
3095
3096       p = pp;
3097       pp = unpack_varlen_hex (p + 1, &tid);
3098       if (obuf)
3099         *obuf = pp;
3100       return ptid_t (pid, tid, 0);
3101     }
3102
3103   /* No multi-process.  Just a tid.  */
3104   pp = unpack_varlen_hex (p, &tid);
3105
3106   /* Return null_ptid when no thread id is found.  */
3107   if (p == pp)
3108     {
3109       if (obuf)
3110         *obuf = pp;
3111       return null_ptid;
3112     }
3113
3114   /* Since the stub is not sending a process id, then default to
3115      what's in inferior_ptid, unless it's null at this point.  If so,
3116      then since there's no way to know the pid of the reported
3117      threads, use the magic number.  */
3118   if (inferior_ptid == null_ptid)
3119     pid = magic_null_ptid.pid ();
3120   else
3121     pid = inferior_ptid.pid ();
3122
3123   if (obuf)
3124     *obuf = pp;
3125   return ptid_t (pid, tid, 0);
3126 }
3127
3128 static int
3129 stubhex (int ch)
3130 {
3131   if (ch >= 'a' && ch <= 'f')
3132     return ch - 'a' + 10;
3133   if (ch >= '0' && ch <= '9')
3134     return ch - '0';
3135   if (ch >= 'A' && ch <= 'F')
3136     return ch - 'A' + 10;
3137   return -1;
3138 }
3139
3140 static int
3141 stub_unpack_int (const char *buff, int fieldlength)
3142 {
3143   int nibble;
3144   int retval = 0;
3145
3146   while (fieldlength)
3147     {
3148       nibble = stubhex (*buff++);
3149       retval |= nibble;
3150       fieldlength--;
3151       if (fieldlength)
3152         retval = retval << 4;
3153     }
3154   return retval;
3155 }
3156
3157 static const char *
3158 unpack_nibble (const char *buf, int *val)
3159 {
3160   *val = fromhex (*buf++);
3161   return buf;
3162 }
3163
3164 static const char *
3165 unpack_byte (const char *buf, int *value)
3166 {
3167   *value = stub_unpack_int (buf, 2);
3168   return buf + 2;
3169 }
3170
3171 static char *
3172 pack_int (char *buf, int value)
3173 {
3174   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3175   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3176   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3177   buf = pack_hex_byte (buf, (value & 0xff));
3178   return buf;
3179 }
3180
3181 static const char *
3182 unpack_int (const char *buf, int *value)
3183 {
3184   *value = stub_unpack_int (buf, 8);
3185   return buf + 8;
3186 }
3187
3188 #if 0                   /* Currently unused, uncomment when needed.  */
3189 static char *pack_string (char *pkt, char *string);
3190
3191 static char *
3192 pack_string (char *pkt, char *string)
3193 {
3194   char ch;
3195   int len;
3196
3197   len = strlen (string);
3198   if (len > 200)
3199     len = 200;          /* Bigger than most GDB packets, junk???  */
3200   pkt = pack_hex_byte (pkt, len);
3201   while (len-- > 0)
3202     {
3203       ch = *string++;
3204       if ((ch == '\0') || (ch == '#'))
3205         ch = '*';               /* Protect encapsulation.  */
3206       *pkt++ = ch;
3207     }
3208   return pkt;
3209 }
3210 #endif /* 0 (unused) */
3211
3212 static const char *
3213 unpack_string (const char *src, char *dest, int length)
3214 {
3215   while (length--)
3216     *dest++ = *src++;
3217   *dest = '\0';
3218   return src;
3219 }
3220
3221 static char *
3222 pack_threadid (char *pkt, threadref *id)
3223 {
3224   char *limit;
3225   unsigned char *altid;
3226
3227   altid = (unsigned char *) id;
3228   limit = pkt + BUF_THREAD_ID_SIZE;
3229   while (pkt < limit)
3230     pkt = pack_hex_byte (pkt, *altid++);
3231   return pkt;
3232 }
3233
3234
3235 static const char *
3236 unpack_threadid (const char *inbuf, threadref *id)
3237 {
3238   char *altref;
3239   const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3240   int x, y;
3241
3242   altref = (char *) id;
3243
3244   while (inbuf < limit)
3245     {
3246       x = stubhex (*inbuf++);
3247       y = stubhex (*inbuf++);
3248       *altref++ = (x << 4) | y;
3249     }
3250   return inbuf;
3251 }
3252
3253 /* Externally, threadrefs are 64 bits but internally, they are still
3254    ints.  This is due to a mismatch of specifications.  We would like
3255    to use 64bit thread references internally.  This is an adapter
3256    function.  */
3257
3258 void
3259 int_to_threadref (threadref *id, int value)
3260 {
3261   unsigned char *scan;
3262
3263   scan = (unsigned char *) id;
3264   {
3265     int i = 4;
3266     while (i--)
3267       *scan++ = 0;
3268   }
3269   *scan++ = (value >> 24) & 0xff;
3270   *scan++ = (value >> 16) & 0xff;
3271   *scan++ = (value >> 8) & 0xff;
3272   *scan++ = (value & 0xff);
3273 }
3274
3275 static int
3276 threadref_to_int (threadref *ref)
3277 {
3278   int i, value = 0;
3279   unsigned char *scan;
3280
3281   scan = *ref;
3282   scan += 4;
3283   i = 4;
3284   while (i-- > 0)
3285     value = (value << 8) | ((*scan++) & 0xff);
3286   return value;
3287 }
3288
3289 static void
3290 copy_threadref (threadref *dest, threadref *src)
3291 {
3292   int i;
3293   unsigned char *csrc, *cdest;
3294
3295   csrc = (unsigned char *) src;
3296   cdest = (unsigned char *) dest;
3297   i = 8;
3298   while (i--)
3299     *cdest++ = *csrc++;
3300 }
3301
3302 static int
3303 threadmatch (threadref *dest, threadref *src)
3304 {
3305   /* Things are broken right now, so just assume we got a match.  */
3306 #if 0
3307   unsigned char *srcp, *destp;
3308   int i, result;
3309   srcp = (char *) src;
3310   destp = (char *) dest;
3311
3312   result = 1;
3313   while (i-- > 0)
3314     result &= (*srcp++ == *destp++) ? 1 : 0;
3315   return result;
3316 #endif
3317   return 1;
3318 }
3319
3320 /*
3321    threadid:1,        # always request threadid
3322    context_exists:2,
3323    display:4,
3324    unique_name:8,
3325    more_display:16
3326  */
3327
3328 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
3329
3330 static char *
3331 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3332 {
3333   *pkt++ = 'q';                         /* Info Query */
3334   *pkt++ = 'P';                         /* process or thread info */
3335   pkt = pack_int (pkt, mode);           /* mode */
3336   pkt = pack_threadid (pkt, id);        /* threadid */
3337   *pkt = '\0';                          /* terminate */
3338   return pkt;
3339 }
3340
3341 /* These values tag the fields in a thread info response packet.  */
3342 /* Tagging the fields allows us to request specific fields and to
3343    add more fields as time goes by.  */
3344
3345 #define TAG_THREADID 1          /* Echo the thread identifier.  */
3346 #define TAG_EXISTS 2            /* Is this process defined enough to
3347                                    fetch registers and its stack?  */
3348 #define TAG_DISPLAY 4           /* A short thing maybe to put on a window */
3349 #define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is.  */
3350 #define TAG_MOREDISPLAY 16      /* Whatever the kernel wants to say about
3351                                    the process.  */
3352
3353 int
3354 remote_target::remote_unpack_thread_info_response (const char *pkt,
3355                                                    threadref *expectedref,
3356                                                    gdb_ext_thread_info *info)
3357 {
3358   struct remote_state *rs = get_remote_state ();
3359   int mask, length;
3360   int tag;
3361   threadref ref;
3362   const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit.  */
3363   int retval = 1;
3364
3365   /* info->threadid = 0; FIXME: implement zero_threadref.  */
3366   info->active = 0;
3367   info->display[0] = '\0';
3368   info->shortname[0] = '\0';
3369   info->more_display[0] = '\0';
3370
3371   /* Assume the characters indicating the packet type have been
3372      stripped.  */
3373   pkt = unpack_int (pkt, &mask);        /* arg mask */
3374   pkt = unpack_threadid (pkt, &ref);
3375
3376   if (mask == 0)
3377     warning (_("Incomplete response to threadinfo request."));
3378   if (!threadmatch (&ref, expectedref))
3379     {                   /* This is an answer to a different request.  */
3380       warning (_("ERROR RMT Thread info mismatch."));
3381       return 0;
3382     }
3383   copy_threadref (&info->threadid, &ref);
3384
3385   /* Loop on tagged fields , try to bail if something goes wrong.  */
3386
3387   /* Packets are terminated with nulls.  */
3388   while ((pkt < limit) && mask && *pkt)
3389     {
3390       pkt = unpack_int (pkt, &tag);     /* tag */
3391       pkt = unpack_byte (pkt, &length); /* length */
3392       if (!(tag & mask))                /* Tags out of synch with mask.  */
3393         {
3394           warning (_("ERROR RMT: threadinfo tag mismatch."));
3395           retval = 0;
3396           break;
3397         }
3398       if (tag == TAG_THREADID)
3399         {
3400           if (length != 16)
3401             {
3402               warning (_("ERROR RMT: length of threadid is not 16."));
3403               retval = 0;
3404               break;
3405             }
3406           pkt = unpack_threadid (pkt, &ref);
3407           mask = mask & ~TAG_THREADID;
3408           continue;
3409         }
3410       if (tag == TAG_EXISTS)
3411         {
3412           info->active = stub_unpack_int (pkt, length);
3413           pkt += length;
3414           mask = mask & ~(TAG_EXISTS);
3415           if (length > 8)
3416             {
3417               warning (_("ERROR RMT: 'exists' length too long."));
3418               retval = 0;
3419               break;
3420             }
3421           continue;
3422         }
3423       if (tag == TAG_THREADNAME)
3424         {
3425           pkt = unpack_string (pkt, &info->shortname[0], length);
3426           mask = mask & ~TAG_THREADNAME;
3427           continue;
3428         }
3429       if (tag == TAG_DISPLAY)
3430         {
3431           pkt = unpack_string (pkt, &info->display[0], length);
3432           mask = mask & ~TAG_DISPLAY;
3433           continue;
3434         }
3435       if (tag == TAG_MOREDISPLAY)
3436         {
3437           pkt = unpack_string (pkt, &info->more_display[0], length);
3438           mask = mask & ~TAG_MOREDISPLAY;
3439           continue;
3440         }
3441       warning (_("ERROR RMT: unknown thread info tag."));
3442       break;                    /* Not a tag we know about.  */
3443     }
3444   return retval;
3445 }
3446
3447 int
3448 remote_target::remote_get_threadinfo (threadref *threadid,
3449                                       int fieldset,
3450                                       gdb_ext_thread_info *info)
3451 {
3452   struct remote_state *rs = get_remote_state ();
3453   int result;
3454
3455   pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3456   putpkt (rs->buf);
3457   getpkt (&rs->buf, 0);
3458
3459   if (rs->buf[0] == '\0')
3460     return 0;
3461
3462   result = remote_unpack_thread_info_response (&rs->buf[2],
3463                                                threadid, info);
3464   return result;
3465 }
3466
3467 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
3468
3469 static char *
3470 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3471                          threadref *nextthread)
3472 {
3473   *pkt++ = 'q';                 /* info query packet */
3474   *pkt++ = 'L';                 /* Process LIST or threadLIST request */
3475   pkt = pack_nibble (pkt, startflag);           /* initflag 1 bytes */
3476   pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
3477   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
3478   *pkt = '\0';
3479   return pkt;
3480 }
3481
3482 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3483
3484 int
3485 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3486                                           threadref *original_echo,
3487                                           threadref *resultlist,
3488                                           int *doneflag)
3489 {
3490   struct remote_state *rs = get_remote_state ();
3491   int count, resultcount, done;
3492
3493   resultcount = 0;
3494   /* Assume the 'q' and 'M chars have been stripped.  */
3495   const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3496   /* done parse past here */
3497   pkt = unpack_byte (pkt, &count);      /* count field */
3498   pkt = unpack_nibble (pkt, &done);
3499   /* The first threadid is the argument threadid.  */
3500   pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
3501   while ((count-- > 0) && (pkt < limit))
3502     {
3503       pkt = unpack_threadid (pkt, resultlist++);
3504       if (resultcount++ >= result_limit)
3505         break;
3506     }
3507   if (doneflag)
3508     *doneflag = done;
3509   return resultcount;
3510 }
3511
3512 /* Fetch the next batch of threads from the remote.  Returns -1 if the
3513    qL packet is not supported, 0 on error and 1 on success.  */
3514
3515 int
3516 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3517                                       int result_limit, int *done, int *result_count,
3518                                       threadref *threadlist)
3519 {
3520   struct remote_state *rs = get_remote_state ();
3521   int result = 1;
3522
3523   /* Truncate result limit to be smaller than the packet size.  */
3524   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3525       >= get_remote_packet_size ())
3526     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3527
3528   pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3529                            nextthread);
3530   putpkt (rs->buf);
3531   getpkt (&rs->buf, 0);
3532   if (rs->buf[0] == '\0')
3533     {
3534       /* Packet not supported.  */
3535       return -1;
3536     }
3537
3538   *result_count =
3539     parse_threadlist_response (&rs->buf[2], result_limit,
3540                                &rs->echo_nextthread, threadlist, done);
3541
3542   if (!threadmatch (&rs->echo_nextthread, nextthread))
3543     {
3544       /* FIXME: This is a good reason to drop the packet.  */
3545       /* Possibly, there is a duplicate response.  */
3546       /* Possibilities :
3547          retransmit immediatly - race conditions
3548          retransmit after timeout - yes
3549          exit
3550          wait for packet, then exit
3551        */
3552       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3553       return 0;                 /* I choose simply exiting.  */
3554     }
3555   if (*result_count <= 0)
3556     {
3557       if (*done != 1)
3558         {
3559           warning (_("RMT ERROR : failed to get remote thread list."));
3560           result = 0;
3561         }
3562       return result;            /* break; */
3563     }
3564   if (*result_count > result_limit)
3565     {
3566       *result_count = 0;
3567       warning (_("RMT ERROR: threadlist response longer than requested."));
3568       return 0;
3569     }
3570   return result;
3571 }
3572
3573 /* Fetch the list of remote threads, with the qL packet, and call
3574    STEPFUNCTION for each thread found.  Stops iterating and returns 1
3575    if STEPFUNCTION returns true.  Stops iterating and returns 0 if the
3576    STEPFUNCTION returns false.  If the packet is not supported,
3577    returns -1.  */
3578
3579 int
3580 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3581                                            void *context, int looplimit)
3582 {
3583   struct remote_state *rs = get_remote_state ();
3584   int done, i, result_count;
3585   int startflag = 1;
3586   int result = 1;
3587   int loopcount = 0;
3588
3589   done = 0;
3590   while (!done)
3591     {
3592       if (loopcount++ > looplimit)
3593         {
3594           result = 0;
3595           warning (_("Remote fetch threadlist -infinite loop-."));
3596           break;
3597         }
3598       result = remote_get_threadlist (startflag, &rs->nextthread,
3599                                       MAXTHREADLISTRESULTS,
3600                                       &done, &result_count,
3601                                       rs->resultthreadlist);
3602       if (result <= 0)
3603         break;
3604       /* Clear for later iterations.  */
3605       startflag = 0;
3606       /* Setup to resume next batch of thread references, set nextthread.  */
3607       if (result_count >= 1)
3608         copy_threadref (&rs->nextthread,
3609                         &rs->resultthreadlist[result_count - 1]);
3610       i = 0;
3611       while (result_count--)
3612         {
3613           if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3614             {
3615               result = 0;
3616               break;
3617             }
3618         }
3619     }
3620   return result;
3621 }
3622
3623 /* A thread found on the remote target.  */
3624
3625 struct thread_item
3626 {
3627   explicit thread_item (ptid_t ptid_)
3628   : ptid (ptid_)
3629   {}
3630
3631   thread_item (thread_item &&other) = default;
3632   thread_item &operator= (thread_item &&other) = default;
3633
3634   DISABLE_COPY_AND_ASSIGN (thread_item);
3635
3636   /* The thread's PTID.  */
3637   ptid_t ptid;
3638
3639   /* The thread's extra info.  */
3640   std::string extra;
3641
3642   /* The thread's name.  */
3643   std::string name;
3644
3645   /* The core the thread was running on.  -1 if not known.  */
3646   int core = -1;
3647
3648   /* The thread handle associated with the thread.  */
3649   gdb::byte_vector thread_handle;
3650 };
3651
3652 /* Context passed around to the various methods listing remote
3653    threads.  As new threads are found, they're added to the ITEMS
3654    vector.  */
3655
3656 struct threads_listing_context
3657 {
3658   /* Return true if this object contains an entry for a thread with ptid
3659      PTID.  */
3660
3661   bool contains_thread (ptid_t ptid) const
3662   {
3663     auto match_ptid = [&] (const thread_item &item)
3664       {
3665         return item.ptid == ptid;
3666       };
3667
3668     auto it = std::find_if (this->items.begin (),
3669                             this->items.end (),
3670                             match_ptid);
3671
3672     return it != this->items.end ();
3673   }
3674
3675   /* Remove the thread with ptid PTID.  */
3676
3677   void remove_thread (ptid_t ptid)
3678   {
3679     auto match_ptid = [&] (const thread_item &item)
3680       {
3681         return item.ptid == ptid;
3682       };
3683
3684     auto it = std::remove_if (this->items.begin (),
3685                               this->items.end (),
3686                               match_ptid);
3687
3688     if (it != this->items.end ())
3689       this->items.erase (it);
3690   }
3691
3692   /* The threads found on the remote target.  */
3693   std::vector<thread_item> items;
3694 };
3695
3696 static int
3697 remote_newthread_step (threadref *ref, void *data)
3698 {
3699   struct threads_listing_context *context
3700     = (struct threads_listing_context *) data;
3701   int pid = inferior_ptid.pid ();
3702   int lwp = threadref_to_int (ref);
3703   ptid_t ptid (pid, lwp);
3704
3705   context->items.emplace_back (ptid);
3706
3707   return 1;                     /* continue iterator */
3708 }
3709
3710 #define CRAZY_MAX_THREADS 1000
3711
3712 ptid_t
3713 remote_target::remote_current_thread (ptid_t oldpid)
3714 {
3715   struct remote_state *rs = get_remote_state ();
3716
3717   putpkt ("qC");
3718   getpkt (&rs->buf, 0);
3719   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3720     {
3721       const char *obuf;
3722       ptid_t result;
3723
3724       result = read_ptid (&rs->buf[2], &obuf);
3725       if (*obuf != '\0')
3726         remote_debug_printf ("warning: garbage in qC reply");
3727
3728       return result;
3729     }
3730   else
3731     return oldpid;
3732 }
3733
3734 /* List remote threads using the deprecated qL packet.  */
3735
3736 int
3737 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3738 {
3739   if (remote_threadlist_iterator (remote_newthread_step, context,
3740                                   CRAZY_MAX_THREADS) >= 0)
3741     return 1;
3742
3743   return 0;
3744 }
3745
3746 #if defined(HAVE_LIBEXPAT)
3747
3748 static void
3749 start_thread (struct gdb_xml_parser *parser,
3750               const struct gdb_xml_element *element,
3751               void *user_data,
3752               std::vector<gdb_xml_value> &attributes)
3753 {
3754   struct threads_listing_context *data
3755     = (struct threads_listing_context *) user_data;
3756   struct gdb_xml_value *attr;
3757
3758   char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3759   ptid_t ptid = read_ptid (id, NULL);
3760
3761   data->items.emplace_back (ptid);
3762   thread_item &item = data->items.back ();
3763
3764   attr = xml_find_attribute (attributes, "core");
3765   if (attr != NULL)
3766     item.core = *(ULONGEST *) attr->value.get ();
3767
3768   attr = xml_find_attribute (attributes, "name");
3769   if (attr != NULL)
3770     item.name = (const char *) attr->value.get ();
3771
3772   attr = xml_find_attribute (attributes, "handle");
3773   if (attr != NULL)
3774     item.thread_handle = hex2bin ((const char *) attr->value.get ());
3775 }
3776
3777 static void
3778 end_thread (struct gdb_xml_parser *parser,
3779             const struct gdb_xml_element *element,
3780             void *user_data, const char *body_text)
3781 {
3782   struct threads_listing_context *data
3783     = (struct threads_listing_context *) user_data;
3784
3785   if (body_text != NULL && *body_text != '\0')
3786     data->items.back ().extra = body_text;
3787 }
3788
3789 const struct gdb_xml_attribute thread_attributes[] = {
3790   { "id", GDB_XML_AF_NONE, NULL, NULL },
3791   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3792   { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3793   { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3794   { NULL, GDB_XML_AF_NONE, NULL, NULL }
3795 };
3796
3797 const struct gdb_xml_element thread_children[] = {
3798   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3799 };
3800
3801 const struct gdb_xml_element threads_children[] = {
3802   { "thread", thread_attributes, thread_children,
3803     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3804     start_thread, end_thread },
3805   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3806 };
3807
3808 const struct gdb_xml_element threads_elements[] = {
3809   { "threads", NULL, threads_children,
3810     GDB_XML_EF_NONE, NULL, NULL },
3811   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3812 };
3813
3814 #endif
3815
3816 /* List remote threads using qXfer:threads:read.  */
3817
3818 int
3819 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
3820 {
3821 #if defined(HAVE_LIBEXPAT)
3822   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3823     {
3824       gdb::optional<gdb::char_vector> xml
3825         = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
3826
3827       if (xml && (*xml)[0] != '\0')
3828         {
3829           gdb_xml_parse_quick (_("threads"), "threads.dtd",
3830                                threads_elements, xml->data (), context);
3831         }
3832
3833       return 1;
3834     }
3835 #endif
3836
3837   return 0;
3838 }
3839
3840 /* List remote threads using qfThreadInfo/qsThreadInfo.  */
3841
3842 int
3843 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
3844 {
3845   struct remote_state *rs = get_remote_state ();
3846
3847   if (rs->use_threadinfo_query)
3848     {
3849       const char *bufp;
3850
3851       putpkt ("qfThreadInfo");
3852       getpkt (&rs->buf, 0);
3853       bufp = rs->buf.data ();
3854       if (bufp[0] != '\0')              /* q packet recognized */
3855         {
3856           while (*bufp++ == 'm')        /* reply contains one or more TID */
3857             {
3858               do
3859                 {
3860                   ptid_t ptid = read_ptid (bufp, &bufp);
3861                   context->items.emplace_back (ptid);
3862                 }
3863               while (*bufp++ == ',');   /* comma-separated list */
3864               putpkt ("qsThreadInfo");
3865               getpkt (&rs->buf, 0);
3866               bufp = rs->buf.data ();
3867             }
3868           return 1;
3869         }
3870       else
3871         {
3872           /* Packet not recognized.  */
3873           rs->use_threadinfo_query = 0;
3874         }
3875     }
3876
3877   return 0;
3878 }
3879
3880 /* Return true if INF only has one non-exited thread.  */
3881
3882 static bool
3883 has_single_non_exited_thread (inferior *inf)
3884 {
3885   int count = 0;
3886   for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
3887     if (++count > 1)
3888       break;
3889   return count == 1;
3890 }
3891
3892 /* Implement the to_update_thread_list function for the remote
3893    targets.  */
3894
3895 void
3896 remote_target::update_thread_list ()
3897 {
3898   struct threads_listing_context context;
3899   int got_list = 0;
3900
3901   /* We have a few different mechanisms to fetch the thread list.  Try
3902      them all, starting with the most preferred one first, falling
3903      back to older methods.  */
3904   if (remote_get_threads_with_qxfer (&context)
3905       || remote_get_threads_with_qthreadinfo (&context)
3906       || remote_get_threads_with_ql (&context))
3907     {
3908       got_list = 1;
3909
3910       if (context.items.empty ()
3911           && remote_thread_always_alive (inferior_ptid))
3912         {
3913           /* Some targets don't really support threads, but still
3914              reply an (empty) thread list in response to the thread
3915              listing packets, instead of replying "packet not
3916              supported".  Exit early so we don't delete the main
3917              thread.  */
3918           return;
3919         }
3920
3921       /* CONTEXT now holds the current thread list on the remote
3922          target end.  Delete GDB-side threads no longer found on the
3923          target.  */
3924       for (thread_info *tp : all_threads_safe ())
3925         {
3926           if (tp->inf->process_target () != this)
3927             continue;
3928
3929           if (!context.contains_thread (tp->ptid))
3930             {
3931               /* Do not remove the thread if it is the last thread in
3932                  the inferior.  This situation happens when we have a
3933                  pending exit process status to process.  Otherwise we
3934                  may end up with a seemingly live inferior (i.e.  pid
3935                  != 0) that has no threads.  */
3936               if (has_single_non_exited_thread (tp->inf))
3937                 continue;
3938
3939               /* Not found.  */
3940               delete_thread (tp);
3941             }
3942         }
3943
3944       /* Remove any unreported fork child threads from CONTEXT so
3945          that we don't interfere with follow fork, which is where
3946          creation of such threads is handled.  */
3947       remove_new_fork_children (&context);
3948
3949       /* And now add threads we don't know about yet to our list.  */
3950       for (thread_item &item : context.items)
3951         {
3952           if (item.ptid != null_ptid)
3953             {
3954               /* In non-stop mode, we assume new found threads are
3955                  executing until proven otherwise with a stop reply.
3956                  In all-stop, we can only get here if all threads are
3957                  stopped.  */
3958               int executing = target_is_non_stop_p () ? 1 : 0;
3959
3960               remote_notice_new_inferior (item.ptid, executing);
3961
3962               thread_info *tp = find_thread_ptid (this, item.ptid);
3963               remote_thread_info *info = get_remote_thread_info (tp);
3964               info->core = item.core;
3965               info->extra = std::move (item.extra);
3966               info->name = std::move (item.name);
3967               info->thread_handle = std::move (item.thread_handle);
3968             }
3969         }
3970     }
3971
3972   if (!got_list)
3973     {
3974       /* If no thread listing method is supported, then query whether
3975          each known thread is alive, one by one, with the T packet.
3976          If the target doesn't support threads at all, then this is a
3977          no-op.  See remote_thread_alive.  */
3978       prune_threads ();
3979     }
3980 }
3981
3982 /*
3983  * Collect a descriptive string about the given thread.
3984  * The target may say anything it wants to about the thread
3985  * (typically info about its blocked / runnable state, name, etc.).
3986  * This string will appear in the info threads display.
3987  *
3988  * Optional: targets are not required to implement this function.
3989  */
3990
3991 const char *
3992 remote_target::extra_thread_info (thread_info *tp)
3993 {
3994   struct remote_state *rs = get_remote_state ();
3995   int set;
3996   threadref id;
3997   struct gdb_ext_thread_info threadinfo;
3998
3999   if (rs->remote_desc == 0)             /* paranoia */
4000     internal_error (__FILE__, __LINE__,
4001                     _("remote_threads_extra_info"));
4002
4003   if (tp->ptid == magic_null_ptid
4004       || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4005     /* This is the main thread which was added by GDB.  The remote
4006        server doesn't know about it.  */
4007     return NULL;
4008
4009   std::string &extra = get_remote_thread_info (tp)->extra;
4010
4011   /* If already have cached info, use it.  */
4012   if (!extra.empty ())
4013     return extra.c_str ();
4014
4015   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4016     {
4017       /* If we're using qXfer:threads:read, then the extra info is
4018          included in the XML.  So if we didn't have anything cached,
4019          it's because there's really no extra info.  */
4020       return NULL;
4021     }
4022
4023   if (rs->use_threadextra_query)
4024     {
4025       char *b = rs->buf.data ();
4026       char *endb = b + get_remote_packet_size ();
4027
4028       xsnprintf (b, endb - b, "qThreadExtraInfo,");
4029       b += strlen (b);
4030       write_ptid (b, endb, tp->ptid);
4031
4032       putpkt (rs->buf);
4033       getpkt (&rs->buf, 0);
4034       if (rs->buf[0] != 0)
4035         {
4036           extra.resize (strlen (rs->buf.data ()) / 2);
4037           hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4038           return extra.c_str ();
4039         }
4040     }
4041
4042   /* If the above query fails, fall back to the old method.  */
4043   rs->use_threadextra_query = 0;
4044   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4045     | TAG_MOREDISPLAY | TAG_DISPLAY;
4046   int_to_threadref (&id, tp->ptid.lwp ());
4047   if (remote_get_threadinfo (&id, set, &threadinfo))
4048     if (threadinfo.active)
4049       {
4050         if (*threadinfo.shortname)
4051           string_appendf (extra, " Name: %s", threadinfo.shortname);
4052         if (*threadinfo.display)
4053           {
4054             if (!extra.empty ())
4055               extra += ',';
4056             string_appendf (extra, " State: %s", threadinfo.display);
4057           }
4058         if (*threadinfo.more_display)
4059           {
4060             if (!extra.empty ())
4061               extra += ',';
4062             string_appendf (extra, " Priority: %s", threadinfo.more_display);
4063           }
4064         return extra.c_str ();
4065       }
4066   return NULL;
4067 }
4068 \f
4069
4070 bool
4071 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4072                                             struct static_tracepoint_marker *marker)
4073 {
4074   struct remote_state *rs = get_remote_state ();
4075   char *p = rs->buf.data ();
4076
4077   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4078   p += strlen (p);
4079   p += hexnumstr (p, addr);
4080   putpkt (rs->buf);
4081   getpkt (&rs->buf, 0);
4082   p = rs->buf.data ();
4083
4084   if (*p == 'E')
4085     error (_("Remote failure reply: %s"), p);
4086
4087   if (*p++ == 'm')
4088     {
4089       parse_static_tracepoint_marker_definition (p, NULL, marker);
4090       return true;
4091     }
4092
4093   return false;
4094 }
4095
4096 std::vector<static_tracepoint_marker>
4097 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4098 {
4099   struct remote_state *rs = get_remote_state ();
4100   std::vector<static_tracepoint_marker> markers;
4101   const char *p;
4102   static_tracepoint_marker marker;
4103
4104   /* Ask for a first packet of static tracepoint marker
4105      definition.  */
4106   putpkt ("qTfSTM");
4107   getpkt (&rs->buf, 0);
4108   p = rs->buf.data ();
4109   if (*p == 'E')
4110     error (_("Remote failure reply: %s"), p);
4111
4112   while (*p++ == 'm')
4113     {
4114       do
4115         {
4116           parse_static_tracepoint_marker_definition (p, &p, &marker);
4117
4118           if (strid == NULL || marker.str_id == strid)
4119             markers.push_back (std::move (marker));
4120         }
4121       while (*p++ == ',');      /* comma-separated list */
4122       /* Ask for another packet of static tracepoint definition.  */
4123       putpkt ("qTsSTM");
4124       getpkt (&rs->buf, 0);
4125       p = rs->buf.data ();
4126     }
4127
4128   return markers;
4129 }
4130
4131 \f
4132 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
4133
4134 ptid_t
4135 remote_target::get_ada_task_ptid (long lwp, long thread)
4136 {
4137   return ptid_t (inferior_ptid.pid (), lwp, 0);
4138 }
4139 \f
4140
4141 /* Restart the remote side; this is an extended protocol operation.  */
4142
4143 void
4144 remote_target::extended_remote_restart ()
4145 {
4146   struct remote_state *rs = get_remote_state ();
4147
4148   /* Send the restart command; for reasons I don't understand the
4149      remote side really expects a number after the "R".  */
4150   xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4151   putpkt (rs->buf);
4152
4153   remote_fileio_reset ();
4154 }
4155 \f
4156 /* Clean up connection to a remote debugger.  */
4157
4158 void
4159 remote_target::close ()
4160 {
4161   /* Make sure we leave stdin registered in the event loop.  */
4162   terminal_ours ();
4163
4164   trace_reset_local_state ();
4165
4166   delete this;
4167 }
4168
4169 remote_target::~remote_target ()
4170 {
4171   struct remote_state *rs = get_remote_state ();
4172
4173   /* Check for NULL because we may get here with a partially
4174      constructed target/connection.  */
4175   if (rs->remote_desc == nullptr)
4176     return;
4177
4178   serial_close (rs->remote_desc);
4179
4180   /* We are destroying the remote target, so we should discard
4181      everything of this target.  */
4182   discard_pending_stop_replies_in_queue ();
4183
4184   if (rs->remote_async_inferior_event_token)
4185     delete_async_event_handler (&rs->remote_async_inferior_event_token);
4186
4187   delete rs->notif_state;
4188 }
4189
4190 /* Query the remote side for the text, data and bss offsets.  */
4191
4192 void
4193 remote_target::get_offsets ()
4194 {
4195   struct remote_state *rs = get_remote_state ();
4196   char *buf;
4197   char *ptr;
4198   int lose, num_segments = 0, do_sections, do_segments;
4199   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4200
4201   if (current_program_space->symfile_object_file == NULL)
4202     return;
4203
4204   putpkt ("qOffsets");
4205   getpkt (&rs->buf, 0);
4206   buf = rs->buf.data ();
4207
4208   if (buf[0] == '\000')
4209     return;                     /* Return silently.  Stub doesn't support
4210                                    this command.  */
4211   if (buf[0] == 'E')
4212     {
4213       warning (_("Remote failure reply: %s"), buf);
4214       return;
4215     }
4216
4217   /* Pick up each field in turn.  This used to be done with scanf, but
4218      scanf will make trouble if CORE_ADDR size doesn't match
4219      conversion directives correctly.  The following code will work
4220      with any size of CORE_ADDR.  */
4221   text_addr = data_addr = bss_addr = 0;
4222   ptr = buf;
4223   lose = 0;
4224
4225   if (startswith (ptr, "Text="))
4226     {
4227       ptr += 5;
4228       /* Don't use strtol, could lose on big values.  */
4229       while (*ptr && *ptr != ';')
4230         text_addr = (text_addr << 4) + fromhex (*ptr++);
4231
4232       if (startswith (ptr, ";Data="))
4233         {
4234           ptr += 6;
4235           while (*ptr && *ptr != ';')
4236             data_addr = (data_addr << 4) + fromhex (*ptr++);
4237         }
4238       else
4239         lose = 1;
4240
4241       if (!lose && startswith (ptr, ";Bss="))
4242         {
4243           ptr += 5;
4244           while (*ptr && *ptr != ';')
4245             bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4246
4247           if (bss_addr != data_addr)
4248             warning (_("Target reported unsupported offsets: %s"), buf);
4249         }
4250       else
4251         lose = 1;
4252     }
4253   else if (startswith (ptr, "TextSeg="))
4254     {
4255       ptr += 8;
4256       /* Don't use strtol, could lose on big values.  */
4257       while (*ptr && *ptr != ';')
4258         text_addr = (text_addr << 4) + fromhex (*ptr++);
4259       num_segments = 1;
4260
4261       if (startswith (ptr, ";DataSeg="))
4262         {
4263           ptr += 9;
4264           while (*ptr && *ptr != ';')
4265             data_addr = (data_addr << 4) + fromhex (*ptr++);
4266           num_segments++;
4267         }
4268     }
4269   else
4270     lose = 1;
4271
4272   if (lose)
4273     error (_("Malformed response to offset query, %s"), buf);
4274   else if (*ptr != '\0')
4275     warning (_("Target reported unsupported offsets: %s"), buf);
4276
4277   objfile *objf = current_program_space->symfile_object_file;
4278   section_offsets offs = objf->section_offsets;
4279
4280   symfile_segment_data_up data = get_symfile_segment_data (objf->obfd);
4281   do_segments = (data != NULL);
4282   do_sections = num_segments == 0;
4283
4284   if (num_segments > 0)
4285     {
4286       segments[0] = text_addr;
4287       segments[1] = data_addr;
4288     }
4289   /* If we have two segments, we can still try to relocate everything
4290      by assuming that the .text and .data offsets apply to the whole
4291      text and data segments.  Convert the offsets given in the packet
4292      to base addresses for symfile_map_offsets_to_segments.  */
4293   else if (data != nullptr && data->segments.size () == 2)
4294     {
4295       segments[0] = data->segments[0].base + text_addr;
4296       segments[1] = data->segments[1].base + data_addr;
4297       num_segments = 2;
4298     }
4299   /* If the object file has only one segment, assume that it is text
4300      rather than data; main programs with no writable data are rare,
4301      but programs with no code are useless.  Of course the code might
4302      have ended up in the data segment... to detect that we would need
4303      the permissions here.  */
4304   else if (data && data->segments.size () == 1)
4305     {
4306       segments[0] = data->segments[0].base + text_addr;
4307       num_segments = 1;
4308     }
4309   /* There's no way to relocate by segment.  */
4310   else
4311     do_segments = 0;
4312
4313   if (do_segments)
4314     {
4315       int ret = symfile_map_offsets_to_segments (objf->obfd,
4316                                                  data.get (), offs,
4317                                                  num_segments, segments);
4318
4319       if (ret == 0 && !do_sections)
4320         error (_("Can not handle qOffsets TextSeg "
4321                  "response with this symbol file"));
4322
4323       if (ret > 0)
4324         do_sections = 0;
4325     }
4326
4327   if (do_sections)
4328     {
4329       offs[SECT_OFF_TEXT (objf)] = text_addr;
4330
4331       /* This is a temporary kludge to force data and bss to use the
4332          same offsets because that's what nlmconv does now.  The real
4333          solution requires changes to the stub and remote.c that I
4334          don't have time to do right now.  */
4335
4336       offs[SECT_OFF_DATA (objf)] = data_addr;
4337       offs[SECT_OFF_BSS (objf)] = data_addr;
4338     }
4339
4340   objfile_relocate (objf, offs);
4341 }
4342
4343 /* Send interrupt_sequence to remote target.  */
4344
4345 void
4346 remote_target::send_interrupt_sequence ()
4347 {
4348   struct remote_state *rs = get_remote_state ();
4349
4350   if (interrupt_sequence_mode == interrupt_sequence_control_c)
4351     remote_serial_write ("\x03", 1);
4352   else if (interrupt_sequence_mode == interrupt_sequence_break)
4353     serial_send_break (rs->remote_desc);
4354   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4355     {
4356       serial_send_break (rs->remote_desc);
4357       remote_serial_write ("g", 1);
4358     }
4359   else
4360     internal_error (__FILE__, __LINE__,
4361                     _("Invalid value for interrupt_sequence_mode: %s."),
4362                     interrupt_sequence_mode);
4363 }
4364
4365
4366 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4367    and extract the PTID.  Returns NULL_PTID if not found.  */
4368
4369 static ptid_t
4370 stop_reply_extract_thread (const char *stop_reply)
4371 {
4372   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4373     {
4374       const char *p;
4375
4376       /* Txx r:val ; r:val (...)  */
4377       p = &stop_reply[3];
4378
4379       /* Look for "register" named "thread".  */
4380       while (*p != '\0')
4381         {
4382           const char *p1;
4383
4384           p1 = strchr (p, ':');
4385           if (p1 == NULL)
4386             return null_ptid;
4387
4388           if (strncmp (p, "thread", p1 - p) == 0)
4389             return read_ptid (++p1, &p);
4390
4391           p1 = strchr (p, ';');
4392           if (p1 == NULL)
4393             return null_ptid;
4394           p1++;
4395
4396           p = p1;
4397         }
4398     }
4399
4400   return null_ptid;
4401 }
4402
4403 /* Determine the remote side's current thread.  If we have a stop
4404    reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4405    "thread" register we can extract the current thread from.  If not,
4406    ask the remote which is the current thread with qC.  The former
4407    method avoids a roundtrip.  */
4408
4409 ptid_t
4410 remote_target::get_current_thread (const char *wait_status)
4411 {
4412   ptid_t ptid = null_ptid;
4413
4414   /* Note we don't use remote_parse_stop_reply as that makes use of
4415      the target architecture, which we haven't yet fully determined at
4416      this point.  */
4417   if (wait_status != NULL)
4418     ptid = stop_reply_extract_thread (wait_status);
4419   if (ptid == null_ptid)
4420     ptid = remote_current_thread (inferior_ptid);
4421
4422   return ptid;
4423 }
4424
4425 /* Query the remote target for which is the current thread/process,
4426    add it to our tables, and update INFERIOR_PTID.  The caller is
4427    responsible for setting the state such that the remote end is ready
4428    to return the current thread.
4429
4430    This function is called after handling the '?' or 'vRun' packets,
4431    whose response is a stop reply from which we can also try
4432    extracting the thread.  If the target doesn't support the explicit
4433    qC query, we infer the current thread from that stop reply, passed
4434    in in WAIT_STATUS, which may be NULL.
4435
4436    The function returns pointer to the main thread of the inferior. */
4437
4438 thread_info *
4439 remote_target::add_current_inferior_and_thread (const char *wait_status)
4440 {
4441   struct remote_state *rs = get_remote_state ();
4442   bool fake_pid_p = false;
4443
4444   switch_to_no_thread ();
4445
4446   /* Now, if we have thread information, update the current thread's
4447      ptid.  */
4448   ptid_t curr_ptid = get_current_thread (wait_status);
4449
4450   if (curr_ptid != null_ptid)
4451     {
4452       if (!remote_multi_process_p (rs))
4453         fake_pid_p = true;
4454     }
4455   else
4456     {
4457       /* Without this, some commands which require an active target
4458          (such as kill) won't work.  This variable serves (at least)
4459          double duty as both the pid of the target process (if it has
4460          such), and as a flag indicating that a target is active.  */
4461       curr_ptid = magic_null_ptid;
4462       fake_pid_p = true;
4463     }
4464
4465   remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4466
4467   /* Add the main thread and switch to it.  Don't try reading
4468      registers yet, since we haven't fetched the target description
4469      yet.  */
4470   thread_info *tp = add_thread_silent (this, curr_ptid);
4471   switch_to_thread_no_regs (tp);
4472
4473   return tp;
4474 }
4475
4476 /* Print info about a thread that was found already stopped on
4477    connection.  */
4478
4479 static void
4480 print_one_stopped_thread (struct thread_info *thread)
4481 {
4482   struct target_waitstatus *ws = &thread->suspend.waitstatus;
4483
4484   switch_to_thread (thread);
4485   thread->suspend.stop_pc = get_frame_pc (get_current_frame ());
4486   set_current_sal_from_frame (get_current_frame ());
4487
4488   thread->suspend.waitstatus_pending_p = 0;
4489
4490   if (ws->kind == TARGET_WAITKIND_STOPPED)
4491     {
4492       enum gdb_signal sig = ws->value.sig;
4493
4494       if (signal_print_state (sig))
4495         gdb::observers::signal_received.notify (sig);
4496     }
4497   gdb::observers::normal_stop.notify (NULL, 1);
4498 }
4499
4500 /* Process all initial stop replies the remote side sent in response
4501    to the ? packet.  These indicate threads that were already stopped
4502    on initial connection.  We mark these threads as stopped and print
4503    their current frame before giving the user the prompt.  */
4504
4505 void
4506 remote_target::process_initial_stop_replies (int from_tty)
4507 {
4508   int pending_stop_replies = stop_reply_queue_length ();
4509   struct thread_info *selected = NULL;
4510   struct thread_info *lowest_stopped = NULL;
4511   struct thread_info *first = NULL;
4512
4513   /* Consume the initial pending events.  */
4514   while (pending_stop_replies-- > 0)
4515     {
4516       ptid_t waiton_ptid = minus_one_ptid;
4517       ptid_t event_ptid;
4518       struct target_waitstatus ws;
4519       int ignore_event = 0;
4520
4521       memset (&ws, 0, sizeof (ws));
4522       event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4523       if (remote_debug)
4524         print_target_wait_results (waiton_ptid, event_ptid, &ws);
4525
4526       switch (ws.kind)
4527         {
4528         case TARGET_WAITKIND_IGNORE:
4529         case TARGET_WAITKIND_NO_RESUMED:
4530         case TARGET_WAITKIND_SIGNALLED:
4531         case TARGET_WAITKIND_EXITED:
4532           /* We shouldn't see these, but if we do, just ignore.  */
4533           remote_debug_printf ("event ignored");
4534           ignore_event = 1;
4535           break;
4536
4537         case TARGET_WAITKIND_EXECD:
4538           xfree (ws.value.execd_pathname);
4539           break;
4540         default:
4541           break;
4542         }
4543
4544       if (ignore_event)
4545         continue;
4546
4547       thread_info *evthread = find_thread_ptid (this, event_ptid);
4548
4549       if (ws.kind == TARGET_WAITKIND_STOPPED)
4550         {
4551           enum gdb_signal sig = ws.value.sig;
4552
4553           /* Stubs traditionally report SIGTRAP as initial signal,
4554              instead of signal 0.  Suppress it.  */
4555           if (sig == GDB_SIGNAL_TRAP)
4556             sig = GDB_SIGNAL_0;
4557           evthread->suspend.stop_signal = sig;
4558           ws.value.sig = sig;
4559         }
4560
4561       evthread->suspend.waitstatus = ws;
4562
4563       if (ws.kind != TARGET_WAITKIND_STOPPED
4564           || ws.value.sig != GDB_SIGNAL_0)
4565         evthread->suspend.waitstatus_pending_p = 1;
4566
4567       set_executing (this, event_ptid, false);
4568       set_running (this, event_ptid, false);
4569       get_remote_thread_info (evthread)->set_not_resumed ();
4570     }
4571
4572   /* "Notice" the new inferiors before anything related to
4573      registers/memory.  */
4574   for (inferior *inf : all_non_exited_inferiors (this))
4575     {
4576       inf->needs_setup = 1;
4577
4578       if (non_stop)
4579         {
4580           thread_info *thread = any_live_thread_of_inferior (inf);
4581           notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4582                                from_tty);
4583         }
4584     }
4585
4586   /* If all-stop on top of non-stop, pause all threads.  Note this
4587      records the threads' stop pc, so must be done after "noticing"
4588      the inferiors.  */
4589   if (!non_stop)
4590     {
4591       stop_all_threads ();
4592
4593       /* If all threads of an inferior were already stopped, we
4594          haven't setup the inferior yet.  */
4595       for (inferior *inf : all_non_exited_inferiors (this))
4596         {
4597           if (inf->needs_setup)
4598             {
4599               thread_info *thread = any_live_thread_of_inferior (inf);
4600               switch_to_thread_no_regs (thread);
4601               setup_inferior (0);
4602             }
4603         }
4604     }
4605
4606   /* Now go over all threads that are stopped, and print their current
4607      frame.  If all-stop, then if there's a signalled thread, pick
4608      that as current.  */
4609   for (thread_info *thread : all_non_exited_threads (this))
4610     {
4611       if (first == NULL)
4612         first = thread;
4613
4614       if (!non_stop)
4615         thread->set_running (false);
4616       else if (thread->state != THREAD_STOPPED)
4617         continue;
4618
4619       if (selected == NULL
4620           && thread->suspend.waitstatus_pending_p)
4621         selected = thread;
4622
4623       if (lowest_stopped == NULL
4624           || thread->inf->num < lowest_stopped->inf->num
4625           || thread->per_inf_num < lowest_stopped->per_inf_num)
4626         lowest_stopped = thread;
4627
4628       if (non_stop)
4629         print_one_stopped_thread (thread);
4630     }
4631
4632   /* In all-stop, we only print the status of one thread, and leave
4633      others with their status pending.  */
4634   if (!non_stop)
4635     {
4636       thread_info *thread = selected;
4637       if (thread == NULL)
4638         thread = lowest_stopped;
4639       if (thread == NULL)
4640         thread = first;
4641
4642       print_one_stopped_thread (thread);
4643     }
4644
4645   /* For "info program".  */
4646   thread_info *thread = inferior_thread ();
4647   if (thread->state == THREAD_STOPPED)
4648     set_last_target_status (this, inferior_ptid, thread->suspend.waitstatus);
4649 }
4650
4651 /* Start the remote connection and sync state.  */
4652
4653 void
4654 remote_target::start_remote (int from_tty, int extended_p)
4655 {
4656   REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4657
4658   struct remote_state *rs = get_remote_state ();
4659   struct packet_config *noack_config;
4660
4661   /* Signal other parts that we're going through the initial setup,
4662      and so things may not be stable yet.  E.g., we don't try to
4663      install tracepoints until we've relocated symbols.  Also, a
4664      Ctrl-C before we're connected and synced up can't interrupt the
4665      target.  Instead, it offers to drop the (potentially wedged)
4666      connection.  */
4667   rs->starting_up = 1;
4668
4669   QUIT;
4670
4671   if (interrupt_on_connect)
4672     send_interrupt_sequence ();
4673
4674   /* Ack any packet which the remote side has already sent.  */
4675   remote_serial_write ("+", 1);
4676
4677   /* The first packet we send to the target is the optional "supported
4678      packets" request.  If the target can answer this, it will tell us
4679      which later probes to skip.  */
4680   remote_query_supported ();
4681
4682   /* If the stub wants to get a QAllow, compose one and send it.  */
4683   if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4684     set_permissions ();
4685
4686   /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4687      unknown 'v' packet with string "OK".  "OK" gets interpreted by GDB
4688      as a reply to known packet.  For packet "vFile:setfs:" it is an
4689      invalid reply and GDB would return error in
4690      remote_hostio_set_filesystem, making remote files access impossible.
4691      Disable "vFile:setfs:" in such case.  Do not disable other 'v' packets as
4692      other "vFile" packets get correctly detected even on gdbserver < 7.7.  */
4693   {
4694     const char v_mustreplyempty[] = "vMustReplyEmpty";
4695
4696     putpkt (v_mustreplyempty);
4697     getpkt (&rs->buf, 0);
4698     if (strcmp (rs->buf.data (), "OK") == 0)
4699       remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4700     else if (strcmp (rs->buf.data (), "") != 0)
4701       error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4702              rs->buf.data ());
4703   }
4704
4705   /* Next, we possibly activate noack mode.
4706
4707      If the QStartNoAckMode packet configuration is set to AUTO,
4708      enable noack mode if the stub reported a wish for it with
4709      qSupported.
4710
4711      If set to TRUE, then enable noack mode even if the stub didn't
4712      report it in qSupported.  If the stub doesn't reply OK, the
4713      session ends with an error.
4714
4715      If FALSE, then don't activate noack mode, regardless of what the
4716      stub claimed should be the default with qSupported.  */
4717
4718   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4719   if (packet_config_support (noack_config) != PACKET_DISABLE)
4720     {
4721       putpkt ("QStartNoAckMode");
4722       getpkt (&rs->buf, 0);
4723       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4724         rs->noack_mode = 1;
4725     }
4726
4727   if (extended_p)
4728     {
4729       /* Tell the remote that we are using the extended protocol.  */
4730       putpkt ("!");
4731       getpkt (&rs->buf, 0);
4732     }
4733
4734   /* Let the target know which signals it is allowed to pass down to
4735      the program.  */
4736   update_signals_program_target ();
4737
4738   /* Next, if the target can specify a description, read it.  We do
4739      this before anything involving memory or registers.  */
4740   target_find_description ();
4741
4742   /* Next, now that we know something about the target, update the
4743      address spaces in the program spaces.  */
4744   update_address_spaces ();
4745
4746   /* On OSs where the list of libraries is global to all
4747      processes, we fetch them early.  */
4748   if (gdbarch_has_global_solist (target_gdbarch ()))
4749     solib_add (NULL, from_tty, auto_solib_add);
4750
4751   if (target_is_non_stop_p ())
4752     {
4753       if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4754         error (_("Non-stop mode requested, but remote "
4755                  "does not support non-stop"));
4756
4757       putpkt ("QNonStop:1");
4758       getpkt (&rs->buf, 0);
4759
4760       if (strcmp (rs->buf.data (), "OK") != 0)
4761         error (_("Remote refused setting non-stop mode with: %s"),
4762                rs->buf.data ());
4763
4764       /* Find about threads and processes the stub is already
4765          controlling.  We default to adding them in the running state.
4766          The '?' query below will then tell us about which threads are
4767          stopped.  */
4768       this->update_thread_list ();
4769     }
4770   else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4771     {
4772       /* Don't assume that the stub can operate in all-stop mode.
4773          Request it explicitly.  */
4774       putpkt ("QNonStop:0");
4775       getpkt (&rs->buf, 0);
4776
4777       if (strcmp (rs->buf.data (), "OK") != 0)
4778         error (_("Remote refused setting all-stop mode with: %s"),
4779                rs->buf.data ());
4780     }
4781
4782   /* Upload TSVs regardless of whether the target is running or not.  The
4783      remote stub, such as GDBserver, may have some predefined or builtin
4784      TSVs, even if the target is not running.  */
4785   if (get_trace_status (current_trace_status ()) != -1)
4786     {
4787       struct uploaded_tsv *uploaded_tsvs = NULL;
4788
4789       upload_trace_state_variables (&uploaded_tsvs);
4790       merge_uploaded_trace_state_variables (&uploaded_tsvs);
4791     }
4792
4793   /* Check whether the target is running now.  */
4794   putpkt ("?");
4795   getpkt (&rs->buf, 0);
4796
4797   if (!target_is_non_stop_p ())
4798     {
4799       char *wait_status = NULL;
4800
4801       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4802         {
4803           if (!extended_p)
4804             error (_("The target is not running (try extended-remote?)"));
4805
4806           /* We're connected, but not running.  Drop out before we
4807              call start_remote.  */
4808           rs->starting_up = 0;
4809           return;
4810         }
4811       else
4812         {
4813           /* Save the reply for later.  */
4814           wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
4815           strcpy (wait_status, rs->buf.data ());
4816         }
4817
4818       /* Fetch thread list.  */
4819       target_update_thread_list ();
4820
4821       /* Let the stub know that we want it to return the thread.  */
4822       set_continue_thread (minus_one_ptid);
4823
4824       if (thread_count (this) == 0)
4825         {
4826           /* Target has no concept of threads at all.  GDB treats
4827              non-threaded target as single-threaded; add a main
4828              thread.  */
4829           thread_info *tp = add_current_inferior_and_thread (wait_status);
4830           get_remote_thread_info (tp)->set_resumed ();
4831         }
4832       else
4833         {
4834           /* We have thread information; select the thread the target
4835              says should be current.  If we're reconnecting to a
4836              multi-threaded program, this will ideally be the thread
4837              that last reported an event before GDB disconnected.  */
4838           ptid_t curr_thread = get_current_thread (wait_status);
4839           if (curr_thread == null_ptid)
4840             {
4841               /* Odd... The target was able to list threads, but not
4842                  tell us which thread was current (no "thread"
4843                  register in T stop reply?).  Just pick the first
4844                  thread in the thread list then.  */
4845
4846               remote_debug_printf ("warning: couldn't determine remote "
4847                                    "current thread; picking first in list.");
4848
4849               for (thread_info *tp : all_non_exited_threads (this,
4850                                                              minus_one_ptid))
4851                 {
4852                   switch_to_thread (tp);
4853                   break;
4854                 }
4855             }
4856           else
4857             switch_to_thread (find_thread_ptid (this, curr_thread));
4858         }
4859
4860       /* init_wait_for_inferior should be called before get_offsets in order
4861          to manage `inserted' flag in bp loc in a correct state.
4862          breakpoint_init_inferior, called from init_wait_for_inferior, set
4863          `inserted' flag to 0, while before breakpoint_re_set, called from
4864          start_remote, set `inserted' flag to 1.  In the initialization of
4865          inferior, breakpoint_init_inferior should be called first, and then
4866          breakpoint_re_set can be called.  If this order is broken, state of
4867          `inserted' flag is wrong, and cause some problems on breakpoint
4868          manipulation.  */
4869       init_wait_for_inferior ();
4870
4871       get_offsets ();           /* Get text, data & bss offsets.  */
4872
4873       /* If we could not find a description using qXfer, and we know
4874          how to do it some other way, try again.  This is not
4875          supported for non-stop; it could be, but it is tricky if
4876          there are no stopped threads when we connect.  */
4877       if (remote_read_description_p (this)
4878           && gdbarch_target_desc (target_gdbarch ()) == NULL)
4879         {
4880           target_clear_description ();
4881           target_find_description ();
4882         }
4883
4884       /* Use the previously fetched status.  */
4885       gdb_assert (wait_status != NULL);
4886       strcpy (rs->buf.data (), wait_status);
4887       rs->cached_wait_status = 1;
4888
4889       ::start_remote (from_tty); /* Initialize gdb process mechanisms.  */
4890     }
4891   else
4892     {
4893       /* Clear WFI global state.  Do this before finding about new
4894          threads and inferiors, and setting the current inferior.
4895          Otherwise we would clear the proceed status of the current
4896          inferior when we want its stop_soon state to be preserved
4897          (see notice_new_inferior).  */
4898       init_wait_for_inferior ();
4899
4900       /* In non-stop, we will either get an "OK", meaning that there
4901          are no stopped threads at this time; or, a regular stop
4902          reply.  In the latter case, there may be more than one thread
4903          stopped --- we pull them all out using the vStopped
4904          mechanism.  */
4905       if (strcmp (rs->buf.data (), "OK") != 0)
4906         {
4907           struct notif_client *notif = &notif_client_stop;
4908
4909           /* remote_notif_get_pending_replies acks this one, and gets
4910              the rest out.  */
4911           rs->notif_state->pending_event[notif_client_stop.id]
4912             = remote_notif_parse (this, notif, rs->buf.data ());
4913           remote_notif_get_pending_events (notif);
4914         }
4915
4916       if (thread_count (this) == 0)
4917         {
4918           if (!extended_p)
4919             error (_("The target is not running (try extended-remote?)"));
4920
4921           /* We're connected, but not running.  Drop out before we
4922              call start_remote.  */
4923           rs->starting_up = 0;
4924           return;
4925         }
4926
4927       /* Report all signals during attach/startup.  */
4928       pass_signals ({});
4929
4930       /* If there are already stopped threads, mark them stopped and
4931          report their stops before giving the prompt to the user.  */
4932       process_initial_stop_replies (from_tty);
4933
4934       if (target_can_async_p ())
4935         target_async (1);
4936     }
4937
4938   /* If we connected to a live target, do some additional setup.  */
4939   if (target_has_execution ())
4940     {
4941       /* No use without a symbol-file.  */
4942       if (current_program_space->symfile_object_file)
4943         remote_check_symbols ();
4944     }
4945
4946   /* Possibly the target has been engaged in a trace run started
4947      previously; find out where things are at.  */
4948   if (get_trace_status (current_trace_status ()) != -1)
4949     {
4950       struct uploaded_tp *uploaded_tps = NULL;
4951
4952       if (current_trace_status ()->running)
4953         printf_filtered (_("Trace is already running on the target.\n"));
4954
4955       upload_tracepoints (&uploaded_tps);
4956
4957       merge_uploaded_tracepoints (&uploaded_tps);
4958     }
4959
4960   /* Possibly the target has been engaged in a btrace record started
4961      previously; find out where things are at.  */
4962   remote_btrace_maybe_reopen ();
4963
4964   /* The thread and inferior lists are now synchronized with the
4965      target, our symbols have been relocated, and we're merged the
4966      target's tracepoints with ours.  We're done with basic start
4967      up.  */
4968   rs->starting_up = 0;
4969
4970   /* Maybe breakpoints are global and need to be inserted now.  */
4971   if (breakpoints_should_be_inserted_now ())
4972     insert_breakpoints ();
4973 }
4974
4975 const char *
4976 remote_target::connection_string ()
4977 {
4978   remote_state *rs = get_remote_state ();
4979
4980   if (rs->remote_desc->name != NULL)
4981     return rs->remote_desc->name;
4982   else
4983     return NULL;
4984 }
4985
4986 /* Open a connection to a remote debugger.
4987    NAME is the filename used for communication.  */
4988
4989 void
4990 remote_target::open (const char *name, int from_tty)
4991 {
4992   open_1 (name, from_tty, 0);
4993 }
4994
4995 /* Open a connection to a remote debugger using the extended
4996    remote gdb protocol.  NAME is the filename used for communication.  */
4997
4998 void
4999 extended_remote_target::open (const char *name, int from_tty)
5000 {
5001   open_1 (name, from_tty, 1 /*extended_p */);
5002 }
5003
5004 /* Reset all packets back to "unknown support".  Called when opening a
5005    new connection to a remote target.  */
5006
5007 static void
5008 reset_all_packet_configs_support (void)
5009 {
5010   int i;
5011
5012   for (i = 0; i < PACKET_MAX; i++)
5013     remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5014 }
5015
5016 /* Initialize all packet configs.  */
5017
5018 static void
5019 init_all_packet_configs (void)
5020 {
5021   int i;
5022
5023   for (i = 0; i < PACKET_MAX; i++)
5024     {
5025       remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5026       remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5027     }
5028 }
5029
5030 /* Symbol look-up.  */
5031
5032 void
5033 remote_target::remote_check_symbols ()
5034 {
5035   char *tmp;
5036   int end;
5037
5038   /* The remote side has no concept of inferiors that aren't running
5039      yet, it only knows about running processes.  If we're connected
5040      but our current inferior is not running, we should not invite the
5041      remote target to request symbol lookups related to its
5042      (unrelated) current process.  */
5043   if (!target_has_execution ())
5044     return;
5045
5046   if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5047     return;
5048
5049   /* Make sure the remote is pointing at the right process.  Note
5050      there's no way to select "no process".  */
5051   set_general_process ();
5052
5053   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
5054      because we need both at the same time.  */
5055   gdb::char_vector msg (get_remote_packet_size ());
5056   gdb::char_vector reply (get_remote_packet_size ());
5057
5058   /* Invite target to request symbol lookups.  */
5059
5060   putpkt ("qSymbol::");
5061   getpkt (&reply, 0);
5062   packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
5063
5064   while (startswith (reply.data (), "qSymbol:"))
5065     {
5066       struct bound_minimal_symbol sym;
5067
5068       tmp = &reply[8];
5069       end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5070                      strlen (tmp) / 2);
5071       msg[end] = '\0';
5072       sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5073       if (sym.minsym == NULL)
5074         xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5075                    &reply[8]);
5076       else
5077         {
5078           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5079           CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
5080
5081           /* If this is a function address, return the start of code
5082              instead of any data function descriptor.  */
5083           sym_addr = gdbarch_convert_from_func_ptr_addr
5084             (target_gdbarch (), sym_addr, current_inferior ()->top_target ());
5085
5086           xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5087                      phex_nz (sym_addr, addr_size), &reply[8]);
5088         }
5089
5090       putpkt (msg.data ());
5091       getpkt (&reply, 0);
5092     }
5093 }
5094
5095 static struct serial *
5096 remote_serial_open (const char *name)
5097 {
5098   static int udp_warning = 0;
5099
5100   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
5101      of in ser-tcp.c, because it is the remote protocol assuming that the
5102      serial connection is reliable and not the serial connection promising
5103      to be.  */
5104   if (!udp_warning && startswith (name, "udp:"))
5105     {
5106       warning (_("The remote protocol may be unreliable over UDP.\n"
5107                  "Some events may be lost, rendering further debugging "
5108                  "impossible."));
5109       udp_warning = 1;
5110     }
5111
5112   return serial_open (name);
5113 }
5114
5115 /* Inform the target of our permission settings.  The permission flags
5116    work without this, but if the target knows the settings, it can do
5117    a couple things.  First, it can add its own check, to catch cases
5118    that somehow manage to get by the permissions checks in target
5119    methods.  Second, if the target is wired to disallow particular
5120    settings (for instance, a system in the field that is not set up to
5121    be able to stop at a breakpoint), it can object to any unavailable
5122    permissions.  */
5123
5124 void
5125 remote_target::set_permissions ()
5126 {
5127   struct remote_state *rs = get_remote_state ();
5128
5129   xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5130              "WriteReg:%x;WriteMem:%x;"
5131              "InsertBreak:%x;InsertTrace:%x;"
5132              "InsertFastTrace:%x;Stop:%x",
5133              may_write_registers, may_write_memory,
5134              may_insert_breakpoints, may_insert_tracepoints,
5135              may_insert_fast_tracepoints, may_stop);
5136   putpkt (rs->buf);
5137   getpkt (&rs->buf, 0);
5138
5139   /* If the target didn't like the packet, warn the user.  Do not try
5140      to undo the user's settings, that would just be maddening.  */
5141   if (strcmp (rs->buf.data (), "OK") != 0)
5142     warning (_("Remote refused setting permissions with: %s"),
5143              rs->buf.data ());
5144 }
5145
5146 /* This type describes each known response to the qSupported
5147    packet.  */
5148 struct protocol_feature
5149 {
5150   /* The name of this protocol feature.  */
5151   const char *name;
5152
5153   /* The default for this protocol feature.  */
5154   enum packet_support default_support;
5155
5156   /* The function to call when this feature is reported, or after
5157      qSupported processing if the feature is not supported.
5158      The first argument points to this structure.  The second
5159      argument indicates whether the packet requested support be
5160      enabled, disabled, or probed (or the default, if this function
5161      is being called at the end of processing and this feature was
5162      not reported).  The third argument may be NULL; if not NULL, it
5163      is a NUL-terminated string taken from the packet following
5164      this feature's name and an equals sign.  */
5165   void (*func) (remote_target *remote, const struct protocol_feature *,
5166                 enum packet_support, const char *);
5167
5168   /* The corresponding packet for this feature.  Only used if
5169      FUNC is remote_supported_packet.  */
5170   int packet;
5171 };
5172
5173 static void
5174 remote_supported_packet (remote_target *remote,
5175                          const struct protocol_feature *feature,
5176                          enum packet_support support,
5177                          const char *argument)
5178 {
5179   if (argument)
5180     {
5181       warning (_("Remote qSupported response supplied an unexpected value for"
5182                  " \"%s\"."), feature->name);
5183       return;
5184     }
5185
5186   remote_protocol_packets[feature->packet].support = support;
5187 }
5188
5189 void
5190 remote_target::remote_packet_size (const protocol_feature *feature,
5191                                    enum packet_support support, const char *value)
5192 {
5193   struct remote_state *rs = get_remote_state ();
5194
5195   int packet_size;
5196   char *value_end;
5197
5198   if (support != PACKET_ENABLE)
5199     return;
5200
5201   if (value == NULL || *value == '\0')
5202     {
5203       warning (_("Remote target reported \"%s\" without a size."),
5204                feature->name);
5205       return;
5206     }
5207
5208   errno = 0;
5209   packet_size = strtol (value, &value_end, 16);
5210   if (errno != 0 || *value_end != '\0' || packet_size < 0)
5211     {
5212       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5213                feature->name, value);
5214       return;
5215     }
5216
5217   /* Record the new maximum packet size.  */
5218   rs->explicit_packet_size = packet_size;
5219 }
5220
5221 static void
5222 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5223                     enum packet_support support, const char *value)
5224 {
5225   remote->remote_packet_size (feature, support, value);
5226 }
5227
5228 static const struct protocol_feature remote_protocol_features[] = {
5229   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5230   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5231     PACKET_qXfer_auxv },
5232   { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5233     PACKET_qXfer_exec_file },
5234   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5235     PACKET_qXfer_features },
5236   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5237     PACKET_qXfer_libraries },
5238   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5239     PACKET_qXfer_libraries_svr4 },
5240   { "augmented-libraries-svr4-read", PACKET_DISABLE,
5241     remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5242   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5243     PACKET_qXfer_memory_map },
5244   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5245     PACKET_qXfer_osdata },
5246   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5247     PACKET_qXfer_threads },
5248   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5249     PACKET_qXfer_traceframe_info },
5250   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5251     PACKET_QPassSignals },
5252   { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5253     PACKET_QCatchSyscalls },
5254   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5255     PACKET_QProgramSignals },
5256   { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5257     PACKET_QSetWorkingDir },
5258   { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5259     PACKET_QStartupWithShell },
5260   { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5261     PACKET_QEnvironmentHexEncoded },
5262   { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5263     PACKET_QEnvironmentReset },
5264   { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5265     PACKET_QEnvironmentUnset },
5266   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5267     PACKET_QStartNoAckMode },
5268   { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5269     PACKET_multiprocess_feature },
5270   { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5271   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5272     PACKET_qXfer_siginfo_read },
5273   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5274     PACKET_qXfer_siginfo_write },
5275   { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5276     PACKET_ConditionalTracepoints },
5277   { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5278     PACKET_ConditionalBreakpoints },
5279   { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5280     PACKET_BreakpointCommands },
5281   { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5282     PACKET_FastTracepoints },
5283   { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5284     PACKET_StaticTracepoints },
5285   {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5286    PACKET_InstallInTrace},
5287   { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5288     PACKET_DisconnectedTracing_feature },
5289   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5290     PACKET_bc },
5291   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5292     PACKET_bs },
5293   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5294     PACKET_TracepointSource },
5295   { "QAllow", PACKET_DISABLE, remote_supported_packet,
5296     PACKET_QAllow },
5297   { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5298     PACKET_EnableDisableTracepoints_feature },
5299   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5300     PACKET_qXfer_fdpic },
5301   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5302     PACKET_qXfer_uib },
5303   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5304     PACKET_QDisableRandomization },
5305   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5306   { "QTBuffer:size", PACKET_DISABLE,
5307     remote_supported_packet, PACKET_QTBuffer_size},
5308   { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5309   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5310   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5311   { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5312   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5313     PACKET_qXfer_btrace },
5314   { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5315     PACKET_qXfer_btrace_conf },
5316   { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5317     PACKET_Qbtrace_conf_bts_size },
5318   { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5319   { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5320   { "fork-events", PACKET_DISABLE, remote_supported_packet,
5321     PACKET_fork_event_feature },
5322   { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5323     PACKET_vfork_event_feature },
5324   { "exec-events", PACKET_DISABLE, remote_supported_packet,
5325     PACKET_exec_event_feature },
5326   { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5327     PACKET_Qbtrace_conf_pt_size },
5328   { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5329   { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5330   { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5331   { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5332     PACKET_memory_tagging_feature },
5333 };
5334
5335 static char *remote_support_xml;
5336
5337 /* Register string appended to "xmlRegisters=" in qSupported query.  */
5338
5339 void
5340 register_remote_support_xml (const char *xml)
5341 {
5342 #if defined(HAVE_LIBEXPAT)
5343   if (remote_support_xml == NULL)
5344     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5345   else
5346     {
5347       char *copy = xstrdup (remote_support_xml + 13);
5348       char *saveptr;
5349       char *p = strtok_r (copy, ",", &saveptr);
5350
5351       do
5352         {
5353           if (strcmp (p, xml) == 0)
5354             {
5355               /* already there */
5356               xfree (copy);
5357               return;
5358             }
5359         }
5360       while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5361       xfree (copy);
5362
5363       remote_support_xml = reconcat (remote_support_xml,
5364                                      remote_support_xml, ",", xml,
5365                                      (char *) NULL);
5366     }
5367 #endif
5368 }
5369
5370 static void
5371 remote_query_supported_append (std::string *msg, const char *append)
5372 {
5373   if (!msg->empty ())
5374     msg->append (";");
5375   msg->append (append);
5376 }
5377
5378 void
5379 remote_target::remote_query_supported ()
5380 {
5381   struct remote_state *rs = get_remote_state ();
5382   char *next;
5383   int i;
5384   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5385
5386   /* The packet support flags are handled differently for this packet
5387      than for most others.  We treat an error, a disabled packet, and
5388      an empty response identically: any features which must be reported
5389      to be used will be automatically disabled.  An empty buffer
5390      accomplishes this, since that is also the representation for a list
5391      containing no features.  */
5392
5393   rs->buf[0] = 0;
5394   if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5395     {
5396       std::string q;
5397
5398       if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5399         remote_query_supported_append (&q, "multiprocess+");
5400
5401       if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5402         remote_query_supported_append (&q, "swbreak+");
5403       if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5404         remote_query_supported_append (&q, "hwbreak+");
5405
5406       remote_query_supported_append (&q, "qRelocInsn+");
5407
5408       if (packet_set_cmd_state (PACKET_fork_event_feature)
5409           != AUTO_BOOLEAN_FALSE)
5410         remote_query_supported_append (&q, "fork-events+");
5411       if (packet_set_cmd_state (PACKET_vfork_event_feature)
5412           != AUTO_BOOLEAN_FALSE)
5413         remote_query_supported_append (&q, "vfork-events+");
5414       if (packet_set_cmd_state (PACKET_exec_event_feature)
5415           != AUTO_BOOLEAN_FALSE)
5416         remote_query_supported_append (&q, "exec-events+");
5417
5418       if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5419         remote_query_supported_append (&q, "vContSupported+");
5420
5421       if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5422         remote_query_supported_append (&q, "QThreadEvents+");
5423
5424       if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5425         remote_query_supported_append (&q, "no-resumed+");
5426
5427       if (packet_set_cmd_state (PACKET_memory_tagging_feature)
5428           != AUTO_BOOLEAN_FALSE)
5429         remote_query_supported_append (&q, "memory-tagging+");
5430
5431       /* Keep this one last to work around a gdbserver <= 7.10 bug in
5432          the qSupported:xmlRegisters=i386 handling.  */
5433       if (remote_support_xml != NULL
5434           && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5435         remote_query_supported_append (&q, remote_support_xml);
5436
5437       q = "qSupported:" + q;
5438       putpkt (q.c_str ());
5439
5440       getpkt (&rs->buf, 0);
5441
5442       /* If an error occured, warn, but do not return - just reset the
5443          buffer to empty and go on to disable features.  */
5444       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5445           == PACKET_ERROR)
5446         {
5447           warning (_("Remote failure reply: %s"), rs->buf.data ());
5448           rs->buf[0] = 0;
5449         }
5450     }
5451
5452   memset (seen, 0, sizeof (seen));
5453
5454   next = rs->buf.data ();
5455   while (*next)
5456     {
5457       enum packet_support is_supported;
5458       char *p, *end, *name_end, *value;
5459
5460       /* First separate out this item from the rest of the packet.  If
5461          there's another item after this, we overwrite the separator
5462          (terminated strings are much easier to work with).  */
5463       p = next;
5464       end = strchr (p, ';');
5465       if (end == NULL)
5466         {
5467           end = p + strlen (p);
5468           next = end;
5469         }
5470       else
5471         {
5472           *end = '\0';
5473           next = end + 1;
5474
5475           if (end == p)
5476             {
5477               warning (_("empty item in \"qSupported\" response"));
5478               continue;
5479             }
5480         }
5481
5482       name_end = strchr (p, '=');
5483       if (name_end)
5484         {
5485           /* This is a name=value entry.  */
5486           is_supported = PACKET_ENABLE;
5487           value = name_end + 1;
5488           *name_end = '\0';
5489         }
5490       else
5491         {
5492           value = NULL;
5493           switch (end[-1])
5494             {
5495             case '+':
5496               is_supported = PACKET_ENABLE;
5497               break;
5498
5499             case '-':
5500               is_supported = PACKET_DISABLE;
5501               break;
5502
5503             case '?':
5504               is_supported = PACKET_SUPPORT_UNKNOWN;
5505               break;
5506
5507             default:
5508               warning (_("unrecognized item \"%s\" "
5509                          "in \"qSupported\" response"), p);
5510               continue;
5511             }
5512           end[-1] = '\0';
5513         }
5514
5515       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5516         if (strcmp (remote_protocol_features[i].name, p) == 0)
5517           {
5518             const struct protocol_feature *feature;
5519
5520             seen[i] = 1;
5521             feature = &remote_protocol_features[i];
5522             feature->func (this, feature, is_supported, value);
5523             break;
5524           }
5525     }
5526
5527   /* If we increased the packet size, make sure to increase the global
5528      buffer size also.  We delay this until after parsing the entire
5529      qSupported packet, because this is the same buffer we were
5530      parsing.  */
5531   if (rs->buf.size () < rs->explicit_packet_size)
5532     rs->buf.resize (rs->explicit_packet_size);
5533
5534   /* Handle the defaults for unmentioned features.  */
5535   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5536     if (!seen[i])
5537       {
5538         const struct protocol_feature *feature;
5539
5540         feature = &remote_protocol_features[i];
5541         feature->func (this, feature, feature->default_support, NULL);
5542       }
5543 }
5544
5545 /* Serial QUIT handler for the remote serial descriptor.
5546
5547    Defers handling a Ctrl-C until we're done with the current
5548    command/response packet sequence, unless:
5549
5550    - We're setting up the connection.  Don't send a remote interrupt
5551      request, as we're not fully synced yet.  Quit immediately
5552      instead.
5553
5554    - The target has been resumed in the foreground
5555      (target_terminal::is_ours is false) with a synchronous resume
5556      packet, and we're blocked waiting for the stop reply, thus a
5557      Ctrl-C should be immediately sent to the target.
5558
5559    - We get a second Ctrl-C while still within the same serial read or
5560      write.  In that case the serial is seemingly wedged --- offer to
5561      quit/disconnect.
5562
5563    - We see a second Ctrl-C without target response, after having
5564      previously interrupted the target.  In that case the target/stub
5565      is probably wedged --- offer to quit/disconnect.
5566 */
5567
5568 void
5569 remote_target::remote_serial_quit_handler ()
5570 {
5571   struct remote_state *rs = get_remote_state ();
5572
5573   if (check_quit_flag ())
5574     {
5575       /* If we're starting up, we're not fully synced yet.  Quit
5576          immediately.  */
5577       if (rs->starting_up)
5578         quit ();
5579       else if (rs->got_ctrlc_during_io)
5580         {
5581           if (query (_("The target is not responding to GDB commands.\n"
5582                        "Stop debugging it? ")))
5583             remote_unpush_and_throw (this);
5584         }
5585       /* If ^C has already been sent once, offer to disconnect.  */
5586       else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5587         interrupt_query ();
5588       /* All-stop protocol, and blocked waiting for stop reply.  Send
5589          an interrupt request.  */
5590       else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5591         target_interrupt ();
5592       else
5593         rs->got_ctrlc_during_io = 1;
5594     }
5595 }
5596
5597 /* The remote_target that is current while the quit handler is
5598    overridden with remote_serial_quit_handler.  */
5599 static remote_target *curr_quit_handler_target;
5600
5601 static void
5602 remote_serial_quit_handler ()
5603 {
5604   curr_quit_handler_target->remote_serial_quit_handler ();
5605 }
5606
5607 /* Remove the remote target from the target stack of each inferior
5608    that is using it.  Upper targets depend on it so remove them
5609    first.  */
5610
5611 static void
5612 remote_unpush_target (remote_target *target)
5613 {
5614   /* We have to unpush the target from all inferiors, even those that
5615      aren't running.  */
5616   scoped_restore_current_inferior restore_current_inferior;
5617
5618   for (inferior *inf : all_inferiors (target))
5619     {
5620       switch_to_inferior_no_thread (inf);
5621       pop_all_targets_at_and_above (process_stratum);
5622       generic_mourn_inferior ();
5623     }
5624 }
5625
5626 static void
5627 remote_unpush_and_throw (remote_target *target)
5628 {
5629   remote_unpush_target (target);
5630   throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5631 }
5632
5633 void
5634 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5635 {
5636   remote_target *curr_remote = get_current_remote_target ();
5637
5638   if (name == 0)
5639     error (_("To open a remote debug connection, you need to specify what\n"
5640            "serial device is attached to the remote system\n"
5641            "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5642
5643   /* If we're connected to a running target, target_preopen will kill it.
5644      Ask this question first, before target_preopen has a chance to kill
5645      anything.  */
5646   if (curr_remote != NULL && !target_has_execution ())
5647     {
5648       if (from_tty
5649           && !query (_("Already connected to a remote target.  Disconnect? ")))
5650         error (_("Still connected."));
5651     }
5652
5653   /* Here the possibly existing remote target gets unpushed.  */
5654   target_preopen (from_tty);
5655
5656   remote_fileio_reset ();
5657   reopen_exec_file ();
5658   reread_symbols ();
5659
5660   remote_target *remote
5661     = (extended_p ? new extended_remote_target () : new remote_target ());
5662   target_ops_up target_holder (remote);
5663
5664   remote_state *rs = remote->get_remote_state ();
5665
5666   /* See FIXME above.  */
5667   if (!target_async_permitted)
5668     rs->wait_forever_enabled_p = 1;
5669
5670   rs->remote_desc = remote_serial_open (name);
5671   if (!rs->remote_desc)
5672     perror_with_name (name);
5673
5674   if (baud_rate != -1)
5675     {
5676       if (serial_setbaudrate (rs->remote_desc, baud_rate))
5677         {
5678           /* The requested speed could not be set.  Error out to
5679              top level after closing remote_desc.  Take care to
5680              set remote_desc to NULL to avoid closing remote_desc
5681              more than once.  */
5682           serial_close (rs->remote_desc);
5683           rs->remote_desc = NULL;
5684           perror_with_name (name);
5685         }
5686     }
5687
5688   serial_setparity (rs->remote_desc, serial_parity);
5689   serial_raw (rs->remote_desc);
5690
5691   /* If there is something sitting in the buffer we might take it as a
5692      response to a command, which would be bad.  */
5693   serial_flush_input (rs->remote_desc);
5694
5695   if (from_tty)
5696     {
5697       puts_filtered ("Remote debugging using ");
5698       puts_filtered (name);
5699       puts_filtered ("\n");
5700     }
5701
5702   /* Switch to using the remote target now.  */
5703   current_inferior ()->push_target (std::move (target_holder));
5704
5705   /* Register extra event sources in the event loop.  */
5706   rs->remote_async_inferior_event_token
5707     = create_async_event_handler (remote_async_inferior_event_handler, nullptr,
5708                                   "remote");
5709   rs->notif_state = remote_notif_state_allocate (remote);
5710
5711   /* Reset the target state; these things will be queried either by
5712      remote_query_supported or as they are needed.  */
5713   reset_all_packet_configs_support ();
5714   rs->cached_wait_status = 0;
5715   rs->explicit_packet_size = 0;
5716   rs->noack_mode = 0;
5717   rs->extended = extended_p;
5718   rs->waiting_for_stop_reply = 0;
5719   rs->ctrlc_pending_p = 0;
5720   rs->got_ctrlc_during_io = 0;
5721
5722   rs->general_thread = not_sent_ptid;
5723   rs->continue_thread = not_sent_ptid;
5724   rs->remote_traceframe_number = -1;
5725
5726   rs->last_resume_exec_dir = EXEC_FORWARD;
5727
5728   /* Probe for ability to use "ThreadInfo" query, as required.  */
5729   rs->use_threadinfo_query = 1;
5730   rs->use_threadextra_query = 1;
5731
5732   rs->readahead_cache.invalidate ();
5733
5734   if (target_async_permitted)
5735     {
5736       /* FIXME: cagney/1999-09-23: During the initial connection it is
5737          assumed that the target is already ready and able to respond to
5738          requests.  Unfortunately remote_start_remote() eventually calls
5739          wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
5740          around this.  Eventually a mechanism that allows
5741          wait_for_inferior() to expect/get timeouts will be
5742          implemented.  */
5743       rs->wait_forever_enabled_p = 0;
5744     }
5745
5746   /* First delete any symbols previously loaded from shared libraries.  */
5747   no_shared_libraries (NULL, 0);
5748
5749   /* Start the remote connection.  If error() or QUIT, discard this
5750      target (we'd otherwise be in an inconsistent state) and then
5751      propogate the error on up the exception chain.  This ensures that
5752      the caller doesn't stumble along blindly assuming that the
5753      function succeeded.  The CLI doesn't have this problem but other
5754      UI's, such as MI do.
5755
5756      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5757      this function should return an error indication letting the
5758      caller restore the previous state.  Unfortunately the command
5759      ``target remote'' is directly wired to this function making that
5760      impossible.  On a positive note, the CLI side of this problem has
5761      been fixed - the function set_cmd_context() makes it possible for
5762      all the ``target ....'' commands to share a common callback
5763      function.  See cli-dump.c.  */
5764   {
5765
5766     try
5767       {
5768         remote->start_remote (from_tty, extended_p);
5769       }
5770     catch (const gdb_exception &ex)
5771       {
5772         /* Pop the partially set up target - unless something else did
5773            already before throwing the exception.  */
5774         if (ex.error != TARGET_CLOSE_ERROR)
5775           remote_unpush_target (remote);
5776         throw;
5777       }
5778   }
5779
5780   remote_btrace_reset (rs);
5781
5782   if (target_async_permitted)
5783     rs->wait_forever_enabled_p = 1;
5784 }
5785
5786 /* Detach the specified process.  */
5787
5788 void
5789 remote_target::remote_detach_pid (int pid)
5790 {
5791   struct remote_state *rs = get_remote_state ();
5792
5793   /* This should not be necessary, but the handling for D;PID in
5794      GDBserver versions prior to 8.2 incorrectly assumes that the
5795      selected process points to the same process we're detaching,
5796      leading to misbehavior (and possibly GDBserver crashing) when it
5797      does not.  Since it's easy and cheap, work around it by forcing
5798      GDBserver to select GDB's current process.  */
5799   set_general_process ();
5800
5801   if (remote_multi_process_p (rs))
5802     xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
5803   else
5804     strcpy (rs->buf.data (), "D");
5805
5806   putpkt (rs->buf);
5807   getpkt (&rs->buf, 0);
5808
5809   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5810     ;
5811   else if (rs->buf[0] == '\0')
5812     error (_("Remote doesn't know how to detach"));
5813   else
5814     error (_("Can't detach process."));
5815 }
5816
5817 /* This detaches a program to which we previously attached, using
5818    inferior_ptid to identify the process.  After this is done, GDB
5819    can be used to debug some other program.  We better not have left
5820    any breakpoints in the target program or it'll die when it hits
5821    one.  */
5822
5823 void
5824 remote_target::remote_detach_1 (inferior *inf, int from_tty)
5825 {
5826   int pid = inferior_ptid.pid ();
5827   struct remote_state *rs = get_remote_state ();
5828   int is_fork_parent;
5829
5830   if (!target_has_execution ())
5831     error (_("No process to detach from."));
5832
5833   target_announce_detach (from_tty);
5834
5835   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
5836     {
5837       /* If we're in breakpoints-always-inserted mode, or the inferior
5838          is running, we have to remove breakpoints before detaching.
5839          We don't do this in common code instead because not all
5840          targets support removing breakpoints while the target is
5841          running.  The remote target / gdbserver does, though.  */
5842       remove_breakpoints_inf (current_inferior ());
5843     }
5844
5845   /* Tell the remote target to detach.  */
5846   remote_detach_pid (pid);
5847
5848   /* Exit only if this is the only active inferior.  */
5849   if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
5850     puts_filtered (_("Ending remote debugging.\n"));
5851
5852   thread_info *tp = find_thread_ptid (this, inferior_ptid);
5853
5854   /* Check to see if we are detaching a fork parent.  Note that if we
5855      are detaching a fork child, tp == NULL.  */
5856   is_fork_parent = (tp != NULL
5857                     && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5858
5859   /* If doing detach-on-fork, we don't mourn, because that will delete
5860      breakpoints that should be available for the followed inferior.  */
5861   if (!is_fork_parent)
5862     {
5863       /* Save the pid as a string before mourning, since that will
5864          unpush the remote target, and we need the string after.  */
5865       std::string infpid = target_pid_to_str (ptid_t (pid));
5866
5867       target_mourn_inferior (inferior_ptid);
5868       if (print_inferior_events)
5869         printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5870                            inf->num, infpid.c_str ());
5871     }
5872   else
5873     {
5874       switch_to_no_thread ();
5875       detach_inferior (current_inferior ());
5876     }
5877 }
5878
5879 void
5880 remote_target::detach (inferior *inf, int from_tty)
5881 {
5882   remote_detach_1 (inf, from_tty);
5883 }
5884
5885 void
5886 extended_remote_target::detach (inferior *inf, int from_tty)
5887 {
5888   remote_detach_1 (inf, from_tty);
5889 }
5890
5891 /* Target follow-fork function for remote targets.  On entry, and
5892    at return, the current inferior is the fork parent.
5893
5894    Note that although this is currently only used for extended-remote,
5895    it is named remote_follow_fork in anticipation of using it for the
5896    remote target as well.  */
5897
5898 bool
5899 remote_target::follow_fork (bool follow_child, bool detach_fork)
5900 {
5901   struct remote_state *rs = get_remote_state ();
5902   enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5903
5904   if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5905       || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5906     {
5907       /* When following the parent and detaching the child, we detach
5908          the child here.  For the case of following the child and
5909          detaching the parent, the detach is done in the target-
5910          independent follow fork code in infrun.c.  We can't use
5911          target_detach when detaching an unfollowed child because
5912          the client side doesn't know anything about the child.  */
5913       if (detach_fork && !follow_child)
5914         {
5915           /* Detach the fork child.  */
5916           ptid_t child_ptid;
5917           pid_t child_pid;
5918
5919           child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5920           child_pid = child_ptid.pid ();
5921
5922           remote_detach_pid (child_pid);
5923         }
5924     }
5925
5926   return false;
5927 }
5928
5929 /* Target follow-exec function for remote targets.  Save EXECD_PATHNAME
5930    in the program space of the new inferior.  On entry and at return the
5931    current inferior is the exec'ing inferior.  INF is the new exec'd
5932    inferior, which may be the same as the exec'ing inferior unless
5933    follow-exec-mode is "new".  */
5934
5935 void
5936 remote_target::follow_exec (struct inferior *inf, const char *execd_pathname)
5937 {
5938   /* We know that this is a target file name, so if it has the "target:"
5939      prefix we strip it off before saving it in the program space.  */
5940   if (is_target_filename (execd_pathname))
5941     execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5942
5943   set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5944 }
5945
5946 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
5947
5948 void
5949 remote_target::disconnect (const char *args, int from_tty)
5950 {
5951   if (args)
5952     error (_("Argument given to \"disconnect\" when remotely debugging."));
5953
5954   /* Make sure we unpush even the extended remote targets.  Calling
5955      target_mourn_inferior won't unpush, and
5956      remote_target::mourn_inferior won't unpush if there is more than
5957      one inferior left.  */
5958   remote_unpush_target (this);
5959
5960   if (from_tty)
5961     puts_filtered ("Ending remote debugging.\n");
5962 }
5963
5964 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
5965    be chatty about it.  */
5966
5967 void
5968 extended_remote_target::attach (const char *args, int from_tty)
5969 {
5970   struct remote_state *rs = get_remote_state ();
5971   int pid;
5972   char *wait_status = NULL;
5973
5974   pid = parse_pid_to_attach (args);
5975
5976   /* Remote PID can be freely equal to getpid, do not check it here the same
5977      way as in other targets.  */
5978
5979   if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5980     error (_("This target does not support attaching to a process"));
5981
5982   if (from_tty)
5983     {
5984       const char *exec_file = get_exec_file (0);
5985
5986       if (exec_file)
5987         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5988                            target_pid_to_str (ptid_t (pid)).c_str ());
5989       else
5990         printf_unfiltered (_("Attaching to %s\n"),
5991                            target_pid_to_str (ptid_t (pid)).c_str ());
5992     }
5993
5994   xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
5995   putpkt (rs->buf);
5996   getpkt (&rs->buf, 0);
5997
5998   switch (packet_ok (rs->buf,
5999                      &remote_protocol_packets[PACKET_vAttach]))
6000     {
6001     case PACKET_OK:
6002       if (!target_is_non_stop_p ())
6003         {
6004           /* Save the reply for later.  */
6005           wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6006           strcpy (wait_status, rs->buf.data ());
6007         }
6008       else if (strcmp (rs->buf.data (), "OK") != 0)
6009         error (_("Attaching to %s failed with: %s"),
6010                target_pid_to_str (ptid_t (pid)).c_str (),
6011                rs->buf.data ());
6012       break;
6013     case PACKET_UNKNOWN:
6014       error (_("This target does not support attaching to a process"));
6015     default:
6016       error (_("Attaching to %s failed"),
6017              target_pid_to_str (ptid_t (pid)).c_str ());
6018     }
6019
6020   switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6021
6022   inferior_ptid = ptid_t (pid);
6023
6024   if (target_is_non_stop_p ())
6025     {
6026       /* Get list of threads.  */
6027       update_thread_list ();
6028
6029       thread_info *thread = first_thread_of_inferior (current_inferior ());
6030       if (thread != nullptr)
6031         switch_to_thread (thread);
6032
6033       /* Invalidate our notion of the remote current thread.  */
6034       record_currthread (rs, minus_one_ptid);
6035     }
6036   else
6037     {
6038       /* Now, if we have thread information, update the main thread's
6039          ptid.  */
6040       ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6041
6042       /* Add the main thread to the thread list.  */
6043       thread_info *thr = add_thread_silent (this, curr_ptid);
6044
6045       switch_to_thread (thr);
6046
6047       /* Don't consider the thread stopped until we've processed the
6048          saved stop reply.  */
6049       set_executing (this, thr->ptid, true);
6050     }
6051
6052   /* Next, if the target can specify a description, read it.  We do
6053      this before anything involving memory or registers.  */
6054   target_find_description ();
6055
6056   if (!target_is_non_stop_p ())
6057     {
6058       /* Use the previously fetched status.  */
6059       gdb_assert (wait_status != NULL);
6060
6061       if (target_can_async_p ())
6062         {
6063           struct notif_event *reply
6064             =  remote_notif_parse (this, &notif_client_stop, wait_status);
6065
6066           push_stop_reply ((struct stop_reply *) reply);
6067
6068           target_async (1);
6069         }
6070       else
6071         {
6072           gdb_assert (wait_status != NULL);
6073           strcpy (rs->buf.data (), wait_status);
6074           rs->cached_wait_status = 1;
6075         }
6076     }
6077   else
6078     {
6079       gdb_assert (wait_status == NULL);
6080
6081       gdb_assert (target_can_async_p ());
6082       target_async (1);
6083     }
6084 }
6085
6086 /* Implementation of the to_post_attach method.  */
6087
6088 void
6089 extended_remote_target::post_attach (int pid)
6090 {
6091   /* Get text, data & bss offsets.  */
6092   get_offsets ();
6093
6094   /* In certain cases GDB might not have had the chance to start
6095      symbol lookup up until now.  This could happen if the debugged
6096      binary is not using shared libraries, the vsyscall page is not
6097      present (on Linux) and the binary itself hadn't changed since the
6098      debugging process was started.  */
6099   if (current_program_space->symfile_object_file != NULL)
6100     remote_check_symbols();
6101 }
6102
6103 \f
6104 /* Check for the availability of vCont.  This function should also check
6105    the response.  */
6106
6107 void
6108 remote_target::remote_vcont_probe ()
6109 {
6110   remote_state *rs = get_remote_state ();
6111   char *buf;
6112
6113   strcpy (rs->buf.data (), "vCont?");
6114   putpkt (rs->buf);
6115   getpkt (&rs->buf, 0);
6116   buf = rs->buf.data ();
6117
6118   /* Make sure that the features we assume are supported.  */
6119   if (startswith (buf, "vCont"))
6120     {
6121       char *p = &buf[5];
6122       int support_c, support_C;
6123
6124       rs->supports_vCont.s = 0;
6125       rs->supports_vCont.S = 0;
6126       support_c = 0;
6127       support_C = 0;
6128       rs->supports_vCont.t = 0;
6129       rs->supports_vCont.r = 0;
6130       while (p && *p == ';')
6131         {
6132           p++;
6133           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6134             rs->supports_vCont.s = 1;
6135           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6136             rs->supports_vCont.S = 1;
6137           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6138             support_c = 1;
6139           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6140             support_C = 1;
6141           else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6142             rs->supports_vCont.t = 1;
6143           else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6144             rs->supports_vCont.r = 1;
6145
6146           p = strchr (p, ';');
6147         }
6148
6149       /* If c, and C are not all supported, we can't use vCont.  Clearing
6150          BUF will make packet_ok disable the packet.  */
6151       if (!support_c || !support_C)
6152         buf[0] = 0;
6153     }
6154
6155   packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCont]);
6156   rs->supports_vCont_probed = true;
6157 }
6158
6159 /* Helper function for building "vCont" resumptions.  Write a
6160    resumption to P.  ENDP points to one-passed-the-end of the buffer
6161    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
6162    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6163    resumed thread should be single-stepped and/or signalled.  If PTID
6164    equals minus_one_ptid, then all threads are resumed; if PTID
6165    represents a process, then all threads of the process are resumed;
6166    the thread to be stepped and/or signalled is given in the global
6167    INFERIOR_PTID.  */
6168
6169 char *
6170 remote_target::append_resumption (char *p, char *endp,
6171                                   ptid_t ptid, int step, gdb_signal siggnal)
6172 {
6173   struct remote_state *rs = get_remote_state ();
6174
6175   if (step && siggnal != GDB_SIGNAL_0)
6176     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6177   else if (step
6178            /* GDB is willing to range step.  */
6179            && use_range_stepping
6180            /* Target supports range stepping.  */
6181            && rs->supports_vCont.r
6182            /* We don't currently support range stepping multiple
6183               threads with a wildcard (though the protocol allows it,
6184               so stubs shouldn't make an active effort to forbid
6185               it).  */
6186            && !(remote_multi_process_p (rs) && ptid.is_pid ()))
6187     {
6188       struct thread_info *tp;
6189
6190       if (ptid == minus_one_ptid)
6191         {
6192           /* If we don't know about the target thread's tid, then
6193              we're resuming magic_null_ptid (see caller).  */
6194           tp = find_thread_ptid (this, magic_null_ptid);
6195         }
6196       else
6197         tp = find_thread_ptid (this, ptid);
6198       gdb_assert (tp != NULL);
6199
6200       if (tp->control.may_range_step)
6201         {
6202           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6203
6204           p += xsnprintf (p, endp - p, ";r%s,%s",
6205                           phex_nz (tp->control.step_range_start,
6206                                    addr_size),
6207                           phex_nz (tp->control.step_range_end,
6208                                    addr_size));
6209         }
6210       else
6211         p += xsnprintf (p, endp - p, ";s");
6212     }
6213   else if (step)
6214     p += xsnprintf (p, endp - p, ";s");
6215   else if (siggnal != GDB_SIGNAL_0)
6216     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6217   else
6218     p += xsnprintf (p, endp - p, ";c");
6219
6220   if (remote_multi_process_p (rs) && ptid.is_pid ())
6221     {
6222       ptid_t nptid;
6223
6224       /* All (-1) threads of process.  */
6225       nptid = ptid_t (ptid.pid (), -1, 0);
6226
6227       p += xsnprintf (p, endp - p, ":");
6228       p = write_ptid (p, endp, nptid);
6229     }
6230   else if (ptid != minus_one_ptid)
6231     {
6232       p += xsnprintf (p, endp - p, ":");
6233       p = write_ptid (p, endp, ptid);
6234     }
6235
6236   return p;
6237 }
6238
6239 /* Clear the thread's private info on resume.  */
6240
6241 static void
6242 resume_clear_thread_private_info (struct thread_info *thread)
6243 {
6244   if (thread->priv != NULL)
6245     {
6246       remote_thread_info *priv = get_remote_thread_info (thread);
6247
6248       priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6249       priv->watch_data_address = 0;
6250     }
6251 }
6252
6253 /* Append a vCont continue-with-signal action for threads that have a
6254    non-zero stop signal.  */
6255
6256 char *
6257 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6258                                                   ptid_t ptid)
6259 {
6260   for (thread_info *thread : all_non_exited_threads (this, ptid))
6261     if (inferior_ptid != thread->ptid
6262         && thread->suspend.stop_signal != GDB_SIGNAL_0)
6263       {
6264         p = append_resumption (p, endp, thread->ptid,
6265                                0, thread->suspend.stop_signal);
6266         thread->suspend.stop_signal = GDB_SIGNAL_0;
6267         resume_clear_thread_private_info (thread);
6268       }
6269
6270   return p;
6271 }
6272
6273 /* Set the target running, using the packets that use Hc
6274    (c/s/C/S).  */
6275
6276 void
6277 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6278                                       gdb_signal siggnal)
6279 {
6280   struct remote_state *rs = get_remote_state ();
6281   char *buf;
6282
6283   rs->last_sent_signal = siggnal;
6284   rs->last_sent_step = step;
6285
6286   /* The c/s/C/S resume packets use Hc, so set the continue
6287      thread.  */
6288   if (ptid == minus_one_ptid)
6289     set_continue_thread (any_thread_ptid);
6290   else
6291     set_continue_thread (ptid);
6292
6293   for (thread_info *thread : all_non_exited_threads (this))
6294     resume_clear_thread_private_info (thread);
6295
6296   buf = rs->buf.data ();
6297   if (::execution_direction == EXEC_REVERSE)
6298     {
6299       /* We don't pass signals to the target in reverse exec mode.  */
6300       if (info_verbose && siggnal != GDB_SIGNAL_0)
6301         warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6302                  siggnal);
6303
6304       if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6305         error (_("Remote reverse-step not supported."));
6306       if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6307         error (_("Remote reverse-continue not supported."));
6308
6309       strcpy (buf, step ? "bs" : "bc");
6310     }
6311   else if (siggnal != GDB_SIGNAL_0)
6312     {
6313       buf[0] = step ? 'S' : 'C';
6314       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6315       buf[2] = tohex (((int) siggnal) & 0xf);
6316       buf[3] = '\0';
6317     }
6318   else
6319     strcpy (buf, step ? "s" : "c");
6320
6321   putpkt (buf);
6322 }
6323
6324 /* Resume the remote inferior by using a "vCont" packet.  The thread
6325    to be resumed is PTID; STEP and SIGGNAL indicate whether the
6326    resumed thread should be single-stepped and/or signalled.  If PTID
6327    equals minus_one_ptid, then all threads are resumed; the thread to
6328    be stepped and/or signalled is given in the global INFERIOR_PTID.
6329    This function returns non-zero iff it resumes the inferior.
6330
6331    This function issues a strict subset of all possible vCont commands
6332    at the moment.  */
6333
6334 int
6335 remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6336                                          enum gdb_signal siggnal)
6337 {
6338   struct remote_state *rs = get_remote_state ();
6339   char *p;
6340   char *endp;
6341
6342   /* No reverse execution actions defined for vCont.  */
6343   if (::execution_direction == EXEC_REVERSE)
6344     return 0;
6345
6346   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6347     remote_vcont_probe ();
6348
6349   if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6350     return 0;
6351
6352   p = rs->buf.data ();
6353   endp = p + get_remote_packet_size ();
6354
6355   /* If we could generate a wider range of packets, we'd have to worry
6356      about overflowing BUF.  Should there be a generic
6357      "multi-part-packet" packet?  */
6358
6359   p += xsnprintf (p, endp - p, "vCont");
6360
6361   if (ptid == magic_null_ptid)
6362     {
6363       /* MAGIC_NULL_PTID means that we don't have any active threads,
6364          so we don't have any TID numbers the inferior will
6365          understand.  Make sure to only send forms that do not specify
6366          a TID.  */
6367       append_resumption (p, endp, minus_one_ptid, step, siggnal);
6368     }
6369   else if (ptid == minus_one_ptid || ptid.is_pid ())
6370     {
6371       /* Resume all threads (of all processes, or of a single
6372          process), with preference for INFERIOR_PTID.  This assumes
6373          inferior_ptid belongs to the set of all threads we are about
6374          to resume.  */
6375       if (step || siggnal != GDB_SIGNAL_0)
6376         {
6377           /* Step inferior_ptid, with or without signal.  */
6378           p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6379         }
6380
6381       /* Also pass down any pending signaled resumption for other
6382          threads not the current.  */
6383       p = append_pending_thread_resumptions (p, endp, ptid);
6384
6385       /* And continue others without a signal.  */
6386       append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
6387     }
6388   else
6389     {
6390       /* Scheduler locking; resume only PTID.  */
6391       append_resumption (p, endp, ptid, step, siggnal);
6392     }
6393
6394   gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6395   putpkt (rs->buf);
6396
6397   if (target_is_non_stop_p ())
6398     {
6399       /* In non-stop, the stub replies to vCont with "OK".  The stop
6400          reply will be reported asynchronously by means of a `%Stop'
6401          notification.  */
6402       getpkt (&rs->buf, 0);
6403       if (strcmp (rs->buf.data (), "OK") != 0)
6404         error (_("Unexpected vCont reply in non-stop mode: %s"),
6405                rs->buf.data ());
6406     }
6407
6408   return 1;
6409 }
6410
6411 /* Tell the remote machine to resume.  */
6412
6413 void
6414 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
6415 {
6416   struct remote_state *rs = get_remote_state ();
6417
6418   /* When connected in non-stop mode, the core resumes threads
6419      individually.  Resuming remote threads directly in target_resume
6420      would thus result in sending one packet per thread.  Instead, to
6421      minimize roundtrip latency, here we just store the resume
6422      request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6423      resumption will be done in remote_target::commit_resume, where we'll be
6424      able to do vCont action coalescing.  */
6425   if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6426     {
6427       remote_thread_info *remote_thr;
6428
6429       if (minus_one_ptid == ptid || ptid.is_pid ())
6430         remote_thr = get_remote_thread_info (this, inferior_ptid);
6431       else
6432         remote_thr = get_remote_thread_info (this, ptid);
6433
6434       /* We don't expect the core to ask to resume an already resumed (from
6435          its point of view) thread.  */
6436       gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6437
6438       remote_thr->set_resumed_pending_vcont (step, siggnal);
6439       return;
6440     }
6441
6442   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6443      (explained in remote-notif.c:handle_notification) so
6444      remote_notif_process is not called.  We need find a place where
6445      it is safe to start a 'vNotif' sequence.  It is good to do it
6446      before resuming inferior, because inferior was stopped and no RSP
6447      traffic at that moment.  */
6448   if (!target_is_non_stop_p ())
6449     remote_notif_process (rs->notif_state, &notif_client_stop);
6450
6451   rs->last_resume_exec_dir = ::execution_direction;
6452
6453   /* Prefer vCont, and fallback to s/c/S/C, which use Hc.  */
6454   if (!remote_resume_with_vcont (ptid, step, siggnal))
6455     remote_resume_with_hc (ptid, step, siggnal);
6456
6457   /* Update resumed state tracked by the remote target.  */
6458   for (thread_info *tp : all_non_exited_threads (this, ptid))
6459     get_remote_thread_info (tp)->set_resumed ();
6460
6461   /* We are about to start executing the inferior, let's register it
6462      with the event loop.  NOTE: this is the one place where all the
6463      execution commands end up.  We could alternatively do this in each
6464      of the execution commands in infcmd.c.  */
6465   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6466      into infcmd.c in order to allow inferior function calls to work
6467      NOT asynchronously.  */
6468   if (target_can_async_p ())
6469     target_async (1);
6470
6471   /* We've just told the target to resume.  The remote server will
6472      wait for the inferior to stop, and then send a stop reply.  In
6473      the mean time, we can't start another command/query ourselves
6474      because the stub wouldn't be ready to process it.  This applies
6475      only to the base all-stop protocol, however.  In non-stop (which
6476      only supports vCont), the stub replies with an "OK", and is
6477      immediate able to process further serial input.  */
6478   if (!target_is_non_stop_p ())
6479     rs->waiting_for_stop_reply = 1;
6480 }
6481
6482 static int is_pending_fork_parent_thread (struct thread_info *thread);
6483
6484 /* Private per-inferior info for target remote processes.  */
6485
6486 struct remote_inferior : public private_inferior
6487 {
6488   /* Whether we can send a wildcard vCont for this process.  */
6489   bool may_wildcard_vcont = true;
6490 };
6491
6492 /* Get the remote private inferior data associated to INF.  */
6493
6494 static remote_inferior *
6495 get_remote_inferior (inferior *inf)
6496 {
6497   if (inf->priv == NULL)
6498     inf->priv.reset (new remote_inferior);
6499
6500   return static_cast<remote_inferior *> (inf->priv.get ());
6501 }
6502
6503 struct stop_reply : public notif_event
6504 {
6505   ~stop_reply ();
6506
6507   /* The identifier of the thread about this event  */
6508   ptid_t ptid;
6509
6510   /* The remote state this event is associated with.  When the remote
6511      connection, represented by a remote_state object, is closed,
6512      all the associated stop_reply events should be released.  */
6513   struct remote_state *rs;
6514
6515   struct target_waitstatus ws;
6516
6517   /* The architecture associated with the expedited registers.  */
6518   gdbarch *arch;
6519
6520   /* Expedited registers.  This makes remote debugging a bit more
6521      efficient for those targets that provide critical registers as
6522      part of their normal status mechanism (as another roundtrip to
6523      fetch them is avoided).  */
6524   std::vector<cached_reg_t> regcache;
6525
6526   enum target_stop_reason stop_reason;
6527
6528   CORE_ADDR watch_data_address;
6529
6530   int core;
6531 };
6532
6533 /* Class used to track the construction of a vCont packet in the
6534    outgoing packet buffer.  This is used to send multiple vCont
6535    packets if we have more actions than would fit a single packet.  */
6536
6537 class vcont_builder
6538 {
6539 public:
6540   explicit vcont_builder (remote_target *remote)
6541     : m_remote (remote)
6542   {
6543     restart ();
6544   }
6545
6546   void flush ();
6547   void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6548
6549 private:
6550   void restart ();
6551
6552   /* The remote target.  */
6553   remote_target *m_remote;
6554
6555   /* Pointer to the first action.  P points here if no action has been
6556      appended yet.  */
6557   char *m_first_action;
6558
6559   /* Where the next action will be appended.  */
6560   char *m_p;
6561
6562   /* The end of the buffer.  Must never write past this.  */
6563   char *m_endp;
6564 };
6565
6566 /* Prepare the outgoing buffer for a new vCont packet.  */
6567
6568 void
6569 vcont_builder::restart ()
6570 {
6571   struct remote_state *rs = m_remote->get_remote_state ();
6572
6573   m_p = rs->buf.data ();
6574   m_endp = m_p + m_remote->get_remote_packet_size ();
6575   m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6576   m_first_action = m_p;
6577 }
6578
6579 /* If the vCont packet being built has any action, send it to the
6580    remote end.  */
6581
6582 void
6583 vcont_builder::flush ()
6584 {
6585   struct remote_state *rs;
6586
6587   if (m_p == m_first_action)
6588     return;
6589
6590   rs = m_remote->get_remote_state ();
6591   m_remote->putpkt (rs->buf);
6592   m_remote->getpkt (&rs->buf, 0);
6593   if (strcmp (rs->buf.data (), "OK") != 0)
6594     error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
6595 }
6596
6597 /* The largest action is range-stepping, with its two addresses.  This
6598    is more than sufficient.  If a new, bigger action is created, it'll
6599    quickly trigger a failed assertion in append_resumption (and we'll
6600    just bump this).  */
6601 #define MAX_ACTION_SIZE 200
6602
6603 /* Append a new vCont action in the outgoing packet being built.  If
6604    the action doesn't fit the packet along with previous actions, push
6605    what we've got so far to the remote end and start over a new vCont
6606    packet (with the new action).  */
6607
6608 void
6609 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6610 {
6611   char buf[MAX_ACTION_SIZE + 1];
6612
6613   char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6614                                             ptid, step, siggnal);
6615
6616   /* Check whether this new action would fit in the vCont packet along
6617      with previous actions.  If not, send what we've got so far and
6618      start a new vCont packet.  */
6619   size_t rsize = endp - buf;
6620   if (rsize > m_endp - m_p)
6621     {
6622       flush ();
6623       restart ();
6624
6625       /* Should now fit.  */
6626       gdb_assert (rsize <= m_endp - m_p);
6627     }
6628
6629   memcpy (m_p, buf, rsize);
6630   m_p += rsize;
6631   *m_p = '\0';
6632 }
6633
6634 /* to_commit_resume implementation.  */
6635
6636 void
6637 remote_target::commit_resumed ()
6638 {
6639   int any_process_wildcard;
6640   int may_global_wildcard_vcont;
6641
6642   /* If connected in all-stop mode, we'd send the remote resume
6643      request directly from remote_resume.  Likewise if
6644      reverse-debugging, as there are no defined vCont actions for
6645      reverse execution.  */
6646   if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6647     return;
6648
6649   /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6650      instead of resuming all threads of each process individually.
6651      However, if any thread of a process must remain halted, we can't
6652      send wildcard resumes and must send one action per thread.
6653
6654      Care must be taken to not resume threads/processes the server
6655      side already told us are stopped, but the core doesn't know about
6656      yet, because the events are still in the vStopped notification
6657      queue.  For example:
6658
6659        #1 => vCont s:p1.1;c
6660        #2 <= OK
6661        #3 <= %Stopped T05 p1.1
6662        #4 => vStopped
6663        #5 <= T05 p1.2
6664        #6 => vStopped
6665        #7 <= OK
6666        #8 (infrun handles the stop for p1.1 and continues stepping)
6667        #9 => vCont s:p1.1;c
6668
6669      The last vCont above would resume thread p1.2 by mistake, because
6670      the server has no idea that the event for p1.2 had not been
6671      handled yet.
6672
6673      The server side must similarly ignore resume actions for the
6674      thread that has a pending %Stopped notification (and any other
6675      threads with events pending), until GDB acks the notification
6676      with vStopped.  Otherwise, e.g., the following case is
6677      mishandled:
6678
6679        #1 => g  (or any other packet)
6680        #2 <= [registers]
6681        #3 <= %Stopped T05 p1.2
6682        #4 => vCont s:p1.1;c
6683        #5 <= OK
6684
6685      Above, the server must not resume thread p1.2.  GDB can't know
6686      that p1.2 stopped until it acks the %Stopped notification, and
6687      since from GDB's perspective all threads should be running, it
6688      sends a "c" action.
6689
6690      Finally, special care must also be given to handling fork/vfork
6691      events.  A (v)fork event actually tells us that two processes
6692      stopped -- the parent and the child.  Until we follow the fork,
6693      we must not resume the child.  Therefore, if we have a pending
6694      fork follow, we must not send a global wildcard resume action
6695      (vCont;c).  We can still send process-wide wildcards though.  */
6696
6697   /* Start by assuming a global wildcard (vCont;c) is possible.  */
6698   may_global_wildcard_vcont = 1;
6699
6700   /* And assume every process is individually wildcard-able too.  */
6701   for (inferior *inf : all_non_exited_inferiors (this))
6702     {
6703       remote_inferior *priv = get_remote_inferior (inf);
6704
6705       priv->may_wildcard_vcont = true;
6706     }
6707
6708   /* Check for any pending events (not reported or processed yet) and
6709      disable process and global wildcard resumes appropriately.  */
6710   check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6711
6712   bool any_pending_vcont_resume = false;
6713
6714   for (thread_info *tp : all_non_exited_threads (this))
6715     {
6716       remote_thread_info *priv = get_remote_thread_info (tp);
6717
6718       /* If a thread of a process is not meant to be resumed, then we
6719          can't wildcard that process.  */
6720       if (priv->get_resume_state () == resume_state::NOT_RESUMED)
6721         {
6722           get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6723
6724           /* And if we can't wildcard a process, we can't wildcard
6725              everything either.  */
6726           may_global_wildcard_vcont = 0;
6727           continue;
6728         }
6729
6730       if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
6731         any_pending_vcont_resume = true;
6732
6733       /* If a thread is the parent of an unfollowed fork, then we
6734          can't do a global wildcard, as that would resume the fork
6735          child.  */
6736       if (is_pending_fork_parent_thread (tp))
6737         may_global_wildcard_vcont = 0;
6738     }
6739
6740   /* We didn't have any resumed thread pending a vCont resume, so nothing to
6741      do.  */
6742   if (!any_pending_vcont_resume)
6743     return;
6744
6745   /* Now let's build the vCont packet(s).  Actions must be appended
6746      from narrower to wider scopes (thread -> process -> global).  If
6747      we end up with too many actions for a single packet vcont_builder
6748      flushes the current vCont packet to the remote side and starts a
6749      new one.  */
6750   struct vcont_builder vcont_builder (this);
6751
6752   /* Threads first.  */
6753   for (thread_info *tp : all_non_exited_threads (this))
6754     {
6755       remote_thread_info *remote_thr = get_remote_thread_info (tp);
6756
6757       /* If the thread was previously vCont-resumed, no need to send a specific
6758          action for it.  If we didn't receive a resume request for it, don't
6759          send an action for it either.  */
6760       if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
6761         continue;
6762
6763       gdb_assert (!thread_is_in_step_over_chain (tp));
6764
6765       /* We should never be commit-resuming a thread that has a stop reply.
6766          Otherwise, we would end up reporting a stop event for a thread while
6767          it is running on the remote target.  */
6768       remote_state *rs = get_remote_state ();
6769       for (const auto &stop_reply : rs->stop_reply_queue)
6770         gdb_assert (stop_reply->ptid != tp->ptid);
6771
6772       const resumed_pending_vcont_info &info
6773         = remote_thr->resumed_pending_vcont_info ();
6774
6775       /* Check if we need to send a specific action for this thread.  If not,
6776          it will be included in a wildcard resume instead.  */
6777       if (info.step || info.sig != GDB_SIGNAL_0
6778           || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
6779         vcont_builder.push_action (tp->ptid, info.step, info.sig);
6780
6781       remote_thr->set_resumed ();
6782     }
6783
6784   /* Now check whether we can send any process-wide wildcard.  This is
6785      to avoid sending a global wildcard in the case nothing is
6786      supposed to be resumed.  */
6787   any_process_wildcard = 0;
6788
6789   for (inferior *inf : all_non_exited_inferiors (this))
6790     {
6791       if (get_remote_inferior (inf)->may_wildcard_vcont)
6792         {
6793           any_process_wildcard = 1;
6794           break;
6795         }
6796     }
6797
6798   if (any_process_wildcard)
6799     {
6800       /* If all processes are wildcard-able, then send a single "c"
6801          action, otherwise, send an "all (-1) threads of process"
6802          continue action for each running process, if any.  */
6803       if (may_global_wildcard_vcont)
6804         {
6805           vcont_builder.push_action (minus_one_ptid,
6806                                      false, GDB_SIGNAL_0);
6807         }
6808       else
6809         {
6810           for (inferior *inf : all_non_exited_inferiors (this))
6811             {
6812               if (get_remote_inferior (inf)->may_wildcard_vcont)
6813                 {
6814                   vcont_builder.push_action (ptid_t (inf->pid),
6815                                              false, GDB_SIGNAL_0);
6816                 }
6817             }
6818         }
6819     }
6820
6821   vcont_builder.flush ();
6822 }
6823
6824 /* Implementation of target_has_pending_events.  */
6825
6826 bool
6827 remote_target::has_pending_events ()
6828 {
6829   if (target_can_async_p ())
6830     {
6831       remote_state *rs = get_remote_state ();
6832
6833       if (async_event_handler_marked (rs->remote_async_inferior_event_token))
6834         return true;
6835
6836       /* Note that BUFCNT can be negative, indicating sticky
6837          error.  */
6838       if (rs->remote_desc->bufcnt != 0)
6839         return true;
6840     }
6841   return false;
6842 }
6843
6844 \f
6845
6846 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
6847    thread, all threads of a remote process, or all threads of all
6848    processes.  */
6849
6850 void
6851 remote_target::remote_stop_ns (ptid_t ptid)
6852 {
6853   struct remote_state *rs = get_remote_state ();
6854   char *p = rs->buf.data ();
6855   char *endp = p + get_remote_packet_size ();
6856
6857   /* If any thread that needs to stop was resumed but pending a vCont
6858      resume, generate a phony stop_reply.  However, first check
6859      whether the thread wasn't resumed with a signal.  Generating a
6860      phony stop in that case would result in losing the signal.  */
6861   bool needs_commit = false;
6862   for (thread_info *tp : all_non_exited_threads (this, ptid))
6863     {
6864       remote_thread_info *remote_thr = get_remote_thread_info (tp);
6865
6866       if (remote_thr->get_resume_state ()
6867           == resume_state::RESUMED_PENDING_VCONT)
6868         {
6869           const resumed_pending_vcont_info &info
6870             = remote_thr->resumed_pending_vcont_info ();
6871           if (info.sig != GDB_SIGNAL_0)
6872             {
6873               /* This signal must be forwarded to the inferior.  We
6874                  could commit-resume just this thread, but its simpler
6875                  to just commit-resume everything.  */
6876               needs_commit = true;
6877               break;
6878             }
6879         }
6880     }
6881
6882   if (needs_commit)
6883     commit_resumed ();
6884   else
6885     for (thread_info *tp : all_non_exited_threads (this, ptid))
6886       {
6887         remote_thread_info *remote_thr = get_remote_thread_info (tp);
6888
6889         if (remote_thr->get_resume_state ()
6890             == resume_state::RESUMED_PENDING_VCONT)
6891           {
6892             remote_debug_printf ("Enqueueing phony stop reply for thread pending "
6893                                  "vCont-resume (%d, %ld, %ld)", tp->ptid.pid(),
6894                                  tp->ptid.lwp (), tp->ptid.tid ());
6895
6896             /* Check that the thread wasn't resumed with a signal.
6897                Generating a phony stop would result in losing the
6898                signal.  */
6899             const resumed_pending_vcont_info &info
6900               = remote_thr->resumed_pending_vcont_info ();
6901             gdb_assert (info.sig == GDB_SIGNAL_0);
6902
6903             stop_reply *sr = new stop_reply ();
6904             sr->ptid = tp->ptid;
6905             sr->rs = rs;
6906             sr->ws.kind = TARGET_WAITKIND_STOPPED;
6907             sr->ws.value.sig = GDB_SIGNAL_0;
6908             sr->arch = tp->inf->gdbarch;
6909             sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6910             sr->watch_data_address = 0;
6911             sr->core = 0;
6912             this->push_stop_reply (sr);
6913
6914             /* Pretend that this thread was actually resumed on the
6915                remote target, then stopped.  If we leave it in the
6916                RESUMED_PENDING_VCONT state and the commit_resumed
6917                method is called while the stop reply is still in the
6918                queue, we'll end up reporting a stop event to the core
6919                for that thread while it is running on the remote
6920                target... that would be bad.  */
6921             remote_thr->set_resumed ();
6922           }
6923       }
6924
6925   /* FIXME: This supports_vCont_probed check is a workaround until
6926      packet_support is per-connection.  */
6927   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN
6928       || !rs->supports_vCont_probed)
6929     remote_vcont_probe ();
6930
6931   if (!rs->supports_vCont.t)
6932     error (_("Remote server does not support stopping threads"));
6933
6934   if (ptid == minus_one_ptid
6935       || (!remote_multi_process_p (rs) && ptid.is_pid ()))
6936     p += xsnprintf (p, endp - p, "vCont;t");
6937   else
6938     {
6939       ptid_t nptid;
6940
6941       p += xsnprintf (p, endp - p, "vCont;t:");
6942
6943       if (ptid.is_pid ())
6944           /* All (-1) threads of process.  */
6945         nptid = ptid_t (ptid.pid (), -1, 0);
6946       else
6947         {
6948           /* Small optimization: if we already have a stop reply for
6949              this thread, no use in telling the stub we want this
6950              stopped.  */
6951           if (peek_stop_reply (ptid))
6952             return;
6953
6954           nptid = ptid;
6955         }
6956
6957       write_ptid (p, endp, nptid);
6958     }
6959
6960   /* In non-stop, we get an immediate OK reply.  The stop reply will
6961      come in asynchronously by notification.  */
6962   putpkt (rs->buf);
6963   getpkt (&rs->buf, 0);
6964   if (strcmp (rs->buf.data (), "OK") != 0)
6965     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
6966            rs->buf.data ());
6967 }
6968
6969 /* All-stop version of target_interrupt.  Sends a break or a ^C to
6970    interrupt the remote target.  It is undefined which thread of which
6971    process reports the interrupt.  */
6972
6973 void
6974 remote_target::remote_interrupt_as ()
6975 {
6976   struct remote_state *rs = get_remote_state ();
6977
6978   rs->ctrlc_pending_p = 1;
6979
6980   /* If the inferior is stopped already, but the core didn't know
6981      about it yet, just ignore the request.  The cached wait status
6982      will be collected in remote_wait.  */
6983   if (rs->cached_wait_status)
6984     return;
6985
6986   /* Send interrupt_sequence to remote target.  */
6987   send_interrupt_sequence ();
6988 }
6989
6990 /* Non-stop version of target_interrupt.  Uses `vCtrlC' to interrupt
6991    the remote target.  It is undefined which thread of which process
6992    reports the interrupt.  Throws an error if the packet is not
6993    supported by the server.  */
6994
6995 void
6996 remote_target::remote_interrupt_ns ()
6997 {
6998   struct remote_state *rs = get_remote_state ();
6999   char *p = rs->buf.data ();
7000   char *endp = p + get_remote_packet_size ();
7001
7002   xsnprintf (p, endp - p, "vCtrlC");
7003
7004   /* In non-stop, we get an immediate OK reply.  The stop reply will
7005      come in asynchronously by notification.  */
7006   putpkt (rs->buf);
7007   getpkt (&rs->buf, 0);
7008
7009   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
7010     {
7011     case PACKET_OK:
7012       break;
7013     case PACKET_UNKNOWN:
7014       error (_("No support for interrupting the remote target."));
7015     case PACKET_ERROR:
7016       error (_("Interrupting target failed: %s"), rs->buf.data ());
7017     }
7018 }
7019
7020 /* Implement the to_stop function for the remote targets.  */
7021
7022 void
7023 remote_target::stop (ptid_t ptid)
7024 {
7025   REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7026
7027   if (target_is_non_stop_p ())
7028     remote_stop_ns (ptid);
7029   else
7030     {
7031       /* We don't currently have a way to transparently pause the
7032          remote target in all-stop mode.  Interrupt it instead.  */
7033       remote_interrupt_as ();
7034     }
7035 }
7036
7037 /* Implement the to_interrupt function for the remote targets.  */
7038
7039 void
7040 remote_target::interrupt ()
7041 {
7042   REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7043
7044   if (target_is_non_stop_p ())
7045     remote_interrupt_ns ();
7046   else
7047     remote_interrupt_as ();
7048 }
7049
7050 /* Implement the to_pass_ctrlc function for the remote targets.  */
7051
7052 void
7053 remote_target::pass_ctrlc ()
7054 {
7055   REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7056
7057   struct remote_state *rs = get_remote_state ();
7058
7059   /* If we're starting up, we're not fully synced yet.  Quit
7060      immediately.  */
7061   if (rs->starting_up)
7062     quit ();
7063   /* If ^C has already been sent once, offer to disconnect.  */
7064   else if (rs->ctrlc_pending_p)
7065     interrupt_query ();
7066   else
7067     target_interrupt ();
7068 }
7069
7070 /* Ask the user what to do when an interrupt is received.  */
7071
7072 void
7073 remote_target::interrupt_query ()
7074 {
7075   struct remote_state *rs = get_remote_state ();
7076
7077   if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7078     {
7079       if (query (_("The target is not responding to interrupt requests.\n"
7080                    "Stop debugging it? ")))
7081         {
7082           remote_unpush_target (this);
7083           throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7084         }
7085     }
7086   else
7087     {
7088       if (query (_("Interrupted while waiting for the program.\n"
7089                    "Give up waiting? ")))
7090         quit ();
7091     }
7092 }
7093
7094 /* Enable/disable target terminal ownership.  Most targets can use
7095    terminal groups to control terminal ownership.  Remote targets are
7096    different in that explicit transfer of ownership to/from GDB/target
7097    is required.  */
7098
7099 void
7100 remote_target::terminal_inferior ()
7101 {
7102   /* NOTE: At this point we could also register our selves as the
7103      recipient of all input.  Any characters typed could then be
7104      passed on down to the target.  */
7105 }
7106
7107 void
7108 remote_target::terminal_ours ()
7109 {
7110 }
7111
7112 static void
7113 remote_console_output (const char *msg)
7114 {
7115   const char *p;
7116
7117   for (p = msg; p[0] && p[1]; p += 2)
7118     {
7119       char tb[2];
7120       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7121
7122       tb[0] = c;
7123       tb[1] = 0;
7124       gdb_stdtarg->puts (tb);
7125     }
7126   gdb_stdtarg->flush ();
7127 }
7128
7129 /* Return the length of the stop reply queue.  */
7130
7131 int
7132 remote_target::stop_reply_queue_length ()
7133 {
7134   remote_state *rs = get_remote_state ();
7135   return rs->stop_reply_queue.size ();
7136 }
7137
7138 static void
7139 remote_notif_stop_parse (remote_target *remote,
7140                          struct notif_client *self, const char *buf,
7141                          struct notif_event *event)
7142 {
7143   remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7144 }
7145
7146 static void
7147 remote_notif_stop_ack (remote_target *remote,
7148                        struct notif_client *self, const char *buf,
7149                        struct notif_event *event)
7150 {
7151   struct stop_reply *stop_reply = (struct stop_reply *) event;
7152
7153   /* acknowledge */
7154   putpkt (remote, self->ack_command);
7155
7156   /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7157      the notification.  It was left in the queue because we need to
7158      acknowledge it and pull the rest of the notifications out.  */
7159   if (stop_reply->ws.kind != TARGET_WAITKIND_IGNORE)
7160     remote->push_stop_reply (stop_reply);
7161 }
7162
7163 static int
7164 remote_notif_stop_can_get_pending_events (remote_target *remote,
7165                                           struct notif_client *self)
7166 {
7167   /* We can't get pending events in remote_notif_process for
7168      notification stop, and we have to do this in remote_wait_ns
7169      instead.  If we fetch all queued events from stub, remote stub
7170      may exit and we have no chance to process them back in
7171      remote_wait_ns.  */
7172   remote_state *rs = remote->get_remote_state ();
7173   mark_async_event_handler (rs->remote_async_inferior_event_token);
7174   return 0;
7175 }
7176
7177 stop_reply::~stop_reply ()
7178 {
7179   for (cached_reg_t &reg : regcache)
7180     xfree (reg.data);
7181 }
7182
7183 static notif_event_up
7184 remote_notif_stop_alloc_reply ()
7185 {
7186   return notif_event_up (new struct stop_reply ());
7187 }
7188
7189 /* A client of notification Stop.  */
7190
7191 struct notif_client notif_client_stop =
7192 {
7193   "Stop",
7194   "vStopped",
7195   remote_notif_stop_parse,
7196   remote_notif_stop_ack,
7197   remote_notif_stop_can_get_pending_events,
7198   remote_notif_stop_alloc_reply,
7199   REMOTE_NOTIF_STOP,
7200 };
7201
7202 /* Determine if THREAD_PTID is a pending fork parent thread.  ARG contains
7203    the pid of the process that owns the threads we want to check, or
7204    -1 if we want to check all threads.  */
7205
7206 static int
7207 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
7208                         ptid_t thread_ptid)
7209 {
7210   if (ws->kind == TARGET_WAITKIND_FORKED
7211       || ws->kind == TARGET_WAITKIND_VFORKED)
7212     {
7213       if (event_pid == -1 || event_pid == thread_ptid.pid ())
7214         return 1;
7215     }
7216
7217   return 0;
7218 }
7219
7220 /* Return the thread's pending status used to determine whether the
7221    thread is a fork parent stopped at a fork event.  */
7222
7223 static struct target_waitstatus *
7224 thread_pending_fork_status (struct thread_info *thread)
7225 {
7226   if (thread->suspend.waitstatus_pending_p)
7227     return &thread->suspend.waitstatus;
7228   else
7229     return &thread->pending_follow;
7230 }
7231
7232 /* Determine if THREAD is a pending fork parent thread.  */
7233
7234 static int
7235 is_pending_fork_parent_thread (struct thread_info *thread)
7236 {
7237   struct target_waitstatus *ws = thread_pending_fork_status (thread);
7238   int pid = -1;
7239
7240   return is_pending_fork_parent (ws, pid, thread->ptid);
7241 }
7242
7243 /* If CONTEXT contains any fork child threads that have not been
7244    reported yet, remove them from the CONTEXT list.  If such a
7245    thread exists it is because we are stopped at a fork catchpoint
7246    and have not yet called follow_fork, which will set up the
7247    host-side data structures for the new process.  */
7248
7249 void
7250 remote_target::remove_new_fork_children (threads_listing_context *context)
7251 {
7252   int pid = -1;
7253   struct notif_client *notif = &notif_client_stop;
7254
7255   /* For any threads stopped at a fork event, remove the corresponding
7256      fork child threads from the CONTEXT list.  */
7257   for (thread_info *thread : all_non_exited_threads (this))
7258     {
7259       struct target_waitstatus *ws = thread_pending_fork_status (thread);
7260
7261       if (is_pending_fork_parent (ws, pid, thread->ptid))
7262         context->remove_thread (ws->value.related_pid);
7263     }
7264
7265   /* Check for any pending fork events (not reported or processed yet)
7266      in process PID and remove those fork child threads from the
7267      CONTEXT list as well.  */
7268   remote_notif_get_pending_events (notif);
7269   for (auto &event : get_remote_state ()->stop_reply_queue)
7270     if (event->ws.kind == TARGET_WAITKIND_FORKED
7271         || event->ws.kind == TARGET_WAITKIND_VFORKED
7272         || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
7273       context->remove_thread (event->ws.value.related_pid);
7274 }
7275
7276 /* Check whether any event pending in the vStopped queue would prevent
7277    a global or process wildcard vCont action.  Clear
7278    *may_global_wildcard if we can't do a global wildcard (vCont;c),
7279    and clear the event inferior's may_wildcard_vcont flag if we can't
7280    do a process-wide wildcard resume (vCont;c:pPID.-1).  */
7281
7282 void
7283 remote_target::check_pending_events_prevent_wildcard_vcont
7284   (int *may_global_wildcard)
7285 {
7286   struct notif_client *notif = &notif_client_stop;
7287
7288   remote_notif_get_pending_events (notif);
7289   for (auto &event : get_remote_state ()->stop_reply_queue)
7290     {
7291       if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
7292           || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
7293         continue;
7294
7295       if (event->ws.kind == TARGET_WAITKIND_FORKED
7296           || event->ws.kind == TARGET_WAITKIND_VFORKED)
7297         *may_global_wildcard = 0;
7298
7299       /* This may be the first time we heard about this process.
7300          Regardless, we must not do a global wildcard resume, otherwise
7301          we'd resume this process too.  */
7302       *may_global_wildcard = 0;
7303       if (event->ptid != null_ptid)
7304         {
7305           inferior *inf = find_inferior_ptid (this, event->ptid);
7306           if (inf != NULL)
7307             get_remote_inferior (inf)->may_wildcard_vcont = false;
7308         }
7309     }
7310 }
7311
7312 /* Discard all pending stop replies of inferior INF.  */
7313
7314 void
7315 remote_target::discard_pending_stop_replies (struct inferior *inf)
7316 {
7317   struct stop_reply *reply;
7318   struct remote_state *rs = get_remote_state ();
7319   struct remote_notif_state *rns = rs->notif_state;
7320
7321   /* This function can be notified when an inferior exists.  When the
7322      target is not remote, the notification state is NULL.  */
7323   if (rs->remote_desc == NULL)
7324     return;
7325
7326   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7327
7328   /* Discard the in-flight notification.  */
7329   if (reply != NULL && reply->ptid.pid () == inf->pid)
7330     {
7331       /* Leave the notification pending, since the server expects that
7332          we acknowledge it with vStopped.  But clear its contents, so
7333          that later on when we acknowledge it, we also discard it.  */
7334       reply->ws.kind = TARGET_WAITKIND_IGNORE;
7335
7336       if (remote_debug)
7337         fprintf_unfiltered (gdb_stdlog,
7338                             "discarded in-flight notification\n");
7339     }
7340
7341   /* Discard the stop replies we have already pulled with
7342      vStopped.  */
7343   auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7344                               rs->stop_reply_queue.end (),
7345                               [=] (const stop_reply_up &event)
7346                               {
7347                                 return event->ptid.pid () == inf->pid;
7348                               });
7349   rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7350 }
7351
7352 /* Discard the stop replies for RS in stop_reply_queue.  */
7353
7354 void
7355 remote_target::discard_pending_stop_replies_in_queue ()
7356 {
7357   remote_state *rs = get_remote_state ();
7358
7359   /* Discard the stop replies we have already pulled with
7360      vStopped.  */
7361   auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7362                               rs->stop_reply_queue.end (),
7363                               [=] (const stop_reply_up &event)
7364                               {
7365                                 return event->rs == rs;
7366                               });
7367   rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7368 }
7369
7370 /* Remove the first reply in 'stop_reply_queue' which matches
7371    PTID.  */
7372
7373 struct stop_reply *
7374 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7375 {
7376   remote_state *rs = get_remote_state ();
7377
7378   auto iter = std::find_if (rs->stop_reply_queue.begin (),
7379                             rs->stop_reply_queue.end (),
7380                             [=] (const stop_reply_up &event)
7381                             {
7382                               return event->ptid.matches (ptid);
7383                             });
7384   struct stop_reply *result;
7385   if (iter == rs->stop_reply_queue.end ())
7386     result = nullptr;
7387   else
7388     {
7389       result = iter->release ();
7390       rs->stop_reply_queue.erase (iter);
7391     }
7392
7393   if (notif_debug)
7394     fprintf_unfiltered (gdb_stdlog,
7395                         "notif: discard queued event: 'Stop' in %s\n",
7396                         target_pid_to_str (ptid).c_str ());
7397
7398   return result;
7399 }
7400
7401 /* Look for a queued stop reply belonging to PTID.  If one is found,
7402    remove it from the queue, and return it.  Returns NULL if none is
7403    found.  If there are still queued events left to process, tell the
7404    event loop to get back to target_wait soon.  */
7405
7406 struct stop_reply *
7407 remote_target::queued_stop_reply (ptid_t ptid)
7408 {
7409   remote_state *rs = get_remote_state ();
7410   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7411
7412   if (!rs->stop_reply_queue.empty ())
7413     {
7414       /* There's still at least an event left.  */
7415       mark_async_event_handler (rs->remote_async_inferior_event_token);
7416     }
7417
7418   return r;
7419 }
7420
7421 /* Push a fully parsed stop reply in the stop reply queue.  Since we
7422    know that we now have at least one queued event left to pass to the
7423    core side, tell the event loop to get back to target_wait soon.  */
7424
7425 void
7426 remote_target::push_stop_reply (struct stop_reply *new_event)
7427 {
7428   remote_state *rs = get_remote_state ();
7429   rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7430
7431   if (notif_debug)
7432     fprintf_unfiltered (gdb_stdlog,
7433                         "notif: push 'Stop' %s to queue %d\n",
7434                         target_pid_to_str (new_event->ptid).c_str (),
7435                         int (rs->stop_reply_queue.size ()));
7436
7437   mark_async_event_handler (rs->remote_async_inferior_event_token);
7438 }
7439
7440 /* Returns true if we have a stop reply for PTID.  */
7441
7442 int
7443 remote_target::peek_stop_reply (ptid_t ptid)
7444 {
7445   remote_state *rs = get_remote_state ();
7446   for (auto &event : rs->stop_reply_queue)
7447     if (ptid == event->ptid
7448         && event->ws.kind == TARGET_WAITKIND_STOPPED)
7449       return 1;
7450   return 0;
7451 }
7452
7453 /* Helper for remote_parse_stop_reply.  Return nonzero if the substring
7454    starting with P and ending with PEND matches PREFIX.  */
7455
7456 static int
7457 strprefix (const char *p, const char *pend, const char *prefix)
7458 {
7459   for ( ; p < pend; p++, prefix++)
7460     if (*p != *prefix)
7461       return 0;
7462   return *prefix == '\0';
7463 }
7464
7465 /* Parse the stop reply in BUF.  Either the function succeeds, and the
7466    result is stored in EVENT, or throws an error.  */
7467
7468 void
7469 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7470 {
7471   remote_arch_state *rsa = NULL;
7472   ULONGEST addr;
7473   const char *p;
7474   int skipregs = 0;
7475
7476   event->ptid = null_ptid;
7477   event->rs = get_remote_state ();
7478   event->ws.kind = TARGET_WAITKIND_IGNORE;
7479   event->ws.value.integer = 0;
7480   event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7481   event->regcache.clear ();
7482   event->core = -1;
7483
7484   switch (buf[0])
7485     {
7486     case 'T':           /* Status with PC, SP, FP, ...  */
7487       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
7488       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
7489             ss = signal number
7490             n... = register number
7491             r... = register contents
7492       */
7493
7494       p = &buf[3];      /* after Txx */
7495       while (*p)
7496         {
7497           const char *p1;
7498           int fieldsize;
7499
7500           p1 = strchr (p, ':');
7501           if (p1 == NULL)
7502             error (_("Malformed packet(a) (missing colon): %s\n\
7503 Packet: '%s'\n"),
7504                    p, buf);
7505           if (p == p1)
7506             error (_("Malformed packet(a) (missing register number): %s\n\
7507 Packet: '%s'\n"),
7508                    p, buf);
7509
7510           /* Some "registers" are actually extended stop information.
7511              Note if you're adding a new entry here: GDB 7.9 and
7512              earlier assume that all register "numbers" that start
7513              with an hex digit are real register numbers.  Make sure
7514              the server only sends such a packet if it knows the
7515              client understands it.  */
7516
7517           if (strprefix (p, p1, "thread"))
7518             event->ptid = read_ptid (++p1, &p);
7519           else if (strprefix (p, p1, "syscall_entry"))
7520             {
7521               ULONGEST sysno;
7522
7523               event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7524               p = unpack_varlen_hex (++p1, &sysno);
7525               event->ws.value.syscall_number = (int) sysno;
7526             }
7527           else if (strprefix (p, p1, "syscall_return"))
7528             {
7529               ULONGEST sysno;
7530
7531               event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7532               p = unpack_varlen_hex (++p1, &sysno);
7533               event->ws.value.syscall_number = (int) sysno;
7534             }
7535           else if (strprefix (p, p1, "watch")
7536                    || strprefix (p, p1, "rwatch")
7537                    || strprefix (p, p1, "awatch"))
7538             {
7539               event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7540               p = unpack_varlen_hex (++p1, &addr);
7541               event->watch_data_address = (CORE_ADDR) addr;
7542             }
7543           else if (strprefix (p, p1, "swbreak"))
7544             {
7545               event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7546
7547               /* Make sure the stub doesn't forget to indicate support
7548                  with qSupported.  */
7549               if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7550                 error (_("Unexpected swbreak stop reason"));
7551
7552               /* The value part is documented as "must be empty",
7553                  though we ignore it, in case we ever decide to make
7554                  use of it in a backward compatible way.  */
7555               p = strchrnul (p1 + 1, ';');
7556             }
7557           else if (strprefix (p, p1, "hwbreak"))
7558             {
7559               event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7560
7561               /* Make sure the stub doesn't forget to indicate support
7562                  with qSupported.  */
7563               if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7564                 error (_("Unexpected hwbreak stop reason"));
7565
7566               /* See above.  */
7567               p = strchrnul (p1 + 1, ';');
7568             }
7569           else if (strprefix (p, p1, "library"))
7570             {
7571               event->ws.kind = TARGET_WAITKIND_LOADED;
7572               p = strchrnul (p1 + 1, ';');
7573             }
7574           else if (strprefix (p, p1, "replaylog"))
7575             {
7576               event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7577               /* p1 will indicate "begin" or "end", but it makes
7578                  no difference for now, so ignore it.  */
7579               p = strchrnul (p1 + 1, ';');
7580             }
7581           else if (strprefix (p, p1, "core"))
7582             {
7583               ULONGEST c;
7584
7585               p = unpack_varlen_hex (++p1, &c);
7586               event->core = c;
7587             }
7588           else if (strprefix (p, p1, "fork"))
7589             {
7590               event->ws.value.related_pid = read_ptid (++p1, &p);
7591               event->ws.kind = TARGET_WAITKIND_FORKED;
7592             }
7593           else if (strprefix (p, p1, "vfork"))
7594             {
7595               event->ws.value.related_pid = read_ptid (++p1, &p);
7596               event->ws.kind = TARGET_WAITKIND_VFORKED;
7597             }
7598           else if (strprefix (p, p1, "vforkdone"))
7599             {
7600               event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
7601               p = strchrnul (p1 + 1, ';');
7602             }
7603           else if (strprefix (p, p1, "exec"))
7604             {
7605               ULONGEST ignored;
7606               int pathlen;
7607
7608               /* Determine the length of the execd pathname.  */
7609               p = unpack_varlen_hex (++p1, &ignored);
7610               pathlen = (p - p1) / 2;
7611
7612               /* Save the pathname for event reporting and for
7613                  the next run command.  */
7614               gdb::unique_xmalloc_ptr<char[]> pathname
7615                 ((char *) xmalloc (pathlen + 1));
7616               hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
7617               pathname[pathlen] = '\0';
7618
7619               /* This is freed during event handling.  */
7620               event->ws.value.execd_pathname = pathname.release ();
7621               event->ws.kind = TARGET_WAITKIND_EXECD;
7622
7623               /* Skip the registers included in this packet, since
7624                  they may be for an architecture different from the
7625                  one used by the original program.  */
7626               skipregs = 1;
7627             }
7628           else if (strprefix (p, p1, "create"))
7629             {
7630               event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
7631               p = strchrnul (p1 + 1, ';');
7632             }
7633           else
7634             {
7635               ULONGEST pnum;
7636               const char *p_temp;
7637
7638               if (skipregs)
7639                 {
7640                   p = strchrnul (p1 + 1, ';');
7641                   p++;
7642                   continue;
7643                 }
7644
7645               /* Maybe a real ``P'' register number.  */
7646               p_temp = unpack_varlen_hex (p, &pnum);
7647               /* If the first invalid character is the colon, we got a
7648                  register number.  Otherwise, it's an unknown stop
7649                  reason.  */
7650               if (p_temp == p1)
7651                 {
7652                   /* If we haven't parsed the event's thread yet, find
7653                      it now, in order to find the architecture of the
7654                      reported expedited registers.  */
7655                   if (event->ptid == null_ptid)
7656                     {
7657                       /* If there is no thread-id information then leave
7658                          the event->ptid as null_ptid.  Later in
7659                          process_stop_reply we will pick a suitable
7660                          thread.  */
7661                       const char *thr = strstr (p1 + 1, ";thread:");
7662                       if (thr != NULL)
7663                         event->ptid = read_ptid (thr + strlen (";thread:"),
7664                                                  NULL);
7665                     }
7666
7667                   if (rsa == NULL)
7668                     {
7669                       inferior *inf
7670                         = (event->ptid == null_ptid
7671                            ? NULL
7672                            : find_inferior_ptid (this, event->ptid));
7673                       /* If this is the first time we learn anything
7674                          about this process, skip the registers
7675                          included in this packet, since we don't yet
7676                          know which architecture to use to parse them.
7677                          We'll determine the architecture later when
7678                          we process the stop reply and retrieve the
7679                          target description, via
7680                          remote_notice_new_inferior ->
7681                          post_create_inferior.  */
7682                       if (inf == NULL)
7683                         {
7684                           p = strchrnul (p1 + 1, ';');
7685                           p++;
7686                           continue;
7687                         }
7688
7689                       event->arch = inf->gdbarch;
7690                       rsa = event->rs->get_remote_arch_state (event->arch);
7691                     }
7692
7693                   packet_reg *reg
7694                     = packet_reg_from_pnum (event->arch, rsa, pnum);
7695                   cached_reg_t cached_reg;
7696
7697                   if (reg == NULL)
7698                     error (_("Remote sent bad register number %s: %s\n\
7699 Packet: '%s'\n"),
7700                            hex_string (pnum), p, buf);
7701
7702                   cached_reg.num = reg->regnum;
7703                   cached_reg.data = (gdb_byte *)
7704                     xmalloc (register_size (event->arch, reg->regnum));
7705
7706                   p = p1 + 1;
7707                   fieldsize = hex2bin (p, cached_reg.data,
7708                                        register_size (event->arch, reg->regnum));
7709                   p += 2 * fieldsize;
7710                   if (fieldsize < register_size (event->arch, reg->regnum))
7711                     warning (_("Remote reply is too short: %s"), buf);
7712
7713                   event->regcache.push_back (cached_reg);
7714                 }
7715               else
7716                 {
7717                   /* Not a number.  Silently skip unknown optional
7718                      info.  */
7719                   p = strchrnul (p1 + 1, ';');
7720                 }
7721             }
7722
7723           if (*p != ';')
7724             error (_("Remote register badly formatted: %s\nhere: %s"),
7725                    buf, p);
7726           ++p;
7727         }
7728
7729       if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7730         break;
7731
7732       /* fall through */
7733     case 'S':           /* Old style status, just signal only.  */
7734       {
7735         int sig;
7736
7737         event->ws.kind = TARGET_WAITKIND_STOPPED;
7738         sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7739         if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7740           event->ws.value.sig = (enum gdb_signal) sig;
7741         else
7742           event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7743       }
7744       break;
7745     case 'w':           /* Thread exited.  */
7746       {
7747         ULONGEST value;
7748
7749         event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7750         p = unpack_varlen_hex (&buf[1], &value);
7751         event->ws.value.integer = value;
7752         if (*p != ';')
7753           error (_("stop reply packet badly formatted: %s"), buf);
7754         event->ptid = read_ptid (++p, NULL);
7755         break;
7756       }
7757     case 'W':           /* Target exited.  */
7758     case 'X':
7759       {
7760         ULONGEST value;
7761
7762         /* GDB used to accept only 2 hex chars here.  Stubs should
7763            only send more if they detect GDB supports multi-process
7764            support.  */
7765         p = unpack_varlen_hex (&buf[1], &value);
7766
7767         if (buf[0] == 'W')
7768           {
7769             /* The remote process exited.  */
7770             event->ws.kind = TARGET_WAITKIND_EXITED;
7771             event->ws.value.integer = value;
7772           }
7773         else
7774           {
7775             /* The remote process exited with a signal.  */
7776             event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7777             if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7778               event->ws.value.sig = (enum gdb_signal) value;
7779             else
7780               event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7781           }
7782
7783         /* If no process is specified, return null_ptid, and let the
7784            caller figure out the right process to use.  */
7785         int pid = 0;
7786         if (*p == '\0')
7787           ;
7788         else if (*p == ';')
7789           {
7790             p++;
7791
7792             if (*p == '\0')
7793               ;
7794             else if (startswith (p, "process:"))
7795               {
7796                 ULONGEST upid;
7797
7798                 p += sizeof ("process:") - 1;
7799                 unpack_varlen_hex (p, &upid);
7800                 pid = upid;
7801               }
7802             else
7803               error (_("unknown stop reply packet: %s"), buf);
7804           }
7805         else
7806           error (_("unknown stop reply packet: %s"), buf);
7807         event->ptid = ptid_t (pid);
7808       }
7809       break;
7810     case 'N':
7811       event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7812       event->ptid = minus_one_ptid;
7813       break;
7814     }
7815 }
7816
7817 /* When the stub wants to tell GDB about a new notification reply, it
7818    sends a notification (%Stop, for example).  Those can come it at
7819    any time, hence, we have to make sure that any pending
7820    putpkt/getpkt sequence we're making is finished, before querying
7821    the stub for more events with the corresponding ack command
7822    (vStopped, for example).  E.g., if we started a vStopped sequence
7823    immediately upon receiving the notification, something like this
7824    could happen:
7825
7826     1.1) --> Hg 1
7827     1.2) <-- OK
7828     1.3) --> g
7829     1.4) <-- %Stop
7830     1.5) --> vStopped
7831     1.6) <-- (registers reply to step #1.3)
7832
7833    Obviously, the reply in step #1.6 would be unexpected to a vStopped
7834    query.
7835
7836    To solve this, whenever we parse a %Stop notification successfully,
7837    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7838    doing whatever we were doing:
7839
7840     2.1) --> Hg 1
7841     2.2) <-- OK
7842     2.3) --> g
7843     2.4) <-- %Stop
7844       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7845     2.5) <-- (registers reply to step #2.3)
7846
7847    Eventually after step #2.5, we return to the event loop, which
7848    notices there's an event on the
7849    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7850    associated callback --- the function below.  At this point, we're
7851    always safe to start a vStopped sequence. :
7852
7853     2.6) --> vStopped
7854     2.7) <-- T05 thread:2
7855     2.8) --> vStopped
7856     2.9) --> OK
7857 */
7858
7859 void
7860 remote_target::remote_notif_get_pending_events (notif_client *nc)
7861 {
7862   struct remote_state *rs = get_remote_state ();
7863
7864   if (rs->notif_state->pending_event[nc->id] != NULL)
7865     {
7866       if (notif_debug)
7867         fprintf_unfiltered (gdb_stdlog,
7868                             "notif: process: '%s' ack pending event\n",
7869                             nc->name);
7870
7871       /* acknowledge */
7872       nc->ack (this, nc, rs->buf.data (),
7873                rs->notif_state->pending_event[nc->id]);
7874       rs->notif_state->pending_event[nc->id] = NULL;
7875
7876       while (1)
7877         {
7878           getpkt (&rs->buf, 0);
7879           if (strcmp (rs->buf.data (), "OK") == 0)
7880             break;
7881           else
7882             remote_notif_ack (this, nc, rs->buf.data ());
7883         }
7884     }
7885   else
7886     {
7887       if (notif_debug)
7888         fprintf_unfiltered (gdb_stdlog,
7889                             "notif: process: '%s' no pending reply\n",
7890                             nc->name);
7891     }
7892 }
7893
7894 /* Wrapper around remote_target::remote_notif_get_pending_events to
7895    avoid having to export the whole remote_target class.  */
7896
7897 void
7898 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7899 {
7900   remote->remote_notif_get_pending_events (nc);
7901 }
7902
7903 /* Called from process_stop_reply when the stop packet we are responding
7904    to didn't include a process-id or thread-id.  STATUS is the stop event
7905    we are responding to.
7906
7907    It is the task of this function to select a suitable thread (or process)
7908    and return its ptid, this is the thread (or process) we will assume the
7909    stop event came from.
7910
7911    In some cases there isn't really any choice about which thread (or
7912    process) is selected, a basic remote with a single process containing a
7913    single thread might choose not to send any process-id or thread-id in
7914    its stop packets, this function will select and return the one and only
7915    thread.
7916
7917    However, if a target supports multiple threads (or processes) and still
7918    doesn't include a thread-id (or process-id) in its stop packet then
7919    first, this is a badly behaving target, and second, we're going to have
7920    to select a thread (or process) at random and use that.  This function
7921    will print a warning to the user if it detects that there is the
7922    possibility that GDB is guessing which thread (or process) to
7923    report.
7924
7925    Note that this is called before GDB fetches the updated thread list from the
7926    target.  So it's possible for the stop reply to be ambiguous and for GDB to
7927    not realize it.  For example, if there's initially one thread, the target
7928    spawns a second thread, and then sends a stop reply without an id that
7929    concerns the first thread.  GDB will assume the stop reply is about the
7930    first thread - the only thread it knows about - without printing a warning.
7931    Anyway, if the remote meant for the stop reply to be about the second thread,
7932    then it would be really broken, because GDB doesn't know about that thread
7933    yet.  */
7934
7935 ptid_t
7936 remote_target::select_thread_for_ambiguous_stop_reply
7937   (const struct target_waitstatus *status)
7938 {
7939   /* Some stop events apply to all threads in an inferior, while others
7940      only apply to a single thread.  */
7941   bool process_wide_stop
7942     = (status->kind == TARGET_WAITKIND_EXITED
7943        || status->kind == TARGET_WAITKIND_SIGNALLED);
7944
7945   thread_info *first_resumed_thread = nullptr;
7946   bool ambiguous = false;
7947
7948   /* Consider all non-exited threads of the target, find the first resumed
7949      one.  */
7950   for (thread_info *thr : all_non_exited_threads (this))
7951     {
7952       remote_thread_info *remote_thr = get_remote_thread_info (thr);
7953
7954       if (remote_thr->get_resume_state () != resume_state::RESUMED)
7955         continue;
7956
7957       if (first_resumed_thread == nullptr)
7958         first_resumed_thread = thr;
7959       else if (!process_wide_stop
7960                || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
7961         ambiguous = true;
7962     }
7963
7964   gdb_assert (first_resumed_thread != nullptr);
7965
7966   /* Warn if the remote target is sending ambiguous stop replies.  */
7967   if (ambiguous)
7968     {
7969       static bool warned = false;
7970
7971       if (!warned)
7972         {
7973           /* If you are seeing this warning then the remote target has
7974              stopped without specifying a thread-id, but the target
7975              does have multiple threads (or inferiors), and so GDB is
7976              having to guess which thread stopped.
7977
7978              Examples of what might cause this are the target sending
7979              and 'S' stop packet, or a 'T' stop packet and not
7980              including a thread-id.
7981
7982              Additionally, the target might send a 'W' or 'X packet
7983              without including a process-id, when the target has
7984              multiple running inferiors.  */
7985           if (process_wide_stop)
7986             warning (_("multi-inferior target stopped without "
7987                        "sending a process-id, using first "
7988                        "non-exited inferior"));
7989           else
7990             warning (_("multi-threaded target stopped without "
7991                        "sending a thread-id, using first "
7992                        "non-exited thread"));
7993           warned = true;
7994         }
7995     }
7996
7997   /* If this is a stop for all threads then don't use a particular threads
7998      ptid, instead create a new ptid where only the pid field is set.  */
7999   if (process_wide_stop)
8000     return ptid_t (first_resumed_thread->ptid.pid ());
8001   else
8002     return first_resumed_thread->ptid;
8003 }
8004
8005 /* Called when it is decided that STOP_REPLY holds the info of the
8006    event that is to be returned to the core.  This function always
8007    destroys STOP_REPLY.  */
8008
8009 ptid_t
8010 remote_target::process_stop_reply (struct stop_reply *stop_reply,
8011                                    struct target_waitstatus *status)
8012 {
8013   *status = stop_reply->ws;
8014   ptid_t ptid = stop_reply->ptid;
8015
8016   /* If no thread/process was reported by the stub then select a suitable
8017      thread/process.  */
8018   if (ptid == null_ptid)
8019     ptid = select_thread_for_ambiguous_stop_reply (status);
8020   gdb_assert (ptid != null_ptid);
8021
8022   if (status->kind != TARGET_WAITKIND_EXITED
8023       && status->kind != TARGET_WAITKIND_SIGNALLED
8024       && status->kind != TARGET_WAITKIND_NO_RESUMED)
8025     {
8026       /* Expedited registers.  */
8027       if (!stop_reply->regcache.empty ())
8028         {
8029           struct regcache *regcache
8030             = get_thread_arch_regcache (this, ptid, stop_reply->arch);
8031
8032           for (cached_reg_t &reg : stop_reply->regcache)
8033             {
8034               regcache->raw_supply (reg.num, reg.data);
8035               xfree (reg.data);
8036             }
8037
8038           stop_reply->regcache.clear ();
8039         }
8040
8041       remote_notice_new_inferior (ptid, 0);
8042       remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8043       remote_thr->core = stop_reply->core;
8044       remote_thr->stop_reason = stop_reply->stop_reason;
8045       remote_thr->watch_data_address = stop_reply->watch_data_address;
8046
8047       if (target_is_non_stop_p ())
8048         {
8049           /* If the target works in non-stop mode, a stop-reply indicates that
8050              only this thread stopped.  */
8051           remote_thr->set_not_resumed ();
8052         }
8053       else
8054         {
8055           /* If the target works in all-stop mode, a stop-reply indicates that
8056              all the target's threads stopped.  */
8057           for (thread_info *tp : all_non_exited_threads (this))
8058             get_remote_thread_info (tp)->set_not_resumed ();
8059         }
8060     }
8061
8062   delete stop_reply;
8063   return ptid;
8064 }
8065
8066 /* The non-stop mode version of target_wait.  */
8067
8068 ptid_t
8069 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8070                         target_wait_flags options)
8071 {
8072   struct remote_state *rs = get_remote_state ();
8073   struct stop_reply *stop_reply;
8074   int ret;
8075   int is_notif = 0;
8076
8077   /* If in non-stop mode, get out of getpkt even if a
8078      notification is received.  */
8079
8080   ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
8081   while (1)
8082     {
8083       if (ret != -1 && !is_notif)
8084         switch (rs->buf[0])
8085           {
8086           case 'E':             /* Error of some sort.  */
8087             /* We're out of sync with the target now.  Did it continue
8088                or not?  We can't tell which thread it was in non-stop,
8089                so just ignore this.  */
8090             warning (_("Remote failure reply: %s"), rs->buf.data ());
8091             break;
8092           case 'O':             /* Console output.  */
8093             remote_console_output (&rs->buf[1]);
8094             break;
8095           default:
8096             warning (_("Invalid remote reply: %s"), rs->buf.data ());
8097             break;
8098           }
8099
8100       /* Acknowledge a pending stop reply that may have arrived in the
8101          mean time.  */
8102       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8103         remote_notif_get_pending_events (&notif_client_stop);
8104
8105       /* If indeed we noticed a stop reply, we're done.  */
8106       stop_reply = queued_stop_reply (ptid);
8107       if (stop_reply != NULL)
8108         return process_stop_reply (stop_reply, status);
8109
8110       /* Still no event.  If we're just polling for an event, then
8111          return to the event loop.  */
8112       if (options & TARGET_WNOHANG)
8113         {
8114           status->kind = TARGET_WAITKIND_IGNORE;
8115           return minus_one_ptid;
8116         }
8117
8118       /* Otherwise do a blocking wait.  */
8119       ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
8120     }
8121 }
8122
8123 /* Return the first resumed thread.  */
8124
8125 static ptid_t
8126 first_remote_resumed_thread (remote_target *target)
8127 {
8128   for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8129     if (tp->resumed)
8130       return tp->ptid;
8131   return null_ptid;
8132 }
8133
8134 /* Wait until the remote machine stops, then return, storing status in
8135    STATUS just as `wait' would.  */
8136
8137 ptid_t
8138 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8139                         target_wait_flags options)
8140 {
8141   struct remote_state *rs = get_remote_state ();
8142   ptid_t event_ptid = null_ptid;
8143   char *buf;
8144   struct stop_reply *stop_reply;
8145
8146  again:
8147
8148   status->kind = TARGET_WAITKIND_IGNORE;
8149   status->value.integer = 0;
8150
8151   stop_reply = queued_stop_reply (ptid);
8152   if (stop_reply != NULL)
8153     return process_stop_reply (stop_reply, status);
8154
8155   if (rs->cached_wait_status)
8156     /* Use the cached wait status, but only once.  */
8157     rs->cached_wait_status = 0;
8158   else
8159     {
8160       int ret;
8161       int is_notif;
8162       int forever = ((options & TARGET_WNOHANG) == 0
8163                      && rs->wait_forever_enabled_p);
8164
8165       if (!rs->waiting_for_stop_reply)
8166         {
8167           status->kind = TARGET_WAITKIND_NO_RESUMED;
8168           return minus_one_ptid;
8169         }
8170
8171       /* FIXME: cagney/1999-09-27: If we're in async mode we should
8172          _never_ wait for ever -> test on target_is_async_p().
8173          However, before we do that we need to ensure that the caller
8174          knows how to take the target into/out of async mode.  */
8175       ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
8176
8177       /* GDB gets a notification.  Return to core as this event is
8178          not interesting.  */
8179       if (ret != -1 && is_notif)
8180         return minus_one_ptid;
8181
8182       if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8183         return minus_one_ptid;
8184     }
8185
8186   buf = rs->buf.data ();
8187
8188   /* Assume that the target has acknowledged Ctrl-C unless we receive
8189      an 'F' or 'O' packet.  */
8190   if (buf[0] != 'F' && buf[0] != 'O')
8191     rs->ctrlc_pending_p = 0;
8192
8193   switch (buf[0])
8194     {
8195     case 'E':           /* Error of some sort.  */
8196       /* We're out of sync with the target now.  Did it continue or
8197          not?  Not is more likely, so report a stop.  */
8198       rs->waiting_for_stop_reply = 0;
8199
8200       warning (_("Remote failure reply: %s"), buf);
8201       status->kind = TARGET_WAITKIND_STOPPED;
8202       status->value.sig = GDB_SIGNAL_0;
8203       break;
8204     case 'F':           /* File-I/O request.  */
8205       /* GDB may access the inferior memory while handling the File-I/O
8206          request, but we don't want GDB accessing memory while waiting
8207          for a stop reply.  See the comments in putpkt_binary.  Set
8208          waiting_for_stop_reply to 0 temporarily.  */
8209       rs->waiting_for_stop_reply = 0;
8210       remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8211       rs->ctrlc_pending_p = 0;
8212       /* GDB handled the File-I/O request, and the target is running
8213          again.  Keep waiting for events.  */
8214       rs->waiting_for_stop_reply = 1;
8215       break;
8216     case 'N': case 'T': case 'S': case 'X': case 'W':
8217       {
8218         /* There is a stop reply to handle.  */
8219         rs->waiting_for_stop_reply = 0;
8220
8221         stop_reply
8222           = (struct stop_reply *) remote_notif_parse (this,
8223                                                       &notif_client_stop,
8224                                                       rs->buf.data ());
8225
8226         event_ptid = process_stop_reply (stop_reply, status);
8227         break;
8228       }
8229     case 'O':           /* Console output.  */
8230       remote_console_output (buf + 1);
8231       break;
8232     case '\0':
8233       if (rs->last_sent_signal != GDB_SIGNAL_0)
8234         {
8235           /* Zero length reply means that we tried 'S' or 'C' and the
8236              remote system doesn't support it.  */
8237           target_terminal::ours_for_output ();
8238           printf_filtered
8239             ("Can't send signals to this remote system.  %s not sent.\n",
8240              gdb_signal_to_name (rs->last_sent_signal));
8241           rs->last_sent_signal = GDB_SIGNAL_0;
8242           target_terminal::inferior ();
8243
8244           strcpy (buf, rs->last_sent_step ? "s" : "c");
8245           putpkt (buf);
8246           break;
8247         }
8248       /* fallthrough */
8249     default:
8250       warning (_("Invalid remote reply: %s"), buf);
8251       break;
8252     }
8253
8254   if (status->kind == TARGET_WAITKIND_NO_RESUMED)
8255     return minus_one_ptid;
8256   else if (status->kind == TARGET_WAITKIND_IGNORE)
8257     {
8258       /* Nothing interesting happened.  If we're doing a non-blocking
8259          poll, we're done.  Otherwise, go back to waiting.  */
8260       if (options & TARGET_WNOHANG)
8261         return minus_one_ptid;
8262       else
8263         goto again;
8264     }
8265   else if (status->kind != TARGET_WAITKIND_EXITED
8266            && status->kind != TARGET_WAITKIND_SIGNALLED)
8267     {
8268       if (event_ptid != null_ptid)
8269         record_currthread (rs, event_ptid);
8270       else
8271         event_ptid = first_remote_resumed_thread (this);
8272     }
8273   else
8274     {
8275       /* A process exit.  Invalidate our notion of current thread.  */
8276       record_currthread (rs, minus_one_ptid);
8277       /* It's possible that the packet did not include a pid.  */
8278       if (event_ptid == null_ptid)
8279         event_ptid = first_remote_resumed_thread (this);
8280       /* EVENT_PTID could still be NULL_PTID.  Double-check.  */
8281       if (event_ptid == null_ptid)
8282         event_ptid = magic_null_ptid;
8283     }
8284
8285   return event_ptid;
8286 }
8287
8288 /* Wait until the remote machine stops, then return, storing status in
8289    STATUS just as `wait' would.  */
8290
8291 ptid_t
8292 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8293                      target_wait_flags options)
8294 {
8295   REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8296
8297   remote_state *rs = get_remote_state ();
8298
8299   /* Start by clearing the flag that asks for our wait method to be called,
8300      we'll mark it again at the end if needed.  */
8301   if (target_is_async_p ())
8302     clear_async_event_handler (rs->remote_async_inferior_event_token);
8303
8304   ptid_t event_ptid;
8305
8306   if (target_is_non_stop_p ())
8307     event_ptid = wait_ns (ptid, status, options);
8308   else
8309     event_ptid = wait_as (ptid, status, options);
8310
8311   if (target_is_async_p ())
8312     {
8313       /* If there are events left in the queue, or unacknowledged
8314          notifications, then tell the event loop to call us again.  */
8315       if (!rs->stop_reply_queue.empty ()
8316           || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8317         mark_async_event_handler (rs->remote_async_inferior_event_token);
8318     }
8319
8320   return event_ptid;
8321 }
8322
8323 /* Fetch a single register using a 'p' packet.  */
8324
8325 int
8326 remote_target::fetch_register_using_p (struct regcache *regcache,
8327                                        packet_reg *reg)
8328 {
8329   struct gdbarch *gdbarch = regcache->arch ();
8330   struct remote_state *rs = get_remote_state ();
8331   char *buf, *p;
8332   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8333   int i;
8334
8335   if (packet_support (PACKET_p) == PACKET_DISABLE)
8336     return 0;
8337
8338   if (reg->pnum == -1)
8339     return 0;
8340
8341   p = rs->buf.data ();
8342   *p++ = 'p';
8343   p += hexnumstr (p, reg->pnum);
8344   *p++ = '\0';
8345   putpkt (rs->buf);
8346   getpkt (&rs->buf, 0);
8347
8348   buf = rs->buf.data ();
8349
8350   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_p]))
8351     {
8352     case PACKET_OK:
8353       break;
8354     case PACKET_UNKNOWN:
8355       return 0;
8356     case PACKET_ERROR:
8357       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8358              gdbarch_register_name (regcache->arch (), 
8359                                     reg->regnum), 
8360              buf);
8361     }
8362
8363   /* If this register is unfetchable, tell the regcache.  */
8364   if (buf[0] == 'x')
8365     {
8366       regcache->raw_supply (reg->regnum, NULL);
8367       return 1;
8368     }
8369
8370   /* Otherwise, parse and supply the value.  */
8371   p = buf;
8372   i = 0;
8373   while (p[0] != 0)
8374     {
8375       if (p[1] == 0)
8376         error (_("fetch_register_using_p: early buf termination"));
8377
8378       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8379       p += 2;
8380     }
8381   regcache->raw_supply (reg->regnum, regp);
8382   return 1;
8383 }
8384
8385 /* Fetch the registers included in the target's 'g' packet.  */
8386
8387 int
8388 remote_target::send_g_packet ()
8389 {
8390   struct remote_state *rs = get_remote_state ();
8391   int buf_len;
8392
8393   xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8394   putpkt (rs->buf);
8395   getpkt (&rs->buf, 0);
8396   if (packet_check_result (rs->buf) == PACKET_ERROR)
8397     error (_("Could not read registers; remote failure reply '%s'"),
8398            rs->buf.data ());
8399
8400   /* We can get out of synch in various cases.  If the first character
8401      in the buffer is not a hex character, assume that has happened
8402      and try to fetch another packet to read.  */
8403   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8404          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8405          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8406          && rs->buf[0] != 'x')  /* New: unavailable register value.  */
8407     {
8408       remote_debug_printf ("Bad register packet; fetching a new packet");
8409       getpkt (&rs->buf, 0);
8410     }
8411
8412   buf_len = strlen (rs->buf.data ());
8413
8414   /* Sanity check the received packet.  */
8415   if (buf_len % 2 != 0)
8416     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8417
8418   return buf_len / 2;
8419 }
8420
8421 void
8422 remote_target::process_g_packet (struct regcache *regcache)
8423 {
8424   struct gdbarch *gdbarch = regcache->arch ();
8425   struct remote_state *rs = get_remote_state ();
8426   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8427   int i, buf_len;
8428   char *p;
8429   char *regs;
8430
8431   buf_len = strlen (rs->buf.data ());
8432
8433   /* Further sanity checks, with knowledge of the architecture.  */
8434   if (buf_len > 2 * rsa->sizeof_g_packet)
8435     error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8436              "bytes): %s"),
8437            rsa->sizeof_g_packet, buf_len / 2,
8438            rs->buf.data ());
8439
8440   /* Save the size of the packet sent to us by the target.  It is used
8441      as a heuristic when determining the max size of packets that the
8442      target can safely receive.  */
8443   if (rsa->actual_register_packet_size == 0)
8444     rsa->actual_register_packet_size = buf_len;
8445
8446   /* If this is smaller than we guessed the 'g' packet would be,
8447      update our records.  A 'g' reply that doesn't include a register's
8448      value implies either that the register is not available, or that
8449      the 'p' packet must be used.  */
8450   if (buf_len < 2 * rsa->sizeof_g_packet)
8451     {
8452       long sizeof_g_packet = buf_len / 2;
8453
8454       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8455         {
8456           long offset = rsa->regs[i].offset;
8457           long reg_size = register_size (gdbarch, i);
8458
8459           if (rsa->regs[i].pnum == -1)
8460             continue;
8461
8462           if (offset >= sizeof_g_packet)
8463             rsa->regs[i].in_g_packet = 0;
8464           else if (offset + reg_size > sizeof_g_packet)
8465             error (_("Truncated register %d in remote 'g' packet"), i);
8466           else
8467             rsa->regs[i].in_g_packet = 1;
8468         }
8469
8470       /* Looks valid enough, we can assume this is the correct length
8471          for a 'g' packet.  It's important not to adjust
8472          rsa->sizeof_g_packet if we have truncated registers otherwise
8473          this "if" won't be run the next time the method is called
8474          with a packet of the same size and one of the internal errors
8475          below will trigger instead.  */
8476       rsa->sizeof_g_packet = sizeof_g_packet;
8477     }
8478
8479   regs = (char *) alloca (rsa->sizeof_g_packet);
8480
8481   /* Unimplemented registers read as all bits zero.  */
8482   memset (regs, 0, rsa->sizeof_g_packet);
8483
8484   /* Reply describes registers byte by byte, each byte encoded as two
8485      hex characters.  Suck them all up, then supply them to the
8486      register cacheing/storage mechanism.  */
8487
8488   p = rs->buf.data ();
8489   for (i = 0; i < rsa->sizeof_g_packet; i++)
8490     {
8491       if (p[0] == 0 || p[1] == 0)
8492         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
8493         internal_error (__FILE__, __LINE__,
8494                         _("unexpected end of 'g' packet reply"));
8495
8496       if (p[0] == 'x' && p[1] == 'x')
8497         regs[i] = 0;            /* 'x' */
8498       else
8499         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8500       p += 2;
8501     }
8502
8503   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8504     {
8505       struct packet_reg *r = &rsa->regs[i];
8506       long reg_size = register_size (gdbarch, i);
8507
8508       if (r->in_g_packet)
8509         {
8510           if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8511             /* This shouldn't happen - we adjusted in_g_packet above.  */
8512             internal_error (__FILE__, __LINE__,
8513                             _("unexpected end of 'g' packet reply"));
8514           else if (rs->buf[r->offset * 2] == 'x')
8515             {
8516               gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8517               /* The register isn't available, mark it as such (at
8518                  the same time setting the value to zero).  */
8519               regcache->raw_supply (r->regnum, NULL);
8520             }
8521           else
8522             regcache->raw_supply (r->regnum, regs + r->offset);
8523         }
8524     }
8525 }
8526
8527 void
8528 remote_target::fetch_registers_using_g (struct regcache *regcache)
8529 {
8530   send_g_packet ();
8531   process_g_packet (regcache);
8532 }
8533
8534 /* Make the remote selected traceframe match GDB's selected
8535    traceframe.  */
8536
8537 void
8538 remote_target::set_remote_traceframe ()
8539 {
8540   int newnum;
8541   struct remote_state *rs = get_remote_state ();
8542
8543   if (rs->remote_traceframe_number == get_traceframe_number ())
8544     return;
8545
8546   /* Avoid recursion, remote_trace_find calls us again.  */
8547   rs->remote_traceframe_number = get_traceframe_number ();
8548
8549   newnum = target_trace_find (tfind_number,
8550                               get_traceframe_number (), 0, 0, NULL);
8551
8552   /* Should not happen.  If it does, all bets are off.  */
8553   if (newnum != get_traceframe_number ())
8554     warning (_("could not set remote traceframe"));
8555 }
8556
8557 void
8558 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8559 {
8560   struct gdbarch *gdbarch = regcache->arch ();
8561   struct remote_state *rs = get_remote_state ();
8562   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8563   int i;
8564
8565   set_remote_traceframe ();
8566   set_general_thread (regcache->ptid ());
8567
8568   if (regnum >= 0)
8569     {
8570       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8571
8572       gdb_assert (reg != NULL);
8573
8574       /* If this register might be in the 'g' packet, try that first -
8575          we are likely to read more than one register.  If this is the
8576          first 'g' packet, we might be overly optimistic about its
8577          contents, so fall back to 'p'.  */
8578       if (reg->in_g_packet)
8579         {
8580           fetch_registers_using_g (regcache);
8581           if (reg->in_g_packet)
8582             return;
8583         }
8584
8585       if (fetch_register_using_p (regcache, reg))
8586         return;
8587
8588       /* This register is not available.  */
8589       regcache->raw_supply (reg->regnum, NULL);
8590
8591       return;
8592     }
8593
8594   fetch_registers_using_g (regcache);
8595
8596   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8597     if (!rsa->regs[i].in_g_packet)
8598       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8599         {
8600           /* This register is not available.  */
8601           regcache->raw_supply (i, NULL);
8602         }
8603 }
8604
8605 /* Prepare to store registers.  Since we may send them all (using a
8606    'G' request), we have to read out the ones we don't want to change
8607    first.  */
8608
8609 void
8610 remote_target::prepare_to_store (struct regcache *regcache)
8611 {
8612   struct remote_state *rs = get_remote_state ();
8613   remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8614   int i;
8615
8616   /* Make sure the entire registers array is valid.  */
8617   switch (packet_support (PACKET_P))
8618     {
8619     case PACKET_DISABLE:
8620     case PACKET_SUPPORT_UNKNOWN:
8621       /* Make sure all the necessary registers are cached.  */
8622       for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8623         if (rsa->regs[i].in_g_packet)
8624           regcache->raw_update (rsa->regs[i].regnum);
8625       break;
8626     case PACKET_ENABLE:
8627       break;
8628     }
8629 }
8630
8631 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
8632    packet was not recognized.  */
8633
8634 int
8635 remote_target::store_register_using_P (const struct regcache *regcache,
8636                                        packet_reg *reg)
8637 {
8638   struct gdbarch *gdbarch = regcache->arch ();
8639   struct remote_state *rs = get_remote_state ();
8640   /* Try storing a single register.  */
8641   char *buf = rs->buf.data ();
8642   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8643   char *p;
8644
8645   if (packet_support (PACKET_P) == PACKET_DISABLE)
8646     return 0;
8647
8648   if (reg->pnum == -1)
8649     return 0;
8650
8651   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8652   p = buf + strlen (buf);
8653   regcache->raw_collect (reg->regnum, regp);
8654   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8655   putpkt (rs->buf);
8656   getpkt (&rs->buf, 0);
8657
8658   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8659     {
8660     case PACKET_OK:
8661       return 1;
8662     case PACKET_ERROR:
8663       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8664              gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
8665     case PACKET_UNKNOWN:
8666       return 0;
8667     default:
8668       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8669     }
8670 }
8671
8672 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8673    contents of the register cache buffer.  FIXME: ignores errors.  */
8674
8675 void
8676 remote_target::store_registers_using_G (const struct regcache *regcache)
8677 {
8678   struct remote_state *rs = get_remote_state ();
8679   remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8680   gdb_byte *regs;
8681   char *p;
8682
8683   /* Extract all the registers in the regcache copying them into a
8684      local buffer.  */
8685   {
8686     int i;
8687
8688     regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8689     memset (regs, 0, rsa->sizeof_g_packet);
8690     for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8691       {
8692         struct packet_reg *r = &rsa->regs[i];
8693
8694         if (r->in_g_packet)
8695           regcache->raw_collect (r->regnum, regs + r->offset);
8696       }
8697   }
8698
8699   /* Command describes registers byte by byte,
8700      each byte encoded as two hex characters.  */
8701   p = rs->buf.data ();
8702   *p++ = 'G';
8703   bin2hex (regs, p, rsa->sizeof_g_packet);
8704   putpkt (rs->buf);
8705   getpkt (&rs->buf, 0);
8706   if (packet_check_result (rs->buf) == PACKET_ERROR)
8707     error (_("Could not write registers; remote failure reply '%s'"), 
8708            rs->buf.data ());
8709 }
8710
8711 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8712    of the register cache buffer.  FIXME: ignores errors.  */
8713
8714 void
8715 remote_target::store_registers (struct regcache *regcache, int regnum)
8716 {
8717   struct gdbarch *gdbarch = regcache->arch ();
8718   struct remote_state *rs = get_remote_state ();
8719   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8720   int i;
8721
8722   set_remote_traceframe ();
8723   set_general_thread (regcache->ptid ());
8724
8725   if (regnum >= 0)
8726     {
8727       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8728
8729       gdb_assert (reg != NULL);
8730
8731       /* Always prefer to store registers using the 'P' packet if
8732          possible; we often change only a small number of registers.
8733          Sometimes we change a larger number; we'd need help from a
8734          higher layer to know to use 'G'.  */
8735       if (store_register_using_P (regcache, reg))
8736         return;
8737
8738       /* For now, don't complain if we have no way to write the
8739          register.  GDB loses track of unavailable registers too
8740          easily.  Some day, this may be an error.  We don't have
8741          any way to read the register, either...  */
8742       if (!reg->in_g_packet)
8743         return;
8744
8745       store_registers_using_G (regcache);
8746       return;
8747     }
8748
8749   store_registers_using_G (regcache);
8750
8751   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8752     if (!rsa->regs[i].in_g_packet)
8753       if (!store_register_using_P (regcache, &rsa->regs[i]))
8754         /* See above for why we do not issue an error here.  */
8755         continue;
8756 }
8757 \f
8758
8759 /* Return the number of hex digits in num.  */
8760
8761 static int
8762 hexnumlen (ULONGEST num)
8763 {
8764   int i;
8765
8766   for (i = 0; num != 0; i++)
8767     num >>= 4;
8768
8769   return std::max (i, 1);
8770 }
8771
8772 /* Set BUF to the minimum number of hex digits representing NUM.  */
8773
8774 static int
8775 hexnumstr (char *buf, ULONGEST num)
8776 {
8777   int len = hexnumlen (num);
8778
8779   return hexnumnstr (buf, num, len);
8780 }
8781
8782
8783 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
8784
8785 static int
8786 hexnumnstr (char *buf, ULONGEST num, int width)
8787 {
8788   int i;
8789
8790   buf[width] = '\0';
8791
8792   for (i = width - 1; i >= 0; i--)
8793     {
8794       buf[i] = "0123456789abcdef"[(num & 0xf)];
8795       num >>= 4;
8796     }
8797
8798   return width;
8799 }
8800
8801 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
8802
8803 static CORE_ADDR
8804 remote_address_masked (CORE_ADDR addr)
8805 {
8806   unsigned int address_size = remote_address_size;
8807
8808   /* If "remoteaddresssize" was not set, default to target address size.  */
8809   if (!address_size)
8810     address_size = gdbarch_addr_bit (target_gdbarch ());
8811
8812   if (address_size > 0
8813       && address_size < (sizeof (ULONGEST) * 8))
8814     {
8815       /* Only create a mask when that mask can safely be constructed
8816          in a ULONGEST variable.  */
8817       ULONGEST mask = 1;
8818
8819       mask = (mask << address_size) - 1;
8820       addr &= mask;
8821     }
8822   return addr;
8823 }
8824
8825 /* Determine whether the remote target supports binary downloading.
8826    This is accomplished by sending a no-op memory write of zero length
8827    to the target at the specified address. It does not suffice to send
8828    the whole packet, since many stubs strip the eighth bit and
8829    subsequently compute a wrong checksum, which causes real havoc with
8830    remote_write_bytes.
8831
8832    NOTE: This can still lose if the serial line is not eight-bit
8833    clean.  In cases like this, the user should clear "remote
8834    X-packet".  */
8835
8836 void
8837 remote_target::check_binary_download (CORE_ADDR addr)
8838 {
8839   struct remote_state *rs = get_remote_state ();
8840
8841   switch (packet_support (PACKET_X))
8842     {
8843     case PACKET_DISABLE:
8844       break;
8845     case PACKET_ENABLE:
8846       break;
8847     case PACKET_SUPPORT_UNKNOWN:
8848       {
8849         char *p;
8850
8851         p = rs->buf.data ();
8852         *p++ = 'X';
8853         p += hexnumstr (p, (ULONGEST) addr);
8854         *p++ = ',';
8855         p += hexnumstr (p, (ULONGEST) 0);
8856         *p++ = ':';
8857         *p = '\0';
8858
8859         putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
8860         getpkt (&rs->buf, 0);
8861
8862         if (rs->buf[0] == '\0')
8863           {
8864             remote_debug_printf ("binary downloading NOT supported by target");
8865             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8866           }
8867         else
8868           {
8869             remote_debug_printf ("binary downloading supported by target");
8870             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8871           }
8872         break;
8873       }
8874     }
8875 }
8876
8877 /* Helper function to resize the payload in order to try to get a good
8878    alignment.  We try to write an amount of data such that the next write will
8879    start on an address aligned on REMOTE_ALIGN_WRITES.  */
8880
8881 static int
8882 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8883 {
8884   return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8885 }
8886
8887 /* Write memory data directly to the remote machine.
8888    This does not inform the data cache; the data cache uses this.
8889    HEADER is the starting part of the packet.
8890    MEMADDR is the address in the remote memory space.
8891    MYADDR is the address of the buffer in our space.
8892    LEN_UNITS is the number of addressable units to write.
8893    UNIT_SIZE is the length in bytes of an addressable unit.
8894    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8895    should send data as binary ('X'), or hex-encoded ('M').
8896
8897    The function creates packet of the form
8898        <HEADER><ADDRESS>,<LENGTH>:<DATA>
8899
8900    where encoding of <DATA> is terminated by PACKET_FORMAT.
8901
8902    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8903    are omitted.
8904
8905    Return the transferred status, error or OK (an
8906    'enum target_xfer_status' value).  Save the number of addressable units
8907    transferred in *XFERED_LEN_UNITS.  Only transfer a single packet.
8908
8909    On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8910    exchange between gdb and the stub could look like (?? in place of the
8911    checksum):
8912
8913    -> $m1000,4#??
8914    <- aaaabbbbccccdddd
8915
8916    -> $M1000,3:eeeeffffeeee#??
8917    <- OK
8918
8919    -> $m1000,4#??
8920    <- eeeeffffeeeedddd  */
8921
8922 target_xfer_status
8923 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8924                                        const gdb_byte *myaddr,
8925                                        ULONGEST len_units,
8926                                        int unit_size,
8927                                        ULONGEST *xfered_len_units,
8928                                        char packet_format, int use_length)
8929 {
8930   struct remote_state *rs = get_remote_state ();
8931   char *p;
8932   char *plen = NULL;
8933   int plenlen = 0;
8934   int todo_units;
8935   int units_written;
8936   int payload_capacity_bytes;
8937   int payload_length_bytes;
8938
8939   if (packet_format != 'X' && packet_format != 'M')
8940     internal_error (__FILE__, __LINE__,
8941                     _("remote_write_bytes_aux: bad packet format"));
8942
8943   if (len_units == 0)
8944     return TARGET_XFER_EOF;
8945
8946   payload_capacity_bytes = get_memory_write_packet_size ();
8947
8948   /* The packet buffer will be large enough for the payload;
8949      get_memory_packet_size ensures this.  */
8950   rs->buf[0] = '\0';
8951
8952   /* Compute the size of the actual payload by subtracting out the
8953      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
8954
8955   payload_capacity_bytes -= strlen ("$,:#NN");
8956   if (!use_length)
8957     /* The comma won't be used.  */
8958     payload_capacity_bytes += 1;
8959   payload_capacity_bytes -= strlen (header);
8960   payload_capacity_bytes -= hexnumlen (memaddr);
8961
8962   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
8963
8964   strcat (rs->buf.data (), header);
8965   p = rs->buf.data () + strlen (header);
8966
8967   /* Compute a best guess of the number of bytes actually transfered.  */
8968   if (packet_format == 'X')
8969     {
8970       /* Best guess at number of bytes that will fit.  */
8971       todo_units = std::min (len_units,
8972                              (ULONGEST) payload_capacity_bytes / unit_size);
8973       if (use_length)
8974         payload_capacity_bytes -= hexnumlen (todo_units);
8975       todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8976     }
8977   else
8978     {
8979       /* Number of bytes that will fit.  */
8980       todo_units
8981         = std::min (len_units,
8982                     (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8983       if (use_length)
8984         payload_capacity_bytes -= hexnumlen (todo_units);
8985       todo_units = std::min (todo_units,
8986                              (payload_capacity_bytes / unit_size) / 2);
8987     }
8988
8989   if (todo_units <= 0)
8990     internal_error (__FILE__, __LINE__,
8991                     _("minimum packet size too small to write data"));
8992
8993   /* If we already need another packet, then try to align the end
8994      of this packet to a useful boundary.  */
8995   if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8996     todo_units = align_for_efficient_write (todo_units, memaddr);
8997
8998   /* Append "<memaddr>".  */
8999   memaddr = remote_address_masked (memaddr);
9000   p += hexnumstr (p, (ULONGEST) memaddr);
9001
9002   if (use_length)
9003     {
9004       /* Append ",".  */
9005       *p++ = ',';
9006
9007       /* Append the length and retain its location and size.  It may need to be
9008          adjusted once the packet body has been created.  */
9009       plen = p;
9010       plenlen = hexnumstr (p, (ULONGEST) todo_units);
9011       p += plenlen;
9012     }
9013
9014   /* Append ":".  */
9015   *p++ = ':';
9016   *p = '\0';
9017
9018   /* Append the packet body.  */
9019   if (packet_format == 'X')
9020     {
9021       /* Binary mode.  Send target system values byte by byte, in
9022          increasing byte addresses.  Only escape certain critical
9023          characters.  */
9024       payload_length_bytes =
9025           remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9026                                 &units_written, payload_capacity_bytes);
9027
9028       /* If not all TODO units fit, then we'll need another packet.  Make
9029          a second try to keep the end of the packet aligned.  Don't do
9030          this if the packet is tiny.  */
9031       if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9032         {
9033           int new_todo_units;
9034
9035           new_todo_units = align_for_efficient_write (units_written, memaddr);
9036
9037           if (new_todo_units != units_written)
9038             payload_length_bytes =
9039                 remote_escape_output (myaddr, new_todo_units, unit_size,
9040                                       (gdb_byte *) p, &units_written,
9041                                       payload_capacity_bytes);
9042         }
9043
9044       p += payload_length_bytes;
9045       if (use_length && units_written < todo_units)
9046         {
9047           /* Escape chars have filled up the buffer prematurely,
9048              and we have actually sent fewer units than planned.
9049              Fix-up the length field of the packet.  Use the same
9050              number of characters as before.  */
9051           plen += hexnumnstr (plen, (ULONGEST) units_written,
9052                               plenlen);
9053           *plen = ':';  /* overwrite \0 from hexnumnstr() */
9054         }
9055     }
9056   else
9057     {
9058       /* Normal mode: Send target system values byte by byte, in
9059          increasing byte addresses.  Each byte is encoded as a two hex
9060          value.  */
9061       p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9062       units_written = todo_units;
9063     }
9064
9065   putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9066   getpkt (&rs->buf, 0);
9067
9068   if (rs->buf[0] == 'E')
9069     return TARGET_XFER_E_IO;
9070
9071   /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9072      send fewer units than we'd planned.  */
9073   *xfered_len_units = (ULONGEST) units_written;
9074   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9075 }
9076
9077 /* Write memory data directly to the remote machine.
9078    This does not inform the data cache; the data cache uses this.
9079    MEMADDR is the address in the remote memory space.
9080    MYADDR is the address of the buffer in our space.
9081    LEN is the number of bytes.
9082
9083    Return the transferred status, error or OK (an
9084    'enum target_xfer_status' value).  Save the number of bytes
9085    transferred in *XFERED_LEN.  Only transfer a single packet.  */
9086
9087 target_xfer_status
9088 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9089                                    ULONGEST len, int unit_size,
9090                                    ULONGEST *xfered_len)
9091 {
9092   const char *packet_format = NULL;
9093
9094   /* Check whether the target supports binary download.  */
9095   check_binary_download (memaddr);
9096
9097   switch (packet_support (PACKET_X))
9098     {
9099     case PACKET_ENABLE:
9100       packet_format = "X";
9101       break;
9102     case PACKET_DISABLE:
9103       packet_format = "M";
9104       break;
9105     case PACKET_SUPPORT_UNKNOWN:
9106       internal_error (__FILE__, __LINE__,
9107                       _("remote_write_bytes: bad internal state"));
9108     default:
9109       internal_error (__FILE__, __LINE__, _("bad switch"));
9110     }
9111
9112   return remote_write_bytes_aux (packet_format,
9113                                  memaddr, myaddr, len, unit_size, xfered_len,
9114                                  packet_format[0], 1);
9115 }
9116
9117 /* Read memory data directly from the remote machine.
9118    This does not use the data cache; the data cache uses this.
9119    MEMADDR is the address in the remote memory space.
9120    MYADDR is the address of the buffer in our space.
9121    LEN_UNITS is the number of addressable memory units to read..
9122    UNIT_SIZE is the length in bytes of an addressable unit.
9123
9124    Return the transferred status, error or OK (an
9125    'enum target_xfer_status' value).  Save the number of bytes
9126    transferred in *XFERED_LEN_UNITS.
9127
9128    See the comment of remote_write_bytes_aux for an example of
9129    memory read/write exchange between gdb and the stub.  */
9130
9131 target_xfer_status
9132 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9133                                     ULONGEST len_units,
9134                                     int unit_size, ULONGEST *xfered_len_units)
9135 {
9136   struct remote_state *rs = get_remote_state ();
9137   int buf_size_bytes;           /* Max size of packet output buffer.  */
9138   char *p;
9139   int todo_units;
9140   int decoded_bytes;
9141
9142   buf_size_bytes = get_memory_read_packet_size ();
9143   /* The packet buffer will be large enough for the payload;
9144      get_memory_packet_size ensures this.  */
9145
9146   /* Number of units that will fit.  */
9147   todo_units = std::min (len_units,
9148                          (ULONGEST) (buf_size_bytes / unit_size) / 2);
9149
9150   /* Construct "m"<memaddr>","<len>".  */
9151   memaddr = remote_address_masked (memaddr);
9152   p = rs->buf.data ();
9153   *p++ = 'm';
9154   p += hexnumstr (p, (ULONGEST) memaddr);
9155   *p++ = ',';
9156   p += hexnumstr (p, (ULONGEST) todo_units);
9157   *p = '\0';
9158   putpkt (rs->buf);
9159   getpkt (&rs->buf, 0);
9160   if (rs->buf[0] == 'E'
9161       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9162       && rs->buf[3] == '\0')
9163     return TARGET_XFER_E_IO;
9164   /* Reply describes memory byte by byte, each byte encoded as two hex
9165      characters.  */
9166   p = rs->buf.data ();
9167   decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9168   /* Return what we have.  Let higher layers handle partial reads.  */
9169   *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9170   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9171 }
9172
9173 /* Using the set of read-only target sections of remote, read live
9174    read-only memory.
9175
9176    For interface/parameters/return description see target.h,
9177    to_xfer_partial.  */
9178
9179 target_xfer_status
9180 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9181                                                   ULONGEST memaddr,
9182                                                   ULONGEST len,
9183                                                   int unit_size,
9184                                                   ULONGEST *xfered_len)
9185 {
9186   const struct target_section *secp;
9187
9188   secp = target_section_by_addr (this, memaddr);
9189   if (secp != NULL
9190       && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9191     {
9192       ULONGEST memend = memaddr + len;
9193
9194       const target_section_table *table = target_get_section_table (this);
9195       for (const target_section &p : *table)
9196         {
9197           if (memaddr >= p.addr)
9198             {
9199               if (memend <= p.endaddr)
9200                 {
9201                   /* Entire transfer is within this section.  */
9202                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9203                                               xfered_len);
9204                 }
9205               else if (memaddr >= p.endaddr)
9206                 {
9207                   /* This section ends before the transfer starts.  */
9208                   continue;
9209                 }
9210               else
9211                 {
9212                   /* This section overlaps the transfer.  Just do half.  */
9213                   len = p.endaddr - memaddr;
9214                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9215                                               xfered_len);
9216                 }
9217             }
9218         }
9219     }
9220
9221   return TARGET_XFER_EOF;
9222 }
9223
9224 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9225    first if the requested memory is unavailable in traceframe.
9226    Otherwise, fall back to remote_read_bytes_1.  */
9227
9228 target_xfer_status
9229 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9230                                   gdb_byte *myaddr, ULONGEST len, int unit_size,
9231                                   ULONGEST *xfered_len)
9232 {
9233   if (len == 0)
9234     return TARGET_XFER_EOF;
9235
9236   if (get_traceframe_number () != -1)
9237     {
9238       std::vector<mem_range> available;
9239
9240       /* If we fail to get the set of available memory, then the
9241          target does not support querying traceframe info, and so we
9242          attempt reading from the traceframe anyway (assuming the
9243          target implements the old QTro packet then).  */
9244       if (traceframe_available_memory (&available, memaddr, len))
9245         {
9246           if (available.empty () || available[0].start != memaddr)
9247             {
9248               enum target_xfer_status res;
9249
9250               /* Don't read into the traceframe's available
9251                  memory.  */
9252               if (!available.empty ())
9253                 {
9254                   LONGEST oldlen = len;
9255
9256                   len = available[0].start - memaddr;
9257                   gdb_assert (len <= oldlen);
9258                 }
9259
9260               /* This goes through the topmost target again.  */
9261               res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9262                                                        len, unit_size, xfered_len);
9263               if (res == TARGET_XFER_OK)
9264                 return TARGET_XFER_OK;
9265               else
9266                 {
9267                   /* No use trying further, we know some memory starting
9268                      at MEMADDR isn't available.  */
9269                   *xfered_len = len;
9270                   return (*xfered_len != 0) ?
9271                     TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9272                 }
9273             }
9274
9275           /* Don't try to read more than how much is available, in
9276              case the target implements the deprecated QTro packet to
9277              cater for older GDBs (the target's knowledge of read-only
9278              sections may be outdated by now).  */
9279           len = available[0].length;
9280         }
9281     }
9282
9283   return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9284 }
9285
9286 \f
9287
9288 /* Sends a packet with content determined by the printf format string
9289    FORMAT and the remaining arguments, then gets the reply.  Returns
9290    whether the packet was a success, a failure, or unknown.  */
9291
9292 packet_result
9293 remote_target::remote_send_printf (const char *format, ...)
9294 {
9295   struct remote_state *rs = get_remote_state ();
9296   int max_size = get_remote_packet_size ();
9297   va_list ap;
9298
9299   va_start (ap, format);
9300
9301   rs->buf[0] = '\0';
9302   int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9303
9304   va_end (ap);
9305
9306   if (size >= max_size)
9307     internal_error (__FILE__, __LINE__, _("Too long remote packet."));
9308
9309   if (putpkt (rs->buf) < 0)
9310     error (_("Communication problem with target."));
9311
9312   rs->buf[0] = '\0';
9313   getpkt (&rs->buf, 0);
9314
9315   return packet_check_result (rs->buf);
9316 }
9317
9318 /* Flash writing can take quite some time.  We'll set
9319    effectively infinite timeout for flash operations.
9320    In future, we'll need to decide on a better approach.  */
9321 static const int remote_flash_timeout = 1000;
9322
9323 void
9324 remote_target::flash_erase (ULONGEST address, LONGEST length)
9325 {
9326   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9327   enum packet_result ret;
9328   scoped_restore restore_timeout
9329     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9330
9331   ret = remote_send_printf ("vFlashErase:%s,%s",
9332                             phex (address, addr_size),
9333                             phex (length, 4));
9334   switch (ret)
9335     {
9336     case PACKET_UNKNOWN:
9337       error (_("Remote target does not support flash erase"));
9338     case PACKET_ERROR:
9339       error (_("Error erasing flash with vFlashErase packet"));
9340     default:
9341       break;
9342     }
9343 }
9344
9345 target_xfer_status
9346 remote_target::remote_flash_write (ULONGEST address,
9347                                    ULONGEST length, ULONGEST *xfered_len,
9348                                    const gdb_byte *data)
9349 {
9350   scoped_restore restore_timeout
9351     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9352   return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9353                                  xfered_len,'X', 0);
9354 }
9355
9356 void
9357 remote_target::flash_done ()
9358 {
9359   int ret;
9360
9361   scoped_restore restore_timeout
9362     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9363
9364   ret = remote_send_printf ("vFlashDone");
9365
9366   switch (ret)
9367     {
9368     case PACKET_UNKNOWN:
9369       error (_("Remote target does not support vFlashDone"));
9370     case PACKET_ERROR:
9371       error (_("Error finishing flash operation"));
9372     default:
9373       break;
9374     }
9375 }
9376
9377 void
9378 remote_target::files_info ()
9379 {
9380   puts_filtered ("Debugging a target over a serial line.\n");
9381 }
9382 \f
9383 /* Stuff for dealing with the packets which are part of this protocol.
9384    See comment at top of file for details.  */
9385
9386 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9387    error to higher layers.  Called when a serial error is detected.
9388    The exception message is STRING, followed by a colon and a blank,
9389    the system error message for errno at function entry and final dot
9390    for output compatibility with throw_perror_with_name.  */
9391
9392 static void
9393 unpush_and_perror (remote_target *target, const char *string)
9394 {
9395   int saved_errno = errno;
9396
9397   remote_unpush_target (target);
9398   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9399                safe_strerror (saved_errno));
9400 }
9401
9402 /* Read a single character from the remote end.  The current quit
9403    handler is overridden to avoid quitting in the middle of packet
9404    sequence, as that would break communication with the remote server.
9405    See remote_serial_quit_handler for more detail.  */
9406
9407 int
9408 remote_target::readchar (int timeout)
9409 {
9410   int ch;
9411   struct remote_state *rs = get_remote_state ();
9412
9413   {
9414     scoped_restore restore_quit_target
9415       = make_scoped_restore (&curr_quit_handler_target, this);
9416     scoped_restore restore_quit
9417       = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9418
9419     rs->got_ctrlc_during_io = 0;
9420
9421     ch = serial_readchar (rs->remote_desc, timeout);
9422
9423     if (rs->got_ctrlc_during_io)
9424       set_quit_flag ();
9425   }
9426
9427   if (ch >= 0)
9428     return ch;
9429
9430   switch ((enum serial_rc) ch)
9431     {
9432     case SERIAL_EOF:
9433       remote_unpush_target (this);
9434       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9435       /* no return */
9436     case SERIAL_ERROR:
9437       unpush_and_perror (this, _("Remote communication error.  "
9438                                  "Target disconnected."));
9439       /* no return */
9440     case SERIAL_TIMEOUT:
9441       break;
9442     }
9443   return ch;
9444 }
9445
9446 /* Wrapper for serial_write that closes the target and throws if
9447    writing fails.  The current quit handler is overridden to avoid
9448    quitting in the middle of packet sequence, as that would break
9449    communication with the remote server.  See
9450    remote_serial_quit_handler for more detail.  */
9451
9452 void
9453 remote_target::remote_serial_write (const char *str, int len)
9454 {
9455   struct remote_state *rs = get_remote_state ();
9456
9457   scoped_restore restore_quit_target
9458     = make_scoped_restore (&curr_quit_handler_target, this);
9459   scoped_restore restore_quit
9460     = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9461
9462   rs->got_ctrlc_during_io = 0;
9463
9464   if (serial_write (rs->remote_desc, str, len))
9465     {
9466       unpush_and_perror (this, _("Remote communication error.  "
9467                                  "Target disconnected."));
9468     }
9469
9470   if (rs->got_ctrlc_during_io)
9471     set_quit_flag ();
9472 }
9473
9474 /* Return a string representing an escaped version of BUF, of len N.
9475    E.g. \n is converted to \\n, \t to \\t, etc.  */
9476
9477 static std::string
9478 escape_buffer (const char *buf, int n)
9479 {
9480   string_file stb;
9481
9482   stb.putstrn (buf, n, '\\');
9483   return std::move (stb.string ());
9484 }
9485
9486 /* Display a null-terminated packet on stdout, for debugging, using C
9487    string notation.  */
9488
9489 static void
9490 print_packet (const char *buf)
9491 {
9492   puts_filtered ("\"");
9493   fputstr_filtered (buf, '"', gdb_stdout);
9494   puts_filtered ("\"");
9495 }
9496
9497 int
9498 remote_target::putpkt (const char *buf)
9499 {
9500   return putpkt_binary (buf, strlen (buf));
9501 }
9502
9503 /* Wrapper around remote_target::putpkt to avoid exporting
9504    remote_target.  */
9505
9506 int
9507 putpkt (remote_target *remote, const char *buf)
9508 {
9509   return remote->putpkt (buf);
9510 }
9511
9512 /* Send a packet to the remote machine, with error checking.  The data
9513    of the packet is in BUF.  The string in BUF can be at most
9514    get_remote_packet_size () - 5 to account for the $, # and checksum,
9515    and for a possible /0 if we are debugging (remote_debug) and want
9516    to print the sent packet as a string.  */
9517
9518 int
9519 remote_target::putpkt_binary (const char *buf, int cnt)
9520 {
9521   struct remote_state *rs = get_remote_state ();
9522   int i;
9523   unsigned char csum = 0;
9524   gdb::def_vector<char> data (cnt + 6);
9525   char *buf2 = data.data ();
9526
9527   int ch;
9528   int tcount = 0;
9529   char *p;
9530
9531   /* Catch cases like trying to read memory or listing threads while
9532      we're waiting for a stop reply.  The remote server wouldn't be
9533      ready to handle this request, so we'd hang and timeout.  We don't
9534      have to worry about this in synchronous mode, because in that
9535      case it's not possible to issue a command while the target is
9536      running.  This is not a problem in non-stop mode, because in that
9537      case, the stub is always ready to process serial input.  */
9538   if (!target_is_non_stop_p ()
9539       && target_is_async_p ()
9540       && rs->waiting_for_stop_reply)
9541     {
9542       error (_("Cannot execute this command while the target is running.\n"
9543                "Use the \"interrupt\" command to stop the target\n"
9544                "and then try again."));
9545     }
9546
9547   /* We're sending out a new packet.  Make sure we don't look at a
9548      stale cached response.  */
9549   rs->cached_wait_status = 0;
9550
9551   /* Copy the packet into buffer BUF2, encapsulating it
9552      and giving it a checksum.  */
9553
9554   p = buf2;
9555   *p++ = '$';
9556
9557   for (i = 0; i < cnt; i++)
9558     {
9559       csum += buf[i];
9560       *p++ = buf[i];
9561     }
9562   *p++ = '#';
9563   *p++ = tohex ((csum >> 4) & 0xf);
9564   *p++ = tohex (csum & 0xf);
9565
9566   /* Send it over and over until we get a positive ack.  */
9567
9568   while (1)
9569     {
9570       if (remote_debug)
9571         {
9572           *p = '\0';
9573
9574           int len = (int) (p - buf2);
9575           int max_chars;
9576
9577           if (remote_packet_max_chars < 0)
9578             max_chars = len;
9579           else
9580             max_chars = remote_packet_max_chars;
9581
9582           std::string str
9583             = escape_buffer (buf2, std::min (len, max_chars));
9584
9585           if (len > max_chars)
9586             remote_debug_printf_nofunc
9587               ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9588                len - max_chars);
9589           else
9590             remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9591         }
9592       remote_serial_write (buf2, p - buf2);
9593
9594       /* If this is a no acks version of the remote protocol, send the
9595          packet and move on.  */
9596       if (rs->noack_mode)
9597         break;
9598
9599       /* Read until either a timeout occurs (-2) or '+' is read.
9600          Handle any notification that arrives in the mean time.  */
9601       while (1)
9602         {
9603           ch = readchar (remote_timeout);
9604
9605           switch (ch)
9606             {
9607             case '+':
9608               remote_debug_printf_nofunc ("Received Ack");
9609               return 1;
9610             case '-':
9611               remote_debug_printf_nofunc ("Received Nak");
9612               /* FALLTHROUGH */
9613             case SERIAL_TIMEOUT:
9614               tcount++;
9615               if (tcount > 3)
9616                 return 0;
9617               break;            /* Retransmit buffer.  */
9618             case '$':
9619               {
9620                 remote_debug_printf ("Packet instead of Ack, ignoring it");
9621                 /* It's probably an old response sent because an ACK
9622                    was lost.  Gobble up the packet and ack it so it
9623                    doesn't get retransmitted when we resend this
9624                    packet.  */
9625                 skip_frame ();
9626                 remote_serial_write ("+", 1);
9627                 continue;       /* Now, go look for +.  */
9628               }
9629
9630             case '%':
9631               {
9632                 int val;
9633
9634                 /* If we got a notification, handle it, and go back to looking
9635                    for an ack.  */
9636                 /* We've found the start of a notification.  Now
9637                    collect the data.  */
9638                 val = read_frame (&rs->buf);
9639                 if (val >= 0)
9640                   {
9641                     remote_debug_printf_nofunc
9642                       ("  Notification received: %s",
9643                        escape_buffer (rs->buf.data (), val).c_str ());
9644
9645                     handle_notification (rs->notif_state, rs->buf.data ());
9646                     /* We're in sync now, rewait for the ack.  */
9647                     tcount = 0;
9648                   }
9649                 else
9650                   remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9651                                               rs->buf.data ());
9652                 continue;
9653               }
9654               /* fall-through */
9655             default:
9656               remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9657                                           rs->buf.data ());
9658               continue;
9659             }
9660           break;                /* Here to retransmit.  */
9661         }
9662
9663 #if 0
9664       /* This is wrong.  If doing a long backtrace, the user should be
9665          able to get out next time we call QUIT, without anything as
9666          violent as interrupt_query.  If we want to provide a way out of
9667          here without getting to the next QUIT, it should be based on
9668          hitting ^C twice as in remote_wait.  */
9669       if (quit_flag)
9670         {
9671           quit_flag = 0;
9672           interrupt_query ();
9673         }
9674 #endif
9675     }
9676
9677   return 0;
9678 }
9679
9680 /* Come here after finding the start of a frame when we expected an
9681    ack.  Do our best to discard the rest of this packet.  */
9682
9683 void
9684 remote_target::skip_frame ()
9685 {
9686   int c;
9687
9688   while (1)
9689     {
9690       c = readchar (remote_timeout);
9691       switch (c)
9692         {
9693         case SERIAL_TIMEOUT:
9694           /* Nothing we can do.  */
9695           return;
9696         case '#':
9697           /* Discard the two bytes of checksum and stop.  */
9698           c = readchar (remote_timeout);
9699           if (c >= 0)
9700             c = readchar (remote_timeout);
9701
9702           return;
9703         case '*':               /* Run length encoding.  */
9704           /* Discard the repeat count.  */
9705           c = readchar (remote_timeout);
9706           if (c < 0)
9707             return;
9708           break;
9709         default:
9710           /* A regular character.  */
9711           break;
9712         }
9713     }
9714 }
9715
9716 /* Come here after finding the start of the frame.  Collect the rest
9717    into *BUF, verifying the checksum, length, and handling run-length
9718    compression.  NUL terminate the buffer.  If there is not enough room,
9719    expand *BUF.
9720
9721    Returns -1 on error, number of characters in buffer (ignoring the
9722    trailing NULL) on success. (could be extended to return one of the
9723    SERIAL status indications).  */
9724
9725 long
9726 remote_target::read_frame (gdb::char_vector *buf_p)
9727 {
9728   unsigned char csum;
9729   long bc;
9730   int c;
9731   char *buf = buf_p->data ();
9732   struct remote_state *rs = get_remote_state ();
9733
9734   csum = 0;
9735   bc = 0;
9736
9737   while (1)
9738     {
9739       c = readchar (remote_timeout);
9740       switch (c)
9741         {
9742         case SERIAL_TIMEOUT:
9743           remote_debug_printf ("Timeout in mid-packet, retrying");
9744           return -1;
9745
9746         case '$':
9747           remote_debug_printf ("Saw new packet start in middle of old one");
9748           return -1;            /* Start a new packet, count retries.  */
9749
9750         case '#':
9751           {
9752             unsigned char pktcsum;
9753             int check_0 = 0;
9754             int check_1 = 0;
9755
9756             buf[bc] = '\0';
9757
9758             check_0 = readchar (remote_timeout);
9759             if (check_0 >= 0)
9760               check_1 = readchar (remote_timeout);
9761
9762             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9763               {
9764                 remote_debug_printf ("Timeout in checksum, retrying");
9765                 return -1;
9766               }
9767             else if (check_0 < 0 || check_1 < 0)
9768               {
9769                 remote_debug_printf ("Communication error in checksum");
9770                 return -1;
9771               }
9772
9773             /* Don't recompute the checksum; with no ack packets we
9774                don't have any way to indicate a packet retransmission
9775                is necessary.  */
9776             if (rs->noack_mode)
9777               return bc;
9778
9779             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9780             if (csum == pktcsum)
9781               return bc;
9782
9783             remote_debug_printf
9784               ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
9785                pktcsum, csum, escape_buffer (buf, bc).c_str ());
9786
9787             /* Number of characters in buffer ignoring trailing
9788                NULL.  */
9789             return -1;
9790           }
9791         case '*':               /* Run length encoding.  */
9792           {
9793             int repeat;
9794
9795             csum += c;
9796             c = readchar (remote_timeout);
9797             csum += c;
9798             repeat = c - ' ' + 3;       /* Compute repeat count.  */
9799
9800             /* The character before ``*'' is repeated.  */
9801
9802             if (repeat > 0 && repeat <= 255 && bc > 0)
9803               {
9804                 if (bc + repeat - 1 >= buf_p->size () - 1)
9805                   {
9806                     /* Make some more room in the buffer.  */
9807                     buf_p->resize (buf_p->size () + repeat);
9808                     buf = buf_p->data ();
9809                   }
9810
9811                 memset (&buf[bc], buf[bc - 1], repeat);
9812                 bc += repeat;
9813                 continue;
9814               }
9815
9816             buf[bc] = '\0';
9817             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9818             return -1;
9819           }
9820         default:
9821           if (bc >= buf_p->size () - 1)
9822             {
9823               /* Make some more room in the buffer.  */
9824               buf_p->resize (buf_p->size () * 2);
9825               buf = buf_p->data ();
9826             }
9827
9828           buf[bc++] = c;
9829           csum += c;
9830           continue;
9831         }
9832     }
9833 }
9834
9835 /* Set this to the maximum number of seconds to wait instead of waiting forever
9836    in target_wait().  If this timer times out, then it generates an error and
9837    the command is aborted.  This replaces most of the need for timeouts in the
9838    GDB test suite, and makes it possible to distinguish between a hung target
9839    and one with slow communications.  */
9840
9841 static int watchdog = 0;
9842 static void
9843 show_watchdog (struct ui_file *file, int from_tty,
9844                struct cmd_list_element *c, const char *value)
9845 {
9846   fprintf_filtered (file, _("Watchdog timer is %s.\n"), value);
9847 }
9848
9849 /* Read a packet from the remote machine, with error checking, and
9850    store it in *BUF.  Resize *BUF if necessary to hold the result.  If
9851    FOREVER, wait forever rather than timing out; this is used (in
9852    synchronous mode) to wait for a target that is is executing user
9853    code to stop.  */
9854 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9855    don't have to change all the calls to getpkt to deal with the
9856    return value, because at the moment I don't know what the right
9857    thing to do it for those.  */
9858
9859 void
9860 remote_target::getpkt (gdb::char_vector *buf, int forever)
9861 {
9862   getpkt_sane (buf, forever);
9863 }
9864
9865
9866 /* Read a packet from the remote machine, with error checking, and
9867    store it in *BUF.  Resize *BUF if necessary to hold the result.  If
9868    FOREVER, wait forever rather than timing out; this is used (in
9869    synchronous mode) to wait for a target that is is executing user
9870    code to stop.  If FOREVER == 0, this function is allowed to time
9871    out gracefully and return an indication of this to the caller.
9872    Otherwise return the number of bytes read.  If EXPECTING_NOTIF,
9873    consider receiving a notification enough reason to return to the
9874    caller.  *IS_NOTIF is an output boolean that indicates whether *BUF
9875    holds a notification or not (a regular packet).  */
9876
9877 int
9878 remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
9879                                        int forever, int expecting_notif,
9880                                        int *is_notif)
9881 {
9882   struct remote_state *rs = get_remote_state ();
9883   int c;
9884   int tries;
9885   int timeout;
9886   int val = -1;
9887
9888   /* We're reading a new response.  Make sure we don't look at a
9889      previously cached response.  */
9890   rs->cached_wait_status = 0;
9891
9892   strcpy (buf->data (), "timeout");
9893
9894   if (forever)
9895     timeout = watchdog > 0 ? watchdog : -1;
9896   else if (expecting_notif)
9897     timeout = 0; /* There should already be a char in the buffer.  If
9898                     not, bail out.  */
9899   else
9900     timeout = remote_timeout;
9901
9902 #define MAX_TRIES 3
9903
9904   /* Process any number of notifications, and then return when
9905      we get a packet.  */
9906   for (;;)
9907     {
9908       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9909          times.  */
9910       for (tries = 1; tries <= MAX_TRIES; tries++)
9911         {
9912           /* This can loop forever if the remote side sends us
9913              characters continuously, but if it pauses, we'll get
9914              SERIAL_TIMEOUT from readchar because of timeout.  Then
9915              we'll count that as a retry.
9916
9917              Note that even when forever is set, we will only wait
9918              forever prior to the start of a packet.  After that, we
9919              expect characters to arrive at a brisk pace.  They should
9920              show up within remote_timeout intervals.  */
9921           do
9922             c = readchar (timeout);
9923           while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9924
9925           if (c == SERIAL_TIMEOUT)
9926             {
9927               if (expecting_notif)
9928                 return -1; /* Don't complain, it's normal to not get
9929                               anything in this case.  */
9930
9931               if (forever)      /* Watchdog went off?  Kill the target.  */
9932                 {
9933                   remote_unpush_target (this);
9934                   throw_error (TARGET_CLOSE_ERROR,
9935                                _("Watchdog timeout has expired.  "
9936                                  "Target detached."));
9937                 }
9938
9939               remote_debug_printf ("Timed out.");
9940             }
9941           else
9942             {
9943               /* We've found the start of a packet or notification.
9944                  Now collect the data.  */
9945               val = read_frame (buf);
9946               if (val >= 0)
9947                 break;
9948             }
9949
9950           remote_serial_write ("-", 1);
9951         }
9952
9953       if (tries > MAX_TRIES)
9954         {
9955           /* We have tried hard enough, and just can't receive the
9956              packet/notification.  Give up.  */
9957           printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9958
9959           /* Skip the ack char if we're in no-ack mode.  */
9960           if (!rs->noack_mode)
9961             remote_serial_write ("+", 1);
9962           return -1;
9963         }
9964
9965       /* If we got an ordinary packet, return that to our caller.  */
9966       if (c == '$')
9967         {
9968           if (remote_debug)
9969             {
9970               int max_chars;
9971
9972               if (remote_packet_max_chars < 0)
9973                 max_chars = val;
9974               else
9975                 max_chars = remote_packet_max_chars;
9976
9977               std::string str
9978                 = escape_buffer (buf->data (),
9979                                  std::min (val, max_chars));
9980
9981               if (val > max_chars)
9982                 remote_debug_printf_nofunc
9983                   ("Packet received: %s [%d bytes omitted]", str.c_str (),
9984                    val - max_chars);
9985               else
9986                 remote_debug_printf_nofunc ("Packet received: %s",
9987                                             str.c_str ());
9988             }
9989
9990           /* Skip the ack char if we're in no-ack mode.  */
9991           if (!rs->noack_mode)
9992             remote_serial_write ("+", 1);
9993           if (is_notif != NULL)
9994             *is_notif = 0;
9995           return val;
9996         }
9997
9998        /* If we got a notification, handle it, and go back to looking
9999          for a packet.  */
10000       else
10001         {
10002           gdb_assert (c == '%');
10003
10004           remote_debug_printf_nofunc
10005             ("  Notification received: %s",
10006              escape_buffer (buf->data (), val).c_str ());
10007
10008           if (is_notif != NULL)
10009             *is_notif = 1;
10010
10011           handle_notification (rs->notif_state, buf->data ());
10012
10013           /* Notifications require no acknowledgement.  */
10014
10015           if (expecting_notif)
10016             return val;
10017         }
10018     }
10019 }
10020
10021 int
10022 remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
10023 {
10024   return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
10025 }
10026
10027 int
10028 remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
10029                                      int *is_notif)
10030 {
10031   return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
10032 }
10033
10034 /* Kill any new fork children of process PID that haven't been
10035    processed by follow_fork.  */
10036
10037 void
10038 remote_target::kill_new_fork_children (int pid)
10039 {
10040   remote_state *rs = get_remote_state ();
10041   struct notif_client *notif = &notif_client_stop;
10042
10043   /* Kill the fork child threads of any threads in process PID
10044      that are stopped at a fork event.  */
10045   for (thread_info *thread : all_non_exited_threads (this))
10046     {
10047       struct target_waitstatus *ws = &thread->pending_follow;
10048
10049       if (is_pending_fork_parent (ws, pid, thread->ptid))
10050         {
10051           int child_pid = ws->value.related_pid.pid ();
10052           int res;
10053
10054           res = remote_vkill (child_pid);
10055           if (res != 0)
10056             error (_("Can't kill fork child process %d"), child_pid);
10057         }
10058     }
10059
10060   /* Check for any pending fork events (not reported or processed yet)
10061      in process PID and kill those fork child threads as well.  */
10062   remote_notif_get_pending_events (notif);
10063   for (auto &event : rs->stop_reply_queue)
10064     if (is_pending_fork_parent (&event->ws, pid, event->ptid))
10065       {
10066         int child_pid = event->ws.value.related_pid.pid ();
10067         int res;
10068
10069         res = remote_vkill (child_pid);
10070         if (res != 0)
10071           error (_("Can't kill fork child process %d"), child_pid);
10072       }
10073 }
10074
10075 \f
10076 /* Target hook to kill the current inferior.  */
10077
10078 void
10079 remote_target::kill ()
10080 {
10081   int res = -1;
10082   int pid = inferior_ptid.pid ();
10083   struct remote_state *rs = get_remote_state ();
10084
10085   if (packet_support (PACKET_vKill) != PACKET_DISABLE)
10086     {
10087       /* If we're stopped while forking and we haven't followed yet,
10088          kill the child task.  We need to do this before killing the
10089          parent task because if this is a vfork then the parent will
10090          be sleeping.  */
10091       kill_new_fork_children (pid);
10092
10093       res = remote_vkill (pid);
10094       if (res == 0)
10095         {
10096           target_mourn_inferior (inferior_ptid);
10097           return;
10098         }
10099     }
10100
10101   /* If we are in 'target remote' mode and we are killing the only
10102      inferior, then we will tell gdbserver to exit and unpush the
10103      target.  */
10104   if (res == -1 && !remote_multi_process_p (rs)
10105       && number_of_live_inferiors (this) == 1)
10106     {
10107       remote_kill_k ();
10108
10109       /* We've killed the remote end, we get to mourn it.  If we are
10110          not in extended mode, mourning the inferior also unpushes
10111          remote_ops from the target stack, which closes the remote
10112          connection.  */
10113       target_mourn_inferior (inferior_ptid);
10114
10115       return;
10116     }
10117
10118   error (_("Can't kill process"));
10119 }
10120
10121 /* Send a kill request to the target using the 'vKill' packet.  */
10122
10123 int
10124 remote_target::remote_vkill (int pid)
10125 {
10126   if (packet_support (PACKET_vKill) == PACKET_DISABLE)
10127     return -1;
10128
10129   remote_state *rs = get_remote_state ();
10130
10131   /* Tell the remote target to detach.  */
10132   xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10133   putpkt (rs->buf);
10134   getpkt (&rs->buf, 0);
10135
10136   switch (packet_ok (rs->buf,
10137                      &remote_protocol_packets[PACKET_vKill]))
10138     {
10139     case PACKET_OK:
10140       return 0;
10141     case PACKET_ERROR:
10142       return 1;
10143     case PACKET_UNKNOWN:
10144       return -1;
10145     default:
10146       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
10147     }
10148 }
10149
10150 /* Send a kill request to the target using the 'k' packet.  */
10151
10152 void
10153 remote_target::remote_kill_k ()
10154 {
10155   /* Catch errors so the user can quit from gdb even when we
10156      aren't on speaking terms with the remote system.  */
10157   try
10158     {
10159       putpkt ("k");
10160     }
10161   catch (const gdb_exception_error &ex)
10162     {
10163       if (ex.error == TARGET_CLOSE_ERROR)
10164         {
10165           /* If we got an (EOF) error that caused the target
10166              to go away, then we're done, that's what we wanted.
10167              "k" is susceptible to cause a premature EOF, given
10168              that the remote server isn't actually required to
10169              reply to "k", and it can happen that it doesn't
10170              even get to reply ACK to the "k".  */
10171           return;
10172         }
10173
10174       /* Otherwise, something went wrong.  We didn't actually kill
10175          the target.  Just propagate the exception, and let the
10176          user or higher layers decide what to do.  */
10177       throw;
10178     }
10179 }
10180
10181 void
10182 remote_target::mourn_inferior ()
10183 {
10184   struct remote_state *rs = get_remote_state ();
10185
10186   /* We're no longer interested in notification events of an inferior
10187      that exited or was killed/detached.  */
10188   discard_pending_stop_replies (current_inferior ());
10189
10190   /* In 'target remote' mode with one inferior, we close the connection.  */
10191   if (!rs->extended && number_of_live_inferiors (this) <= 1)
10192     {
10193       remote_unpush_target (this);
10194       return;
10195     }
10196
10197   /* In case we got here due to an error, but we're going to stay
10198      connected.  */
10199   rs->waiting_for_stop_reply = 0;
10200
10201   /* If the current general thread belonged to the process we just
10202      detached from or has exited, the remote side current general
10203      thread becomes undefined.  Considering a case like this:
10204
10205      - We just got here due to a detach.
10206      - The process that we're detaching from happens to immediately
10207        report a global breakpoint being hit in non-stop mode, in the
10208        same thread we had selected before.
10209      - GDB attaches to this process again.
10210      - This event happens to be the next event we handle.
10211
10212      GDB would consider that the current general thread didn't need to
10213      be set on the stub side (with Hg), since for all it knew,
10214      GENERAL_THREAD hadn't changed.
10215
10216      Notice that although in all-stop mode, the remote server always
10217      sets the current thread to the thread reporting the stop event,
10218      that doesn't happen in non-stop mode; in non-stop, the stub *must
10219      not* change the current thread when reporting a breakpoint hit,
10220      due to the decoupling of event reporting and event handling.
10221
10222      To keep things simple, we always invalidate our notion of the
10223      current thread.  */
10224   record_currthread (rs, minus_one_ptid);
10225
10226   /* Call common code to mark the inferior as not running.  */
10227   generic_mourn_inferior ();
10228 }
10229
10230 bool
10231 extended_remote_target::supports_disable_randomization ()
10232 {
10233   return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
10234 }
10235
10236 void
10237 remote_target::extended_remote_disable_randomization (int val)
10238 {
10239   struct remote_state *rs = get_remote_state ();
10240   char *reply;
10241
10242   xsnprintf (rs->buf.data (), get_remote_packet_size (),
10243              "QDisableRandomization:%x", val);
10244   putpkt (rs->buf);
10245   reply = remote_get_noisy_reply ();
10246   if (*reply == '\0')
10247     error (_("Target does not support QDisableRandomization."));
10248   if (strcmp (reply, "OK") != 0)
10249     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10250 }
10251
10252 int
10253 remote_target::extended_remote_run (const std::string &args)
10254 {
10255   struct remote_state *rs = get_remote_state ();
10256   int len;
10257   const char *remote_exec_file = get_remote_exec_file ();
10258
10259   /* If the user has disabled vRun support, or we have detected that
10260      support is not available, do not try it.  */
10261   if (packet_support (PACKET_vRun) == PACKET_DISABLE)
10262     return -1;
10263
10264   strcpy (rs->buf.data (), "vRun;");
10265   len = strlen (rs->buf.data ());
10266
10267   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10268     error (_("Remote file name too long for run packet"));
10269   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10270                       strlen (remote_exec_file));
10271
10272   if (!args.empty ())
10273     {
10274       int i;
10275
10276       gdb_argv argv (args.c_str ());
10277       for (i = 0; argv[i] != NULL; i++)
10278         {
10279           if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10280             error (_("Argument list too long for run packet"));
10281           rs->buf[len++] = ';';
10282           len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10283                               strlen (argv[i]));
10284         }
10285     }
10286
10287   rs->buf[len++] = '\0';
10288
10289   putpkt (rs->buf);
10290   getpkt (&rs->buf, 0);
10291
10292   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
10293     {
10294     case PACKET_OK:
10295       /* We have a wait response.  All is well.  */
10296       return 0;
10297     case PACKET_UNKNOWN:
10298       return -1;
10299     case PACKET_ERROR:
10300       if (remote_exec_file[0] == '\0')
10301         error (_("Running the default executable on the remote target failed; "
10302                  "try \"set remote exec-file\"?"));
10303       else
10304         error (_("Running \"%s\" on the remote target failed"),
10305                remote_exec_file);
10306     default:
10307       gdb_assert_not_reached (_("bad switch"));
10308     }
10309 }
10310
10311 /* Helper function to send set/unset environment packets.  ACTION is
10312    either "set" or "unset".  PACKET is either "QEnvironmentHexEncoded"
10313    or "QEnvironmentUnsetVariable".  VALUE is the variable to be
10314    sent.  */
10315
10316 void
10317 remote_target::send_environment_packet (const char *action,
10318                                         const char *packet,
10319                                         const char *value)
10320 {
10321   remote_state *rs = get_remote_state ();
10322
10323   /* Convert the environment variable to an hex string, which
10324      is the best format to be transmitted over the wire.  */
10325   std::string encoded_value = bin2hex ((const gdb_byte *) value,
10326                                          strlen (value));
10327
10328   xsnprintf (rs->buf.data (), get_remote_packet_size (),
10329              "%s:%s", packet, encoded_value.c_str ());
10330
10331   putpkt (rs->buf);
10332   getpkt (&rs->buf, 0);
10333   if (strcmp (rs->buf.data (), "OK") != 0)
10334     warning (_("Unable to %s environment variable '%s' on remote."),
10335              action, value);
10336 }
10337
10338 /* Helper function to handle the QEnvironment* packets.  */
10339
10340 void
10341 remote_target::extended_remote_environment_support ()
10342 {
10343   remote_state *rs = get_remote_state ();
10344
10345   if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10346     {
10347       putpkt ("QEnvironmentReset");
10348       getpkt (&rs->buf, 0);
10349       if (strcmp (rs->buf.data (), "OK") != 0)
10350         warning (_("Unable to reset environment on remote."));
10351     }
10352
10353   gdb_environ *e = &current_inferior ()->environment;
10354
10355   if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10356     for (const std::string &el : e->user_set_env ())
10357       send_environment_packet ("set", "QEnvironmentHexEncoded",
10358                                el.c_str ());
10359
10360   if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10361     for (const std::string &el : e->user_unset_env ())
10362       send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10363 }
10364
10365 /* Helper function to set the current working directory for the
10366    inferior in the remote target.  */
10367
10368 void
10369 remote_target::extended_remote_set_inferior_cwd ()
10370 {
10371   if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10372     {
10373       const char *inferior_cwd = get_inferior_cwd ();
10374       remote_state *rs = get_remote_state ();
10375
10376       if (inferior_cwd != NULL)
10377         {
10378           std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
10379                                          strlen (inferior_cwd));
10380
10381           xsnprintf (rs->buf.data (), get_remote_packet_size (),
10382                      "QSetWorkingDir:%s", hexpath.c_str ());
10383         }
10384       else
10385         {
10386           /* An empty inferior_cwd means that the user wants us to
10387              reset the remote server's inferior's cwd.  */
10388           xsnprintf (rs->buf.data (), get_remote_packet_size (),
10389                      "QSetWorkingDir:");
10390         }
10391
10392       putpkt (rs->buf);
10393       getpkt (&rs->buf, 0);
10394       if (packet_ok (rs->buf,
10395                      &remote_protocol_packets[PACKET_QSetWorkingDir])
10396           != PACKET_OK)
10397         error (_("\
10398 Remote replied unexpectedly while setting the inferior's working\n\
10399 directory: %s"),
10400                rs->buf.data ());
10401
10402     }
10403 }
10404
10405 /* In the extended protocol we want to be able to do things like
10406    "run" and have them basically work as expected.  So we need
10407    a special create_inferior function.  We support changing the
10408    executable file and the command line arguments, but not the
10409    environment.  */
10410
10411 void
10412 extended_remote_target::create_inferior (const char *exec_file,
10413                                          const std::string &args,
10414                                          char **env, int from_tty)
10415 {
10416   int run_worked;
10417   char *stop_reply;
10418   struct remote_state *rs = get_remote_state ();
10419   const char *remote_exec_file = get_remote_exec_file ();
10420
10421   /* If running asynchronously, register the target file descriptor
10422      with the event loop.  */
10423   if (target_can_async_p ())
10424     target_async (1);
10425
10426   /* Disable address space randomization if requested (and supported).  */
10427   if (supports_disable_randomization ())
10428     extended_remote_disable_randomization (disable_randomization);
10429
10430   /* If startup-with-shell is on, we inform gdbserver to start the
10431      remote inferior using a shell.  */
10432   if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10433     {
10434       xsnprintf (rs->buf.data (), get_remote_packet_size (),
10435                  "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10436       putpkt (rs->buf);
10437       getpkt (&rs->buf, 0);
10438       if (strcmp (rs->buf.data (), "OK") != 0)
10439         error (_("\
10440 Remote replied unexpectedly while setting startup-with-shell: %s"),
10441                rs->buf.data ());
10442     }
10443
10444   extended_remote_environment_support ();
10445
10446   extended_remote_set_inferior_cwd ();
10447
10448   /* Now restart the remote server.  */
10449   run_worked = extended_remote_run (args) != -1;
10450   if (!run_worked)
10451     {
10452       /* vRun was not supported.  Fail if we need it to do what the
10453          user requested.  */
10454       if (remote_exec_file[0])
10455         error (_("Remote target does not support \"set remote exec-file\""));
10456       if (!args.empty ())
10457         error (_("Remote target does not support \"set args\" or run ARGS"));
10458
10459       /* Fall back to "R".  */
10460       extended_remote_restart ();
10461     }
10462
10463   /* vRun's success return is a stop reply.  */
10464   stop_reply = run_worked ? rs->buf.data () : NULL;
10465   add_current_inferior_and_thread (stop_reply);
10466
10467   /* Get updated offsets, if the stub uses qOffsets.  */
10468   get_offsets ();
10469 }
10470 \f
10471
10472 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
10473    the list of conditions (in agent expression bytecode format), if any, the
10474    target needs to evaluate.  The output is placed into the packet buffer
10475    started from BUF and ended at BUF_END.  */
10476
10477 static int
10478 remote_add_target_side_condition (struct gdbarch *gdbarch,
10479                                   struct bp_target_info *bp_tgt, char *buf,
10480                                   char *buf_end)
10481 {
10482   if (bp_tgt->conditions.empty ())
10483     return 0;
10484
10485   buf += strlen (buf);
10486   xsnprintf (buf, buf_end - buf, "%s", ";");
10487   buf++;
10488
10489   /* Send conditions to the target.  */
10490   for (agent_expr *aexpr : bp_tgt->conditions)
10491     {
10492       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10493       buf += strlen (buf);
10494       for (int i = 0; i < aexpr->len; ++i)
10495         buf = pack_hex_byte (buf, aexpr->buf[i]);
10496       *buf = '\0';
10497     }
10498   return 0;
10499 }
10500
10501 static void
10502 remote_add_target_side_commands (struct gdbarch *gdbarch,
10503                                  struct bp_target_info *bp_tgt, char *buf)
10504 {
10505   if (bp_tgt->tcommands.empty ())
10506     return;
10507
10508   buf += strlen (buf);
10509
10510   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10511   buf += strlen (buf);
10512
10513   /* Concatenate all the agent expressions that are commands into the
10514      cmds parameter.  */
10515   for (agent_expr *aexpr : bp_tgt->tcommands)
10516     {
10517       sprintf (buf, "X%x,", aexpr->len);
10518       buf += strlen (buf);
10519       for (int i = 0; i < aexpr->len; ++i)
10520         buf = pack_hex_byte (buf, aexpr->buf[i]);
10521       *buf = '\0';
10522     }
10523 }
10524
10525 /* Insert a breakpoint.  On targets that have software breakpoint
10526    support, we ask the remote target to do the work; on targets
10527    which don't, we insert a traditional memory breakpoint.  */
10528
10529 int
10530 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10531                                   struct bp_target_info *bp_tgt)
10532 {
10533   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10534      If it succeeds, then set the support to PACKET_ENABLE.  If it
10535      fails, and the user has explicitly requested the Z support then
10536      report an error, otherwise, mark it disabled and go on.  */
10537
10538   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10539     {
10540       CORE_ADDR addr = bp_tgt->reqstd_address;
10541       struct remote_state *rs;
10542       char *p, *endbuf;
10543
10544       /* Make sure the remote is pointing at the right process, if
10545          necessary.  */
10546       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10547         set_general_process ();
10548
10549       rs = get_remote_state ();
10550       p = rs->buf.data ();
10551       endbuf = p + get_remote_packet_size ();
10552
10553       *(p++) = 'Z';
10554       *(p++) = '0';
10555       *(p++) = ',';
10556       addr = (ULONGEST) remote_address_masked (addr);
10557       p += hexnumstr (p, addr);
10558       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10559
10560       if (supports_evaluation_of_breakpoint_conditions ())
10561         remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10562
10563       if (can_run_breakpoint_commands ())
10564         remote_add_target_side_commands (gdbarch, bp_tgt, p);
10565
10566       putpkt (rs->buf);
10567       getpkt (&rs->buf, 0);
10568
10569       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10570         {
10571         case PACKET_ERROR:
10572           return -1;
10573         case PACKET_OK:
10574           return 0;
10575         case PACKET_UNKNOWN:
10576           break;
10577         }
10578     }
10579
10580   /* If this breakpoint has target-side commands but this stub doesn't
10581      support Z0 packets, throw error.  */
10582   if (!bp_tgt->tcommands.empty ())
10583     throw_error (NOT_SUPPORTED_ERROR, _("\
10584 Target doesn't support breakpoints that have target side commands."));
10585
10586   return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10587 }
10588
10589 int
10590 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10591                                   struct bp_target_info *bp_tgt,
10592                                   enum remove_bp_reason reason)
10593 {
10594   CORE_ADDR addr = bp_tgt->placed_address;
10595   struct remote_state *rs = get_remote_state ();
10596
10597   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10598     {
10599       char *p = rs->buf.data ();
10600       char *endbuf = p + get_remote_packet_size ();
10601
10602       /* Make sure the remote is pointing at the right process, if
10603          necessary.  */
10604       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10605         set_general_process ();
10606
10607       *(p++) = 'z';
10608       *(p++) = '0';
10609       *(p++) = ',';
10610
10611       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10612       p += hexnumstr (p, addr);
10613       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10614
10615       putpkt (rs->buf);
10616       getpkt (&rs->buf, 0);
10617
10618       return (rs->buf[0] == 'E');
10619     }
10620
10621   return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10622 }
10623
10624 static enum Z_packet_type
10625 watchpoint_to_Z_packet (int type)
10626 {
10627   switch (type)
10628     {
10629     case hw_write:
10630       return Z_PACKET_WRITE_WP;
10631       break;
10632     case hw_read:
10633       return Z_PACKET_READ_WP;
10634       break;
10635     case hw_access:
10636       return Z_PACKET_ACCESS_WP;
10637       break;
10638     default:
10639       internal_error (__FILE__, __LINE__,
10640                       _("hw_bp_to_z: bad watchpoint type %d"), type);
10641     }
10642 }
10643
10644 int
10645 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10646                                   enum target_hw_bp_type type, struct expression *cond)
10647 {
10648   struct remote_state *rs = get_remote_state ();
10649   char *endbuf = rs->buf.data () + get_remote_packet_size ();
10650   char *p;
10651   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10652
10653   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10654     return 1;
10655
10656   /* Make sure the remote is pointing at the right process, if
10657      necessary.  */
10658   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10659     set_general_process ();
10660
10661   xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10662   p = strchr (rs->buf.data (), '\0');
10663   addr = remote_address_masked (addr);
10664   p += hexnumstr (p, (ULONGEST) addr);
10665   xsnprintf (p, endbuf - p, ",%x", len);
10666
10667   putpkt (rs->buf);
10668   getpkt (&rs->buf, 0);
10669
10670   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10671     {
10672     case PACKET_ERROR:
10673       return -1;
10674     case PACKET_UNKNOWN:
10675       return 1;
10676     case PACKET_OK:
10677       return 0;
10678     }
10679   internal_error (__FILE__, __LINE__,
10680                   _("remote_insert_watchpoint: reached end of function"));
10681 }
10682
10683 bool
10684 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10685                                              CORE_ADDR start, int length)
10686 {
10687   CORE_ADDR diff = remote_address_masked (addr - start);
10688
10689   return diff < length;
10690 }
10691
10692
10693 int
10694 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10695                                   enum target_hw_bp_type type, struct expression *cond)
10696 {
10697   struct remote_state *rs = get_remote_state ();
10698   char *endbuf = rs->buf.data () + get_remote_packet_size ();
10699   char *p;
10700   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10701
10702   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10703     return -1;
10704
10705   /* Make sure the remote is pointing at the right process, if
10706      necessary.  */
10707   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10708     set_general_process ();
10709
10710   xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10711   p = strchr (rs->buf.data (), '\0');
10712   addr = remote_address_masked (addr);
10713   p += hexnumstr (p, (ULONGEST) addr);
10714   xsnprintf (p, endbuf - p, ",%x", len);
10715   putpkt (rs->buf);
10716   getpkt (&rs->buf, 0);
10717
10718   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10719     {
10720     case PACKET_ERROR:
10721     case PACKET_UNKNOWN:
10722       return -1;
10723     case PACKET_OK:
10724       return 0;
10725     }
10726   internal_error (__FILE__, __LINE__,
10727                   _("remote_remove_watchpoint: reached end of function"));
10728 }
10729
10730
10731 static int remote_hw_watchpoint_limit = -1;
10732 static int remote_hw_watchpoint_length_limit = -1;
10733 static int remote_hw_breakpoint_limit = -1;
10734
10735 int
10736 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10737 {
10738   if (remote_hw_watchpoint_length_limit == 0)
10739     return 0;
10740   else if (remote_hw_watchpoint_length_limit < 0)
10741     return 1;
10742   else if (len <= remote_hw_watchpoint_length_limit)
10743     return 1;
10744   else
10745     return 0;
10746 }
10747
10748 int
10749 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10750 {
10751   if (type == bp_hardware_breakpoint)
10752     {
10753       if (remote_hw_breakpoint_limit == 0)
10754         return 0;
10755       else if (remote_hw_breakpoint_limit < 0)
10756         return 1;
10757       else if (cnt <= remote_hw_breakpoint_limit)
10758         return 1;
10759     }
10760   else
10761     {
10762       if (remote_hw_watchpoint_limit == 0)
10763         return 0;
10764       else if (remote_hw_watchpoint_limit < 0)
10765         return 1;
10766       else if (ot)
10767         return -1;
10768       else if (cnt <= remote_hw_watchpoint_limit)
10769         return 1;
10770     }
10771   return -1;
10772 }
10773
10774 /* The to_stopped_by_sw_breakpoint method of target remote.  */
10775
10776 bool
10777 remote_target::stopped_by_sw_breakpoint ()
10778 {
10779   struct thread_info *thread = inferior_thread ();
10780
10781   return (thread->priv != NULL
10782           && (get_remote_thread_info (thread)->stop_reason
10783               == TARGET_STOPPED_BY_SW_BREAKPOINT));
10784 }
10785
10786 /* The to_supports_stopped_by_sw_breakpoint method of target
10787    remote.  */
10788
10789 bool
10790 remote_target::supports_stopped_by_sw_breakpoint ()
10791 {
10792   return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10793 }
10794
10795 /* The to_stopped_by_hw_breakpoint method of target remote.  */
10796
10797 bool
10798 remote_target::stopped_by_hw_breakpoint ()
10799 {
10800   struct thread_info *thread = inferior_thread ();
10801
10802   return (thread->priv != NULL
10803           && (get_remote_thread_info (thread)->stop_reason
10804               == TARGET_STOPPED_BY_HW_BREAKPOINT));
10805 }
10806
10807 /* The to_supports_stopped_by_hw_breakpoint method of target
10808    remote.  */
10809
10810 bool
10811 remote_target::supports_stopped_by_hw_breakpoint ()
10812 {
10813   return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10814 }
10815
10816 bool
10817 remote_target::stopped_by_watchpoint ()
10818 {
10819   struct thread_info *thread = inferior_thread ();
10820
10821   return (thread->priv != NULL
10822           && (get_remote_thread_info (thread)->stop_reason
10823               == TARGET_STOPPED_BY_WATCHPOINT));
10824 }
10825
10826 bool
10827 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10828 {
10829   struct thread_info *thread = inferior_thread ();
10830
10831   if (thread->priv != NULL
10832       && (get_remote_thread_info (thread)->stop_reason
10833           == TARGET_STOPPED_BY_WATCHPOINT))
10834     {
10835       *addr_p = get_remote_thread_info (thread)->watch_data_address;
10836       return true;
10837     }
10838
10839   return false;
10840 }
10841
10842
10843 int
10844 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10845                                      struct bp_target_info *bp_tgt)
10846 {
10847   CORE_ADDR addr = bp_tgt->reqstd_address;
10848   struct remote_state *rs;
10849   char *p, *endbuf;
10850   char *message;
10851
10852   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10853     return -1;
10854
10855   /* Make sure the remote is pointing at the right process, if
10856      necessary.  */
10857   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10858     set_general_process ();
10859
10860   rs = get_remote_state ();
10861   p = rs->buf.data ();
10862   endbuf = p + get_remote_packet_size ();
10863
10864   *(p++) = 'Z';
10865   *(p++) = '1';
10866   *(p++) = ',';
10867
10868   addr = remote_address_masked (addr);
10869   p += hexnumstr (p, (ULONGEST) addr);
10870   xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10871
10872   if (supports_evaluation_of_breakpoint_conditions ())
10873     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10874
10875   if (can_run_breakpoint_commands ())
10876     remote_add_target_side_commands (gdbarch, bp_tgt, p);
10877
10878   putpkt (rs->buf);
10879   getpkt (&rs->buf, 0);
10880
10881   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10882     {
10883     case PACKET_ERROR:
10884       if (rs->buf[1] == '.')
10885         {
10886           message = strchr (&rs->buf[2], '.');
10887           if (message)
10888             error (_("Remote failure reply: %s"), message + 1);
10889         }
10890       return -1;
10891     case PACKET_UNKNOWN:
10892       return -1;
10893     case PACKET_OK:
10894       return 0;
10895     }
10896   internal_error (__FILE__, __LINE__,
10897                   _("remote_insert_hw_breakpoint: reached end of function"));
10898 }
10899
10900
10901 int
10902 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10903                                      struct bp_target_info *bp_tgt)
10904 {
10905   CORE_ADDR addr;
10906   struct remote_state *rs = get_remote_state ();
10907   char *p = rs->buf.data ();
10908   char *endbuf = p + get_remote_packet_size ();
10909
10910   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10911     return -1;
10912
10913   /* Make sure the remote is pointing at the right process, if
10914      necessary.  */
10915   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10916     set_general_process ();
10917
10918   *(p++) = 'z';
10919   *(p++) = '1';
10920   *(p++) = ',';
10921
10922   addr = remote_address_masked (bp_tgt->placed_address);
10923   p += hexnumstr (p, (ULONGEST) addr);
10924   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->kind);
10925
10926   putpkt (rs->buf);
10927   getpkt (&rs->buf, 0);
10928
10929   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10930     {
10931     case PACKET_ERROR:
10932     case PACKET_UNKNOWN:
10933       return -1;
10934     case PACKET_OK:
10935       return 0;
10936     }
10937   internal_error (__FILE__, __LINE__,
10938                   _("remote_remove_hw_breakpoint: reached end of function"));
10939 }
10940
10941 /* Verify memory using the "qCRC:" request.  */
10942
10943 int
10944 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10945 {
10946   struct remote_state *rs = get_remote_state ();
10947   unsigned long host_crc, target_crc;
10948   char *tmp;
10949
10950   /* It doesn't make sense to use qCRC if the remote target is
10951      connected but not running.  */
10952   if (target_has_execution ()
10953       && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10954     {
10955       enum packet_result result;
10956
10957       /* Make sure the remote is pointing at the right process.  */
10958       set_general_process ();
10959
10960       /* FIXME: assumes lma can fit into long.  */
10961       xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
10962                  (long) lma, (long) size);
10963       putpkt (rs->buf);
10964
10965       /* Be clever; compute the host_crc before waiting for target
10966          reply.  */
10967       host_crc = xcrc32 (data, size, 0xffffffff);
10968
10969       getpkt (&rs->buf, 0);
10970
10971       result = packet_ok (rs->buf,
10972                           &remote_protocol_packets[PACKET_qCRC]);
10973       if (result == PACKET_ERROR)
10974         return -1;
10975       else if (result == PACKET_OK)
10976         {
10977           for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10978             target_crc = target_crc * 16 + fromhex (*tmp);
10979
10980           return (host_crc == target_crc);
10981         }
10982     }
10983
10984   return simple_verify_memory (this, data, lma, size);
10985 }
10986
10987 /* compare-sections command
10988
10989    With no arguments, compares each loadable section in the exec bfd
10990    with the same memory range on the target, and reports mismatches.
10991    Useful for verifying the image on the target against the exec file.  */
10992
10993 static void
10994 compare_sections_command (const char *args, int from_tty)
10995 {
10996   asection *s;
10997   const char *sectname;
10998   bfd_size_type size;
10999   bfd_vma lma;
11000   int matched = 0;
11001   int mismatched = 0;
11002   int res;
11003   int read_only = 0;
11004
11005   if (!current_program_space->exec_bfd ())
11006     error (_("command cannot be used without an exec file"));
11007
11008   if (args != NULL && strcmp (args, "-r") == 0)
11009     {
11010       read_only = 1;
11011       args = NULL;
11012     }
11013
11014   for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11015     {
11016       if (!(s->flags & SEC_LOAD))
11017         continue;               /* Skip non-loadable section.  */
11018
11019       if (read_only && (s->flags & SEC_READONLY) == 0)
11020         continue;               /* Skip writeable sections */
11021
11022       size = bfd_section_size (s);
11023       if (size == 0)
11024         continue;               /* Skip zero-length section.  */
11025
11026       sectname = bfd_section_name (s);
11027       if (args && strcmp (args, sectname) != 0)
11028         continue;               /* Not the section selected by user.  */
11029
11030       matched = 1;              /* Do this section.  */
11031       lma = s->lma;
11032
11033       gdb::byte_vector sectdata (size);
11034       bfd_get_section_contents (current_program_space->exec_bfd (), s,
11035                                 sectdata.data (), 0, size);
11036
11037       res = target_verify_memory (sectdata.data (), lma, size);
11038
11039       if (res == -1)
11040         error (_("target memory fault, section %s, range %s -- %s"), sectname,
11041                paddress (target_gdbarch (), lma),
11042                paddress (target_gdbarch (), lma + size));
11043
11044       printf_filtered ("Section %s, range %s -- %s: ", sectname,
11045                        paddress (target_gdbarch (), lma),
11046                        paddress (target_gdbarch (), lma + size));
11047       if (res)
11048         printf_filtered ("matched.\n");
11049       else
11050         {
11051           printf_filtered ("MIS-MATCHED!\n");
11052           mismatched++;
11053         }
11054     }
11055   if (mismatched > 0)
11056     warning (_("One or more sections of the target image does not match\n\
11057 the loaded file\n"));
11058   if (args && !matched)
11059     printf_filtered (_("No loaded section named '%s'.\n"), args);
11060 }
11061
11062 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11063    into remote target.  The number of bytes written to the remote
11064    target is returned, or -1 for error.  */
11065
11066 target_xfer_status
11067 remote_target::remote_write_qxfer (const char *object_name,
11068                                    const char *annex, const gdb_byte *writebuf,
11069                                    ULONGEST offset, LONGEST len,
11070                                    ULONGEST *xfered_len,
11071                                    struct packet_config *packet)
11072 {
11073   int i, buf_len;
11074   ULONGEST n;
11075   struct remote_state *rs = get_remote_state ();
11076   int max_size = get_memory_write_packet_size (); 
11077
11078   if (packet_config_support (packet) == PACKET_DISABLE)
11079     return TARGET_XFER_E_IO;
11080
11081   /* Insert header.  */
11082   i = snprintf (rs->buf.data (), max_size, 
11083                 "qXfer:%s:write:%s:%s:",
11084                 object_name, annex ? annex : "",
11085                 phex_nz (offset, sizeof offset));
11086   max_size -= (i + 1);
11087
11088   /* Escape as much data as fits into rs->buf.  */
11089   buf_len = remote_escape_output 
11090     (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11091
11092   if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11093       || getpkt_sane (&rs->buf, 0) < 0
11094       || packet_ok (rs->buf, packet) != PACKET_OK)
11095     return TARGET_XFER_E_IO;
11096
11097   unpack_varlen_hex (rs->buf.data (), &n);
11098
11099   *xfered_len = n;
11100   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11101 }
11102
11103 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11104    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11105    number of bytes read is returned, or 0 for EOF, or -1 for error.
11106    The number of bytes read may be less than LEN without indicating an
11107    EOF.  PACKET is checked and updated to indicate whether the remote
11108    target supports this object.  */
11109
11110 target_xfer_status
11111 remote_target::remote_read_qxfer (const char *object_name,
11112                                   const char *annex,
11113                                   gdb_byte *readbuf, ULONGEST offset,
11114                                   LONGEST len,
11115                                   ULONGEST *xfered_len,
11116                                   struct packet_config *packet)
11117 {
11118   struct remote_state *rs = get_remote_state ();
11119   LONGEST i, n, packet_len;
11120
11121   if (packet_config_support (packet) == PACKET_DISABLE)
11122     return TARGET_XFER_E_IO;
11123
11124   /* Check whether we've cached an end-of-object packet that matches
11125      this request.  */
11126   if (rs->finished_object)
11127     {
11128       if (strcmp (object_name, rs->finished_object) == 0
11129           && strcmp (annex ? annex : "", rs->finished_annex) == 0
11130           && offset == rs->finished_offset)
11131         return TARGET_XFER_EOF;
11132
11133
11134       /* Otherwise, we're now reading something different.  Discard
11135          the cache.  */
11136       xfree (rs->finished_object);
11137       xfree (rs->finished_annex);
11138       rs->finished_object = NULL;
11139       rs->finished_annex = NULL;
11140     }
11141
11142   /* Request only enough to fit in a single packet.  The actual data
11143      may not, since we don't know how much of it will need to be escaped;
11144      the target is free to respond with slightly less data.  We subtract
11145      five to account for the response type and the protocol frame.  */
11146   n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11147   snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11148             "qXfer:%s:read:%s:%s,%s",
11149             object_name, annex ? annex : "",
11150             phex_nz (offset, sizeof offset),
11151             phex_nz (n, sizeof n));
11152   i = putpkt (rs->buf);
11153   if (i < 0)
11154     return TARGET_XFER_E_IO;
11155
11156   rs->buf[0] = '\0';
11157   packet_len = getpkt_sane (&rs->buf, 0);
11158   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
11159     return TARGET_XFER_E_IO;
11160
11161   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11162     error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11163
11164   /* 'm' means there is (or at least might be) more data after this
11165      batch.  That does not make sense unless there's at least one byte
11166      of data in this reply.  */
11167   if (rs->buf[0] == 'm' && packet_len == 1)
11168     error (_("Remote qXfer reply contained no data."));
11169
11170   /* Got some data.  */
11171   i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11172                              packet_len - 1, readbuf, n);
11173
11174   /* 'l' is an EOF marker, possibly including a final block of data,
11175      or possibly empty.  If we have the final block of a non-empty
11176      object, record this fact to bypass a subsequent partial read.  */
11177   if (rs->buf[0] == 'l' && offset + i > 0)
11178     {
11179       rs->finished_object = xstrdup (object_name);
11180       rs->finished_annex = xstrdup (annex ? annex : "");
11181       rs->finished_offset = offset + i;
11182     }
11183
11184   if (i == 0)
11185     return TARGET_XFER_EOF;
11186   else
11187     {
11188       *xfered_len = i;
11189       return TARGET_XFER_OK;
11190     }
11191 }
11192
11193 enum target_xfer_status
11194 remote_target::xfer_partial (enum target_object object,
11195                              const char *annex, gdb_byte *readbuf,
11196                              const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11197                              ULONGEST *xfered_len)
11198 {
11199   struct remote_state *rs;
11200   int i;
11201   char *p2;
11202   char query_type;
11203   int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
11204
11205   set_remote_traceframe ();
11206   set_general_thread (inferior_ptid);
11207
11208   rs = get_remote_state ();
11209
11210   /* Handle memory using the standard memory routines.  */
11211   if (object == TARGET_OBJECT_MEMORY)
11212     {
11213       /* If the remote target is connected but not running, we should
11214          pass this request down to a lower stratum (e.g. the executable
11215          file).  */
11216       if (!target_has_execution ())
11217         return TARGET_XFER_EOF;
11218
11219       if (writebuf != NULL)
11220         return remote_write_bytes (offset, writebuf, len, unit_size,
11221                                    xfered_len);
11222       else
11223         return remote_read_bytes (offset, readbuf, len, unit_size,
11224                                   xfered_len);
11225     }
11226
11227   /* Handle extra signal info using qxfer packets.  */
11228   if (object == TARGET_OBJECT_SIGNAL_INFO)
11229     {
11230       if (readbuf)
11231         return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11232                                   xfered_len, &remote_protocol_packets
11233                                   [PACKET_qXfer_siginfo_read]);
11234       else
11235         return remote_write_qxfer ("siginfo", annex,
11236                                    writebuf, offset, len, xfered_len,
11237                                    &remote_protocol_packets
11238                                    [PACKET_qXfer_siginfo_write]);
11239     }
11240
11241   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11242     {
11243       if (readbuf)
11244         return remote_read_qxfer ("statictrace", annex,
11245                                   readbuf, offset, len, xfered_len,
11246                                   &remote_protocol_packets
11247                                   [PACKET_qXfer_statictrace_read]);
11248       else
11249         return TARGET_XFER_E_IO;
11250     }
11251
11252   /* Only handle flash writes.  */
11253   if (writebuf != NULL)
11254     {
11255       switch (object)
11256         {
11257         case TARGET_OBJECT_FLASH:
11258           return remote_flash_write (offset, len, xfered_len,
11259                                      writebuf);
11260
11261         default:
11262           return TARGET_XFER_E_IO;
11263         }
11264     }
11265
11266   /* Map pre-existing objects onto letters.  DO NOT do this for new
11267      objects!!!  Instead specify new query packets.  */
11268   switch (object)
11269     {
11270     case TARGET_OBJECT_AVR:
11271       query_type = 'R';
11272       break;
11273
11274     case TARGET_OBJECT_AUXV:
11275       gdb_assert (annex == NULL);
11276       return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
11277                                 xfered_len,
11278                                 &remote_protocol_packets[PACKET_qXfer_auxv]);
11279
11280     case TARGET_OBJECT_AVAILABLE_FEATURES:
11281       return remote_read_qxfer
11282         ("features", annex, readbuf, offset, len, xfered_len,
11283          &remote_protocol_packets[PACKET_qXfer_features]);
11284
11285     case TARGET_OBJECT_LIBRARIES:
11286       return remote_read_qxfer
11287         ("libraries", annex, readbuf, offset, len, xfered_len,
11288          &remote_protocol_packets[PACKET_qXfer_libraries]);
11289
11290     case TARGET_OBJECT_LIBRARIES_SVR4:
11291       return remote_read_qxfer
11292         ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11293          &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
11294
11295     case TARGET_OBJECT_MEMORY_MAP:
11296       gdb_assert (annex == NULL);
11297       return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
11298                                  xfered_len,
11299                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);
11300
11301     case TARGET_OBJECT_OSDATA:
11302       /* Should only get here if we're connected.  */
11303       gdb_assert (rs->remote_desc);
11304       return remote_read_qxfer
11305         ("osdata", annex, readbuf, offset, len, xfered_len,
11306         &remote_protocol_packets[PACKET_qXfer_osdata]);
11307
11308     case TARGET_OBJECT_THREADS:
11309       gdb_assert (annex == NULL);
11310       return remote_read_qxfer ("threads", annex, readbuf, offset, len,
11311                                 xfered_len,
11312                                 &remote_protocol_packets[PACKET_qXfer_threads]);
11313
11314     case TARGET_OBJECT_TRACEFRAME_INFO:
11315       gdb_assert (annex == NULL);
11316       return remote_read_qxfer
11317         ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11318          &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
11319
11320     case TARGET_OBJECT_FDPIC:
11321       return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
11322                                 xfered_len,
11323                                 &remote_protocol_packets[PACKET_qXfer_fdpic]);
11324
11325     case TARGET_OBJECT_OPENVMS_UIB:
11326       return remote_read_qxfer ("uib", annex, readbuf, offset, len,
11327                                 xfered_len,
11328                                 &remote_protocol_packets[PACKET_qXfer_uib]);
11329
11330     case TARGET_OBJECT_BTRACE:
11331       return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
11332                                 xfered_len,
11333         &remote_protocol_packets[PACKET_qXfer_btrace]);
11334
11335     case TARGET_OBJECT_BTRACE_CONF:
11336       return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
11337                                 len, xfered_len,
11338         &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11339
11340     case TARGET_OBJECT_EXEC_FILE:
11341       return remote_read_qxfer ("exec-file", annex, readbuf, offset,
11342                                 len, xfered_len,
11343         &remote_protocol_packets[PACKET_qXfer_exec_file]);
11344
11345     default:
11346       return TARGET_XFER_E_IO;
11347     }
11348
11349   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
11350      large enough let the caller deal with it.  */
11351   if (len < get_remote_packet_size ())
11352     return TARGET_XFER_E_IO;
11353   len = get_remote_packet_size ();
11354
11355   /* Except for querying the minimum buffer size, target must be open.  */
11356   if (!rs->remote_desc)
11357     error (_("remote query is only available after target open"));
11358
11359   gdb_assert (annex != NULL);
11360   gdb_assert (readbuf != NULL);
11361
11362   p2 = rs->buf.data ();
11363   *p2++ = 'q';
11364   *p2++ = query_type;
11365
11366   /* We used one buffer char for the remote protocol q command and
11367      another for the query type.  As the remote protocol encapsulation
11368      uses 4 chars plus one extra in case we are debugging
11369      (remote_debug), we have PBUFZIZ - 7 left to pack the query
11370      string.  */
11371   i = 0;
11372   while (annex[i] && (i < (get_remote_packet_size () - 8)))
11373     {
11374       /* Bad caller may have sent forbidden characters.  */
11375       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11376       *p2++ = annex[i];
11377       i++;
11378     }
11379   *p2 = '\0';
11380   gdb_assert (annex[i] == '\0');
11381
11382   i = putpkt (rs->buf);
11383   if (i < 0)
11384     return TARGET_XFER_E_IO;
11385
11386   getpkt (&rs->buf, 0);
11387   strcpy ((char *) readbuf, rs->buf.data ());
11388
11389   *xfered_len = strlen ((char *) readbuf);
11390   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11391 }
11392
11393 /* Implementation of to_get_memory_xfer_limit.  */
11394
11395 ULONGEST
11396 remote_target::get_memory_xfer_limit ()
11397 {
11398   return get_memory_write_packet_size ();
11399 }
11400
11401 int
11402 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11403                               const gdb_byte *pattern, ULONGEST pattern_len,
11404                               CORE_ADDR *found_addrp)
11405 {
11406   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11407   struct remote_state *rs = get_remote_state ();
11408   int max_size = get_memory_write_packet_size ();
11409   struct packet_config *packet =
11410     &remote_protocol_packets[PACKET_qSearch_memory];
11411   /* Number of packet bytes used to encode the pattern;
11412      this could be more than PATTERN_LEN due to escape characters.  */
11413   int escaped_pattern_len;
11414   /* Amount of pattern that was encodable in the packet.  */
11415   int used_pattern_len;
11416   int i;
11417   int found;
11418   ULONGEST found_addr;
11419
11420   auto read_memory = [=] (CORE_ADDR addr, gdb_byte *result, size_t len)
11421     {
11422       return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11423               == len);
11424     };
11425
11426   /* Don't go to the target if we don't have to.  This is done before
11427      checking packet_config_support to avoid the possibility that a
11428      success for this edge case means the facility works in
11429      general.  */
11430   if (pattern_len > search_space_len)
11431     return 0;
11432   if (pattern_len == 0)
11433     {
11434       *found_addrp = start_addr;
11435       return 1;
11436     }
11437
11438   /* If we already know the packet isn't supported, fall back to the simple
11439      way of searching memory.  */
11440
11441   if (packet_config_support (packet) == PACKET_DISABLE)
11442     {
11443       /* Target doesn't provided special support, fall back and use the
11444          standard support (copy memory and do the search here).  */
11445       return simple_search_memory (read_memory, start_addr, search_space_len,
11446                                    pattern, pattern_len, found_addrp);
11447     }
11448
11449   /* Make sure the remote is pointing at the right process.  */
11450   set_general_process ();
11451
11452   /* Insert header.  */
11453   i = snprintf (rs->buf.data (), max_size, 
11454                 "qSearch:memory:%s;%s;",
11455                 phex_nz (start_addr, addr_size),
11456                 phex_nz (search_space_len, sizeof (search_space_len)));
11457   max_size -= (i + 1);
11458
11459   /* Escape as much data as fits into rs->buf.  */
11460   escaped_pattern_len =
11461     remote_escape_output (pattern, pattern_len, 1,
11462                           (gdb_byte *) rs->buf.data () + i,
11463                           &used_pattern_len, max_size);
11464
11465   /* Bail if the pattern is too large.  */
11466   if (used_pattern_len != pattern_len)
11467     error (_("Pattern is too large to transmit to remote target."));
11468
11469   if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11470       || getpkt_sane (&rs->buf, 0) < 0
11471       || packet_ok (rs->buf, packet) != PACKET_OK)
11472     {
11473       /* The request may not have worked because the command is not
11474          supported.  If so, fall back to the simple way.  */
11475       if (packet_config_support (packet) == PACKET_DISABLE)
11476         {
11477           return simple_search_memory (read_memory, start_addr, search_space_len,
11478                                        pattern, pattern_len, found_addrp);
11479         }
11480       return -1;
11481     }
11482
11483   if (rs->buf[0] == '0')
11484     found = 0;
11485   else if (rs->buf[0] == '1')
11486     {
11487       found = 1;
11488       if (rs->buf[1] != ',')
11489         error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11490       unpack_varlen_hex (&rs->buf[2], &found_addr);
11491       *found_addrp = found_addr;
11492     }
11493   else
11494     error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11495
11496   return found;
11497 }
11498
11499 void
11500 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11501 {
11502   struct remote_state *rs = get_remote_state ();
11503   char *p = rs->buf.data ();
11504
11505   if (!rs->remote_desc)
11506     error (_("remote rcmd is only available after target open"));
11507
11508   /* Send a NULL command across as an empty command.  */
11509   if (command == NULL)
11510     command = "";
11511
11512   /* The query prefix.  */
11513   strcpy (rs->buf.data (), "qRcmd,");
11514   p = strchr (rs->buf.data (), '\0');
11515
11516   if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11517       > get_remote_packet_size ())
11518     error (_("\"monitor\" command ``%s'' is too long."), command);
11519
11520   /* Encode the actual command.  */
11521   bin2hex ((const gdb_byte *) command, p, strlen (command));
11522
11523   if (putpkt (rs->buf) < 0)
11524     error (_("Communication problem with target."));
11525
11526   /* get/display the response */
11527   while (1)
11528     {
11529       char *buf;
11530
11531       /* XXX - see also remote_get_noisy_reply().  */
11532       QUIT;                     /* Allow user to bail out with ^C.  */
11533       rs->buf[0] = '\0';
11534       if (getpkt_sane (&rs->buf, 0) == -1)
11535         { 
11536           /* Timeout.  Continue to (try to) read responses.
11537              This is better than stopping with an error, assuming the stub
11538              is still executing the (long) monitor command.
11539              If needed, the user can interrupt gdb using C-c, obtaining
11540              an effect similar to stop on timeout.  */
11541           continue;
11542         }
11543       buf = rs->buf.data ();
11544       if (buf[0] == '\0')
11545         error (_("Target does not support this command."));
11546       if (buf[0] == 'O' && buf[1] != 'K')
11547         {
11548           remote_console_output (buf + 1); /* 'O' message from stub.  */
11549           continue;
11550         }
11551       if (strcmp (buf, "OK") == 0)
11552         break;
11553       if (strlen (buf) == 3 && buf[0] == 'E'
11554           && isdigit (buf[1]) && isdigit (buf[2]))
11555         {
11556           error (_("Protocol error with Rcmd"));
11557         }
11558       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11559         {
11560           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11561
11562           fputc_unfiltered (c, outbuf);
11563         }
11564       break;
11565     }
11566 }
11567
11568 std::vector<mem_region>
11569 remote_target::memory_map ()
11570 {
11571   std::vector<mem_region> result;
11572   gdb::optional<gdb::char_vector> text
11573     = target_read_stralloc (current_inferior ()->top_target (),
11574                             TARGET_OBJECT_MEMORY_MAP, NULL);
11575
11576   if (text)
11577     result = parse_memory_map (text->data ());
11578
11579   return result;
11580 }
11581
11582 static void
11583 packet_command (const char *args, int from_tty)
11584 {
11585   remote_target *remote = get_current_remote_target ();
11586
11587   if (remote == nullptr)
11588     error (_("command can only be used with remote target"));
11589
11590   remote->packet_command (args, from_tty);
11591 }
11592
11593 void
11594 remote_target::packet_command (const char *args, int from_tty)
11595 {
11596   if (!args)
11597     error (_("remote-packet command requires packet text as argument"));
11598
11599   puts_filtered ("sending: ");
11600   print_packet (args);
11601   puts_filtered ("\n");
11602   putpkt (args);
11603
11604   remote_state *rs = get_remote_state ();
11605
11606   getpkt (&rs->buf, 0);
11607   puts_filtered ("received: ");
11608   print_packet (rs->buf.data ());
11609   puts_filtered ("\n");
11610 }
11611
11612 #if 0
11613 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11614
11615 static void display_thread_info (struct gdb_ext_thread_info *info);
11616
11617 static void threadset_test_cmd (char *cmd, int tty);
11618
11619 static void threadalive_test (char *cmd, int tty);
11620
11621 static void threadlist_test_cmd (char *cmd, int tty);
11622
11623 int get_and_display_threadinfo (threadref *ref);
11624
11625 static void threadinfo_test_cmd (char *cmd, int tty);
11626
11627 static int thread_display_step (threadref *ref, void *context);
11628
11629 static void threadlist_update_test_cmd (char *cmd, int tty);
11630
11631 static void init_remote_threadtests (void);
11632
11633 #define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid.  */
11634
11635 static void
11636 threadset_test_cmd (const char *cmd, int tty)
11637 {
11638   int sample_thread = SAMPLE_THREAD;
11639
11640   printf_filtered (_("Remote threadset test\n"));
11641   set_general_thread (sample_thread);
11642 }
11643
11644
11645 static void
11646 threadalive_test (const char *cmd, int tty)
11647 {
11648   int sample_thread = SAMPLE_THREAD;
11649   int pid = inferior_ptid.pid ();
11650   ptid_t ptid = ptid_t (pid, sample_thread, 0);
11651
11652   if (remote_thread_alive (ptid))
11653     printf_filtered ("PASS: Thread alive test\n");
11654   else
11655     printf_filtered ("FAIL: Thread alive test\n");
11656 }
11657
11658 void output_threadid (char *title, threadref *ref);
11659
11660 void
11661 output_threadid (char *title, threadref *ref)
11662 {
11663   char hexid[20];
11664
11665   pack_threadid (&hexid[0], ref);       /* Convert thread id into hex.  */
11666   hexid[16] = 0;
11667   printf_filtered ("%s  %s\n", title, (&hexid[0]));
11668 }
11669
11670 static void
11671 threadlist_test_cmd (const char *cmd, int tty)
11672 {
11673   int startflag = 1;
11674   threadref nextthread;
11675   int done, result_count;
11676   threadref threadlist[3];
11677
11678   printf_filtered ("Remote Threadlist test\n");
11679   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11680                               &result_count, &threadlist[0]))
11681     printf_filtered ("FAIL: threadlist test\n");
11682   else
11683     {
11684       threadref *scan = threadlist;
11685       threadref *limit = scan + result_count;
11686
11687       while (scan < limit)
11688         output_threadid (" thread ", scan++);
11689     }
11690 }
11691
11692 void
11693 display_thread_info (struct gdb_ext_thread_info *info)
11694 {
11695   output_threadid ("Threadid: ", &info->threadid);
11696   printf_filtered ("Name: %s\n ", info->shortname);
11697   printf_filtered ("State: %s\n", info->display);
11698   printf_filtered ("other: %s\n\n", info->more_display);
11699 }
11700
11701 int
11702 get_and_display_threadinfo (threadref *ref)
11703 {
11704   int result;
11705   int set;
11706   struct gdb_ext_thread_info threadinfo;
11707
11708   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11709     | TAG_MOREDISPLAY | TAG_DISPLAY;
11710   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11711     display_thread_info (&threadinfo);
11712   return result;
11713 }
11714
11715 static void
11716 threadinfo_test_cmd (const char *cmd, int tty)
11717 {
11718   int athread = SAMPLE_THREAD;
11719   threadref thread;
11720   int set;
11721
11722   int_to_threadref (&thread, athread);
11723   printf_filtered ("Remote Threadinfo test\n");
11724   if (!get_and_display_threadinfo (&thread))
11725     printf_filtered ("FAIL cannot get thread info\n");
11726 }
11727
11728 static int
11729 thread_display_step (threadref *ref, void *context)
11730 {
11731   /* output_threadid(" threadstep ",ref); *//* simple test */
11732   return get_and_display_threadinfo (ref);
11733 }
11734
11735 static void
11736 threadlist_update_test_cmd (const char *cmd, int tty)
11737 {
11738   printf_filtered ("Remote Threadlist update test\n");
11739   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11740 }
11741
11742 static void
11743 init_remote_threadtests (void)
11744 {
11745   add_com ("tlist", class_obscure, threadlist_test_cmd,
11746            _("Fetch and print the remote list of "
11747              "thread identifiers, one pkt only."));
11748   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11749            _("Fetch and display info about one thread."));
11750   add_com ("tset", class_obscure, threadset_test_cmd,
11751            _("Test setting to a different thread."));
11752   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11753            _("Iterate through updating all remote thread info."));
11754   add_com ("talive", class_obscure, threadalive_test,
11755            _("Remote thread alive test."));
11756 }
11757
11758 #endif /* 0 */
11759
11760 /* Convert a thread ID to a string.  */
11761
11762 std::string
11763 remote_target::pid_to_str (ptid_t ptid)
11764 {
11765   struct remote_state *rs = get_remote_state ();
11766
11767   if (ptid == null_ptid)
11768     return normal_pid_to_str (ptid);
11769   else if (ptid.is_pid ())
11770     {
11771       /* Printing an inferior target id.  */
11772
11773       /* When multi-process extensions are off, there's no way in the
11774          remote protocol to know the remote process id, if there's any
11775          at all.  There's one exception --- when we're connected with
11776          target extended-remote, and we manually attached to a process
11777          with "attach PID".  We don't record anywhere a flag that
11778          allows us to distinguish that case from the case of
11779          connecting with extended-remote and the stub already being
11780          attached to a process, and reporting yes to qAttached, hence
11781          no smart special casing here.  */
11782       if (!remote_multi_process_p (rs))
11783         return "Remote target";
11784
11785       return normal_pid_to_str (ptid);
11786     }
11787   else
11788     {
11789       if (magic_null_ptid == ptid)
11790         return "Thread <main>";
11791       else if (remote_multi_process_p (rs))
11792         if (ptid.lwp () == 0)
11793           return normal_pid_to_str (ptid);
11794         else
11795           return string_printf ("Thread %d.%ld",
11796                                 ptid.pid (), ptid.lwp ());
11797       else
11798         return string_printf ("Thread %ld", ptid.lwp ());
11799     }
11800 }
11801
11802 /* Get the address of the thread local variable in OBJFILE which is
11803    stored at OFFSET within the thread local storage for thread PTID.  */
11804
11805 CORE_ADDR
11806 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11807                                          CORE_ADDR offset)
11808 {
11809   if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11810     {
11811       struct remote_state *rs = get_remote_state ();
11812       char *p = rs->buf.data ();
11813       char *endp = p + get_remote_packet_size ();
11814       enum packet_result result;
11815
11816       strcpy (p, "qGetTLSAddr:");
11817       p += strlen (p);
11818       p = write_ptid (p, endp, ptid);
11819       *p++ = ',';
11820       p += hexnumstr (p, offset);
11821       *p++ = ',';
11822       p += hexnumstr (p, lm);
11823       *p++ = '\0';
11824
11825       putpkt (rs->buf);
11826       getpkt (&rs->buf, 0);
11827       result = packet_ok (rs->buf,
11828                           &remote_protocol_packets[PACKET_qGetTLSAddr]);
11829       if (result == PACKET_OK)
11830         {
11831           ULONGEST addr;
11832
11833           unpack_varlen_hex (rs->buf.data (), &addr);
11834           return addr;
11835         }
11836       else if (result == PACKET_UNKNOWN)
11837         throw_error (TLS_GENERIC_ERROR,
11838                      _("Remote target doesn't support qGetTLSAddr packet"));
11839       else
11840         throw_error (TLS_GENERIC_ERROR,
11841                      _("Remote target failed to process qGetTLSAddr request"));
11842     }
11843   else
11844     throw_error (TLS_GENERIC_ERROR,
11845                  _("TLS not supported or disabled on this target"));
11846   /* Not reached.  */
11847   return 0;
11848 }
11849
11850 /* Provide thread local base, i.e. Thread Information Block address.
11851    Returns 1 if ptid is found and thread_local_base is non zero.  */
11852
11853 bool
11854 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11855 {
11856   if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11857     {
11858       struct remote_state *rs = get_remote_state ();
11859       char *p = rs->buf.data ();
11860       char *endp = p + get_remote_packet_size ();
11861       enum packet_result result;
11862
11863       strcpy (p, "qGetTIBAddr:");
11864       p += strlen (p);
11865       p = write_ptid (p, endp, ptid);
11866       *p++ = '\0';
11867
11868       putpkt (rs->buf);
11869       getpkt (&rs->buf, 0);
11870       result = packet_ok (rs->buf,
11871                           &remote_protocol_packets[PACKET_qGetTIBAddr]);
11872       if (result == PACKET_OK)
11873         {
11874           ULONGEST val;
11875           unpack_varlen_hex (rs->buf.data (), &val);
11876           if (addr)
11877             *addr = (CORE_ADDR) val;
11878           return true;
11879         }
11880       else if (result == PACKET_UNKNOWN)
11881         error (_("Remote target doesn't support qGetTIBAddr packet"));
11882       else
11883         error (_("Remote target failed to process qGetTIBAddr request"));
11884     }
11885   else
11886     error (_("qGetTIBAddr not supported or disabled on this target"));
11887   /* Not reached.  */
11888   return false;
11889 }
11890
11891 /* Support for inferring a target description based on the current
11892    architecture and the size of a 'g' packet.  While the 'g' packet
11893    can have any size (since optional registers can be left off the
11894    end), some sizes are easily recognizable given knowledge of the
11895    approximate architecture.  */
11896
11897 struct remote_g_packet_guess
11898 {
11899   remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
11900     : bytes (bytes_),
11901       tdesc (tdesc_)
11902   {
11903   }
11904
11905   int bytes;
11906   const struct target_desc *tdesc;
11907 };
11908
11909 struct remote_g_packet_data : public allocate_on_obstack
11910 {
11911   std::vector<remote_g_packet_guess> guesses;
11912 };
11913
11914 static struct gdbarch_data *remote_g_packet_data_handle;
11915
11916 static void *
11917 remote_g_packet_data_init (struct obstack *obstack)
11918 {
11919   return new (obstack) remote_g_packet_data;
11920 }
11921
11922 void
11923 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11924                                 const struct target_desc *tdesc)
11925 {
11926   struct remote_g_packet_data *data
11927     = ((struct remote_g_packet_data *)
11928        gdbarch_data (gdbarch, remote_g_packet_data_handle));
11929
11930   gdb_assert (tdesc != NULL);
11931
11932   for (const remote_g_packet_guess &guess : data->guesses)
11933     if (guess.bytes == bytes)
11934       internal_error (__FILE__, __LINE__,
11935                       _("Duplicate g packet description added for size %d"),
11936                       bytes);
11937
11938   data->guesses.emplace_back (bytes, tdesc);
11939 }
11940
11941 /* Return true if remote_read_description would do anything on this target
11942    and architecture, false otherwise.  */
11943
11944 static bool
11945 remote_read_description_p (struct target_ops *target)
11946 {
11947   struct remote_g_packet_data *data
11948     = ((struct remote_g_packet_data *)
11949        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11950
11951   return !data->guesses.empty ();
11952 }
11953
11954 const struct target_desc *
11955 remote_target::read_description ()
11956 {
11957   struct remote_g_packet_data *data
11958     = ((struct remote_g_packet_data *)
11959        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11960
11961   /* Do not try this during initial connection, when we do not know
11962      whether there is a running but stopped thread.  */
11963   if (!target_has_execution () || inferior_ptid == null_ptid)
11964     return beneath ()->read_description ();
11965
11966   if (!data->guesses.empty ())
11967     {
11968       int bytes = send_g_packet ();
11969
11970       for (const remote_g_packet_guess &guess : data->guesses)
11971         if (guess.bytes == bytes)
11972           return guess.tdesc;
11973
11974       /* We discard the g packet.  A minor optimization would be to
11975          hold on to it, and fill the register cache once we have selected
11976          an architecture, but it's too tricky to do safely.  */
11977     }
11978
11979   return beneath ()->read_description ();
11980 }
11981
11982 /* Remote file transfer support.  This is host-initiated I/O, not
11983    target-initiated; for target-initiated, see remote-fileio.c.  */
11984
11985 /* If *LEFT is at least the length of STRING, copy STRING to
11986    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11987    decrease *LEFT.  Otherwise raise an error.  */
11988
11989 static void
11990 remote_buffer_add_string (char **buffer, int *left, const char *string)
11991 {
11992   int len = strlen (string);
11993
11994   if (len > *left)
11995     error (_("Packet too long for target."));
11996
11997   memcpy (*buffer, string, len);
11998   *buffer += len;
11999   *left -= len;
12000
12001   /* NUL-terminate the buffer as a convenience, if there is
12002      room.  */
12003   if (*left)
12004     **buffer = '\0';
12005 }
12006
12007 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12008    *BUFFER, update *BUFFER to point to the new end of the buffer, and
12009    decrease *LEFT.  Otherwise raise an error.  */
12010
12011 static void
12012 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12013                          int len)
12014 {
12015   if (2 * len > *left)
12016     error (_("Packet too long for target."));
12017
12018   bin2hex (bytes, *buffer, len);
12019   *buffer += 2 * len;
12020   *left -= 2 * len;
12021
12022   /* NUL-terminate the buffer as a convenience, if there is
12023      room.  */
12024   if (*left)
12025     **buffer = '\0';
12026 }
12027
12028 /* If *LEFT is large enough, convert VALUE to hex and add it to
12029    *BUFFER, update *BUFFER to point to the new end of the buffer, and
12030    decrease *LEFT.  Otherwise raise an error.  */
12031
12032 static void
12033 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12034 {
12035   int len = hexnumlen (value);
12036
12037   if (len > *left)
12038     error (_("Packet too long for target."));
12039
12040   hexnumstr (*buffer, value);
12041   *buffer += len;
12042   *left -= len;
12043
12044   /* NUL-terminate the buffer as a convenience, if there is
12045      room.  */
12046   if (*left)
12047     **buffer = '\0';
12048 }
12049
12050 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
12051    value, *REMOTE_ERRNO to the remote error number or zero if none
12052    was included, and *ATTACHMENT to point to the start of the annex
12053    if any.  The length of the packet isn't needed here; there may
12054    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12055
12056    Return 0 if the packet could be parsed, -1 if it could not.  If
12057    -1 is returned, the other variables may not be initialized.  */
12058
12059 static int
12060 remote_hostio_parse_result (const char *buffer, int *retcode,
12061                             int *remote_errno, const char **attachment)
12062 {
12063   char *p, *p2;
12064
12065   *remote_errno = 0;
12066   *attachment = NULL;
12067
12068   if (buffer[0] != 'F')
12069     return -1;
12070
12071   errno = 0;
12072   *retcode = strtol (&buffer[1], &p, 16);
12073   if (errno != 0 || p == &buffer[1])
12074     return -1;
12075
12076   /* Check for ",errno".  */
12077   if (*p == ',')
12078     {
12079       errno = 0;
12080       *remote_errno = strtol (p + 1, &p2, 16);
12081       if (errno != 0 || p + 1 == p2)
12082         return -1;
12083       p = p2;
12084     }
12085
12086   /* Check for ";attachment".  If there is no attachment, the
12087      packet should end here.  */
12088   if (*p == ';')
12089     {
12090       *attachment = p + 1;
12091       return 0;
12092     }
12093   else if (*p == '\0')
12094     return 0;
12095   else
12096     return -1;
12097 }
12098
12099 /* Send a prepared I/O packet to the target and read its response.
12100    The prepared packet is in the global RS->BUF before this function
12101    is called, and the answer is there when we return.
12102
12103    COMMAND_BYTES is the length of the request to send, which may include
12104    binary data.  WHICH_PACKET is the packet configuration to check
12105    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
12106    is set to the error number and -1 is returned.  Otherwise the value
12107    returned by the function is returned.
12108
12109    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12110    attachment is expected; an error will be reported if there's a
12111    mismatch.  If one is found, *ATTACHMENT will be set to point into
12112    the packet buffer and *ATTACHMENT_LEN will be set to the
12113    attachment's length.  */
12114
12115 int
12116 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12117                                            int *remote_errno, const char **attachment,
12118                                            int *attachment_len)
12119 {
12120   struct remote_state *rs = get_remote_state ();
12121   int ret, bytes_read;
12122   const char *attachment_tmp;
12123
12124   if (packet_support (which_packet) == PACKET_DISABLE)
12125     {
12126       *remote_errno = FILEIO_ENOSYS;
12127       return -1;
12128     }
12129
12130   putpkt_binary (rs->buf.data (), command_bytes);
12131   bytes_read = getpkt_sane (&rs->buf, 0);
12132
12133   /* If it timed out, something is wrong.  Don't try to parse the
12134      buffer.  */
12135   if (bytes_read < 0)
12136     {
12137       *remote_errno = FILEIO_EINVAL;
12138       return -1;
12139     }
12140
12141   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
12142     {
12143     case PACKET_ERROR:
12144       *remote_errno = FILEIO_EINVAL;
12145       return -1;
12146     case PACKET_UNKNOWN:
12147       *remote_errno = FILEIO_ENOSYS;
12148       return -1;
12149     case PACKET_OK:
12150       break;
12151     }
12152
12153   if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12154                                   &attachment_tmp))
12155     {
12156       *remote_errno = FILEIO_EINVAL;
12157       return -1;
12158     }
12159
12160   /* Make sure we saw an attachment if and only if we expected one.  */
12161   if ((attachment_tmp == NULL && attachment != NULL)
12162       || (attachment_tmp != NULL && attachment == NULL))
12163     {
12164       *remote_errno = FILEIO_EINVAL;
12165       return -1;
12166     }
12167
12168   /* If an attachment was found, it must point into the packet buffer;
12169      work out how many bytes there were.  */
12170   if (attachment_tmp != NULL)
12171     {
12172       *attachment = attachment_tmp;
12173       *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12174     }
12175
12176   return ret;
12177 }
12178
12179 /* See declaration.h.  */
12180
12181 void
12182 readahead_cache::invalidate ()
12183 {
12184   this->fd = -1;
12185 }
12186
12187 /* See declaration.h.  */
12188
12189 void
12190 readahead_cache::invalidate_fd (int fd)
12191 {
12192   if (this->fd == fd)
12193     this->fd = -1;
12194 }
12195
12196 /* Set the filesystem remote_hostio functions that take FILENAME
12197    arguments will use.  Return 0 on success, or -1 if an error
12198    occurs (and set *REMOTE_ERRNO).  */
12199
12200 int
12201 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12202                                              int *remote_errno)
12203 {
12204   struct remote_state *rs = get_remote_state ();
12205   int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12206   char *p = rs->buf.data ();
12207   int left = get_remote_packet_size () - 1;
12208   char arg[9];
12209   int ret;
12210
12211   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12212     return 0;
12213
12214   if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12215     return 0;
12216
12217   remote_buffer_add_string (&p, &left, "vFile:setfs:");
12218
12219   xsnprintf (arg, sizeof (arg), "%x", required_pid);
12220   remote_buffer_add_string (&p, &left, arg);
12221
12222   ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12223                                     remote_errno, NULL, NULL);
12224
12225   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12226     return 0;
12227
12228   if (ret == 0)
12229     rs->fs_pid = required_pid;
12230
12231   return ret;
12232 }
12233
12234 /* Implementation of to_fileio_open.  */
12235
12236 int
12237 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12238                                    int flags, int mode, int warn_if_slow,
12239                                    int *remote_errno)
12240 {
12241   struct remote_state *rs = get_remote_state ();
12242   char *p = rs->buf.data ();
12243   int left = get_remote_packet_size () - 1;
12244
12245   if (warn_if_slow)
12246     {
12247       static int warning_issued = 0;
12248
12249       printf_unfiltered (_("Reading %s from remote target...\n"),
12250                          filename);
12251
12252       if (!warning_issued)
12253         {
12254           warning (_("File transfers from remote targets can be slow."
12255                      " Use \"set sysroot\" to access files locally"
12256                      " instead."));
12257           warning_issued = 1;
12258         }
12259     }
12260
12261   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12262     return -1;
12263
12264   remote_buffer_add_string (&p, &left, "vFile:open:");
12265
12266   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12267                            strlen (filename));
12268   remote_buffer_add_string (&p, &left, ",");
12269
12270   remote_buffer_add_int (&p, &left, flags);
12271   remote_buffer_add_string (&p, &left, ",");
12272
12273   remote_buffer_add_int (&p, &left, mode);
12274
12275   return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12276                                      remote_errno, NULL, NULL);
12277 }
12278
12279 int
12280 remote_target::fileio_open (struct inferior *inf, const char *filename,
12281                             int flags, int mode, int warn_if_slow,
12282                             int *remote_errno)
12283 {
12284   return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12285                              remote_errno);
12286 }
12287
12288 /* Implementation of to_fileio_pwrite.  */
12289
12290 int
12291 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12292                                      ULONGEST offset, int *remote_errno)
12293 {
12294   struct remote_state *rs = get_remote_state ();
12295   char *p = rs->buf.data ();
12296   int left = get_remote_packet_size ();
12297   int out_len;
12298
12299   rs->readahead_cache.invalidate_fd (fd);
12300
12301   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12302
12303   remote_buffer_add_int (&p, &left, fd);
12304   remote_buffer_add_string (&p, &left, ",");
12305
12306   remote_buffer_add_int (&p, &left, offset);
12307   remote_buffer_add_string (&p, &left, ",");
12308
12309   p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12310                              (get_remote_packet_size ()
12311                               - (p - rs->buf.data ())));
12312
12313   return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12314                                      remote_errno, NULL, NULL);
12315 }
12316
12317 int
12318 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12319                               ULONGEST offset, int *remote_errno)
12320 {
12321   return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12322 }
12323
12324 /* Helper for the implementation of to_fileio_pread.  Read the file
12325    from the remote side with vFile:pread.  */
12326
12327 int
12328 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12329                                           ULONGEST offset, int *remote_errno)
12330 {
12331   struct remote_state *rs = get_remote_state ();
12332   char *p = rs->buf.data ();
12333   const char *attachment;
12334   int left = get_remote_packet_size ();
12335   int ret, attachment_len;
12336   int read_len;
12337
12338   remote_buffer_add_string (&p, &left, "vFile:pread:");
12339
12340   remote_buffer_add_int (&p, &left, fd);
12341   remote_buffer_add_string (&p, &left, ",");
12342
12343   remote_buffer_add_int (&p, &left, len);
12344   remote_buffer_add_string (&p, &left, ",");
12345
12346   remote_buffer_add_int (&p, &left, offset);
12347
12348   ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12349                                     remote_errno, &attachment,
12350                                     &attachment_len);
12351
12352   if (ret < 0)
12353     return ret;
12354
12355   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12356                                     read_buf, len);
12357   if (read_len != ret)
12358     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12359
12360   return ret;
12361 }
12362
12363 /* See declaration.h.  */
12364
12365 int
12366 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12367                         ULONGEST offset)
12368 {
12369   if (this->fd == fd
12370       && this->offset <= offset
12371       && offset < this->offset + this->bufsize)
12372     {
12373       ULONGEST max = this->offset + this->bufsize;
12374
12375       if (offset + len > max)
12376         len = max - offset;
12377
12378       memcpy (read_buf, this->buf + offset - this->offset, len);
12379       return len;
12380     }
12381
12382   return 0;
12383 }
12384
12385 /* Implementation of to_fileio_pread.  */
12386
12387 int
12388 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12389                                     ULONGEST offset, int *remote_errno)
12390 {
12391   int ret;
12392   struct remote_state *rs = get_remote_state ();
12393   readahead_cache *cache = &rs->readahead_cache;
12394
12395   ret = cache->pread (fd, read_buf, len, offset);
12396   if (ret > 0)
12397     {
12398       cache->hit_count++;
12399
12400       remote_debug_printf ("readahead cache hit %s",
12401                            pulongest (cache->hit_count));
12402       return ret;
12403     }
12404
12405   cache->miss_count++;
12406
12407   remote_debug_printf ("readahead cache miss %s",
12408                        pulongest (cache->miss_count));
12409
12410   cache->fd = fd;
12411   cache->offset = offset;
12412   cache->bufsize = get_remote_packet_size ();
12413   cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12414
12415   ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12416                                    cache->offset, remote_errno);
12417   if (ret <= 0)
12418     {
12419       cache->invalidate_fd (fd);
12420       return ret;
12421     }
12422
12423   cache->bufsize = ret;
12424   return cache->pread (fd, read_buf, len, offset);
12425 }
12426
12427 int
12428 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12429                              ULONGEST offset, int *remote_errno)
12430 {
12431   return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12432 }
12433
12434 /* Implementation of to_fileio_close.  */
12435
12436 int
12437 remote_target::remote_hostio_close (int fd, int *remote_errno)
12438 {
12439   struct remote_state *rs = get_remote_state ();
12440   char *p = rs->buf.data ();
12441   int left = get_remote_packet_size () - 1;
12442
12443   rs->readahead_cache.invalidate_fd (fd);
12444
12445   remote_buffer_add_string (&p, &left, "vFile:close:");
12446
12447   remote_buffer_add_int (&p, &left, fd);
12448
12449   return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12450                                      remote_errno, NULL, NULL);
12451 }
12452
12453 int
12454 remote_target::fileio_close (int fd, int *remote_errno)
12455 {
12456   return remote_hostio_close (fd, remote_errno);
12457 }
12458
12459 /* Implementation of to_fileio_unlink.  */
12460
12461 int
12462 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12463                                      int *remote_errno)
12464 {
12465   struct remote_state *rs = get_remote_state ();
12466   char *p = rs->buf.data ();
12467   int left = get_remote_packet_size () - 1;
12468
12469   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12470     return -1;
12471
12472   remote_buffer_add_string (&p, &left, "vFile:unlink:");
12473
12474   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12475                            strlen (filename));
12476
12477   return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12478                                      remote_errno, NULL, NULL);
12479 }
12480
12481 int
12482 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12483                               int *remote_errno)
12484 {
12485   return remote_hostio_unlink (inf, filename, remote_errno);
12486 }
12487
12488 /* Implementation of to_fileio_readlink.  */
12489
12490 gdb::optional<std::string>
12491 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12492                                 int *remote_errno)
12493 {
12494   struct remote_state *rs = get_remote_state ();
12495   char *p = rs->buf.data ();
12496   const char *attachment;
12497   int left = get_remote_packet_size ();
12498   int len, attachment_len;
12499   int read_len;
12500
12501   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12502     return {};
12503
12504   remote_buffer_add_string (&p, &left, "vFile:readlink:");
12505
12506   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12507                            strlen (filename));
12508
12509   len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12510                                     remote_errno, &attachment,
12511                                     &attachment_len);
12512
12513   if (len < 0)
12514     return {};
12515
12516   std::string ret (len, '\0');
12517
12518   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12519                                     (gdb_byte *) &ret[0], len);
12520   if (read_len != len)
12521     error (_("Readlink returned %d, but %d bytes."), len, read_len);
12522
12523   return ret;
12524 }
12525
12526 /* Implementation of to_fileio_fstat.  */
12527
12528 int
12529 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12530 {
12531   struct remote_state *rs = get_remote_state ();
12532   char *p = rs->buf.data ();
12533   int left = get_remote_packet_size ();
12534   int attachment_len, ret;
12535   const char *attachment;
12536   struct fio_stat fst;
12537   int read_len;
12538
12539   remote_buffer_add_string (&p, &left, "vFile:fstat:");
12540
12541   remote_buffer_add_int (&p, &left, fd);
12542
12543   ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12544                                     remote_errno, &attachment,
12545                                     &attachment_len);
12546   if (ret < 0)
12547     {
12548       if (*remote_errno != FILEIO_ENOSYS)
12549         return ret;
12550
12551       /* Strictly we should return -1, ENOSYS here, but when
12552          "set sysroot remote:" was implemented in August 2008
12553          BFD's need for a stat function was sidestepped with
12554          this hack.  This was not remedied until March 2015
12555          so we retain the previous behavior to avoid breaking
12556          compatibility.
12557
12558          Note that the memset is a March 2015 addition; older
12559          GDBs set st_size *and nothing else* so the structure
12560          would have garbage in all other fields.  This might
12561          break something but retaining the previous behavior
12562          here would be just too wrong.  */
12563
12564       memset (st, 0, sizeof (struct stat));
12565       st->st_size = INT_MAX;
12566       return 0;
12567     }
12568
12569   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12570                                     (gdb_byte *) &fst, sizeof (fst));
12571
12572   if (read_len != ret)
12573     error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12574
12575   if (read_len != sizeof (fst))
12576     error (_("vFile:fstat returned %d bytes, but expecting %d."),
12577            read_len, (int) sizeof (fst));
12578
12579   remote_fileio_to_host_stat (&fst, st);
12580
12581   return 0;
12582 }
12583
12584 /* Implementation of to_filesystem_is_local.  */
12585
12586 bool
12587 remote_target::filesystem_is_local ()
12588 {
12589   /* Valgrind GDB presents itself as a remote target but works
12590      on the local filesystem: it does not implement remote get
12591      and users are not expected to set a sysroot.  To handle
12592      this case we treat the remote filesystem as local if the
12593      sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12594      does not support vFile:open.  */
12595   if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
12596     {
12597       enum packet_support ps = packet_support (PACKET_vFile_open);
12598
12599       if (ps == PACKET_SUPPORT_UNKNOWN)
12600         {
12601           int fd, remote_errno;
12602
12603           /* Try opening a file to probe support.  The supplied
12604              filename is irrelevant, we only care about whether
12605              the stub recognizes the packet or not.  */
12606           fd = remote_hostio_open (NULL, "just probing",
12607                                    FILEIO_O_RDONLY, 0700, 0,
12608                                    &remote_errno);
12609
12610           if (fd >= 0)
12611             remote_hostio_close (fd, &remote_errno);
12612
12613           ps = packet_support (PACKET_vFile_open);
12614         }
12615
12616       if (ps == PACKET_DISABLE)
12617         {
12618           static int warning_issued = 0;
12619
12620           if (!warning_issued)
12621             {
12622               warning (_("remote target does not support file"
12623                          " transfer, attempting to access files"
12624                          " from local filesystem."));
12625               warning_issued = 1;
12626             }
12627
12628           return true;
12629         }
12630     }
12631
12632   return false;
12633 }
12634
12635 static int
12636 remote_fileio_errno_to_host (int errnum)
12637 {
12638   switch (errnum)
12639     {
12640       case FILEIO_EPERM:
12641         return EPERM;
12642       case FILEIO_ENOENT:
12643         return ENOENT;
12644       case FILEIO_EINTR:
12645         return EINTR;
12646       case FILEIO_EIO:
12647         return EIO;
12648       case FILEIO_EBADF:
12649         return EBADF;
12650       case FILEIO_EACCES:
12651         return EACCES;
12652       case FILEIO_EFAULT:
12653         return EFAULT;
12654       case FILEIO_EBUSY:
12655         return EBUSY;
12656       case FILEIO_EEXIST:
12657         return EEXIST;
12658       case FILEIO_ENODEV:
12659         return ENODEV;
12660       case FILEIO_ENOTDIR:
12661         return ENOTDIR;
12662       case FILEIO_EISDIR:
12663         return EISDIR;
12664       case FILEIO_EINVAL:
12665         return EINVAL;
12666       case FILEIO_ENFILE:
12667         return ENFILE;
12668       case FILEIO_EMFILE:
12669         return EMFILE;
12670       case FILEIO_EFBIG:
12671         return EFBIG;
12672       case FILEIO_ENOSPC:
12673         return ENOSPC;
12674       case FILEIO_ESPIPE:
12675         return ESPIPE;
12676       case FILEIO_EROFS:
12677         return EROFS;
12678       case FILEIO_ENOSYS:
12679         return ENOSYS;
12680       case FILEIO_ENAMETOOLONG:
12681         return ENAMETOOLONG;
12682     }
12683   return -1;
12684 }
12685
12686 static char *
12687 remote_hostio_error (int errnum)
12688 {
12689   int host_error = remote_fileio_errno_to_host (errnum);
12690
12691   if (host_error == -1)
12692     error (_("Unknown remote I/O error %d"), errnum);
12693   else
12694     error (_("Remote I/O error: %s"), safe_strerror (host_error));
12695 }
12696
12697 /* A RAII wrapper around a remote file descriptor.  */
12698
12699 class scoped_remote_fd
12700 {
12701 public:
12702   scoped_remote_fd (remote_target *remote, int fd)
12703     : m_remote (remote), m_fd (fd)
12704   {
12705   }
12706
12707   ~scoped_remote_fd ()
12708   {
12709     if (m_fd != -1)
12710       {
12711         try
12712           {
12713             int remote_errno;
12714             m_remote->remote_hostio_close (m_fd, &remote_errno);
12715           }
12716         catch (...)
12717           {
12718             /* Swallow exception before it escapes the dtor.  If
12719                something goes wrong, likely the connection is gone,
12720                and there's nothing else that can be done.  */
12721           }
12722       }
12723   }
12724
12725   DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12726
12727   /* Release ownership of the file descriptor, and return it.  */
12728   ATTRIBUTE_UNUSED_RESULT int release () noexcept
12729   {
12730     int fd = m_fd;
12731     m_fd = -1;
12732     return fd;
12733   }
12734
12735   /* Return the owned file descriptor.  */
12736   int get () const noexcept
12737   {
12738     return m_fd;
12739   }
12740
12741 private:
12742   /* The remote target.  */
12743   remote_target *m_remote;
12744
12745   /* The owned remote I/O file descriptor.  */
12746   int m_fd;
12747 };
12748
12749 void
12750 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12751 {
12752   remote_target *remote = get_current_remote_target ();
12753
12754   if (remote == nullptr)
12755     error (_("command can only be used with remote target"));
12756
12757   remote->remote_file_put (local_file, remote_file, from_tty);
12758 }
12759
12760 void
12761 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12762                                 int from_tty)
12763 {
12764   int retcode, remote_errno, bytes, io_size;
12765   int bytes_in_buffer;
12766   int saw_eof;
12767   ULONGEST offset;
12768
12769   gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12770   if (file == NULL)
12771     perror_with_name (local_file);
12772
12773   scoped_remote_fd fd
12774     (this, remote_hostio_open (NULL,
12775                                remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12776                                              | FILEIO_O_TRUNC),
12777                                0700, 0, &remote_errno));
12778   if (fd.get () == -1)
12779     remote_hostio_error (remote_errno);
12780
12781   /* Send up to this many bytes at once.  They won't all fit in the
12782      remote packet limit, so we'll transfer slightly fewer.  */
12783   io_size = get_remote_packet_size ();
12784   gdb::byte_vector buffer (io_size);
12785
12786   bytes_in_buffer = 0;
12787   saw_eof = 0;
12788   offset = 0;
12789   while (bytes_in_buffer || !saw_eof)
12790     {
12791       if (!saw_eof)
12792         {
12793           bytes = fread (buffer.data () + bytes_in_buffer, 1,
12794                          io_size - bytes_in_buffer,
12795                          file.get ());
12796           if (bytes == 0)
12797             {
12798               if (ferror (file.get ()))
12799                 error (_("Error reading %s."), local_file);
12800               else
12801                 {
12802                   /* EOF.  Unless there is something still in the
12803                      buffer from the last iteration, we are done.  */
12804                   saw_eof = 1;
12805                   if (bytes_in_buffer == 0)
12806                     break;
12807                 }
12808             }
12809         }
12810       else
12811         bytes = 0;
12812
12813       bytes += bytes_in_buffer;
12814       bytes_in_buffer = 0;
12815
12816       retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12817                                       offset, &remote_errno);
12818
12819       if (retcode < 0)
12820         remote_hostio_error (remote_errno);
12821       else if (retcode == 0)
12822         error (_("Remote write of %d bytes returned 0!"), bytes);
12823       else if (retcode < bytes)
12824         {
12825           /* Short write.  Save the rest of the read data for the next
12826              write.  */
12827           bytes_in_buffer = bytes - retcode;
12828           memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
12829         }
12830
12831       offset += retcode;
12832     }
12833
12834   if (remote_hostio_close (fd.release (), &remote_errno))
12835     remote_hostio_error (remote_errno);
12836
12837   if (from_tty)
12838     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12839 }
12840
12841 void
12842 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12843 {
12844   remote_target *remote = get_current_remote_target ();
12845
12846   if (remote == nullptr)
12847     error (_("command can only be used with remote target"));
12848
12849   remote->remote_file_get (remote_file, local_file, from_tty);
12850 }
12851
12852 void
12853 remote_target::remote_file_get (const char *remote_file, const char *local_file,
12854                                 int from_tty)
12855 {
12856   int remote_errno, bytes, io_size;
12857   ULONGEST offset;
12858
12859   scoped_remote_fd fd
12860     (this, remote_hostio_open (NULL,
12861                                remote_file, FILEIO_O_RDONLY, 0, 0,
12862                                &remote_errno));
12863   if (fd.get () == -1)
12864     remote_hostio_error (remote_errno);
12865
12866   gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12867   if (file == NULL)
12868     perror_with_name (local_file);
12869
12870   /* Send up to this many bytes at once.  They won't all fit in the
12871      remote packet limit, so we'll transfer slightly fewer.  */
12872   io_size = get_remote_packet_size ();
12873   gdb::byte_vector buffer (io_size);
12874
12875   offset = 0;
12876   while (1)
12877     {
12878       bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
12879                                    &remote_errno);
12880       if (bytes == 0)
12881         /* Success, but no bytes, means end-of-file.  */
12882         break;
12883       if (bytes == -1)
12884         remote_hostio_error (remote_errno);
12885
12886       offset += bytes;
12887
12888       bytes = fwrite (buffer.data (), 1, bytes, file.get ());
12889       if (bytes == 0)
12890         perror_with_name (local_file);
12891     }
12892
12893   if (remote_hostio_close (fd.release (), &remote_errno))
12894     remote_hostio_error (remote_errno);
12895
12896   if (from_tty)
12897     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12898 }
12899
12900 void
12901 remote_file_delete (const char *remote_file, int from_tty)
12902 {
12903   remote_target *remote = get_current_remote_target ();
12904
12905   if (remote == nullptr)
12906     error (_("command can only be used with remote target"));
12907
12908   remote->remote_file_delete (remote_file, from_tty);
12909 }
12910
12911 void
12912 remote_target::remote_file_delete (const char *remote_file, int from_tty)
12913 {
12914   int retcode, remote_errno;
12915
12916   retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
12917   if (retcode == -1)
12918     remote_hostio_error (remote_errno);
12919
12920   if (from_tty)
12921     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12922 }
12923
12924 static void
12925 remote_put_command (const char *args, int from_tty)
12926 {
12927   if (args == NULL)
12928     error_no_arg (_("file to put"));
12929
12930   gdb_argv argv (args);
12931   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12932     error (_("Invalid parameters to remote put"));
12933
12934   remote_file_put (argv[0], argv[1], from_tty);
12935 }
12936
12937 static void
12938 remote_get_command (const char *args, int from_tty)
12939 {
12940   if (args == NULL)
12941     error_no_arg (_("file to get"));
12942
12943   gdb_argv argv (args);
12944   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12945     error (_("Invalid parameters to remote get"));
12946
12947   remote_file_get (argv[0], argv[1], from_tty);
12948 }
12949
12950 static void
12951 remote_delete_command (const char *args, int from_tty)
12952 {
12953   if (args == NULL)
12954     error_no_arg (_("file to delete"));
12955
12956   gdb_argv argv (args);
12957   if (argv[0] == NULL || argv[1] != NULL)
12958     error (_("Invalid parameters to remote delete"));
12959
12960   remote_file_delete (argv[0], from_tty);
12961 }
12962
12963 bool
12964 remote_target::can_execute_reverse ()
12965 {
12966   if (packet_support (PACKET_bs) == PACKET_ENABLE
12967       || packet_support (PACKET_bc) == PACKET_ENABLE)
12968     return true;
12969   else
12970     return false;
12971 }
12972
12973 bool
12974 remote_target::supports_non_stop ()
12975 {
12976   return true;
12977 }
12978
12979 bool
12980 remote_target::supports_disable_randomization ()
12981 {
12982   /* Only supported in extended mode.  */
12983   return false;
12984 }
12985
12986 bool
12987 remote_target::supports_multi_process ()
12988 {
12989   struct remote_state *rs = get_remote_state ();
12990
12991   return remote_multi_process_p (rs);
12992 }
12993
12994 static int
12995 remote_supports_cond_tracepoints ()
12996 {
12997   return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12998 }
12999
13000 bool
13001 remote_target::supports_evaluation_of_breakpoint_conditions ()
13002 {
13003   return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
13004 }
13005
13006 static int
13007 remote_supports_fast_tracepoints ()
13008 {
13009   return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13010 }
13011
13012 static int
13013 remote_supports_static_tracepoints ()
13014 {
13015   return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13016 }
13017
13018 static int
13019 remote_supports_install_in_trace ()
13020 {
13021   return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13022 }
13023
13024 bool
13025 remote_target::supports_enable_disable_tracepoint ()
13026 {
13027   return (packet_support (PACKET_EnableDisableTracepoints_feature)
13028           == PACKET_ENABLE);
13029 }
13030
13031 bool
13032 remote_target::supports_string_tracing ()
13033 {
13034   return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13035 }
13036
13037 bool
13038 remote_target::can_run_breakpoint_commands ()
13039 {
13040   return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13041 }
13042
13043 void
13044 remote_target::trace_init ()
13045 {
13046   struct remote_state *rs = get_remote_state ();
13047
13048   putpkt ("QTinit");
13049   remote_get_noisy_reply ();
13050   if (strcmp (rs->buf.data (), "OK") != 0)
13051     error (_("Target does not support this command."));
13052 }
13053
13054 /* Recursive routine to walk through command list including loops, and
13055    download packets for each command.  */
13056
13057 void
13058 remote_target::remote_download_command_source (int num, ULONGEST addr,
13059                                                struct command_line *cmds)
13060 {
13061   struct remote_state *rs = get_remote_state ();
13062   struct command_line *cmd;
13063
13064   for (cmd = cmds; cmd; cmd = cmd->next)
13065     {
13066       QUIT;     /* Allow user to bail out with ^C.  */
13067       strcpy (rs->buf.data (), "QTDPsrc:");
13068       encode_source_string (num, addr, "cmd", cmd->line,
13069                             rs->buf.data () + strlen (rs->buf.data ()),
13070                             rs->buf.size () - strlen (rs->buf.data ()));
13071       putpkt (rs->buf);
13072       remote_get_noisy_reply ();
13073       if (strcmp (rs->buf.data (), "OK"))
13074         warning (_("Target does not support source download."));
13075
13076       if (cmd->control_type == while_control
13077           || cmd->control_type == while_stepping_control)
13078         {
13079           remote_download_command_source (num, addr, cmd->body_list_0.get ());
13080
13081           QUIT; /* Allow user to bail out with ^C.  */
13082           strcpy (rs->buf.data (), "QTDPsrc:");
13083           encode_source_string (num, addr, "cmd", "end",
13084                                 rs->buf.data () + strlen (rs->buf.data ()),
13085                                 rs->buf.size () - strlen (rs->buf.data ()));
13086           putpkt (rs->buf);
13087           remote_get_noisy_reply ();
13088           if (strcmp (rs->buf.data (), "OK"))
13089             warning (_("Target does not support source download."));
13090         }
13091     }
13092 }
13093
13094 void
13095 remote_target::download_tracepoint (struct bp_location *loc)
13096 {
13097   CORE_ADDR tpaddr;
13098   char addrbuf[40];
13099   std::vector<std::string> tdp_actions;
13100   std::vector<std::string> stepping_actions;
13101   char *pkt;
13102   struct breakpoint *b = loc->owner;
13103   struct tracepoint *t = (struct tracepoint *) b;
13104   struct remote_state *rs = get_remote_state ();
13105   int ret;
13106   const char *err_msg = _("Tracepoint packet too large for target.");
13107   size_t size_left;
13108
13109   /* We use a buffer other than rs->buf because we'll build strings
13110      across multiple statements, and other statements in between could
13111      modify rs->buf.  */
13112   gdb::char_vector buf (get_remote_packet_size ());
13113
13114   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13115
13116   tpaddr = loc->address;
13117   strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13118   ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13119                   b->number, addrbuf, /* address */
13120                   (b->enable_state == bp_enabled ? 'E' : 'D'),
13121                   t->step_count, t->pass_count);
13122
13123   if (ret < 0 || ret >= buf.size ())
13124     error ("%s", err_msg);
13125
13126   /* Fast tracepoints are mostly handled by the target, but we can
13127      tell the target how big of an instruction block should be moved
13128      around.  */
13129   if (b->type == bp_fast_tracepoint)
13130     {
13131       /* Only test for support at download time; we may not know
13132          target capabilities at definition time.  */
13133       if (remote_supports_fast_tracepoints ())
13134         {
13135           if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13136                                                 NULL))
13137             {
13138               size_left = buf.size () - strlen (buf.data ());
13139               ret = snprintf (buf.data () + strlen (buf.data ()),
13140                               size_left, ":F%x",
13141                               gdb_insn_length (loc->gdbarch, tpaddr));
13142
13143               if (ret < 0 || ret >= size_left)
13144                 error ("%s", err_msg);
13145             }
13146           else
13147             /* If it passed validation at definition but fails now,
13148                something is very wrong.  */
13149             internal_error (__FILE__, __LINE__,
13150                             _("Fast tracepoint not "
13151                               "valid during download"));
13152         }
13153       else
13154         /* Fast tracepoints are functionally identical to regular
13155            tracepoints, so don't take lack of support as a reason to
13156            give up on the trace run.  */
13157         warning (_("Target does not support fast tracepoints, "
13158                    "downloading %d as regular tracepoint"), b->number);
13159     }
13160   else if (b->type == bp_static_tracepoint)
13161     {
13162       /* Only test for support at download time; we may not know
13163          target capabilities at definition time.  */
13164       if (remote_supports_static_tracepoints ())
13165         {
13166           struct static_tracepoint_marker marker;
13167
13168           if (target_static_tracepoint_marker_at (tpaddr, &marker))
13169             {
13170               size_left = buf.size () - strlen (buf.data ());
13171               ret = snprintf (buf.data () + strlen (buf.data ()),
13172                               size_left, ":S");
13173
13174               if (ret < 0 || ret >= size_left)
13175                 error ("%s", err_msg);
13176             }
13177           else
13178             error (_("Static tracepoint not valid during download"));
13179         }
13180       else
13181         /* Fast tracepoints are functionally identical to regular
13182            tracepoints, so don't take lack of support as a reason
13183            to give up on the trace run.  */
13184         error (_("Target does not support static tracepoints"));
13185     }
13186   /* If the tracepoint has a conditional, make it into an agent
13187      expression and append to the definition.  */
13188   if (loc->cond)
13189     {
13190       /* Only test support at download time, we may not know target
13191          capabilities at definition time.  */
13192       if (remote_supports_cond_tracepoints ())
13193         {
13194           agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13195                                                    loc->cond.get ());
13196
13197           size_left = buf.size () - strlen (buf.data ());
13198
13199           ret = snprintf (buf.data () + strlen (buf.data ()),
13200                           size_left, ":X%x,", aexpr->len);
13201
13202           if (ret < 0 || ret >= size_left)
13203             error ("%s", err_msg);
13204
13205           size_left = buf.size () - strlen (buf.data ());
13206
13207           /* Two bytes to encode each aexpr byte, plus the terminating
13208              null byte.  */
13209           if (aexpr->len * 2 + 1 > size_left)
13210             error ("%s", err_msg);
13211
13212           pkt = buf.data () + strlen (buf.data ());
13213
13214           for (int ndx = 0; ndx < aexpr->len; ++ndx)
13215             pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13216           *pkt = '\0';
13217         }
13218       else
13219         warning (_("Target does not support conditional tracepoints, "
13220                    "ignoring tp %d cond"), b->number);
13221     }
13222
13223   if (b->commands || *default_collect)
13224     {
13225       size_left = buf.size () - strlen (buf.data ());
13226
13227       ret = snprintf (buf.data () + strlen (buf.data ()),
13228                       size_left, "-");
13229
13230       if (ret < 0 || ret >= size_left)
13231         error ("%s", err_msg);
13232     }
13233
13234   putpkt (buf.data ());
13235   remote_get_noisy_reply ();
13236   if (strcmp (rs->buf.data (), "OK"))
13237     error (_("Target does not support tracepoints."));
13238
13239   /* do_single_steps (t); */
13240   for (auto action_it = tdp_actions.begin ();
13241        action_it != tdp_actions.end (); action_it++)
13242     {
13243       QUIT;     /* Allow user to bail out with ^C.  */
13244
13245       bool has_more = ((action_it + 1) != tdp_actions.end ()
13246                        || !stepping_actions.empty ());
13247
13248       ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13249                       b->number, addrbuf, /* address */
13250                       action_it->c_str (),
13251                       has_more ? '-' : 0);
13252
13253       if (ret < 0 || ret >= buf.size ())
13254         error ("%s", err_msg);
13255
13256       putpkt (buf.data ());
13257       remote_get_noisy_reply ();
13258       if (strcmp (rs->buf.data (), "OK"))
13259         error (_("Error on target while setting tracepoints."));
13260     }
13261
13262   for (auto action_it = stepping_actions.begin ();
13263        action_it != stepping_actions.end (); action_it++)
13264     {
13265       QUIT;     /* Allow user to bail out with ^C.  */
13266
13267       bool is_first = action_it == stepping_actions.begin ();
13268       bool has_more = (action_it + 1) != stepping_actions.end ();
13269
13270       ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13271                       b->number, addrbuf, /* address */
13272                       is_first ? "S" : "",
13273                       action_it->c_str (),
13274                       has_more ? "-" : "");
13275
13276       if (ret < 0 || ret >= buf.size ())
13277         error ("%s", err_msg);
13278
13279       putpkt (buf.data ());
13280       remote_get_noisy_reply ();
13281       if (strcmp (rs->buf.data (), "OK"))
13282         error (_("Error on target while setting tracepoints."));
13283     }
13284
13285   if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13286     {
13287       if (b->location != NULL)
13288         {
13289           ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13290
13291           if (ret < 0 || ret >= buf.size ())
13292             error ("%s", err_msg);
13293
13294           encode_source_string (b->number, loc->address, "at",
13295                                 event_location_to_string (b->location.get ()),
13296                                 buf.data () + strlen (buf.data ()),
13297                                 buf.size () - strlen (buf.data ()));
13298           putpkt (buf.data ());
13299           remote_get_noisy_reply ();
13300           if (strcmp (rs->buf.data (), "OK"))
13301             warning (_("Target does not support source download."));
13302         }
13303       if (b->cond_string)
13304         {
13305           ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13306
13307           if (ret < 0 || ret >= buf.size ())
13308             error ("%s", err_msg);
13309
13310           encode_source_string (b->number, loc->address,
13311                                 "cond", b->cond_string,
13312                                 buf.data () + strlen (buf.data ()),
13313                                 buf.size () - strlen (buf.data ()));
13314           putpkt (buf.data ());
13315           remote_get_noisy_reply ();
13316           if (strcmp (rs->buf.data (), "OK"))
13317             warning (_("Target does not support source download."));
13318         }
13319       remote_download_command_source (b->number, loc->address,
13320                                       breakpoint_commands (b));
13321     }
13322 }
13323
13324 bool
13325 remote_target::can_download_tracepoint ()
13326 {
13327   struct remote_state *rs = get_remote_state ();
13328   struct trace_status *ts;
13329   int status;
13330
13331   /* Don't try to install tracepoints until we've relocated our
13332      symbols, and fetched and merged the target's tracepoint list with
13333      ours.  */
13334   if (rs->starting_up)
13335     return false;
13336
13337   ts = current_trace_status ();
13338   status = get_trace_status (ts);
13339
13340   if (status == -1 || !ts->running_known || !ts->running)
13341     return false;
13342
13343   /* If we are in a tracing experiment, but remote stub doesn't support
13344      installing tracepoint in trace, we have to return.  */
13345   if (!remote_supports_install_in_trace ())
13346     return false;
13347
13348   return true;
13349 }
13350
13351
13352 void
13353 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13354 {
13355   struct remote_state *rs = get_remote_state ();
13356   char *p;
13357
13358   xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13359              tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13360              tsv.builtin);
13361   p = rs->buf.data () + strlen (rs->buf.data ());
13362   if ((p - rs->buf.data ()) + tsv.name.length () * 2
13363       >= get_remote_packet_size ())
13364     error (_("Trace state variable name too long for tsv definition packet"));
13365   p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13366   *p++ = '\0';
13367   putpkt (rs->buf);
13368   remote_get_noisy_reply ();
13369   if (rs->buf[0] == '\0')
13370     error (_("Target does not support this command."));
13371   if (strcmp (rs->buf.data (), "OK") != 0)
13372     error (_("Error on target while downloading trace state variable."));
13373 }
13374
13375 void
13376 remote_target::enable_tracepoint (struct bp_location *location)
13377 {
13378   struct remote_state *rs = get_remote_state ();
13379
13380   xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13381              location->owner->number,
13382              phex (location->address, sizeof (CORE_ADDR)));
13383   putpkt (rs->buf);
13384   remote_get_noisy_reply ();
13385   if (rs->buf[0] == '\0')
13386     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13387   if (strcmp (rs->buf.data (), "OK") != 0)
13388     error (_("Error on target while enabling tracepoint."));
13389 }
13390
13391 void
13392 remote_target::disable_tracepoint (struct bp_location *location)
13393 {
13394   struct remote_state *rs = get_remote_state ();
13395
13396   xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13397              location->owner->number,
13398              phex (location->address, sizeof (CORE_ADDR)));
13399   putpkt (rs->buf);
13400   remote_get_noisy_reply ();
13401   if (rs->buf[0] == '\0')
13402     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13403   if (strcmp (rs->buf.data (), "OK") != 0)
13404     error (_("Error on target while disabling tracepoint."));
13405 }
13406
13407 void
13408 remote_target::trace_set_readonly_regions ()
13409 {
13410   asection *s;
13411   bfd_size_type size;
13412   bfd_vma vma;
13413   int anysecs = 0;
13414   int offset = 0;
13415
13416   if (!current_program_space->exec_bfd ())
13417     return;                     /* No information to give.  */
13418
13419   struct remote_state *rs = get_remote_state ();
13420
13421   strcpy (rs->buf.data (), "QTro");
13422   offset = strlen (rs->buf.data ());
13423   for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
13424     {
13425       char tmp1[40], tmp2[40];
13426       int sec_length;
13427
13428       if ((s->flags & SEC_LOAD) == 0 ||
13429       /*  (s->flags & SEC_CODE) == 0 || */
13430           (s->flags & SEC_READONLY) == 0)
13431         continue;
13432
13433       anysecs = 1;
13434       vma = bfd_section_vma (s);
13435       size = bfd_section_size (s);
13436       sprintf_vma (tmp1, vma);
13437       sprintf_vma (tmp2, vma + size);
13438       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13439       if (offset + sec_length + 1 > rs->buf.size ())
13440         {
13441           if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
13442             warning (_("\
13443 Too many sections for read-only sections definition packet."));
13444           break;
13445         }
13446       xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13447                  tmp1, tmp2);
13448       offset += sec_length;
13449     }
13450   if (anysecs)
13451     {
13452       putpkt (rs->buf);
13453       getpkt (&rs->buf, 0);
13454     }
13455 }
13456
13457 void
13458 remote_target::trace_start ()
13459 {
13460   struct remote_state *rs = get_remote_state ();
13461
13462   putpkt ("QTStart");
13463   remote_get_noisy_reply ();
13464   if (rs->buf[0] == '\0')
13465     error (_("Target does not support this command."));
13466   if (strcmp (rs->buf.data (), "OK") != 0)
13467     error (_("Bogus reply from target: %s"), rs->buf.data ());
13468 }
13469
13470 int
13471 remote_target::get_trace_status (struct trace_status *ts)
13472 {
13473   /* Initialize it just to avoid a GCC false warning.  */
13474   char *p = NULL;
13475   enum packet_result result;
13476   struct remote_state *rs = get_remote_state ();
13477
13478   if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13479     return -1;
13480
13481   /* FIXME we need to get register block size some other way.  */
13482   trace_regblock_size
13483     = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13484
13485   putpkt ("qTStatus");
13486
13487   try
13488     {
13489       p = remote_get_noisy_reply ();
13490     }
13491   catch (const gdb_exception_error &ex)
13492     {
13493       if (ex.error != TARGET_CLOSE_ERROR)
13494         {
13495           exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13496           return -1;
13497         }
13498       throw;
13499     }
13500
13501   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13502
13503   /* If the remote target doesn't do tracing, flag it.  */
13504   if (result == PACKET_UNKNOWN)
13505     return -1;
13506
13507   /* We're working with a live target.  */
13508   ts->filename = NULL;
13509
13510   if (*p++ != 'T')
13511     error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13512
13513   /* Function 'parse_trace_status' sets default value of each field of
13514      'ts' at first, so we don't have to do it here.  */
13515   parse_trace_status (p, ts);
13516
13517   return ts->running;
13518 }
13519
13520 void
13521 remote_target::get_tracepoint_status (struct breakpoint *bp,
13522                                       struct uploaded_tp *utp)
13523 {
13524   struct remote_state *rs = get_remote_state ();
13525   char *reply;
13526   struct bp_location *loc;
13527   struct tracepoint *tp = (struct tracepoint *) bp;
13528   size_t size = get_remote_packet_size ();
13529
13530   if (tp)
13531     {
13532       tp->hit_count = 0;
13533       tp->traceframe_usage = 0;
13534       for (loc = tp->loc; loc; loc = loc->next)
13535         {
13536           /* If the tracepoint was never downloaded, don't go asking for
13537              any status.  */
13538           if (tp->number_on_target == 0)
13539             continue;
13540           xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13541                      phex_nz (loc->address, 0));
13542           putpkt (rs->buf);
13543           reply = remote_get_noisy_reply ();
13544           if (reply && *reply)
13545             {
13546               if (*reply == 'V')
13547                 parse_tracepoint_status (reply + 1, bp, utp);
13548             }
13549         }
13550     }
13551   else if (utp)
13552     {
13553       utp->hit_count = 0;
13554       utp->traceframe_usage = 0;
13555       xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13556                  phex_nz (utp->addr, 0));
13557       putpkt (rs->buf);
13558       reply = remote_get_noisy_reply ();
13559       if (reply && *reply)
13560         {
13561           if (*reply == 'V')
13562             parse_tracepoint_status (reply + 1, bp, utp);
13563         }
13564     }
13565 }
13566
13567 void
13568 remote_target::trace_stop ()
13569 {
13570   struct remote_state *rs = get_remote_state ();
13571
13572   putpkt ("QTStop");
13573   remote_get_noisy_reply ();
13574   if (rs->buf[0] == '\0')
13575     error (_("Target does not support this command."));
13576   if (strcmp (rs->buf.data (), "OK") != 0)
13577     error (_("Bogus reply from target: %s"), rs->buf.data ());
13578 }
13579
13580 int
13581 remote_target::trace_find (enum trace_find_type type, int num,
13582                            CORE_ADDR addr1, CORE_ADDR addr2,
13583                            int *tpp)
13584 {
13585   struct remote_state *rs = get_remote_state ();
13586   char *endbuf = rs->buf.data () + get_remote_packet_size ();
13587   char *p, *reply;
13588   int target_frameno = -1, target_tracept = -1;
13589
13590   /* Lookups other than by absolute frame number depend on the current
13591      trace selected, so make sure it is correct on the remote end
13592      first.  */
13593   if (type != tfind_number)
13594     set_remote_traceframe ();
13595
13596   p = rs->buf.data ();
13597   strcpy (p, "QTFrame:");
13598   p = strchr (p, '\0');
13599   switch (type)
13600     {
13601     case tfind_number:
13602       xsnprintf (p, endbuf - p, "%x", num);
13603       break;
13604     case tfind_pc:
13605       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13606       break;
13607     case tfind_tp:
13608       xsnprintf (p, endbuf - p, "tdp:%x", num);
13609       break;
13610     case tfind_range:
13611       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13612                  phex_nz (addr2, 0));
13613       break;
13614     case tfind_outside:
13615       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13616                  phex_nz (addr2, 0));
13617       break;
13618     default:
13619       error (_("Unknown trace find type %d"), type);
13620     }
13621
13622   putpkt (rs->buf);
13623   reply = remote_get_noisy_reply ();
13624   if (*reply == '\0')
13625     error (_("Target does not support this command."));
13626
13627   while (reply && *reply)
13628     switch (*reply)
13629       {
13630       case 'F':
13631         p = ++reply;
13632         target_frameno = (int) strtol (p, &reply, 16);
13633         if (reply == p)
13634           error (_("Unable to parse trace frame number"));
13635         /* Don't update our remote traceframe number cache on failure
13636            to select a remote traceframe.  */
13637         if (target_frameno == -1)
13638           return -1;
13639         break;
13640       case 'T':
13641         p = ++reply;
13642         target_tracept = (int) strtol (p, &reply, 16);
13643         if (reply == p)
13644           error (_("Unable to parse tracepoint number"));
13645         break;
13646       case 'O':         /* "OK"? */
13647         if (reply[1] == 'K' && reply[2] == '\0')
13648           reply += 2;
13649         else
13650           error (_("Bogus reply from target: %s"), reply);
13651         break;
13652       default:
13653         error (_("Bogus reply from target: %s"), reply);
13654       }
13655   if (tpp)
13656     *tpp = target_tracept;
13657
13658   rs->remote_traceframe_number = target_frameno;
13659   return target_frameno;
13660 }
13661
13662 bool
13663 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13664 {
13665   struct remote_state *rs = get_remote_state ();
13666   char *reply;
13667   ULONGEST uval;
13668
13669   set_remote_traceframe ();
13670
13671   xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
13672   putpkt (rs->buf);
13673   reply = remote_get_noisy_reply ();
13674   if (reply && *reply)
13675     {
13676       if (*reply == 'V')
13677         {
13678           unpack_varlen_hex (reply + 1, &uval);
13679           *val = (LONGEST) uval;
13680           return true;
13681         }
13682     }
13683   return false;
13684 }
13685
13686 int
13687 remote_target::save_trace_data (const char *filename)
13688 {
13689   struct remote_state *rs = get_remote_state ();
13690   char *p, *reply;
13691
13692   p = rs->buf.data ();
13693   strcpy (p, "QTSave:");
13694   p += strlen (p);
13695   if ((p - rs->buf.data ()) + strlen (filename) * 2
13696       >= get_remote_packet_size ())
13697     error (_("Remote file name too long for trace save packet"));
13698   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13699   *p++ = '\0';
13700   putpkt (rs->buf);
13701   reply = remote_get_noisy_reply ();
13702   if (*reply == '\0')
13703     error (_("Target does not support this command."));
13704   if (strcmp (reply, "OK") != 0)
13705     error (_("Bogus reply from target: %s"), reply);
13706   return 0;
13707 }
13708
13709 /* This is basically a memory transfer, but needs to be its own packet
13710    because we don't know how the target actually organizes its trace
13711    memory, plus we want to be able to ask for as much as possible, but
13712    not be unhappy if we don't get as much as we ask for.  */
13713
13714 LONGEST
13715 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13716 {
13717   struct remote_state *rs = get_remote_state ();
13718   char *reply;
13719   char *p;
13720   int rslt;
13721
13722   p = rs->buf.data ();
13723   strcpy (p, "qTBuffer:");
13724   p += strlen (p);
13725   p += hexnumstr (p, offset);
13726   *p++ = ',';
13727   p += hexnumstr (p, len);
13728   *p++ = '\0';
13729
13730   putpkt (rs->buf);
13731   reply = remote_get_noisy_reply ();
13732   if (reply && *reply)
13733     {
13734       /* 'l' by itself means we're at the end of the buffer and
13735          there is nothing more to get.  */
13736       if (*reply == 'l')
13737         return 0;
13738
13739       /* Convert the reply into binary.  Limit the number of bytes to
13740          convert according to our passed-in buffer size, rather than
13741          what was returned in the packet; if the target is
13742          unexpectedly generous and gives us a bigger reply than we
13743          asked for, we don't want to crash.  */
13744       rslt = hex2bin (reply, buf, len);
13745       return rslt;
13746     }
13747
13748   /* Something went wrong, flag as an error.  */
13749   return -1;
13750 }
13751
13752 void
13753 remote_target::set_disconnected_tracing (int val)
13754 {
13755   struct remote_state *rs = get_remote_state ();
13756
13757   if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13758     {
13759       char *reply;
13760
13761       xsnprintf (rs->buf.data (), get_remote_packet_size (),
13762                  "QTDisconnected:%x", val);
13763       putpkt (rs->buf);
13764       reply = remote_get_noisy_reply ();
13765       if (*reply == '\0')
13766         error (_("Target does not support this command."));
13767       if (strcmp (reply, "OK") != 0)
13768         error (_("Bogus reply from target: %s"), reply);
13769     }
13770   else if (val)
13771     warning (_("Target does not support disconnected tracing."));
13772 }
13773
13774 int
13775 remote_target::core_of_thread (ptid_t ptid)
13776 {
13777   thread_info *info = find_thread_ptid (this, ptid);
13778
13779   if (info != NULL && info->priv != NULL)
13780     return get_remote_thread_info (info)->core;
13781
13782   return -1;
13783 }
13784
13785 void
13786 remote_target::set_circular_trace_buffer (int val)
13787 {
13788   struct remote_state *rs = get_remote_state ();
13789   char *reply;
13790
13791   xsnprintf (rs->buf.data (), get_remote_packet_size (),
13792              "QTBuffer:circular:%x", val);
13793   putpkt (rs->buf);
13794   reply = remote_get_noisy_reply ();
13795   if (*reply == '\0')
13796     error (_("Target does not support this command."));
13797   if (strcmp (reply, "OK") != 0)
13798     error (_("Bogus reply from target: %s"), reply);
13799 }
13800
13801 traceframe_info_up
13802 remote_target::traceframe_info ()
13803 {
13804   gdb::optional<gdb::char_vector> text
13805     = target_read_stralloc (current_inferior ()->top_target (),
13806                             TARGET_OBJECT_TRACEFRAME_INFO,
13807                             NULL);
13808   if (text)
13809     return parse_traceframe_info (text->data ());
13810
13811   return NULL;
13812 }
13813
13814 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
13815    instruction on which a fast tracepoint may be placed.  Returns -1
13816    if the packet is not supported, and 0 if the minimum instruction
13817    length is unknown.  */
13818
13819 int
13820 remote_target::get_min_fast_tracepoint_insn_len ()
13821 {
13822   struct remote_state *rs = get_remote_state ();
13823   char *reply;
13824
13825   /* If we're not debugging a process yet, the IPA can't be
13826      loaded.  */
13827   if (!target_has_execution ())
13828     return 0;
13829
13830   /* Make sure the remote is pointing at the right process.  */
13831   set_general_process ();
13832
13833   xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
13834   putpkt (rs->buf);
13835   reply = remote_get_noisy_reply ();
13836   if (*reply == '\0')
13837     return -1;
13838   else
13839     {
13840       ULONGEST min_insn_len;
13841
13842       unpack_varlen_hex (reply, &min_insn_len);
13843
13844       return (int) min_insn_len;
13845     }
13846 }
13847
13848 void
13849 remote_target::set_trace_buffer_size (LONGEST val)
13850 {
13851   if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13852     {
13853       struct remote_state *rs = get_remote_state ();
13854       char *buf = rs->buf.data ();
13855       char *endbuf = buf + get_remote_packet_size ();
13856       enum packet_result result;
13857
13858       gdb_assert (val >= 0 || val == -1);
13859       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13860       /* Send -1 as literal "-1" to avoid host size dependency.  */
13861       if (val < 0)
13862         {
13863           *buf++ = '-';
13864           buf += hexnumstr (buf, (ULONGEST) -val);
13865         }
13866       else
13867         buf += hexnumstr (buf, (ULONGEST) val);
13868
13869       putpkt (rs->buf);
13870       remote_get_noisy_reply ();
13871       result = packet_ok (rs->buf,
13872                   &remote_protocol_packets[PACKET_QTBuffer_size]);
13873
13874       if (result != PACKET_OK)
13875         warning (_("Bogus reply from target: %s"), rs->buf.data ());
13876     }
13877 }
13878
13879 bool
13880 remote_target::set_trace_notes (const char *user, const char *notes,
13881                                 const char *stop_notes)
13882 {
13883   struct remote_state *rs = get_remote_state ();
13884   char *reply;
13885   char *buf = rs->buf.data ();
13886   char *endbuf = buf + get_remote_packet_size ();
13887   int nbytes;
13888
13889   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13890   if (user)
13891     {
13892       buf += xsnprintf (buf, endbuf - buf, "user:");
13893       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13894       buf += 2 * nbytes;
13895       *buf++ = ';';
13896     }
13897   if (notes)
13898     {
13899       buf += xsnprintf (buf, endbuf - buf, "notes:");
13900       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13901       buf += 2 * nbytes;
13902       *buf++ = ';';
13903     }
13904   if (stop_notes)
13905     {
13906       buf += xsnprintf (buf, endbuf - buf, "tstop:");
13907       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13908       buf += 2 * nbytes;
13909       *buf++ = ';';
13910     }
13911   /* Ensure the buffer is terminated.  */
13912   *buf = '\0';
13913
13914   putpkt (rs->buf);
13915   reply = remote_get_noisy_reply ();
13916   if (*reply == '\0')
13917     return false;
13918
13919   if (strcmp (reply, "OK") != 0)
13920     error (_("Bogus reply from target: %s"), reply);
13921
13922   return true;
13923 }
13924
13925 bool
13926 remote_target::use_agent (bool use)
13927 {
13928   if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13929     {
13930       struct remote_state *rs = get_remote_state ();
13931
13932       /* If the stub supports QAgent.  */
13933       xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
13934       putpkt (rs->buf);
13935       getpkt (&rs->buf, 0);
13936
13937       if (strcmp (rs->buf.data (), "OK") == 0)
13938         {
13939           ::use_agent = use;
13940           return true;
13941         }
13942     }
13943
13944   return false;
13945 }
13946
13947 bool
13948 remote_target::can_use_agent ()
13949 {
13950   return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13951 }
13952
13953 struct btrace_target_info
13954 {
13955   /* The ptid of the traced thread.  */
13956   ptid_t ptid;
13957
13958   /* The obtained branch trace configuration.  */
13959   struct btrace_config conf;
13960 };
13961
13962 /* Reset our idea of our target's btrace configuration.  */
13963
13964 static void
13965 remote_btrace_reset (remote_state *rs)
13966 {
13967   memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13968 }
13969
13970 /* Synchronize the configuration with the target.  */
13971
13972 void
13973 remote_target::btrace_sync_conf (const btrace_config *conf)
13974 {
13975   struct packet_config *packet;
13976   struct remote_state *rs;
13977   char *buf, *pos, *endbuf;
13978
13979   rs = get_remote_state ();
13980   buf = rs->buf.data ();
13981   endbuf = buf + get_remote_packet_size ();
13982
13983   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13984   if (packet_config_support (packet) == PACKET_ENABLE
13985       && conf->bts.size != rs->btrace_config.bts.size)
13986     {
13987       pos = buf;
13988       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13989                         conf->bts.size);
13990
13991       putpkt (buf);
13992       getpkt (&rs->buf, 0);
13993
13994       if (packet_ok (buf, packet) == PACKET_ERROR)
13995         {
13996           if (buf[0] == 'E' && buf[1] == '.')
13997             error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13998           else
13999             error (_("Failed to configure the BTS buffer size."));
14000         }
14001
14002       rs->btrace_config.bts.size = conf->bts.size;
14003     }
14004
14005   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
14006   if (packet_config_support (packet) == PACKET_ENABLE
14007       && conf->pt.size != rs->btrace_config.pt.size)
14008     {
14009       pos = buf;
14010       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
14011                         conf->pt.size);
14012
14013       putpkt (buf);
14014       getpkt (&rs->buf, 0);
14015
14016       if (packet_ok (buf, packet) == PACKET_ERROR)
14017         {
14018           if (buf[0] == 'E' && buf[1] == '.')
14019             error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14020           else
14021             error (_("Failed to configure the trace buffer size."));
14022         }
14023
14024       rs->btrace_config.pt.size = conf->pt.size;
14025     }
14026 }
14027
14028 /* Read the current thread's btrace configuration from the target and
14029    store it into CONF.  */
14030
14031 static void
14032 btrace_read_config (struct btrace_config *conf)
14033 {
14034   gdb::optional<gdb::char_vector> xml
14035     = target_read_stralloc (current_inferior ()->top_target (),
14036                             TARGET_OBJECT_BTRACE_CONF, "");
14037   if (xml)
14038     parse_xml_btrace_conf (conf, xml->data ());
14039 }
14040
14041 /* Maybe reopen target btrace.  */
14042
14043 void
14044 remote_target::remote_btrace_maybe_reopen ()
14045 {
14046   struct remote_state *rs = get_remote_state ();
14047   int btrace_target_pushed = 0;
14048 #if !defined (HAVE_LIBIPT)
14049   int warned = 0;
14050 #endif
14051
14052   /* Don't bother walking the entirety of the remote thread list when
14053      we know the feature isn't supported by the remote.  */
14054   if (packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14055     return;
14056
14057   scoped_restore_current_thread restore_thread;
14058
14059   for (thread_info *tp : all_non_exited_threads (this))
14060     {
14061       set_general_thread (tp->ptid);
14062
14063       memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14064       btrace_read_config (&rs->btrace_config);
14065
14066       if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14067         continue;
14068
14069 #if !defined (HAVE_LIBIPT)
14070       if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14071         {
14072           if (!warned)
14073             {
14074               warned = 1;
14075               warning (_("Target is recording using Intel Processor Trace "
14076                          "but support was disabled at compile time."));
14077             }
14078
14079           continue;
14080         }
14081 #endif /* !defined (HAVE_LIBIPT) */
14082
14083       /* Push target, once, but before anything else happens.  This way our
14084          changes to the threads will be cleaned up by unpushing the target
14085          in case btrace_read_config () throws.  */
14086       if (!btrace_target_pushed)
14087         {
14088           btrace_target_pushed = 1;
14089           record_btrace_push_target ();
14090           printf_filtered (_("Target is recording using %s.\n"),
14091                            btrace_format_string (rs->btrace_config.format));
14092         }
14093
14094       tp->btrace.target = XCNEW (struct btrace_target_info);
14095       tp->btrace.target->ptid = tp->ptid;
14096       tp->btrace.target->conf = rs->btrace_config;
14097     }
14098 }
14099
14100 /* Enable branch tracing.  */
14101
14102 struct btrace_target_info *
14103 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
14104 {
14105   struct btrace_target_info *tinfo = NULL;
14106   struct packet_config *packet = NULL;
14107   struct remote_state *rs = get_remote_state ();
14108   char *buf = rs->buf.data ();
14109   char *endbuf = buf + get_remote_packet_size ();
14110
14111   switch (conf->format)
14112     {
14113       case BTRACE_FORMAT_BTS:
14114         packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
14115         break;
14116
14117       case BTRACE_FORMAT_PT:
14118         packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
14119         break;
14120     }
14121
14122   if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14123     error (_("Target does not support branch tracing."));
14124
14125   btrace_sync_conf (conf);
14126
14127   set_general_thread (ptid);
14128
14129   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14130   putpkt (rs->buf);
14131   getpkt (&rs->buf, 0);
14132
14133   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14134     {
14135       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14136         error (_("Could not enable branch tracing for %s: %s"),
14137                target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14138       else
14139         error (_("Could not enable branch tracing for %s."),
14140                target_pid_to_str (ptid).c_str ());
14141     }
14142
14143   tinfo = XCNEW (struct btrace_target_info);
14144   tinfo->ptid = ptid;
14145
14146   /* If we fail to read the configuration, we lose some information, but the
14147      tracing itself is not impacted.  */
14148   try
14149     {
14150       btrace_read_config (&tinfo->conf);
14151     }
14152   catch (const gdb_exception_error &err)
14153     {
14154       if (err.message != NULL)
14155         warning ("%s", err.what ());
14156     }
14157
14158   return tinfo;
14159 }
14160
14161 /* Disable branch tracing.  */
14162
14163 void
14164 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14165 {
14166   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
14167   struct remote_state *rs = get_remote_state ();
14168   char *buf = rs->buf.data ();
14169   char *endbuf = buf + get_remote_packet_size ();
14170
14171   if (packet_config_support (packet) != PACKET_ENABLE)
14172     error (_("Target does not support branch tracing."));
14173
14174   set_general_thread (tinfo->ptid);
14175
14176   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14177   putpkt (rs->buf);
14178   getpkt (&rs->buf, 0);
14179
14180   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14181     {
14182       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14183         error (_("Could not disable branch tracing for %s: %s"),
14184                target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14185       else
14186         error (_("Could not disable branch tracing for %s."),
14187                target_pid_to_str (tinfo->ptid).c_str ());
14188     }
14189
14190   xfree (tinfo);
14191 }
14192
14193 /* Teardown branch tracing.  */
14194
14195 void
14196 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14197 {
14198   /* We must not talk to the target during teardown.  */
14199   xfree (tinfo);
14200 }
14201
14202 /* Read the branch trace.  */
14203
14204 enum btrace_error
14205 remote_target::read_btrace (struct btrace_data *btrace,
14206                             struct btrace_target_info *tinfo,
14207                             enum btrace_read_type type)
14208 {
14209   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
14210   const char *annex;
14211
14212   if (packet_config_support (packet) != PACKET_ENABLE)
14213     error (_("Target does not support branch tracing."));
14214
14215 #if !defined(HAVE_LIBEXPAT)
14216   error (_("Cannot process branch tracing result. XML parsing not supported."));
14217 #endif
14218
14219   switch (type)
14220     {
14221     case BTRACE_READ_ALL:
14222       annex = "all";
14223       break;
14224     case BTRACE_READ_NEW:
14225       annex = "new";
14226       break;
14227     case BTRACE_READ_DELTA:
14228       annex = "delta";
14229       break;
14230     default:
14231       internal_error (__FILE__, __LINE__,
14232                       _("Bad branch tracing read type: %u."),
14233                       (unsigned int) type);
14234     }
14235
14236   gdb::optional<gdb::char_vector> xml
14237     = target_read_stralloc (current_inferior ()->top_target (),
14238                             TARGET_OBJECT_BTRACE, annex);
14239   if (!xml)
14240     return BTRACE_ERR_UNKNOWN;
14241
14242   parse_xml_btrace (btrace, xml->data ());
14243
14244   return BTRACE_ERR_NONE;
14245 }
14246
14247 const struct btrace_config *
14248 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14249 {
14250   return &tinfo->conf;
14251 }
14252
14253 bool
14254 remote_target::augmented_libraries_svr4_read ()
14255 {
14256   return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
14257           == PACKET_ENABLE);
14258 }
14259
14260 /* Implementation of to_load.  */
14261
14262 void
14263 remote_target::load (const char *name, int from_tty)
14264 {
14265   generic_load (name, from_tty);
14266 }
14267
14268 /* Accepts an integer PID; returns a string representing a file that
14269    can be opened on the remote side to get the symbols for the child
14270    process.  Returns NULL if the operation is not supported.  */
14271
14272 char *
14273 remote_target::pid_to_exec_file (int pid)
14274 {
14275   static gdb::optional<gdb::char_vector> filename;
14276   char *annex = NULL;
14277
14278   if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14279     return NULL;
14280
14281   inferior *inf = find_inferior_pid (this, pid);
14282   if (inf == NULL)
14283     internal_error (__FILE__, __LINE__,
14284                     _("not currently attached to process %d"), pid);
14285
14286   if (!inf->fake_pid_p)
14287     {
14288       const int annex_size = 9;
14289
14290       annex = (char *) alloca (annex_size);
14291       xsnprintf (annex, annex_size, "%x", pid);
14292     }
14293
14294   filename = target_read_stralloc (current_inferior ()->top_target (),
14295                                    TARGET_OBJECT_EXEC_FILE, annex);
14296
14297   return filename ? filename->data () : nullptr;
14298 }
14299
14300 /* Implement the to_can_do_single_step target_ops method.  */
14301
14302 int
14303 remote_target::can_do_single_step ()
14304 {
14305   /* We can only tell whether target supports single step or not by
14306      supported s and S vCont actions if the stub supports vContSupported
14307      feature.  If the stub doesn't support vContSupported feature,
14308      we have conservatively to think target doesn't supports single
14309      step.  */
14310   if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14311     {
14312       struct remote_state *rs = get_remote_state ();
14313
14314       if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14315         remote_vcont_probe ();
14316
14317       return rs->supports_vCont.s && rs->supports_vCont.S;
14318     }
14319   else
14320     return 0;
14321 }
14322
14323 /* Implementation of the to_execution_direction method for the remote
14324    target.  */
14325
14326 enum exec_direction_kind
14327 remote_target::execution_direction ()
14328 {
14329   struct remote_state *rs = get_remote_state ();
14330
14331   return rs->last_resume_exec_dir;
14332 }
14333
14334 /* Return pointer to the thread_info struct which corresponds to
14335    THREAD_HANDLE (having length HANDLE_LEN).  */
14336
14337 thread_info *
14338 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14339                                              int handle_len,
14340                                              inferior *inf)
14341 {
14342   for (thread_info *tp : all_non_exited_threads (this))
14343     {
14344       remote_thread_info *priv = get_remote_thread_info (tp);
14345
14346       if (tp->inf == inf && priv != NULL)
14347         {
14348           if (handle_len != priv->thread_handle.size ())
14349             error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14350                    handle_len, priv->thread_handle.size ());
14351           if (memcmp (thread_handle, priv->thread_handle.data (),
14352                       handle_len) == 0)
14353             return tp;
14354         }
14355     }
14356
14357   return NULL;
14358 }
14359
14360 gdb::byte_vector
14361 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14362 {
14363   remote_thread_info *priv = get_remote_thread_info (tp);
14364   return priv->thread_handle;
14365 }
14366
14367 bool
14368 remote_target::can_async_p ()
14369 {
14370   struct remote_state *rs = get_remote_state ();
14371
14372   /* We don't go async if the user has explicitly prevented it with the
14373      "maint set target-async" command.  */
14374   if (!target_async_permitted)
14375     return false;
14376
14377   /* We're async whenever the serial device is.  */
14378   return serial_can_async_p (rs->remote_desc);
14379 }
14380
14381 bool
14382 remote_target::is_async_p ()
14383 {
14384   struct remote_state *rs = get_remote_state ();
14385
14386   if (!target_async_permitted)
14387     /* We only enable async when the user specifically asks for it.  */
14388     return false;
14389
14390   /* We're async whenever the serial device is.  */
14391   return serial_is_async_p (rs->remote_desc);
14392 }
14393
14394 /* Pass the SERIAL event on and up to the client.  One day this code
14395    will be able to delay notifying the client of an event until the
14396    point where an entire packet has been received.  */
14397
14398 static serial_event_ftype remote_async_serial_handler;
14399
14400 static void
14401 remote_async_serial_handler (struct serial *scb, void *context)
14402 {
14403   /* Don't propogate error information up to the client.  Instead let
14404      the client find out about the error by querying the target.  */
14405   inferior_event_handler (INF_REG_EVENT);
14406 }
14407
14408 static void
14409 remote_async_inferior_event_handler (gdb_client_data data)
14410 {
14411   inferior_event_handler (INF_REG_EVENT);
14412 }
14413
14414 int
14415 remote_target::async_wait_fd ()
14416 {
14417   struct remote_state *rs = get_remote_state ();
14418   return rs->remote_desc->fd;
14419 }
14420
14421 void
14422 remote_target::async (int enable)
14423 {
14424   struct remote_state *rs = get_remote_state ();
14425
14426   if (enable)
14427     {
14428       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14429
14430       /* If there are pending events in the stop reply queue tell the
14431          event loop to process them.  */
14432       if (!rs->stop_reply_queue.empty ())
14433         mark_async_event_handler (rs->remote_async_inferior_event_token);
14434       /* For simplicity, below we clear the pending events token
14435          without remembering whether it is marked, so here we always
14436          mark it.  If there's actually no pending notification to
14437          process, this ends up being a no-op (other than a spurious
14438          event-loop wakeup).  */
14439       if (target_is_non_stop_p ())
14440         mark_async_event_handler (rs->notif_state->get_pending_events_token);
14441     }
14442   else
14443     {
14444       serial_async (rs->remote_desc, NULL, NULL);
14445       /* If the core is disabling async, it doesn't want to be
14446          disturbed with target events.  Clear all async event sources
14447          too.  */
14448       clear_async_event_handler (rs->remote_async_inferior_event_token);
14449       if (target_is_non_stop_p ())
14450         clear_async_event_handler (rs->notif_state->get_pending_events_token);
14451     }
14452 }
14453
14454 /* Implementation of the to_thread_events method.  */
14455
14456 void
14457 remote_target::thread_events (int enable)
14458 {
14459   struct remote_state *rs = get_remote_state ();
14460   size_t size = get_remote_packet_size ();
14461
14462   if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14463     return;
14464
14465   xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
14466   putpkt (rs->buf);
14467   getpkt (&rs->buf, 0);
14468
14469   switch (packet_ok (rs->buf,
14470                      &remote_protocol_packets[PACKET_QThreadEvents]))
14471     {
14472     case PACKET_OK:
14473       if (strcmp (rs->buf.data (), "OK") != 0)
14474         error (_("Remote refused setting thread events: %s"), rs->buf.data ());
14475       break;
14476     case PACKET_ERROR:
14477       warning (_("Remote failure reply: %s"), rs->buf.data ());
14478       break;
14479     case PACKET_UNKNOWN:
14480       break;
14481     }
14482 }
14483
14484 static void
14485 show_remote_cmd (const char *args, int from_tty)
14486 {
14487   /* We can't just use cmd_show_list here, because we want to skip
14488      the redundant "show remote Z-packet" and the legacy aliases.  */
14489   struct cmd_list_element *list = remote_show_cmdlist;
14490   struct ui_out *uiout = current_uiout;
14491
14492   ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14493   for (; list != NULL; list = list->next)
14494     if (strcmp (list->name, "Z-packet") == 0)
14495       continue;
14496     else if (list->type == not_set_cmd)
14497       /* Alias commands are exactly like the original, except they
14498          don't have the normal type.  */
14499       continue;
14500     else
14501       {
14502         ui_out_emit_tuple option_emitter (uiout, "option");
14503
14504         uiout->field_string ("name", list->name);
14505         uiout->text (":  ");
14506         if (list->type == show_cmd)
14507           do_show_command (NULL, from_tty, list);
14508         else
14509           cmd_func (list, NULL, from_tty);
14510       }
14511 }
14512
14513
14514 /* Function to be called whenever a new objfile (shlib) is detected.  */
14515 static void
14516 remote_new_objfile (struct objfile *objfile)
14517 {
14518   remote_target *remote = get_current_remote_target ();
14519
14520   if (remote != NULL)                   /* Have a remote connection.  */
14521     remote->remote_check_symbols ();
14522 }
14523
14524 /* Pull all the tracepoints defined on the target and create local
14525    data structures representing them.  We don't want to create real
14526    tracepoints yet, we don't want to mess up the user's existing
14527    collection.  */
14528   
14529 int
14530 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14531 {
14532   struct remote_state *rs = get_remote_state ();
14533   char *p;
14534
14535   /* Ask for a first packet of tracepoint definition.  */
14536   putpkt ("qTfP");
14537   getpkt (&rs->buf, 0);
14538   p = rs->buf.data ();
14539   while (*p && *p != 'l')
14540     {
14541       parse_tracepoint_definition (p, utpp);
14542       /* Ask for another packet of tracepoint definition.  */
14543       putpkt ("qTsP");
14544       getpkt (&rs->buf, 0);
14545       p = rs->buf.data ();
14546     }
14547   return 0;
14548 }
14549
14550 int
14551 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14552 {
14553   struct remote_state *rs = get_remote_state ();
14554   char *p;
14555
14556   /* Ask for a first packet of variable definition.  */
14557   putpkt ("qTfV");
14558   getpkt (&rs->buf, 0);
14559   p = rs->buf.data ();
14560   while (*p && *p != 'l')
14561     {
14562       parse_tsv_definition (p, utsvp);
14563       /* Ask for another packet of variable definition.  */
14564       putpkt ("qTsV");
14565       getpkt (&rs->buf, 0);
14566       p = rs->buf.data ();
14567     }
14568   return 0;
14569 }
14570
14571 /* The "set/show range-stepping" show hook.  */
14572
14573 static void
14574 show_range_stepping (struct ui_file *file, int from_tty,
14575                      struct cmd_list_element *c,
14576                      const char *value)
14577 {
14578   fprintf_filtered (file,
14579                     _("Debugger's willingness to use range stepping "
14580                       "is %s.\n"), value);
14581 }
14582
14583 /* Return true if the vCont;r action is supported by the remote
14584    stub.  */
14585
14586 bool
14587 remote_target::vcont_r_supported ()
14588 {
14589   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14590     remote_vcont_probe ();
14591
14592   return (packet_support (PACKET_vCont) == PACKET_ENABLE
14593           && get_remote_state ()->supports_vCont.r);
14594 }
14595
14596 /* The "set/show range-stepping" set hook.  */
14597
14598 static void
14599 set_range_stepping (const char *ignore_args, int from_tty,
14600                     struct cmd_list_element *c)
14601 {
14602   /* When enabling, check whether range stepping is actually supported
14603      by the target, and warn if not.  */
14604   if (use_range_stepping)
14605     {
14606       remote_target *remote = get_current_remote_target ();
14607       if (remote == NULL
14608           || !remote->vcont_r_supported ())
14609         warning (_("Range stepping is not supported by the current target"));
14610     }
14611 }
14612
14613 static void
14614 show_remote_debug (struct ui_file *file, int from_tty,
14615                    struct cmd_list_element *c, const char *value)
14616 {
14617   fprintf_filtered (file, _("Debugging of remote protocol is %s.\n"),
14618                     value);
14619 }
14620
14621 static void
14622 show_remote_timeout (struct ui_file *file, int from_tty,
14623                      struct cmd_list_element *c, const char *value)
14624 {
14625   fprintf_filtered (file,
14626                     _("Timeout limit to wait for target to respond is %s.\n"),
14627                     value);
14628 }
14629
14630 /* Implement the "supports_memory_tagging" target_ops method.  */
14631
14632 bool
14633 remote_target::supports_memory_tagging ()
14634 {
14635   return remote_memory_tagging_p ();
14636 }
14637
14638 /* Create the qMemTags packet given ADDRESS, LEN and TYPE.  */
14639
14640 static void
14641 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14642                               size_t len, int type)
14643 {
14644   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14645
14646   std::string request = string_printf ("qMemTags:%s,%s:%s",
14647                                        phex_nz (address, addr_size),
14648                                        phex_nz (len, sizeof (len)),
14649                                        phex_nz (type, sizeof (type)));
14650
14651   strcpy (packet.data (), request.c_str ());
14652 }
14653
14654 /* Parse the qMemTags packet reply into TAGS.
14655
14656    Return true if successful, false otherwise.  */
14657
14658 static bool
14659 parse_fetch_memtags_reply (const gdb::char_vector &reply,
14660                            gdb::byte_vector &tags)
14661 {
14662   if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
14663     return false;
14664
14665   /* Copy the tag data.  */
14666   tags = hex2bin (reply.data () + 1);
14667
14668   return true;
14669 }
14670
14671 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS.  */
14672
14673 static void
14674 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14675                               size_t len, int type,
14676                               const gdb::byte_vector &tags)
14677 {
14678   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14679
14680   /* Put together the main packet, address and length.  */
14681   std::string request = string_printf ("QMemTags:%s,%s:%s:",
14682                                        phex_nz (address, addr_size),
14683                                        phex_nz (len, sizeof (len)),
14684                                        phex_nz (type, sizeof (type)));
14685   request += bin2hex (tags.data (), tags.size ());
14686
14687   /* Check if we have exceeded the maximum packet size.  */
14688   if (packet.size () < request.length ())
14689     error (_("Contents too big for packet QMemTags."));
14690
14691   strcpy (packet.data (), request.c_str ());
14692 }
14693
14694 /* Implement the "fetch_memtags" target_ops method.  */
14695
14696 bool
14697 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
14698                               gdb::byte_vector &tags, int type)
14699 {
14700   /* Make sure the qMemTags packet is supported.  */
14701   if (!remote_memory_tagging_p ())
14702     gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
14703
14704   struct remote_state *rs = get_remote_state ();
14705
14706   create_fetch_memtags_request (rs->buf, address, len, type);
14707
14708   putpkt (rs->buf);
14709   getpkt (&rs->buf, 0);
14710
14711   return parse_fetch_memtags_reply (rs->buf, tags);
14712 }
14713
14714 /* Implement the "store_memtags" target_ops method.  */
14715
14716 bool
14717 remote_target::store_memtags (CORE_ADDR address, size_t len,
14718                               const gdb::byte_vector &tags, int type)
14719 {
14720   /* Make sure the QMemTags packet is supported.  */
14721   if (!remote_memory_tagging_p ())
14722     gdb_assert_not_reached ("remote store_memtags called with packet disabled");
14723
14724   struct remote_state *rs = get_remote_state ();
14725
14726   create_store_memtags_request (rs->buf, address, len, type, tags);
14727
14728   putpkt (rs->buf);
14729   getpkt (&rs->buf, 0);
14730
14731   /* Verify if the request was successful.  */
14732   return packet_check_result (rs->buf.data ()) == PACKET_OK;
14733 }
14734
14735 #if GDB_SELF_TEST
14736
14737 namespace selftests {
14738
14739 static void
14740 test_memory_tagging_functions ()
14741 {
14742   remote_target remote;
14743
14744   struct packet_config *config
14745     = &remote_protocol_packets[PACKET_memory_tagging_feature];
14746
14747   scoped_restore restore_memtag_support_
14748     = make_scoped_restore (&config->support);
14749
14750   /* Test memory tagging packet support.  */
14751   config->support = PACKET_SUPPORT_UNKNOWN;
14752   SELF_CHECK (remote.supports_memory_tagging () == false);
14753   config->support = PACKET_DISABLE;
14754   SELF_CHECK (remote.supports_memory_tagging () == false);
14755   config->support = PACKET_ENABLE;
14756   SELF_CHECK (remote.supports_memory_tagging () == true);
14757
14758   /* Setup testing.  */
14759   gdb::char_vector packet;
14760   gdb::byte_vector tags, bv;
14761   std::string expected, reply;
14762   packet.resize (32000);
14763
14764   /* Test creating a qMemTags request.  */
14765
14766   expected = "qMemTags:0,0:0";
14767   create_fetch_memtags_request (packet, 0x0, 0x0, 0);
14768   SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14769
14770   expected = "qMemTags:deadbeef,10:1";
14771   create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
14772   SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14773
14774   /* Test parsing a qMemTags reply.  */
14775
14776   /* Error reply, tags vector unmodified.  */
14777   reply = "E00";
14778   strcpy (packet.data (), reply.c_str ());
14779   tags.resize (0);
14780   SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
14781   SELF_CHECK (tags.size () == 0);
14782
14783   /* Valid reply, tags vector updated.  */
14784   tags.resize (0);
14785   bv.resize (0);
14786
14787   for (int i = 0; i < 5; i++)
14788     bv.push_back (i);
14789
14790   reply = "m" + bin2hex (bv.data (), bv.size ());
14791   strcpy (packet.data (), reply.c_str ());
14792
14793   SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
14794   SELF_CHECK (tags.size () == 5);
14795
14796   for (int i = 0; i < 5; i++)
14797     SELF_CHECK (tags[i] == i);
14798
14799   /* Test creating a QMemTags request.  */
14800
14801   /* Empty tag data.  */
14802   tags.resize (0);
14803   expected = "QMemTags:0,0:0:";
14804   create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
14805   SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14806                       expected.length ()) == 0);
14807
14808   /* Non-empty tag data.  */
14809   tags.resize (0);
14810   for (int i = 0; i < 5; i++)
14811     tags.push_back (i);
14812   expected = "QMemTags:deadbeef,ff:1:0001020304";
14813   create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
14814   SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14815                       expected.length ()) == 0);
14816 }
14817
14818 } // namespace selftests
14819 #endif /* GDB_SELF_TEST */
14820
14821 void _initialize_remote ();
14822 void
14823 _initialize_remote ()
14824 {
14825   struct cmd_list_element *cmd;
14826   const char *cmd_name;
14827
14828   /* architecture specific data */
14829   remote_g_packet_data_handle =
14830     gdbarch_data_register_pre_init (remote_g_packet_data_init);
14831
14832   add_target (remote_target_info, remote_target::open);
14833   add_target (extended_remote_target_info, extended_remote_target::open);
14834
14835   /* Hook into new objfile notification.  */
14836   gdb::observers::new_objfile.attach (remote_new_objfile);
14837
14838 #if 0
14839   init_remote_threadtests ();
14840 #endif
14841
14842   /* set/show remote ...  */
14843
14844   add_basic_prefix_cmd ("remote", class_maintenance, _("\
14845 Remote protocol specific variables.\n\
14846 Configure various remote-protocol specific variables such as\n\
14847 the packets being used."),
14848                         &remote_set_cmdlist, "set remote ",
14849                         0 /* allow-unknown */, &setlist);
14850   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14851 Remote protocol specific variables.\n\
14852 Configure various remote-protocol specific variables such as\n\
14853 the packets being used."),
14854                   &remote_show_cmdlist, "show remote ",
14855                   0 /* allow-unknown */, &showlist);
14856
14857   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14858 Compare section data on target to the exec file.\n\
14859 Argument is a single section name (default: all loaded sections).\n\
14860 To compare only read-only loaded sections, specify the -r option."),
14861            &cmdlist);
14862
14863   add_cmd ("packet", class_maintenance, packet_command, _("\
14864 Send an arbitrary packet to a remote target.\n\
14865    maintenance packet TEXT\n\
14866 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14867 this command sends the string TEXT to the inferior, and displays the\n\
14868 response packet.  GDB supplies the initial `$' character, and the\n\
14869 terminating `#' character and checksum."),
14870            &maintenancelist);
14871
14872   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14873 Set whether to send break if interrupted."), _("\
14874 Show whether to send break if interrupted."), _("\
14875 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14876                            set_remotebreak, show_remotebreak,
14877                            &setlist, &showlist);
14878   cmd_name = "remotebreak";
14879   cmd = lookup_cmd (&cmd_name, setlist, "", NULL, -1, 1);
14880   deprecate_cmd (cmd, "set remote interrupt-sequence");
14881   cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14882   cmd = lookup_cmd (&cmd_name, showlist, "", NULL, -1, 1);
14883   deprecate_cmd (cmd, "show remote interrupt-sequence");
14884
14885   add_setshow_enum_cmd ("interrupt-sequence", class_support,
14886                         interrupt_sequence_modes, &interrupt_sequence_mode,
14887                         _("\
14888 Set interrupt sequence to remote target."), _("\
14889 Show interrupt sequence to remote target."), _("\
14890 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14891                         NULL, show_interrupt_sequence,
14892                         &remote_set_cmdlist,
14893                         &remote_show_cmdlist);
14894
14895   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14896                            &interrupt_on_connect, _("\
14897 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
14898 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
14899 If set, interrupt sequence is sent to remote target."),
14900                            NULL, NULL,
14901                            &remote_set_cmdlist, &remote_show_cmdlist);
14902
14903   /* Install commands for configuring memory read/write packets.  */
14904
14905   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14906 Set the maximum number of bytes per memory write packet (deprecated)."),
14907            &setlist);
14908   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14909 Show the maximum number of bytes per memory write packet (deprecated)."),
14910            &showlist);
14911   add_cmd ("memory-write-packet-size", no_class,
14912            set_memory_write_packet_size, _("\
14913 Set the maximum number of bytes per memory-write packet.\n\
14914 Specify the number of bytes in a packet or 0 (zero) for the\n\
14915 default packet size.  The actual limit is further reduced\n\
14916 dependent on the target.  Specify ``fixed'' to disable the\n\
14917 further restriction and ``limit'' to enable that restriction."),
14918            &remote_set_cmdlist);
14919   add_cmd ("memory-read-packet-size", no_class,
14920            set_memory_read_packet_size, _("\
14921 Set the maximum number of bytes per memory-read packet.\n\
14922 Specify the number of bytes in a packet or 0 (zero) for the\n\
14923 default packet size.  The actual limit is further reduced\n\
14924 dependent on the target.  Specify ``fixed'' to disable the\n\
14925 further restriction and ``limit'' to enable that restriction."),
14926            &remote_set_cmdlist);
14927   add_cmd ("memory-write-packet-size", no_class,
14928            show_memory_write_packet_size,
14929            _("Show the maximum number of bytes per memory-write packet."),
14930            &remote_show_cmdlist);
14931   add_cmd ("memory-read-packet-size", no_class,
14932            show_memory_read_packet_size,
14933            _("Show the maximum number of bytes per memory-read packet."),
14934            &remote_show_cmdlist);
14935
14936   add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
14937                             &remote_hw_watchpoint_limit, _("\
14938 Set the maximum number of target hardware watchpoints."), _("\
14939 Show the maximum number of target hardware watchpoints."), _("\
14940 Specify \"unlimited\" for unlimited hardware watchpoints."),
14941                             NULL, show_hardware_watchpoint_limit,
14942                             &remote_set_cmdlist,
14943                             &remote_show_cmdlist);
14944   add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
14945                             no_class,
14946                             &remote_hw_watchpoint_length_limit, _("\
14947 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14948 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14949 Specify \"unlimited\" to allow watchpoints of unlimited size."),
14950                             NULL, show_hardware_watchpoint_length_limit,
14951                             &remote_set_cmdlist, &remote_show_cmdlist);
14952   add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
14953                             &remote_hw_breakpoint_limit, _("\
14954 Set the maximum number of target hardware breakpoints."), _("\
14955 Show the maximum number of target hardware breakpoints."), _("\
14956 Specify \"unlimited\" for unlimited hardware breakpoints."),
14957                             NULL, show_hardware_breakpoint_limit,
14958                             &remote_set_cmdlist, &remote_show_cmdlist);
14959
14960   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14961                              &remote_address_size, _("\
14962 Set the maximum size of the address (in bits) in a memory packet."), _("\
14963 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14964                              NULL,
14965                              NULL, /* FIXME: i18n: */
14966                              &setlist, &showlist);
14967
14968   init_all_packet_configs ();
14969
14970   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14971                          "X", "binary-download", 1);
14972
14973   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14974                          "vCont", "verbose-resume", 0);
14975
14976   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14977                          "QPassSignals", "pass-signals", 0);
14978
14979   add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14980                          "QCatchSyscalls", "catch-syscalls", 0);
14981
14982   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14983                          "QProgramSignals", "program-signals", 0);
14984
14985   add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14986                          "QSetWorkingDir", "set-working-dir", 0);
14987
14988   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14989                          "QStartupWithShell", "startup-with-shell", 0);
14990
14991   add_packet_config_cmd (&remote_protocol_packets
14992                          [PACKET_QEnvironmentHexEncoded],
14993                          "QEnvironmentHexEncoded", "environment-hex-encoded",
14994                          0);
14995
14996   add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14997                          "QEnvironmentReset", "environment-reset",
14998                          0);
14999
15000   add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
15001                          "QEnvironmentUnset", "environment-unset",
15002                          0);
15003
15004   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
15005                          "qSymbol", "symbol-lookup", 0);
15006
15007   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
15008                          "P", "set-register", 1);
15009
15010   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
15011                          "p", "fetch-register", 1);
15012
15013   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
15014                          "Z0", "software-breakpoint", 0);
15015
15016   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
15017                          "Z1", "hardware-breakpoint", 0);
15018
15019   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
15020                          "Z2", "write-watchpoint", 0);
15021
15022   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
15023                          "Z3", "read-watchpoint", 0);
15024
15025   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
15026                          "Z4", "access-watchpoint", 0);
15027
15028   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
15029                          "qXfer:auxv:read", "read-aux-vector", 0);
15030
15031   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
15032                          "qXfer:exec-file:read", "pid-to-exec-file", 0);
15033
15034   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
15035                          "qXfer:features:read", "target-features", 0);
15036
15037   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
15038                          "qXfer:libraries:read", "library-info", 0);
15039
15040   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
15041                          "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15042
15043   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
15044                          "qXfer:memory-map:read", "memory-map", 0);
15045
15046   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
15047                         "qXfer:osdata:read", "osdata", 0);
15048
15049   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
15050                          "qXfer:threads:read", "threads", 0);
15051
15052   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
15053                          "qXfer:siginfo:read", "read-siginfo-object", 0);
15054
15055   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
15056                          "qXfer:siginfo:write", "write-siginfo-object", 0);
15057
15058   add_packet_config_cmd
15059     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
15060      "qXfer:traceframe-info:read", "traceframe-info", 0);
15061
15062   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
15063                          "qXfer:uib:read", "unwind-info-block", 0);
15064
15065   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
15066                          "qGetTLSAddr", "get-thread-local-storage-address",
15067                          0);
15068
15069   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
15070                          "qGetTIBAddr", "get-thread-information-block-address",
15071                          0);
15072
15073   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
15074                          "bc", "reverse-continue", 0);
15075
15076   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
15077                          "bs", "reverse-step", 0);
15078
15079   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
15080                          "qSupported", "supported-packets", 0);
15081
15082   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
15083                          "qSearch:memory", "search-memory", 0);
15084
15085   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
15086                          "qTStatus", "trace-status", 0);
15087
15088   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
15089                          "vFile:setfs", "hostio-setfs", 0);
15090
15091   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
15092                          "vFile:open", "hostio-open", 0);
15093
15094   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
15095                          "vFile:pread", "hostio-pread", 0);
15096
15097   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
15098                          "vFile:pwrite", "hostio-pwrite", 0);
15099
15100   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
15101                          "vFile:close", "hostio-close", 0);
15102
15103   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
15104                          "vFile:unlink", "hostio-unlink", 0);
15105
15106   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
15107                          "vFile:readlink", "hostio-readlink", 0);
15108
15109   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
15110                          "vFile:fstat", "hostio-fstat", 0);
15111
15112   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
15113                          "vAttach", "attach", 0);
15114
15115   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
15116                          "vRun", "run", 0);
15117
15118   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
15119                          "QStartNoAckMode", "noack", 0);
15120
15121   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
15122                          "vKill", "kill", 0);
15123
15124   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
15125                          "qAttached", "query-attached", 0);
15126
15127   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
15128                          "ConditionalTracepoints",
15129                          "conditional-tracepoints", 0);
15130
15131   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
15132                          "ConditionalBreakpoints",
15133                          "conditional-breakpoints", 0);
15134
15135   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
15136                          "BreakpointCommands",
15137                          "breakpoint-commands", 0);
15138
15139   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
15140                          "FastTracepoints", "fast-tracepoints", 0);
15141
15142   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
15143                          "TracepointSource", "TracepointSource", 0);
15144
15145   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
15146                          "QAllow", "allow", 0);
15147
15148   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
15149                          "StaticTracepoints", "static-tracepoints", 0);
15150
15151   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
15152                          "InstallInTrace", "install-in-trace", 0);
15153
15154   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
15155                          "qXfer:statictrace:read", "read-sdata-object", 0);
15156
15157   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
15158                          "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
15159
15160   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
15161                          "QDisableRandomization", "disable-randomization", 0);
15162
15163   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
15164                          "QAgent", "agent", 0);
15165
15166   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
15167                          "QTBuffer:size", "trace-buffer-size", 0);
15168
15169   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
15170        "Qbtrace:off", "disable-btrace", 0);
15171
15172   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
15173        "Qbtrace:bts", "enable-btrace-bts", 0);
15174
15175   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
15176        "Qbtrace:pt", "enable-btrace-pt", 0);
15177
15178   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
15179        "qXfer:btrace", "read-btrace", 0);
15180
15181   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
15182        "qXfer:btrace-conf", "read-btrace-conf", 0);
15183
15184   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
15185        "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
15186
15187   add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
15188        "multiprocess-feature", "multiprocess-feature", 0);
15189
15190   add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
15191                          "swbreak-feature", "swbreak-feature", 0);
15192
15193   add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
15194                          "hwbreak-feature", "hwbreak-feature", 0);
15195
15196   add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
15197                          "fork-event-feature", "fork-event-feature", 0);
15198
15199   add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
15200                          "vfork-event-feature", "vfork-event-feature", 0);
15201
15202   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
15203        "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
15204
15205   add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
15206                          "vContSupported", "verbose-resume-supported", 0);
15207
15208   add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
15209                          "exec-event-feature", "exec-event-feature", 0);
15210
15211   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
15212                          "vCtrlC", "ctrl-c", 0);
15213
15214   add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
15215                          "QThreadEvents", "thread-events", 0);
15216
15217   add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
15218                          "N stop reply", "no-resumed-stop-reply", 0);
15219
15220   add_packet_config_cmd (&remote_protocol_packets[PACKET_memory_tagging_feature],
15221                          "memory-tagging-feature", "memory-tagging-feature", 0);
15222
15223   /* Assert that we've registered "set remote foo-packet" commands
15224      for all packet configs.  */
15225   {
15226     int i;
15227
15228     for (i = 0; i < PACKET_MAX; i++)
15229       {
15230         /* Ideally all configs would have a command associated.  Some
15231            still don't though.  */
15232         int excepted;
15233
15234         switch (i)
15235           {
15236           case PACKET_QNonStop:
15237           case PACKET_EnableDisableTracepoints_feature:
15238           case PACKET_tracenz_feature:
15239           case PACKET_DisconnectedTracing_feature:
15240           case PACKET_augmented_libraries_svr4_read_feature:
15241           case PACKET_qCRC:
15242             /* Additions to this list need to be well justified:
15243                pre-existing packets are OK; new packets are not.  */
15244             excepted = 1;
15245             break;
15246           default:
15247             excepted = 0;
15248             break;
15249           }
15250
15251         /* This catches both forgetting to add a config command, and
15252            forgetting to remove a packet from the exception list.  */
15253         gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
15254       }
15255   }
15256
15257   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
15258      Z sub-packet has its own set and show commands, but users may
15259      have sets to this variable in their .gdbinit files (or in their
15260      documentation).  */
15261   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
15262                                 &remote_Z_packet_detect, _("\
15263 Set use of remote protocol `Z' packets."), _("\
15264 Show use of remote protocol `Z' packets."), _("\
15265 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
15266 packets."),
15267                                 set_remote_protocol_Z_packet_cmd,
15268                                 show_remote_protocol_Z_packet_cmd,
15269                                 /* FIXME: i18n: Use of remote protocol
15270                                    `Z' packets is %s.  */
15271                                 &remote_set_cmdlist, &remote_show_cmdlist);
15272
15273   add_basic_prefix_cmd ("remote", class_files, _("\
15274 Manipulate files on the remote system.\n\
15275 Transfer files to and from the remote target system."),
15276                         &remote_cmdlist, "remote ",
15277                         0 /* allow-unknown */, &cmdlist);
15278
15279   add_cmd ("put", class_files, remote_put_command,
15280            _("Copy a local file to the remote system."),
15281            &remote_cmdlist);
15282
15283   add_cmd ("get", class_files, remote_get_command,
15284            _("Copy a remote file to the local system."),
15285            &remote_cmdlist);
15286
15287   add_cmd ("delete", class_files, remote_delete_command,
15288            _("Delete a remote file."),
15289            &remote_cmdlist);
15290
15291   add_setshow_string_noescape_cmd ("exec-file", class_files,
15292                                    &remote_exec_file_var, _("\
15293 Set the remote pathname for \"run\"."), _("\
15294 Show the remote pathname for \"run\"."), NULL,
15295                                    set_remote_exec_file,
15296                                    show_remote_exec_file,
15297                                    &remote_set_cmdlist,
15298                                    &remote_show_cmdlist);
15299
15300   add_setshow_boolean_cmd ("range-stepping", class_run,
15301                            &use_range_stepping, _("\
15302 Enable or disable range stepping."), _("\
15303 Show whether target-assisted range stepping is enabled."), _("\
15304 If on, and the target supports it, when stepping a source line, GDB\n\
15305 tells the target to step the corresponding range of addresses itself instead\n\
15306 of issuing multiple single-steps.  This speeds up source level\n\
15307 stepping.  If off, GDB always issues single-steps, even if range\n\
15308 stepping is supported by the target.  The default is on."),
15309                            set_range_stepping,
15310                            show_range_stepping,
15311                            &setlist,
15312                            &showlist);
15313
15314   add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15315 Set watchdog timer."), _("\
15316 Show watchdog timer."), _("\
15317 When non-zero, this timeout is used instead of waiting forever for a target\n\
15318 to finish a low-level step or continue operation.  If the specified amount\n\
15319 of time passes without a response from the target, an error occurs."),
15320                             NULL,
15321                             show_watchdog,
15322                             &setlist, &showlist);
15323
15324   add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15325                                        &remote_packet_max_chars, _("\
15326 Set the maximum number of characters to display for each remote packet."), _("\
15327 Show the maximum number of characters to display for each remote packet."), _("\
15328 Specify \"unlimited\" to display all the characters."),
15329                                        NULL, show_remote_packet_max_chars,
15330                                        &setdebuglist, &showdebuglist);
15331
15332   add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15333                            _("Set debugging of remote protocol."),
15334                            _("Show debugging of remote protocol."),
15335                            _("\
15336 When enabled, each packet sent or received with the remote target\n\
15337 is displayed."),
15338                            NULL,
15339                            show_remote_debug,
15340                            &setdebuglist, &showdebuglist);
15341
15342   add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15343                                        &remote_timeout, _("\
15344 Set timeout limit to wait for target to respond."), _("\
15345 Show timeout limit to wait for target to respond."), _("\
15346 This value is used to set the time limit for gdb to wait for a response\n\
15347 from the target."),
15348                                        NULL,
15349                                        show_remote_timeout,
15350                                        &setlist, &showlist);
15351
15352   /* Eventually initialize fileio.  See fileio.c */
15353   initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
15354
15355 #if GDB_SELF_TEST
15356   selftests::register_test ("remote_memory_tagging",
15357                             selftests::test_memory_tagging_functions);
15358 #endif
15359 }
This page took 0.901944 seconds and 4 git commands to generate.