Home | History | Annotate | Line # | Download | only in gdb
remote.c revision 1.1.1.8
      1 /* Remote target communications for serial-line targets in custom GDB protocol
      2 
      3    Copyright (C) 1988-2023 Free Software Foundation, Inc.
      4 
      5    This file is part of GDB.
      6 
      7    This program is free software; you can redistribute it and/or modify
      8    it under the terms of the GNU General Public License as published by
      9    the Free Software Foundation; either version 3 of the License, or
     10    (at your option) any later version.
     11 
     12    This program is distributed in the hope that it will be useful,
     13    but WITHOUT ANY WARRANTY; without even the implied warranty of
     14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     15    GNU General Public License for more details.
     16 
     17    You should have received a copy of the GNU General Public License
     18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
     19 
     20 /* See the GDB User Guide for details of the GDB remote protocol.  */
     21 
     22 #include "defs.h"
     23 #include <ctype.h>
     24 #include <fcntl.h>
     25 #include "inferior.h"
     26 #include "infrun.h"
     27 #include "bfd.h"
     28 #include "symfile.h"
     29 #include "target.h"
     30 #include "process-stratum-target.h"
     31 #include "gdbcmd.h"
     32 #include "objfiles.h"
     33 #include "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 "gdbsupport/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   /* True, if in no ack mode.  That is, neither GDB nor the stub will
    262      expect acks from each other.  The connection is assumed to be
    263      reliable.  */
    264   bool noack_mode = false;
    265 
    266   /* True if we're connected in extended remote mode.  */
    267   bool extended = false;
    268 
    269   /* True if we resumed the target and we're waiting for the target to
    270      stop.  In the mean time, we can't start another command/query.
    271      The remote server wouldn't be ready to process it, so we'd
    272      timeout waiting for a reply that would never come and eventually
    273      we'd close the connection.  This can happen in asynchronous mode
    274      because we allow GDB commands while the target is running.  */
    275   bool waiting_for_stop_reply = false;
    276 
    277   /* The status of the stub support for the various vCont actions.  */
    278   vCont_action_support supports_vCont;
    279   /* Whether vCont support was probed already.  This is a workaround
    280      until packet_support is per-connection.  */
    281   bool supports_vCont_probed;
    282 
    283   /* True if the user has pressed Ctrl-C, but the target hasn't
    284      responded to that.  */
    285   bool ctrlc_pending_p = false;
    286 
    287   /* True if we saw a Ctrl-C while reading or writing from/to the
    288      remote descriptor.  At that point it is not safe to send a remote
    289      interrupt packet, so we instead remember we saw the Ctrl-C and
    290      process it once we're done with sending/receiving the current
    291      packet, which should be shortly.  If however that takes too long,
    292      and the user presses Ctrl-C again, we offer to disconnect.  */
    293   bool got_ctrlc_during_io = false;
    294 
    295   /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
    296      remote_open knows that we don't have a file open when the program
    297      starts.  */
    298   struct serial *remote_desc = nullptr;
    299 
    300   /* These are the threads which we last sent to the remote system.  The
    301      TID member will be -1 for all or -2 for not sent yet.  */
    302   ptid_t general_thread = null_ptid;
    303   ptid_t continue_thread = null_ptid;
    304 
    305   /* This is the traceframe which we last selected on the remote system.
    306      It will be -1 if no traceframe is selected.  */
    307   int remote_traceframe_number = -1;
    308 
    309   char *last_pass_packet = nullptr;
    310 
    311   /* The last QProgramSignals packet sent to the target.  We bypass
    312      sending a new program signals list down to the target if the new
    313      packet is exactly the same as the last we sent.  IOW, we only let
    314      the target know about program signals list changes.  */
    315   char *last_program_signals_packet = nullptr;
    316 
    317   gdb_signal last_sent_signal = GDB_SIGNAL_0;
    318 
    319   bool last_sent_step = false;
    320 
    321   /* The execution direction of the last resume we got.  */
    322   exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
    323 
    324   char *finished_object = nullptr;
    325   char *finished_annex = nullptr;
    326   ULONGEST finished_offset = 0;
    327 
    328   /* Should we try the 'ThreadInfo' query packet?
    329 
    330      This variable (NOT available to the user: auto-detect only!)
    331      determines whether GDB will use the new, simpler "ThreadInfo"
    332      query or the older, more complex syntax for thread queries.
    333      This is an auto-detect variable (set to true at each connect,
    334      and set to false when the target fails to recognize it).  */
    335   bool use_threadinfo_query = false;
    336   bool use_threadextra_query = false;
    337 
    338   threadref echo_nextthread {};
    339   threadref nextthread {};
    340   threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
    341 
    342   /* The state of remote notification.  */
    343   struct remote_notif_state *notif_state = nullptr;
    344 
    345   /* The branch trace configuration.  */
    346   struct btrace_config btrace_config {};
    347 
    348   /* The argument to the last "vFile:setfs:" packet we sent, used
    349      to avoid sending repeated unnecessary "vFile:setfs:" packets.
    350      Initialized to -1 to indicate that no "vFile:setfs:" packet
    351      has yet been sent.  */
    352   int fs_pid = -1;
    353 
    354   /* A readahead cache for vFile:pread.  Often, reading a binary
    355      involves a sequence of small reads.  E.g., when parsing an ELF
    356      file.  A readahead cache helps mostly the case of remote
    357      debugging on a connection with higher latency, due to the
    358      request/reply nature of the RSP.  We only cache data for a single
    359      file descriptor at a time.  */
    360   struct readahead_cache readahead_cache;
    361 
    362   /* The list of already fetched and acknowledged stop events.  This
    363      queue is used for notification Stop, and other notifications
    364      don't need queue for their events, because the notification
    365      events of Stop can't be consumed immediately, so that events
    366      should be queued first, and be consumed by remote_wait_{ns,as}
    367      one per time.  Other notifications can consume their events
    368      immediately, so queue is not needed for them.  */
    369   std::vector<stop_reply_up> stop_reply_queue;
    370 
    371   /* Asynchronous signal handle registered as event loop source for
    372      when we have pending events ready to be passed to the core.  */
    373   struct async_event_handler *remote_async_inferior_event_token = nullptr;
    374 
    375   /* FIXME: cagney/1999-09-23: Even though getpkt was called with
    376      ``forever'' still use the normal timeout mechanism.  This is
    377      currently used by the ASYNC code to guarentee that target reads
    378      during the initial connect always time-out.  Once getpkt has been
    379      modified to return a timeout indication and, in turn
    380      remote_wait()/wait_for_inferior() have gained a timeout parameter
    381      this can go away.  */
    382   int wait_forever_enabled_p = 1;
    383 
    384 private:
    385   /* Mapping of remote protocol data for each gdbarch.  Usually there
    386      is only one entry here, though we may see more with stubs that
    387      support multi-process.  */
    388   std::unordered_map<struct gdbarch *, remote_arch_state>
    389     m_arch_states;
    390 };
    391 
    392 static const target_info remote_target_info = {
    393   "remote",
    394   N_("Remote target using gdb-specific protocol"),
    395   remote_doc
    396 };
    397 
    398 class remote_target : public process_stratum_target
    399 {
    400 public:
    401   remote_target () = default;
    402   ~remote_target () override;
    403 
    404   const target_info &info () const override
    405   { return remote_target_info; }
    406 
    407   const char *connection_string () override;
    408 
    409   thread_control_capabilities get_thread_control_capabilities () override
    410   { return tc_schedlock; }
    411 
    412   /* Open a remote connection.  */
    413   static void open (const char *, int);
    414 
    415   void close () override;
    416 
    417   void detach (inferior *, int) override;
    418   void disconnect (const char *, int) override;
    419 
    420   void commit_resumed () override;
    421   void resume (ptid_t, int, enum gdb_signal) override;
    422   ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
    423   bool has_pending_events () override;
    424 
    425   void fetch_registers (struct regcache *, int) override;
    426   void store_registers (struct regcache *, int) override;
    427   void prepare_to_store (struct regcache *) override;
    428 
    429   int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
    430 
    431   int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
    432 			 enum remove_bp_reason) override;
    433 
    434 
    435   bool stopped_by_sw_breakpoint () override;
    436   bool supports_stopped_by_sw_breakpoint () override;
    437 
    438   bool stopped_by_hw_breakpoint () override;
    439 
    440   bool supports_stopped_by_hw_breakpoint () override;
    441 
    442   bool stopped_by_watchpoint () override;
    443 
    444   bool stopped_data_address (CORE_ADDR *) override;
    445 
    446   bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
    447 
    448   int can_use_hw_breakpoint (enum bptype, int, int) override;
    449 
    450   int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
    451 
    452   int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
    453 
    454   int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
    455 
    456   int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
    457 			 struct expression *) override;
    458 
    459   int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
    460 			 struct expression *) override;
    461 
    462   void kill () override;
    463 
    464   void load (const char *, int) override;
    465 
    466   void mourn_inferior () override;
    467 
    468   void pass_signals (gdb::array_view<const unsigned char>) override;
    469 
    470   int set_syscall_catchpoint (int, bool, int,
    471 			      gdb::array_view<const int>) override;
    472 
    473   void program_signals (gdb::array_view<const unsigned char>) override;
    474 
    475   bool thread_alive (ptid_t ptid) override;
    476 
    477   const char *thread_name (struct thread_info *) override;
    478 
    479   void update_thread_list () override;
    480 
    481   std::string pid_to_str (ptid_t) override;
    482 
    483   const char *extra_thread_info (struct thread_info *) override;
    484 
    485   ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
    486 
    487   thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
    488 					     int handle_len,
    489 					     inferior *inf) override;
    490 
    491   gdb::byte_vector thread_info_to_thread_handle (struct thread_info *tp)
    492 						 override;
    493 
    494   void stop (ptid_t) override;
    495 
    496   void interrupt () override;
    497 
    498   void pass_ctrlc () override;
    499 
    500   enum target_xfer_status xfer_partial (enum target_object object,
    501 					const char *annex,
    502 					gdb_byte *readbuf,
    503 					const gdb_byte *writebuf,
    504 					ULONGEST offset, ULONGEST len,
    505 					ULONGEST *xfered_len) override;
    506 
    507   ULONGEST get_memory_xfer_limit () override;
    508 
    509   void rcmd (const char *command, struct ui_file *output) override;
    510 
    511   const char *pid_to_exec_file (int pid) override;
    512 
    513   void log_command (const char *cmd) override
    514   {
    515     serial_log_command (this, cmd);
    516   }
    517 
    518   CORE_ADDR get_thread_local_address (ptid_t ptid,
    519 				      CORE_ADDR load_module_addr,
    520 				      CORE_ADDR offset) override;
    521 
    522   bool can_execute_reverse () override;
    523 
    524   std::vector<mem_region> memory_map () override;
    525 
    526   void flash_erase (ULONGEST address, LONGEST length) override;
    527 
    528   void flash_done () override;
    529 
    530   const struct target_desc *read_description () override;
    531 
    532   int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
    533 		     const gdb_byte *pattern, ULONGEST pattern_len,
    534 		     CORE_ADDR *found_addrp) override;
    535 
    536   bool can_async_p () override;
    537 
    538   bool is_async_p () override;
    539 
    540   void async (bool) override;
    541 
    542   int async_wait_fd () override;
    543 
    544   void thread_events (int) override;
    545 
    546   int can_do_single_step () override;
    547 
    548   void terminal_inferior () override;
    549 
    550   void terminal_ours () override;
    551 
    552   bool supports_non_stop () override;
    553 
    554   bool supports_multi_process () override;
    555 
    556   bool supports_disable_randomization () override;
    557 
    558   bool filesystem_is_local () override;
    559 
    560 
    561   int fileio_open (struct inferior *inf, const char *filename,
    562 		   int flags, int mode, int warn_if_slow,
    563 		   fileio_error *target_errno) override;
    564 
    565   int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
    566 		     ULONGEST offset, fileio_error *target_errno) override;
    567 
    568   int fileio_pread (int fd, gdb_byte *read_buf, int len,
    569 		    ULONGEST offset, fileio_error *target_errno) override;
    570 
    571   int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
    572 
    573   int fileio_close (int fd, fileio_error *target_errno) override;
    574 
    575   int fileio_unlink (struct inferior *inf,
    576 		     const char *filename,
    577 		     fileio_error *target_errno) override;
    578 
    579   gdb::optional<std::string>
    580     fileio_readlink (struct inferior *inf,
    581 		     const char *filename,
    582 		     fileio_error *target_errno) override;
    583 
    584   bool supports_enable_disable_tracepoint () override;
    585 
    586   bool supports_string_tracing () override;
    587 
    588   bool supports_evaluation_of_breakpoint_conditions () override;
    589 
    590   bool can_run_breakpoint_commands () override;
    591 
    592   void trace_init () override;
    593 
    594   void download_tracepoint (struct bp_location *location) override;
    595 
    596   bool can_download_tracepoint () override;
    597 
    598   void download_trace_state_variable (const trace_state_variable &tsv) override;
    599 
    600   void enable_tracepoint (struct bp_location *location) override;
    601 
    602   void disable_tracepoint (struct bp_location *location) override;
    603 
    604   void trace_set_readonly_regions () override;
    605 
    606   void trace_start () override;
    607 
    608   int get_trace_status (struct trace_status *ts) override;
    609 
    610   void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
    611     override;
    612 
    613   void trace_stop () override;
    614 
    615   int trace_find (enum trace_find_type type, int num,
    616 		  CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
    617 
    618   bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
    619 
    620   int save_trace_data (const char *filename) override;
    621 
    622   int upload_tracepoints (struct uploaded_tp **utpp) override;
    623 
    624   int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
    625 
    626   LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
    627 
    628   int get_min_fast_tracepoint_insn_len () override;
    629 
    630   void set_disconnected_tracing (int val) override;
    631 
    632   void set_circular_trace_buffer (int val) override;
    633 
    634   void set_trace_buffer_size (LONGEST val) override;
    635 
    636   bool set_trace_notes (const char *user, const char *notes,
    637 			const char *stopnotes) override;
    638 
    639   int core_of_thread (ptid_t ptid) override;
    640 
    641   int verify_memory (const gdb_byte *data,
    642 		     CORE_ADDR memaddr, ULONGEST size) override;
    643 
    644 
    645   bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
    646 
    647   void set_permissions () override;
    648 
    649   bool static_tracepoint_marker_at (CORE_ADDR,
    650 				    struct static_tracepoint_marker *marker)
    651     override;
    652 
    653   std::vector<static_tracepoint_marker>
    654     static_tracepoint_markers_by_strid (const char *id) override;
    655 
    656   traceframe_info_up traceframe_info () override;
    657 
    658   bool use_agent (bool use) override;
    659   bool can_use_agent () override;
    660 
    661   struct btrace_target_info *
    662     enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
    663 
    664   void disable_btrace (struct btrace_target_info *tinfo) override;
    665 
    666   void teardown_btrace (struct btrace_target_info *tinfo) override;
    667 
    668   enum btrace_error read_btrace (struct btrace_data *data,
    669 				 struct btrace_target_info *btinfo,
    670 				 enum btrace_read_type type) override;
    671 
    672   const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
    673   bool augmented_libraries_svr4_read () override;
    674   void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
    675   void follow_exec (inferior *, ptid_t, const char *) override;
    676   int insert_fork_catchpoint (int) override;
    677   int remove_fork_catchpoint (int) override;
    678   int insert_vfork_catchpoint (int) override;
    679   int remove_vfork_catchpoint (int) override;
    680   int insert_exec_catchpoint (int) override;
    681   int remove_exec_catchpoint (int) override;
    682   enum exec_direction_kind execution_direction () override;
    683 
    684   bool supports_memory_tagging () override;
    685 
    686   bool fetch_memtags (CORE_ADDR address, size_t len,
    687 		      gdb::byte_vector &tags, int type) override;
    688 
    689   bool store_memtags (CORE_ADDR address, size_t len,
    690 		      const gdb::byte_vector &tags, int type) override;
    691 
    692 public: /* Remote specific methods.  */
    693 
    694   void remote_download_command_source (int num, ULONGEST addr,
    695 				       struct command_line *cmds);
    696 
    697   void remote_file_put (const char *local_file, const char *remote_file,
    698 			int from_tty);
    699   void remote_file_get (const char *remote_file, const char *local_file,
    700 			int from_tty);
    701   void remote_file_delete (const char *remote_file, int from_tty);
    702 
    703   int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
    704 			   ULONGEST offset, fileio_error *remote_errno);
    705   int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
    706 			    ULONGEST offset, fileio_error *remote_errno);
    707   int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
    708 				 ULONGEST offset, fileio_error *remote_errno);
    709 
    710   int remote_hostio_send_command (int command_bytes, int which_packet,
    711 				  fileio_error *remote_errno, const char **attachment,
    712 				  int *attachment_len);
    713   int remote_hostio_set_filesystem (struct inferior *inf,
    714 				    fileio_error *remote_errno);
    715   /* We should get rid of this and use fileio_open directly.  */
    716   int remote_hostio_open (struct inferior *inf, const char *filename,
    717 			  int flags, int mode, int warn_if_slow,
    718 			  fileio_error *remote_errno);
    719   int remote_hostio_close (int fd, fileio_error *remote_errno);
    720 
    721   int remote_hostio_unlink (inferior *inf, const char *filename,
    722 			    fileio_error *remote_errno);
    723 
    724   struct remote_state *get_remote_state ();
    725 
    726   long get_remote_packet_size (void);
    727   long get_memory_packet_size (struct memory_packet_config *config);
    728 
    729   long get_memory_write_packet_size ();
    730   long get_memory_read_packet_size ();
    731 
    732   char *append_pending_thread_resumptions (char *p, char *endp,
    733 					   ptid_t ptid);
    734   static void open_1 (const char *name, int from_tty, int extended_p);
    735   void start_remote (int from_tty, int extended_p);
    736   void remote_detach_1 (struct inferior *inf, int from_tty);
    737 
    738   char *append_resumption (char *p, char *endp,
    739 			   ptid_t ptid, int step, gdb_signal siggnal);
    740   int remote_resume_with_vcont (ptid_t scope_ptid, int step,
    741 				gdb_signal siggnal);
    742 
    743   thread_info *add_current_inferior_and_thread (const char *wait_status);
    744 
    745   ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
    746 		  target_wait_flags options);
    747   ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
    748 		  target_wait_flags options);
    749 
    750   ptid_t process_stop_reply (struct stop_reply *stop_reply,
    751 			     target_waitstatus *status);
    752 
    753   ptid_t select_thread_for_ambiguous_stop_reply
    754     (const struct target_waitstatus &status);
    755 
    756   void remote_notice_new_inferior (ptid_t currthread, bool executing);
    757 
    758   void print_one_stopped_thread (thread_info *thread);
    759   void process_initial_stop_replies (int from_tty);
    760 
    761   thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
    762 				  bool silent_p);
    763 
    764   void btrace_sync_conf (const btrace_config *conf);
    765 
    766   void remote_btrace_maybe_reopen ();
    767 
    768   void remove_new_fork_children (threads_listing_context *context);
    769   void kill_new_fork_children (inferior *inf);
    770   void discard_pending_stop_replies (struct inferior *inf);
    771   int stop_reply_queue_length ();
    772 
    773   void check_pending_events_prevent_wildcard_vcont
    774     (bool *may_global_wildcard_vcont);
    775 
    776   void discard_pending_stop_replies_in_queue ();
    777   struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
    778   struct stop_reply *queued_stop_reply (ptid_t ptid);
    779   int peek_stop_reply (ptid_t ptid);
    780   void remote_parse_stop_reply (const char *buf, stop_reply *event);
    781 
    782   void remote_stop_ns (ptid_t ptid);
    783   void remote_interrupt_as ();
    784   void remote_interrupt_ns ();
    785 
    786   char *remote_get_noisy_reply ();
    787   int remote_query_attached (int pid);
    788   inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
    789 				 int try_open_exec);
    790 
    791   ptid_t remote_current_thread (ptid_t oldpid);
    792   ptid_t get_current_thread (const char *wait_status);
    793 
    794   void set_thread (ptid_t ptid, int gen);
    795   void set_general_thread (ptid_t ptid);
    796   void set_continue_thread (ptid_t ptid);
    797   void set_general_process ();
    798 
    799   char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
    800 
    801   int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
    802 					  gdb_ext_thread_info *info);
    803   int remote_get_threadinfo (threadref *threadid, int fieldset,
    804 			     gdb_ext_thread_info *info);
    805 
    806   int parse_threadlist_response (const char *pkt, int result_limit,
    807 				 threadref *original_echo,
    808 				 threadref *resultlist,
    809 				 int *doneflag);
    810   int remote_get_threadlist (int startflag, threadref *nextthread,
    811 			     int result_limit, int *done, int *result_count,
    812 			     threadref *threadlist);
    813 
    814   int remote_threadlist_iterator (rmt_thread_action stepfunction,
    815 				  void *context, int looplimit);
    816 
    817   int remote_get_threads_with_ql (threads_listing_context *context);
    818   int remote_get_threads_with_qxfer (threads_listing_context *context);
    819   int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
    820 
    821   void extended_remote_restart ();
    822 
    823   void get_offsets ();
    824 
    825   void remote_check_symbols ();
    826 
    827   void remote_supported_packet (const struct protocol_feature *feature,
    828 				enum packet_support support,
    829 				const char *argument);
    830 
    831   void remote_query_supported ();
    832 
    833   void remote_packet_size (const protocol_feature *feature,
    834 			   packet_support support, const char *value);
    835 
    836   void remote_serial_quit_handler ();
    837 
    838   void remote_detach_pid (int pid);
    839 
    840   void remote_vcont_probe ();
    841 
    842   void remote_resume_with_hc (ptid_t ptid, int step,
    843 			      gdb_signal siggnal);
    844 
    845   void send_interrupt_sequence ();
    846   void interrupt_query ();
    847 
    848   void remote_notif_get_pending_events (notif_client *nc);
    849 
    850   int fetch_register_using_p (struct regcache *regcache,
    851 			      packet_reg *reg);
    852   int send_g_packet ();
    853   void process_g_packet (struct regcache *regcache);
    854   void fetch_registers_using_g (struct regcache *regcache);
    855   int store_register_using_P (const struct regcache *regcache,
    856 			      packet_reg *reg);
    857   void store_registers_using_G (const struct regcache *regcache);
    858 
    859   void set_remote_traceframe ();
    860 
    861   void check_binary_download (CORE_ADDR addr);
    862 
    863   target_xfer_status remote_write_bytes_aux (const char *header,
    864 					     CORE_ADDR memaddr,
    865 					     const gdb_byte *myaddr,
    866 					     ULONGEST len_units,
    867 					     int unit_size,
    868 					     ULONGEST *xfered_len_units,
    869 					     char packet_format,
    870 					     int use_length);
    871 
    872   target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
    873 					 const gdb_byte *myaddr, ULONGEST len,
    874 					 int unit_size, ULONGEST *xfered_len);
    875 
    876   target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
    877 					  ULONGEST len_units,
    878 					  int unit_size, ULONGEST *xfered_len_units);
    879 
    880   target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
    881 							ULONGEST memaddr,
    882 							ULONGEST len,
    883 							int unit_size,
    884 							ULONGEST *xfered_len);
    885 
    886   target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
    887 					gdb_byte *myaddr, ULONGEST len,
    888 					int unit_size,
    889 					ULONGEST *xfered_len);
    890 
    891   packet_result remote_send_printf (const char *format, ...)
    892     ATTRIBUTE_PRINTF (2, 3);
    893 
    894   target_xfer_status remote_flash_write (ULONGEST address,
    895 					 ULONGEST length, ULONGEST *xfered_len,
    896 					 const gdb_byte *data);
    897 
    898   int readchar (int timeout);
    899 
    900   void remote_serial_write (const char *str, int len);
    901 
    902   int putpkt (const char *buf);
    903   int putpkt_binary (const char *buf, int cnt);
    904 
    905   int putpkt (const gdb::char_vector &buf)
    906   {
    907     return putpkt (buf.data ());
    908   }
    909 
    910   void skip_frame ();
    911   long read_frame (gdb::char_vector *buf_p);
    912   void getpkt (gdb::char_vector *buf, int forever);
    913   int getpkt_or_notif_sane_1 (gdb::char_vector *buf, int forever,
    914 			      int expecting_notif, int *is_notif);
    915   int getpkt_sane (gdb::char_vector *buf, int forever);
    916   int getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
    917 			    int *is_notif);
    918   int remote_vkill (int pid);
    919   void remote_kill_k ();
    920 
    921   void extended_remote_disable_randomization (int val);
    922   int extended_remote_run (const std::string &args);
    923 
    924   void send_environment_packet (const char *action,
    925 				const char *packet,
    926 				const char *value);
    927 
    928   void extended_remote_environment_support ();
    929   void extended_remote_set_inferior_cwd ();
    930 
    931   target_xfer_status remote_write_qxfer (const char *object_name,
    932 					 const char *annex,
    933 					 const gdb_byte *writebuf,
    934 					 ULONGEST offset, LONGEST len,
    935 					 ULONGEST *xfered_len,
    936 					 struct packet_config *packet);
    937 
    938   target_xfer_status remote_read_qxfer (const char *object_name,
    939 					const char *annex,
    940 					gdb_byte *readbuf, ULONGEST offset,
    941 					LONGEST len,
    942 					ULONGEST *xfered_len,
    943 					struct packet_config *packet);
    944 
    945   void push_stop_reply (struct stop_reply *new_event);
    946 
    947   bool vcont_r_supported ();
    948 
    949 private:
    950 
    951   bool start_remote_1 (int from_tty, int extended_p);
    952 
    953   /* The remote state.  Don't reference this directly.  Use the
    954      get_remote_state method instead.  */
    955   remote_state m_remote_state;
    956 };
    957 
    958 static const target_info extended_remote_target_info = {
    959   "extended-remote",
    960   N_("Extended remote target using gdb-specific protocol"),
    961   remote_doc
    962 };
    963 
    964 /* Set up the extended remote target by extending the standard remote
    965    target and adding to it.  */
    966 
    967 class extended_remote_target final : public remote_target
    968 {
    969 public:
    970   const target_info &info () const override
    971   { return extended_remote_target_info; }
    972 
    973   /* Open an extended-remote connection.  */
    974   static void open (const char *, int);
    975 
    976   bool can_create_inferior () override { return true; }
    977   void create_inferior (const char *, const std::string &,
    978 			char **, int) override;
    979 
    980   void detach (inferior *, int) override;
    981 
    982   bool can_attach () override { return true; }
    983   void attach (const char *, int) override;
    984 
    985   void post_attach (int) override;
    986   bool supports_disable_randomization () override;
    987 };
    988 
    989 struct stop_reply : public notif_event
    990 {
    991   ~stop_reply ();
    992 
    993   /* The identifier of the thread about this event  */
    994   ptid_t ptid;
    995 
    996   /* The remote state this event is associated with.  When the remote
    997      connection, represented by a remote_state object, is closed,
    998      all the associated stop_reply events should be released.  */
    999   struct remote_state *rs;
   1000 
   1001   struct target_waitstatus ws;
   1002 
   1003   /* The architecture associated with the expedited registers.  */
   1004   gdbarch *arch;
   1005 
   1006   /* Expedited registers.  This makes remote debugging a bit more
   1007      efficient for those targets that provide critical registers as
   1008      part of their normal status mechanism (as another roundtrip to
   1009      fetch them is avoided).  */
   1010   std::vector<cached_reg_t> regcache;
   1011 
   1012   enum target_stop_reason stop_reason;
   1013 
   1014   CORE_ADDR watch_data_address;
   1015 
   1016   int core;
   1017 };
   1018 
   1019 /* Return TARGET as a remote_target if it is one, else nullptr.  */
   1020 
   1021 static remote_target *
   1022 as_remote_target (process_stratum_target *target)
   1023 {
   1024   return dynamic_cast<remote_target *> (target);
   1025 }
   1026 
   1027 /* See remote.h.  */
   1028 
   1029 bool
   1030 is_remote_target (process_stratum_target *target)
   1031 {
   1032   return as_remote_target (target) != nullptr;
   1033 }
   1034 
   1035 /* Per-program-space data key.  */
   1036 static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
   1037   remote_pspace_data;
   1038 
   1039 /* The variable registered as the control variable used by the
   1040    remote exec-file commands.  While the remote exec-file setting is
   1041    per-program-space, the set/show machinery uses this as the
   1042    location of the remote exec-file value.  */
   1043 static std::string remote_exec_file_var;
   1044 
   1045 /* The size to align memory write packets, when practical.  The protocol
   1046    does not guarantee any alignment, and gdb will generate short
   1047    writes and unaligned writes, but even as a best-effort attempt this
   1048    can improve bulk transfers.  For instance, if a write is misaligned
   1049    relative to the target's data bus, the stub may need to make an extra
   1050    round trip fetching data from the target.  This doesn't make a
   1051    huge difference, but it's easy to do, so we try to be helpful.
   1052 
   1053    The alignment chosen is arbitrary; usually data bus width is
   1054    important here, not the possibly larger cache line size.  */
   1055 enum { REMOTE_ALIGN_WRITES = 16 };
   1056 
   1057 /* Prototypes for local functions.  */
   1058 
   1059 static int hexnumlen (ULONGEST num);
   1060 
   1061 static int stubhex (int ch);
   1062 
   1063 static int hexnumstr (char *, ULONGEST);
   1064 
   1065 static int hexnumnstr (char *, ULONGEST, int);
   1066 
   1067 static CORE_ADDR remote_address_masked (CORE_ADDR);
   1068 
   1069 static int stub_unpack_int (const char *buff, int fieldlength);
   1070 
   1071 struct packet_config;
   1072 
   1073 static void show_remote_protocol_packet_cmd (struct ui_file *file,
   1074 					     int from_tty,
   1075 					     struct cmd_list_element *c,
   1076 					     const char *value);
   1077 
   1078 static ptid_t read_ptid (const char *buf, const char **obuf);
   1079 
   1080 static void remote_async_inferior_event_handler (gdb_client_data);
   1081 
   1082 static bool remote_read_description_p (struct target_ops *target);
   1083 
   1084 static void remote_console_output (const char *msg);
   1085 
   1086 static void remote_btrace_reset (remote_state *rs);
   1087 
   1088 static void remote_unpush_and_throw (remote_target *target);
   1089 
   1090 /* For "remote".  */
   1091 
   1092 static struct cmd_list_element *remote_cmdlist;
   1093 
   1094 /* For "set remote" and "show remote".  */
   1095 
   1096 static struct cmd_list_element *remote_set_cmdlist;
   1097 static struct cmd_list_element *remote_show_cmdlist;
   1098 
   1099 /* Controls whether GDB is willing to use range stepping.  */
   1100 
   1101 static bool use_range_stepping = true;
   1102 
   1103 /* From the remote target's point of view, each thread is in one of these three
   1104    states.  */
   1105 enum class resume_state
   1106 {
   1107   /* Not resumed - we haven't been asked to resume this thread.  */
   1108   NOT_RESUMED,
   1109 
   1110   /* We have been asked to resume this thread, but haven't sent a vCont action
   1111      for it yet.  We'll need to consider it next time commit_resume is
   1112      called.  */
   1113   RESUMED_PENDING_VCONT,
   1114 
   1115   /* We have been asked to resume this thread, and we have sent a vCont action
   1116      for it.  */
   1117   RESUMED,
   1118 };
   1119 
   1120 /* Information about a thread's pending vCont-resume.  Used when a thread is in
   1121    the remote_resume_state::RESUMED_PENDING_VCONT state.  remote_target::resume
   1122    stores this information which is then picked up by
   1123    remote_target::commit_resume to know which is the proper action for this
   1124    thread to include in the vCont packet.  */
   1125 struct resumed_pending_vcont_info
   1126 {
   1127   /* True if the last resume call for this thread was a step request, false
   1128      if a continue request.  */
   1129   bool step;
   1130 
   1131   /* The signal specified in the last resume call for this thread.  */
   1132   gdb_signal sig;
   1133 };
   1134 
   1135 /* Private data that we'll store in (struct thread_info)->priv.  */
   1136 struct remote_thread_info : public private_thread_info
   1137 {
   1138   std::string extra;
   1139   std::string name;
   1140   int core = -1;
   1141 
   1142   /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
   1143      sequence of bytes.  */
   1144   gdb::byte_vector thread_handle;
   1145 
   1146   /* Whether the target stopped for a breakpoint/watchpoint.  */
   1147   enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
   1148 
   1149   /* This is set to the data address of the access causing the target
   1150      to stop for a watchpoint.  */
   1151   CORE_ADDR watch_data_address = 0;
   1152 
   1153   /* Get the thread's resume state.  */
   1154   enum resume_state get_resume_state () const
   1155   {
   1156     return m_resume_state;
   1157   }
   1158 
   1159   /* Put the thread in the NOT_RESUMED state.  */
   1160   void set_not_resumed ()
   1161   {
   1162     m_resume_state = resume_state::NOT_RESUMED;
   1163   }
   1164 
   1165   /* Put the thread in the RESUMED_PENDING_VCONT state.  */
   1166   void set_resumed_pending_vcont (bool step, gdb_signal sig)
   1167   {
   1168     m_resume_state = resume_state::RESUMED_PENDING_VCONT;
   1169     m_resumed_pending_vcont_info.step = step;
   1170     m_resumed_pending_vcont_info.sig = sig;
   1171   }
   1172 
   1173   /* Get the information this thread's pending vCont-resumption.
   1174 
   1175      Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
   1176      state.  */
   1177   const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
   1178   {
   1179     gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
   1180 
   1181     return m_resumed_pending_vcont_info;
   1182   }
   1183 
   1184   /* Put the thread in the VCONT_RESUMED state.  */
   1185   void set_resumed ()
   1186   {
   1187     m_resume_state = resume_state::RESUMED;
   1188   }
   1189 
   1190 private:
   1191   /* Resume state for this thread.  This is used to implement vCont action
   1192      coalescing (only when the target operates in non-stop mode).
   1193 
   1194      remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
   1195      which notes that this thread must be considered in the next commit_resume
   1196      call.
   1197 
   1198      remote_target::commit_resume sends a vCont packet with actions for the
   1199      threads in the RESUMED_PENDING_VCONT state and moves them to the
   1200      VCONT_RESUMED state.
   1201 
   1202      When reporting a stop to the core for a thread, that thread is moved back
   1203      to the NOT_RESUMED state.  */
   1204   enum resume_state m_resume_state = resume_state::NOT_RESUMED;
   1205 
   1206   /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state.  */
   1207   struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
   1208 };
   1209 
   1210 remote_state::remote_state ()
   1211   : buf (400)
   1212 {
   1213 }
   1214 
   1215 remote_state::~remote_state ()
   1216 {
   1217   xfree (this->last_pass_packet);
   1218   xfree (this->last_program_signals_packet);
   1219   xfree (this->finished_object);
   1220   xfree (this->finished_annex);
   1221 }
   1222 
   1223 /* Utility: generate error from an incoming stub packet.  */
   1224 static void
   1225 trace_error (char *buf)
   1226 {
   1227   if (*buf++ != 'E')
   1228     return;			/* not an error msg */
   1229   switch (*buf)
   1230     {
   1231     case '1':			/* malformed packet error */
   1232       if (*++buf == '0')	/*   general case: */
   1233 	error (_("remote.c: error in outgoing packet."));
   1234       else
   1235 	error (_("remote.c: error in outgoing packet at field #%ld."),
   1236 	       strtol (buf, NULL, 16));
   1237     default:
   1238       error (_("Target returns error code '%s'."), buf);
   1239     }
   1240 }
   1241 
   1242 /* Utility: wait for reply from stub, while accepting "O" packets.  */
   1243 
   1244 char *
   1245 remote_target::remote_get_noisy_reply ()
   1246 {
   1247   struct remote_state *rs = get_remote_state ();
   1248 
   1249   do				/* Loop on reply from remote stub.  */
   1250     {
   1251       char *buf;
   1252 
   1253       QUIT;			/* Allow user to bail out with ^C.  */
   1254       getpkt (&rs->buf, 0);
   1255       buf = rs->buf.data ();
   1256       if (buf[0] == 'E')
   1257 	trace_error (buf);
   1258       else if (startswith (buf, "qRelocInsn:"))
   1259 	{
   1260 	  ULONGEST ul;
   1261 	  CORE_ADDR from, to, org_to;
   1262 	  const char *p, *pp;
   1263 	  int adjusted_size = 0;
   1264 	  int relocated = 0;
   1265 
   1266 	  p = buf + strlen ("qRelocInsn:");
   1267 	  pp = unpack_varlen_hex (p, &ul);
   1268 	  if (*pp != ';')
   1269 	    error (_("invalid qRelocInsn packet: %s"), buf);
   1270 	  from = ul;
   1271 
   1272 	  p = pp + 1;
   1273 	  unpack_varlen_hex (p, &ul);
   1274 	  to = ul;
   1275 
   1276 	  org_to = to;
   1277 
   1278 	  try
   1279 	    {
   1280 	      gdbarch_relocate_instruction (target_gdbarch (), &to, from);
   1281 	      relocated = 1;
   1282 	    }
   1283 	  catch (const gdb_exception &ex)
   1284 	    {
   1285 	      if (ex.error == MEMORY_ERROR)
   1286 		{
   1287 		  /* Propagate memory errors silently back to the
   1288 		     target.  The stub may have limited the range of
   1289 		     addresses we can write to, for example.  */
   1290 		}
   1291 	      else
   1292 		{
   1293 		  /* Something unexpectedly bad happened.  Be verbose
   1294 		     so we can tell what, and propagate the error back
   1295 		     to the stub, so it doesn't get stuck waiting for
   1296 		     a response.  */
   1297 		  exception_fprintf (gdb_stderr, ex,
   1298 				     _("warning: relocating instruction: "));
   1299 		}
   1300 	      putpkt ("E01");
   1301 	    }
   1302 
   1303 	  if (relocated)
   1304 	    {
   1305 	      adjusted_size = to - org_to;
   1306 
   1307 	      xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
   1308 	      putpkt (buf);
   1309 	    }
   1310 	}
   1311       else if (buf[0] == 'O' && buf[1] != 'K')
   1312 	remote_console_output (buf + 1);	/* 'O' message from stub */
   1313       else
   1314 	return buf;		/* Here's the actual reply.  */
   1315     }
   1316   while (1);
   1317 }
   1318 
   1319 struct remote_arch_state *
   1320 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
   1321 {
   1322   remote_arch_state *rsa;
   1323 
   1324   auto it = this->m_arch_states.find (gdbarch);
   1325   if (it == this->m_arch_states.end ())
   1326     {
   1327       auto p = this->m_arch_states.emplace (std::piecewise_construct,
   1328 					    std::forward_as_tuple (gdbarch),
   1329 					    std::forward_as_tuple (gdbarch));
   1330       rsa = &p.first->second;
   1331 
   1332       /* Make sure that the packet buffer is plenty big enough for
   1333 	 this architecture.  */
   1334       if (this->buf.size () < rsa->remote_packet_size)
   1335 	this->buf.resize (2 * rsa->remote_packet_size);
   1336     }
   1337   else
   1338     rsa = &it->second;
   1339 
   1340   return rsa;
   1341 }
   1342 
   1343 /* Fetch the global remote target state.  */
   1344 
   1345 remote_state *
   1346 remote_target::get_remote_state ()
   1347 {
   1348   /* Make sure that the remote architecture state has been
   1349      initialized, because doing so might reallocate rs->buf.  Any
   1350      function which calls getpkt also needs to be mindful of changes
   1351      to rs->buf, but this call limits the number of places which run
   1352      into trouble.  */
   1353   m_remote_state.get_remote_arch_state (target_gdbarch ());
   1354 
   1355   return &m_remote_state;
   1356 }
   1357 
   1358 /* Fetch the remote exec-file from the current program space.  */
   1359 
   1360 static const char *
   1361 get_remote_exec_file (void)
   1362 {
   1363   char *remote_exec_file;
   1364 
   1365   remote_exec_file = remote_pspace_data.get (current_program_space);
   1366   if (remote_exec_file == NULL)
   1367     return "";
   1368 
   1369   return remote_exec_file;
   1370 }
   1371 
   1372 /* Set the remote exec file for PSPACE.  */
   1373 
   1374 static void
   1375 set_pspace_remote_exec_file (struct program_space *pspace,
   1376 			     const char *remote_exec_file)
   1377 {
   1378   char *old_file = remote_pspace_data.get (pspace);
   1379 
   1380   xfree (old_file);
   1381   remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
   1382 }
   1383 
   1384 /* The "set/show remote exec-file" set command hook.  */
   1385 
   1386 static void
   1387 set_remote_exec_file (const char *ignored, int from_tty,
   1388 		      struct cmd_list_element *c)
   1389 {
   1390   set_pspace_remote_exec_file (current_program_space,
   1391 			       remote_exec_file_var.c_str ());
   1392 }
   1393 
   1394 /* The "set/show remote exec-file" show command hook.  */
   1395 
   1396 static void
   1397 show_remote_exec_file (struct ui_file *file, int from_tty,
   1398 		       struct cmd_list_element *cmd, const char *value)
   1399 {
   1400   gdb_printf (file, "%s\n", get_remote_exec_file ());
   1401 }
   1402 
   1403 static int
   1404 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
   1405 {
   1406   int regnum, num_remote_regs, offset;
   1407   struct packet_reg **remote_regs;
   1408 
   1409   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
   1410     {
   1411       struct packet_reg *r = &regs[regnum];
   1412 
   1413       if (register_size (gdbarch, regnum) == 0)
   1414 	/* Do not try to fetch zero-sized (placeholder) registers.  */
   1415 	r->pnum = -1;
   1416       else
   1417 	r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
   1418 
   1419       r->regnum = regnum;
   1420     }
   1421 
   1422   /* Define the g/G packet format as the contents of each register
   1423      with a remote protocol number, in order of ascending protocol
   1424      number.  */
   1425 
   1426   remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
   1427   for (num_remote_regs = 0, regnum = 0;
   1428        regnum < gdbarch_num_regs (gdbarch);
   1429        regnum++)
   1430     if (regs[regnum].pnum != -1)
   1431       remote_regs[num_remote_regs++] = &regs[regnum];
   1432 
   1433   std::sort (remote_regs, remote_regs + num_remote_regs,
   1434 	     [] (const packet_reg *a, const packet_reg *b)
   1435 	      { return a->pnum < b->pnum; });
   1436 
   1437   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
   1438     {
   1439       remote_regs[regnum]->in_g_packet = 1;
   1440       remote_regs[regnum]->offset = offset;
   1441       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
   1442     }
   1443 
   1444   return offset;
   1445 }
   1446 
   1447 /* Given the architecture described by GDBARCH, return the remote
   1448    protocol register's number and the register's offset in the g/G
   1449    packets of GDB register REGNUM, in PNUM and POFFSET respectively.
   1450    If the target does not have a mapping for REGNUM, return false,
   1451    otherwise, return true.  */
   1452 
   1453 int
   1454 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
   1455 				   int *pnum, int *poffset)
   1456 {
   1457   gdb_assert (regnum < gdbarch_num_regs (gdbarch));
   1458 
   1459   std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
   1460 
   1461   map_regcache_remote_table (gdbarch, regs.data ());
   1462 
   1463   *pnum = regs[regnum].pnum;
   1464   *poffset = regs[regnum].offset;
   1465 
   1466   return *pnum != -1;
   1467 }
   1468 
   1469 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
   1470 {
   1471   /* Use the architecture to build a regnum<->pnum table, which will be
   1472      1:1 unless a feature set specifies otherwise.  */
   1473   this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
   1474 
   1475   /* Record the maximum possible size of the g packet - it may turn out
   1476      to be smaller.  */
   1477   this->sizeof_g_packet
   1478     = map_regcache_remote_table (gdbarch, this->regs.get ());
   1479 
   1480   /* Default maximum number of characters in a packet body.  Many
   1481      remote stubs have a hardwired buffer size of 400 bytes
   1482      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
   1483      as the maximum packet-size to ensure that the packet and an extra
   1484      NUL character can always fit in the buffer.  This stops GDB
   1485      trashing stubs that try to squeeze an extra NUL into what is
   1486      already a full buffer (As of 1999-12-04 that was most stubs).  */
   1487   this->remote_packet_size = 400 - 1;
   1488 
   1489   /* This one is filled in when a ``g'' packet is received.  */
   1490   this->actual_register_packet_size = 0;
   1491 
   1492   /* Should rsa->sizeof_g_packet needs more space than the
   1493      default, adjust the size accordingly.  Remember that each byte is
   1494      encoded as two characters.  32 is the overhead for the packet
   1495      header / footer.  NOTE: cagney/1999-10-26: I suspect that 8
   1496      (``$NN:G...#NN'') is a better guess, the below has been padded a
   1497      little.  */
   1498   if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
   1499     this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
   1500 }
   1501 
   1502 /* Get a pointer to the current remote target.  If not connected to a
   1503    remote target, return NULL.  */
   1504 
   1505 static remote_target *
   1506 get_current_remote_target ()
   1507 {
   1508   target_ops *proc_target = current_inferior ()->process_target ();
   1509   return dynamic_cast<remote_target *> (proc_target);
   1510 }
   1511 
   1512 /* Return the current allowed size of a remote packet.  This is
   1513    inferred from the current architecture, and should be used to
   1514    limit the length of outgoing packets.  */
   1515 long
   1516 remote_target::get_remote_packet_size ()
   1517 {
   1518   struct remote_state *rs = get_remote_state ();
   1519   remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
   1520 
   1521   if (rs->explicit_packet_size)
   1522     return rs->explicit_packet_size;
   1523 
   1524   return rsa->remote_packet_size;
   1525 }
   1526 
   1527 static struct packet_reg *
   1528 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
   1529 			long regnum)
   1530 {
   1531   if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
   1532     return NULL;
   1533   else
   1534     {
   1535       struct packet_reg *r = &rsa->regs[regnum];
   1536 
   1537       gdb_assert (r->regnum == regnum);
   1538       return r;
   1539     }
   1540 }
   1541 
   1542 static struct packet_reg *
   1543 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
   1544 		      LONGEST pnum)
   1545 {
   1546   int i;
   1547 
   1548   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
   1549     {
   1550       struct packet_reg *r = &rsa->regs[i];
   1551 
   1552       if (r->pnum == pnum)
   1553 	return r;
   1554     }
   1555   return NULL;
   1556 }
   1557 
   1558 /* Allow the user to specify what sequence to send to the remote
   1559    when he requests a program interruption: Although ^C is usually
   1560    what remote systems expect (this is the default, here), it is
   1561    sometimes preferable to send a break.  On other systems such
   1562    as the Linux kernel, a break followed by g, which is Magic SysRq g
   1563    is required in order to interrupt the execution.  */
   1564 const char interrupt_sequence_control_c[] = "Ctrl-C";
   1565 const char interrupt_sequence_break[] = "BREAK";
   1566 const char interrupt_sequence_break_g[] = "BREAK-g";
   1567 static const char *const interrupt_sequence_modes[] =
   1568   {
   1569     interrupt_sequence_control_c,
   1570     interrupt_sequence_break,
   1571     interrupt_sequence_break_g,
   1572     NULL
   1573   };
   1574 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
   1575 
   1576 static void
   1577 show_interrupt_sequence (struct ui_file *file, int from_tty,
   1578 			 struct cmd_list_element *c,
   1579 			 const char *value)
   1580 {
   1581   if (interrupt_sequence_mode == interrupt_sequence_control_c)
   1582     gdb_printf (file,
   1583 		_("Send the ASCII ETX character (Ctrl-c) "
   1584 		  "to the remote target to interrupt the "
   1585 		  "execution of the program.\n"));
   1586   else if (interrupt_sequence_mode == interrupt_sequence_break)
   1587     gdb_printf (file,
   1588 		_("send a break signal to the remote target "
   1589 		  "to interrupt the execution of the program.\n"));
   1590   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
   1591     gdb_printf (file,
   1592 		_("Send a break signal and 'g' a.k.a. Magic SysRq g to "
   1593 		  "the remote target to interrupt the execution "
   1594 		  "of Linux kernel.\n"));
   1595   else
   1596     internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
   1597 		    interrupt_sequence_mode);
   1598 }
   1599 
   1600 /* This boolean variable specifies whether interrupt_sequence is sent
   1601    to the remote target when gdb connects to it.
   1602    This is mostly needed when you debug the Linux kernel: The Linux kernel
   1603    expects BREAK g which is Magic SysRq g for connecting gdb.  */
   1604 static bool interrupt_on_connect = false;
   1605 
   1606 /* This variable is used to implement the "set/show remotebreak" commands.
   1607    Since these commands are now deprecated in favor of "set/show remote
   1608    interrupt-sequence", it no longer has any effect on the code.  */
   1609 static bool remote_break;
   1610 
   1611 static void
   1612 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
   1613 {
   1614   if (remote_break)
   1615     interrupt_sequence_mode = interrupt_sequence_break;
   1616   else
   1617     interrupt_sequence_mode = interrupt_sequence_control_c;
   1618 }
   1619 
   1620 static void
   1621 show_remotebreak (struct ui_file *file, int from_tty,
   1622 		  struct cmd_list_element *c,
   1623 		  const char *value)
   1624 {
   1625 }
   1626 
   1627 /* This variable sets the number of bits in an address that are to be
   1628    sent in a memory ("M" or "m") packet.  Normally, after stripping
   1629    leading zeros, the entire address would be sent.  This variable
   1630    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
   1631    initial implementation of remote.c restricted the address sent in
   1632    memory packets to ``host::sizeof long'' bytes - (typically 32
   1633    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
   1634    address was never sent.  Since fixing this bug may cause a break in
   1635    some remote targets this variable is principally provided to
   1636    facilitate backward compatibility.  */
   1637 
   1638 static unsigned int remote_address_size;
   1639 
   1640 
   1641 /* User configurable variables for the number of characters in a
   1643    memory read/write packet.  MIN (rsa->remote_packet_size,
   1644    rsa->sizeof_g_packet) is the default.  Some targets need smaller
   1645    values (fifo overruns, et.al.) and some users need larger values
   1646    (speed up transfers).  The variables ``preferred_*'' (the user
   1647    request), ``current_*'' (what was actually set) and ``forced_*''
   1648    (Positive - a soft limit, negative - a hard limit).  */
   1649 
   1650 struct memory_packet_config
   1651 {
   1652   const char *name;
   1653   long size;
   1654   int fixed_p;
   1655 };
   1656 
   1657 /* The default max memory-write-packet-size, when the setting is
   1658    "fixed".  The 16k is historical.  (It came from older GDB's using
   1659    alloca for buffers and the knowledge (folklore?) that some hosts
   1660    don't cope very well with large alloca calls.)  */
   1661 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
   1662 
   1663 /* The minimum remote packet size for memory transfers.  Ensures we
   1664    can write at least one byte.  */
   1665 #define MIN_MEMORY_PACKET_SIZE 20
   1666 
   1667 /* Get the memory packet size, assuming it is fixed.  */
   1668 
   1669 static long
   1670 get_fixed_memory_packet_size (struct memory_packet_config *config)
   1671 {
   1672   gdb_assert (config->fixed_p);
   1673 
   1674   if (config->size <= 0)
   1675     return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
   1676   else
   1677     return config->size;
   1678 }
   1679 
   1680 /* Compute the current size of a read/write packet.  Since this makes
   1681    use of ``actual_register_packet_size'' the computation is dynamic.  */
   1682 
   1683 long
   1684 remote_target::get_memory_packet_size (struct memory_packet_config *config)
   1685 {
   1686   struct remote_state *rs = get_remote_state ();
   1687   remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
   1688 
   1689   long what_they_get;
   1690   if (config->fixed_p)
   1691     what_they_get = get_fixed_memory_packet_size (config);
   1692   else
   1693     {
   1694       what_they_get = get_remote_packet_size ();
   1695       /* Limit the packet to the size specified by the user.  */
   1696       if (config->size > 0
   1697 	  && what_they_get > config->size)
   1698 	what_they_get = config->size;
   1699 
   1700       /* Limit it to the size of the targets ``g'' response unless we have
   1701 	 permission from the stub to use a larger packet size.  */
   1702       if (rs->explicit_packet_size == 0
   1703 	  && rsa->actual_register_packet_size > 0
   1704 	  && what_they_get > rsa->actual_register_packet_size)
   1705 	what_they_get = rsa->actual_register_packet_size;
   1706     }
   1707   if (what_they_get < MIN_MEMORY_PACKET_SIZE)
   1708     what_they_get = MIN_MEMORY_PACKET_SIZE;
   1709 
   1710   /* Make sure there is room in the global buffer for this packet
   1711      (including its trailing NUL byte).  */
   1712   if (rs->buf.size () < what_they_get + 1)
   1713     rs->buf.resize (2 * what_they_get);
   1714 
   1715   return what_they_get;
   1716 }
   1717 
   1718 /* Update the size of a read/write packet.  If they user wants
   1719    something really big then do a sanity check.  */
   1720 
   1721 static void
   1722 set_memory_packet_size (const char *args, struct memory_packet_config *config)
   1723 {
   1724   int fixed_p = config->fixed_p;
   1725   long size = config->size;
   1726 
   1727   if (args == NULL)
   1728     error (_("Argument required (integer, `fixed' or `limited')."));
   1729   else if (strcmp (args, "hard") == 0
   1730       || strcmp (args, "fixed") == 0)
   1731     fixed_p = 1;
   1732   else if (strcmp (args, "soft") == 0
   1733 	   || strcmp (args, "limit") == 0)
   1734     fixed_p = 0;
   1735   else
   1736     {
   1737       char *end;
   1738 
   1739       size = strtoul (args, &end, 0);
   1740       if (args == end)
   1741 	error (_("Invalid %s (bad syntax)."), config->name);
   1742 
   1743       /* Instead of explicitly capping the size of a packet to or
   1744 	 disallowing it, the user is allowed to set the size to
   1745 	 something arbitrarily large.  */
   1746     }
   1747 
   1748   /* Extra checks?  */
   1749   if (fixed_p && !config->fixed_p)
   1750     {
   1751       /* So that the query shows the correct value.  */
   1752       long query_size = (size <= 0
   1753 			 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
   1754 			 : size);
   1755 
   1756       if (! query (_("The target may not be able to correctly handle a %s\n"
   1757 		   "of %ld bytes. Change the packet size? "),
   1758 		   config->name, query_size))
   1759 	error (_("Packet size not changed."));
   1760     }
   1761   /* Update the config.  */
   1762   config->fixed_p = fixed_p;
   1763   config->size = size;
   1764 }
   1765 
   1766 static void
   1767 show_memory_packet_size (struct memory_packet_config *config)
   1768 {
   1769   if (config->size == 0)
   1770     gdb_printf (_("The %s is 0 (default). "), config->name);
   1771   else
   1772     gdb_printf (_("The %s is %ld. "), config->name, config->size);
   1773   if (config->fixed_p)
   1774     gdb_printf (_("Packets are fixed at %ld bytes.\n"),
   1775 		get_fixed_memory_packet_size (config));
   1776   else
   1777     {
   1778       remote_target *remote = get_current_remote_target ();
   1779 
   1780       if (remote != NULL)
   1781 	gdb_printf (_("Packets are limited to %ld bytes.\n"),
   1782 		    remote->get_memory_packet_size (config));
   1783       else
   1784 	gdb_puts ("The actual limit will be further reduced "
   1785 		  "dependent on the target.\n");
   1786     }
   1787 }
   1788 
   1789 /* FIXME: needs to be per-remote-target.  */
   1790 static struct memory_packet_config memory_write_packet_config =
   1791 {
   1792   "memory-write-packet-size",
   1793 };
   1794 
   1795 static void
   1796 set_memory_write_packet_size (const char *args, int from_tty)
   1797 {
   1798   set_memory_packet_size (args, &memory_write_packet_config);
   1799 }
   1800 
   1801 static void
   1802 show_memory_write_packet_size (const char *args, int from_tty)
   1803 {
   1804   show_memory_packet_size (&memory_write_packet_config);
   1805 }
   1806 
   1807 /* Show the number of hardware watchpoints that can be used.  */
   1808 
   1809 static void
   1810 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
   1811 				struct cmd_list_element *c,
   1812 				const char *value)
   1813 {
   1814   gdb_printf (file, _("The maximum number of target hardware "
   1815 		      "watchpoints is %s.\n"), value);
   1816 }
   1817 
   1818 /* Show the length limit (in bytes) for hardware watchpoints.  */
   1819 
   1820 static void
   1821 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
   1822 				       struct cmd_list_element *c,
   1823 				       const char *value)
   1824 {
   1825   gdb_printf (file, _("The maximum length (in bytes) of a target "
   1826 		      "hardware watchpoint is %s.\n"), value);
   1827 }
   1828 
   1829 /* Show the number of hardware breakpoints that can be used.  */
   1830 
   1831 static void
   1832 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
   1833 				struct cmd_list_element *c,
   1834 				const char *value)
   1835 {
   1836   gdb_printf (file, _("The maximum number of target hardware "
   1837 		      "breakpoints is %s.\n"), value);
   1838 }
   1839 
   1840 /* Controls the maximum number of characters to display in the debug output
   1841    for each remote packet.  The remaining characters are omitted.  */
   1842 
   1843 static int remote_packet_max_chars = 512;
   1844 
   1845 /* Show the maximum number of characters to display for each remote packet
   1846    when remote debugging is enabled.  */
   1847 
   1848 static void
   1849 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
   1850 			      struct cmd_list_element *c,
   1851 			      const char *value)
   1852 {
   1853   gdb_printf (file, _("Number of remote packet characters to "
   1854 		      "display is %s.\n"), value);
   1855 }
   1856 
   1857 long
   1858 remote_target::get_memory_write_packet_size ()
   1859 {
   1860   return get_memory_packet_size (&memory_write_packet_config);
   1861 }
   1862 
   1863 /* FIXME: needs to be per-remote-target.  */
   1864 static struct memory_packet_config memory_read_packet_config =
   1865 {
   1866   "memory-read-packet-size",
   1867 };
   1868 
   1869 static void
   1870 set_memory_read_packet_size (const char *args, int from_tty)
   1871 {
   1872   set_memory_packet_size (args, &memory_read_packet_config);
   1873 }
   1874 
   1875 static void
   1876 show_memory_read_packet_size (const char *args, int from_tty)
   1877 {
   1878   show_memory_packet_size (&memory_read_packet_config);
   1879 }
   1880 
   1881 long
   1882 remote_target::get_memory_read_packet_size ()
   1883 {
   1884   long size = get_memory_packet_size (&memory_read_packet_config);
   1885 
   1886   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
   1887      extra buffer size argument before the memory read size can be
   1888      increased beyond this.  */
   1889   if (size > get_remote_packet_size ())
   1890     size = get_remote_packet_size ();
   1891   return size;
   1892 }
   1893 
   1894 
   1895 
   1897 struct packet_config
   1898   {
   1899     const char *name;
   1900     const char *title;
   1901 
   1902     /* If auto, GDB auto-detects support for this packet or feature,
   1903        either through qSupported, or by trying the packet and looking
   1904        at the response.  If true, GDB assumes the target supports this
   1905        packet.  If false, the packet is disabled.  Configs that don't
   1906        have an associated command always have this set to auto.  */
   1907     enum auto_boolean detect;
   1908 
   1909     /* The "show remote foo-packet" command created for this packet.  */
   1910     cmd_list_element *show_cmd;
   1911 
   1912     /* Does the target support this packet?  */
   1913     enum packet_support support;
   1914   };
   1915 
   1916 static enum packet_support packet_config_support (struct packet_config *config);
   1917 static enum packet_support packet_support (int packet);
   1918 
   1919 static void
   1920 show_packet_config_cmd (ui_file *file, struct packet_config *config)
   1921 {
   1922   const char *support = "internal-error";
   1923 
   1924   switch (packet_config_support (config))
   1925     {
   1926     case PACKET_ENABLE:
   1927       support = "enabled";
   1928       break;
   1929     case PACKET_DISABLE:
   1930       support = "disabled";
   1931       break;
   1932     case PACKET_SUPPORT_UNKNOWN:
   1933       support = "unknown";
   1934       break;
   1935     }
   1936   switch (config->detect)
   1937     {
   1938     case AUTO_BOOLEAN_AUTO:
   1939       gdb_printf (file,
   1940 		  _("Support for the `%s' packet "
   1941 		    "is auto-detected, currently %s.\n"),
   1942 		  config->name, support);
   1943       break;
   1944     case AUTO_BOOLEAN_TRUE:
   1945     case AUTO_BOOLEAN_FALSE:
   1946       gdb_printf (file,
   1947 		  _("Support for the `%s' packet is currently %s.\n"),
   1948 		  config->name, support);
   1949       break;
   1950     }
   1951 }
   1952 
   1953 static void
   1954 add_packet_config_cmd (struct packet_config *config, const char *name,
   1955 		       const char *title, int legacy)
   1956 {
   1957   config->name = name;
   1958   config->title = title;
   1959   gdb::unique_xmalloc_ptr<char> set_doc
   1960     = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
   1961 		  name, title);
   1962   gdb::unique_xmalloc_ptr<char> show_doc
   1963     = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
   1964 		  name, title);
   1965   /* set/show TITLE-packet {auto,on,off} */
   1966   gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
   1967   set_show_commands cmds
   1968     = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
   1969 				    &config->detect, set_doc.get (),
   1970 				    show_doc.get (), NULL, /* help_doc */
   1971 				    NULL,
   1972 				    show_remote_protocol_packet_cmd,
   1973 				    &remote_set_cmdlist, &remote_show_cmdlist);
   1974   config->show_cmd = cmds.show;
   1975 
   1976   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
   1977   if (legacy)
   1978     {
   1979       /* It's not clear who should take ownership of the LEGACY_NAME string
   1980 	 created below, so, for now, place the string into a static vector
   1981 	 which ensures the strings is released when GDB exits.  */
   1982       static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
   1983       gdb::unique_xmalloc_ptr<char> legacy_name
   1984 	= xstrprintf ("%s-packet", name);
   1985       add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
   1986 		     &remote_set_cmdlist);
   1987       add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
   1988 		     &remote_show_cmdlist);
   1989       legacy_names.emplace_back (std::move (legacy_name));
   1990     }
   1991 }
   1992 
   1993 static enum packet_result
   1994 packet_check_result (const char *buf)
   1995 {
   1996   if (buf[0] != '\0')
   1997     {
   1998       /* The stub recognized the packet request.  Check that the
   1999 	 operation succeeded.  */
   2000       if (buf[0] == 'E'
   2001 	  && isxdigit (buf[1]) && isxdigit (buf[2])
   2002 	  && buf[3] == '\0')
   2003 	/* "Enn"  - definitely an error.  */
   2004 	return PACKET_ERROR;
   2005 
   2006       /* Always treat "E." as an error.  This will be used for
   2007 	 more verbose error messages, such as E.memtypes.  */
   2008       if (buf[0] == 'E' && buf[1] == '.')
   2009 	return PACKET_ERROR;
   2010 
   2011       /* The packet may or may not be OK.  Just assume it is.  */
   2012       return PACKET_OK;
   2013     }
   2014   else
   2015     /* The stub does not support the packet.  */
   2016     return PACKET_UNKNOWN;
   2017 }
   2018 
   2019 static enum packet_result
   2020 packet_check_result (const gdb::char_vector &buf)
   2021 {
   2022   return packet_check_result (buf.data ());
   2023 }
   2024 
   2025 static enum packet_result
   2026 packet_ok (const char *buf, struct packet_config *config)
   2027 {
   2028   enum packet_result result;
   2029 
   2030   if (config->detect != AUTO_BOOLEAN_TRUE
   2031       && config->support == PACKET_DISABLE)
   2032     internal_error (_("packet_ok: attempt to use a disabled packet"));
   2033 
   2034   result = packet_check_result (buf);
   2035   switch (result)
   2036     {
   2037     case PACKET_OK:
   2038     case PACKET_ERROR:
   2039       /* The stub recognized the packet request.  */
   2040       if (config->support == PACKET_SUPPORT_UNKNOWN)
   2041 	{
   2042 	  remote_debug_printf ("Packet %s (%s) is supported",
   2043 			       config->name, config->title);
   2044 	  config->support = PACKET_ENABLE;
   2045 	}
   2046       break;
   2047     case PACKET_UNKNOWN:
   2048       /* The stub does not support the packet.  */
   2049       if (config->detect == AUTO_BOOLEAN_AUTO
   2050 	  && config->support == PACKET_ENABLE)
   2051 	{
   2052 	  /* If the stub previously indicated that the packet was
   2053 	     supported then there is a protocol error.  */
   2054 	  error (_("Protocol error: %s (%s) conflicting enabled responses."),
   2055 		 config->name, config->title);
   2056 	}
   2057       else if (config->detect == AUTO_BOOLEAN_TRUE)
   2058 	{
   2059 	  /* The user set it wrong.  */
   2060 	  error (_("Enabled packet %s (%s) not recognized by stub"),
   2061 		 config->name, config->title);
   2062 	}
   2063 
   2064       remote_debug_printf ("Packet %s (%s) is NOT supported",
   2065 			   config->name, config->title);
   2066       config->support = PACKET_DISABLE;
   2067       break;
   2068     }
   2069 
   2070   return result;
   2071 }
   2072 
   2073 static enum packet_result
   2074 packet_ok (const gdb::char_vector &buf, struct packet_config *config)
   2075 {
   2076   return packet_ok (buf.data (), config);
   2077 }
   2078 
   2079 enum {
   2080   PACKET_vCont = 0,
   2081   PACKET_X,
   2082   PACKET_qSymbol,
   2083   PACKET_P,
   2084   PACKET_p,
   2085   PACKET_Z0,
   2086   PACKET_Z1,
   2087   PACKET_Z2,
   2088   PACKET_Z3,
   2089   PACKET_Z4,
   2090   PACKET_vFile_setfs,
   2091   PACKET_vFile_open,
   2092   PACKET_vFile_pread,
   2093   PACKET_vFile_pwrite,
   2094   PACKET_vFile_close,
   2095   PACKET_vFile_unlink,
   2096   PACKET_vFile_readlink,
   2097   PACKET_vFile_fstat,
   2098   PACKET_qXfer_auxv,
   2099   PACKET_qXfer_features,
   2100   PACKET_qXfer_exec_file,
   2101   PACKET_qXfer_libraries,
   2102   PACKET_qXfer_libraries_svr4,
   2103   PACKET_qXfer_memory_map,
   2104   PACKET_qXfer_osdata,
   2105   PACKET_qXfer_threads,
   2106   PACKET_qXfer_statictrace_read,
   2107   PACKET_qXfer_traceframe_info,
   2108   PACKET_qXfer_uib,
   2109   PACKET_qGetTIBAddr,
   2110   PACKET_qGetTLSAddr,
   2111   PACKET_qSupported,
   2112   PACKET_qTStatus,
   2113   PACKET_QPassSignals,
   2114   PACKET_QCatchSyscalls,
   2115   PACKET_QProgramSignals,
   2116   PACKET_QSetWorkingDir,
   2117   PACKET_QStartupWithShell,
   2118   PACKET_QEnvironmentHexEncoded,
   2119   PACKET_QEnvironmentReset,
   2120   PACKET_QEnvironmentUnset,
   2121   PACKET_qCRC,
   2122   PACKET_qSearch_memory,
   2123   PACKET_vAttach,
   2124   PACKET_vRun,
   2125   PACKET_QStartNoAckMode,
   2126   PACKET_vKill,
   2127   PACKET_qXfer_siginfo_read,
   2128   PACKET_qXfer_siginfo_write,
   2129   PACKET_qAttached,
   2130 
   2131   /* Support for conditional tracepoints.  */
   2132   PACKET_ConditionalTracepoints,
   2133 
   2134   /* Support for target-side breakpoint conditions.  */
   2135   PACKET_ConditionalBreakpoints,
   2136 
   2137   /* Support for target-side breakpoint commands.  */
   2138   PACKET_BreakpointCommands,
   2139 
   2140   /* Support for fast tracepoints.  */
   2141   PACKET_FastTracepoints,
   2142 
   2143   /* Support for static tracepoints.  */
   2144   PACKET_StaticTracepoints,
   2145 
   2146   /* Support for installing tracepoints while a trace experiment is
   2147      running.  */
   2148   PACKET_InstallInTrace,
   2149 
   2150   PACKET_bc,
   2151   PACKET_bs,
   2152   PACKET_TracepointSource,
   2153   PACKET_QAllow,
   2154   PACKET_qXfer_fdpic,
   2155   PACKET_QDisableRandomization,
   2156   PACKET_QAgent,
   2157   PACKET_QTBuffer_size,
   2158   PACKET_Qbtrace_off,
   2159   PACKET_Qbtrace_bts,
   2160   PACKET_Qbtrace_pt,
   2161   PACKET_qXfer_btrace,
   2162 
   2163   /* Support for the QNonStop packet.  */
   2164   PACKET_QNonStop,
   2165 
   2166   /* Support for the QThreadEvents packet.  */
   2167   PACKET_QThreadEvents,
   2168 
   2169   /* Support for multi-process extensions.  */
   2170   PACKET_multiprocess_feature,
   2171 
   2172   /* Support for enabling and disabling tracepoints while a trace
   2173      experiment is running.  */
   2174   PACKET_EnableDisableTracepoints_feature,
   2175 
   2176   /* Support for collecting strings using the tracenz bytecode.  */
   2177   PACKET_tracenz_feature,
   2178 
   2179   /* Support for continuing to run a trace experiment while GDB is
   2180      disconnected.  */
   2181   PACKET_DisconnectedTracing_feature,
   2182 
   2183   /* Support for qXfer:libraries-svr4:read with a non-empty annex.  */
   2184   PACKET_augmented_libraries_svr4_read_feature,
   2185 
   2186   /* Support for the qXfer:btrace-conf:read packet.  */
   2187   PACKET_qXfer_btrace_conf,
   2188 
   2189   /* Support for the Qbtrace-conf:bts:size packet.  */
   2190   PACKET_Qbtrace_conf_bts_size,
   2191 
   2192   /* Support for swbreak+ feature.  */
   2193   PACKET_swbreak_feature,
   2194 
   2195   /* Support for hwbreak+ feature.  */
   2196   PACKET_hwbreak_feature,
   2197 
   2198   /* Support for fork events.  */
   2199   PACKET_fork_event_feature,
   2200 
   2201   /* Support for vfork events.  */
   2202   PACKET_vfork_event_feature,
   2203 
   2204   /* Support for the Qbtrace-conf:pt:size packet.  */
   2205   PACKET_Qbtrace_conf_pt_size,
   2206 
   2207   /* Support for exec events.  */
   2208   PACKET_exec_event_feature,
   2209 
   2210   /* Support for query supported vCont actions.  */
   2211   PACKET_vContSupported,
   2212 
   2213   /* Support remote CTRL-C.  */
   2214   PACKET_vCtrlC,
   2215 
   2216   /* Support TARGET_WAITKIND_NO_RESUMED.  */
   2217   PACKET_no_resumed,
   2218 
   2219   /* Support for memory tagging, allocation tag fetch/store
   2220      packets and the tag violation stop replies.  */
   2221   PACKET_memory_tagging_feature,
   2222 
   2223   PACKET_MAX
   2224 };
   2225 
   2226 /* FIXME: needs to be per-remote-target.  Ignoring this for now,
   2227    assuming all remote targets are the same server (thus all support
   2228    the same packets).  */
   2229 static struct packet_config remote_protocol_packets[PACKET_MAX];
   2230 
   2231 /* Returns the packet's corresponding "set remote foo-packet" command
   2232    state.  See struct packet_config for more details.  */
   2233 
   2234 static enum auto_boolean
   2235 packet_set_cmd_state (int packet)
   2236 {
   2237   return remote_protocol_packets[packet].detect;
   2238 }
   2239 
   2240 /* Returns whether a given packet or feature is supported.  This takes
   2241    into account the state of the corresponding "set remote foo-packet"
   2242    command, which may be used to bypass auto-detection.  */
   2243 
   2244 static enum packet_support
   2245 packet_config_support (struct packet_config *config)
   2246 {
   2247   switch (config->detect)
   2248     {
   2249     case AUTO_BOOLEAN_TRUE:
   2250       return PACKET_ENABLE;
   2251     case AUTO_BOOLEAN_FALSE:
   2252       return PACKET_DISABLE;
   2253     case AUTO_BOOLEAN_AUTO:
   2254       return config->support;
   2255     default:
   2256       gdb_assert_not_reached ("bad switch");
   2257     }
   2258 }
   2259 
   2260 /* Same as packet_config_support, but takes the packet's enum value as
   2261    argument.  */
   2262 
   2263 static enum packet_support
   2264 packet_support (int packet)
   2265 {
   2266   struct packet_config *config = &remote_protocol_packets[packet];
   2267 
   2268   return packet_config_support (config);
   2269 }
   2270 
   2271 static void
   2272 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
   2273 				 struct cmd_list_element *c,
   2274 				 const char *value)
   2275 {
   2276   struct packet_config *packet;
   2277   gdb_assert (c->var.has_value ());
   2278 
   2279   for (packet = remote_protocol_packets;
   2280        packet < &remote_protocol_packets[PACKET_MAX];
   2281        packet++)
   2282     {
   2283       if (c == packet->show_cmd)
   2284 	{
   2285 	  show_packet_config_cmd (file, packet);
   2286 	  return;
   2287 	}
   2288     }
   2289   internal_error (_("Could not find config for %s"),
   2290 		  c->name);
   2291 }
   2292 
   2293 /* Should we try one of the 'Z' requests?  */
   2294 
   2295 enum Z_packet_type
   2296 {
   2297   Z_PACKET_SOFTWARE_BP,
   2298   Z_PACKET_HARDWARE_BP,
   2299   Z_PACKET_WRITE_WP,
   2300   Z_PACKET_READ_WP,
   2301   Z_PACKET_ACCESS_WP,
   2302   NR_Z_PACKET_TYPES
   2303 };
   2304 
   2305 /* For compatibility with older distributions.  Provide a ``set remote
   2306    Z-packet ...'' command that updates all the Z packet types.  */
   2307 
   2308 static enum auto_boolean remote_Z_packet_detect;
   2309 
   2310 static void
   2311 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
   2312 				  struct cmd_list_element *c)
   2313 {
   2314   int i;
   2315 
   2316   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
   2317     remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
   2318 }
   2319 
   2320 static void
   2321 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
   2322 				   struct cmd_list_element *c,
   2323 				   const char *value)
   2324 {
   2325   int i;
   2326 
   2327   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
   2328     {
   2329       show_packet_config_cmd (file, &remote_protocol_packets[PACKET_Z0 + i]);
   2330     }
   2331 }
   2332 
   2333 /* Returns true if the multi-process extensions are in effect.  */
   2334 
   2335 static int
   2336 remote_multi_process_p (struct remote_state *rs)
   2337 {
   2338   return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
   2339 }
   2340 
   2341 /* Returns true if fork events are supported.  */
   2342 
   2343 static int
   2344 remote_fork_event_p (struct remote_state *rs)
   2345 {
   2346   return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
   2347 }
   2348 
   2349 /* Returns true if vfork events are supported.  */
   2350 
   2351 static int
   2352 remote_vfork_event_p (struct remote_state *rs)
   2353 {
   2354   return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
   2355 }
   2356 
   2357 /* Returns true if exec events are supported.  */
   2358 
   2359 static int
   2360 remote_exec_event_p (struct remote_state *rs)
   2361 {
   2362   return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
   2363 }
   2364 
   2365 /* Returns true if memory tagging is supported, false otherwise.  */
   2366 
   2367 static bool
   2368 remote_memory_tagging_p ()
   2369 {
   2370   return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE;
   2371 }
   2372 
   2373 /* Insert fork catchpoint target routine.  If fork events are enabled
   2374    then return success, nothing more to do.  */
   2375 
   2376 int
   2377 remote_target::insert_fork_catchpoint (int pid)
   2378 {
   2379   struct remote_state *rs = get_remote_state ();
   2380 
   2381   return !remote_fork_event_p (rs);
   2382 }
   2383 
   2384 /* Remove fork catchpoint target routine.  Nothing to do, just
   2385    return success.  */
   2386 
   2387 int
   2388 remote_target::remove_fork_catchpoint (int pid)
   2389 {
   2390   return 0;
   2391 }
   2392 
   2393 /* Insert vfork catchpoint target routine.  If vfork events are enabled
   2394    then return success, nothing more to do.  */
   2395 
   2396 int
   2397 remote_target::insert_vfork_catchpoint (int pid)
   2398 {
   2399   struct remote_state *rs = get_remote_state ();
   2400 
   2401   return !remote_vfork_event_p (rs);
   2402 }
   2403 
   2404 /* Remove vfork catchpoint target routine.  Nothing to do, just
   2405    return success.  */
   2406 
   2407 int
   2408 remote_target::remove_vfork_catchpoint (int pid)
   2409 {
   2410   return 0;
   2411 }
   2412 
   2413 /* Insert exec catchpoint target routine.  If exec events are
   2414    enabled, just return success.  */
   2415 
   2416 int
   2417 remote_target::insert_exec_catchpoint (int pid)
   2418 {
   2419   struct remote_state *rs = get_remote_state ();
   2420 
   2421   return !remote_exec_event_p (rs);
   2422 }
   2423 
   2424 /* Remove exec catchpoint target routine.  Nothing to do, just
   2425    return success.  */
   2426 
   2427 int
   2428 remote_target::remove_exec_catchpoint (int pid)
   2429 {
   2430   return 0;
   2431 }
   2432 
   2433 
   2434 
   2436 /* Take advantage of the fact that the TID field is not used, to tag
   2437    special ptids with it set to != 0.  */
   2438 static const ptid_t magic_null_ptid (42000, -1, 1);
   2439 static const ptid_t not_sent_ptid (42000, -2, 1);
   2440 static const ptid_t any_thread_ptid (42000, 0, 1);
   2441 
   2442 /* Find out if the stub attached to PID (and hence GDB should offer to
   2443    detach instead of killing it when bailing out).  */
   2444 
   2445 int
   2446 remote_target::remote_query_attached (int pid)
   2447 {
   2448   struct remote_state *rs = get_remote_state ();
   2449   size_t size = get_remote_packet_size ();
   2450 
   2451   if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
   2452     return 0;
   2453 
   2454   if (remote_multi_process_p (rs))
   2455     xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
   2456   else
   2457     xsnprintf (rs->buf.data (), size, "qAttached");
   2458 
   2459   putpkt (rs->buf);
   2460   getpkt (&rs->buf, 0);
   2461 
   2462   switch (packet_ok (rs->buf,
   2463 		     &remote_protocol_packets[PACKET_qAttached]))
   2464     {
   2465     case PACKET_OK:
   2466       if (strcmp (rs->buf.data (), "1") == 0)
   2467 	return 1;
   2468       break;
   2469     case PACKET_ERROR:
   2470       warning (_("Remote failure reply: %s"), rs->buf.data ());
   2471       break;
   2472     case PACKET_UNKNOWN:
   2473       break;
   2474     }
   2475 
   2476   return 0;
   2477 }
   2478 
   2479 /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
   2480    has been invented by GDB, instead of reported by the target.  Since
   2481    we can be connected to a remote system before before knowing about
   2482    any inferior, mark the target with execution when we find the first
   2483    inferior.  If ATTACHED is 1, then we had just attached to this
   2484    inferior.  If it is 0, then we just created this inferior.  If it
   2485    is -1, then try querying the remote stub to find out if it had
   2486    attached to the inferior or not.  If TRY_OPEN_EXEC is true then
   2487    attempt to open this inferior's executable as the main executable
   2488    if no main executable is open already.  */
   2489 
   2490 inferior *
   2491 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
   2492 				    int try_open_exec)
   2493 {
   2494   struct inferior *inf;
   2495 
   2496   /* Check whether this process we're learning about is to be
   2497      considered attached, or if is to be considered to have been
   2498      spawned by the stub.  */
   2499   if (attached == -1)
   2500     attached = remote_query_attached (pid);
   2501 
   2502   if (gdbarch_has_global_solist (target_gdbarch ()))
   2503     {
   2504       /* If the target shares code across all inferiors, then every
   2505 	 attach adds a new inferior.  */
   2506       inf = add_inferior (pid);
   2507 
   2508       /* ... and every inferior is bound to the same program space.
   2509 	 However, each inferior may still have its own address
   2510 	 space.  */
   2511       inf->aspace = maybe_new_address_space ();
   2512       inf->pspace = current_program_space;
   2513     }
   2514   else
   2515     {
   2516       /* In the traditional debugging scenario, there's a 1-1 match
   2517 	 between program/address spaces.  We simply bind the inferior
   2518 	 to the program space's address space.  */
   2519       inf = current_inferior ();
   2520 
   2521       /* However, if the current inferior is already bound to a
   2522 	 process, find some other empty inferior.  */
   2523       if (inf->pid != 0)
   2524 	{
   2525 	  inf = nullptr;
   2526 	  for (inferior *it : all_inferiors ())
   2527 	    if (it->pid == 0)
   2528 	      {
   2529 		inf = it;
   2530 		break;
   2531 	      }
   2532 	}
   2533       if (inf == nullptr)
   2534 	{
   2535 	  /* Since all inferiors were already bound to a process, add
   2536 	     a new inferior.  */
   2537 	  inf = add_inferior_with_spaces ();
   2538 	}
   2539       switch_to_inferior_no_thread (inf);
   2540       inf->push_target (this);
   2541       inferior_appeared (inf, pid);
   2542     }
   2543 
   2544   inf->attach_flag = attached;
   2545   inf->fake_pid_p = fake_pid_p;
   2546 
   2547   /* If no main executable is currently open then attempt to
   2548      open the file that was executed to create this inferior.  */
   2549   if (try_open_exec && get_exec_file (0) == NULL)
   2550     exec_file_locate_attach (pid, 0, 1);
   2551 
   2552   /* Check for exec file mismatch, and let the user solve it.  */
   2553   validate_exec_file (1);
   2554 
   2555   return inf;
   2556 }
   2557 
   2558 static remote_thread_info *get_remote_thread_info (thread_info *thread);
   2559 static remote_thread_info *get_remote_thread_info (remote_target *target,
   2560 						   ptid_t ptid);
   2561 
   2562 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
   2563    according to EXECUTING and RUNNING respectively.  If SILENT_P (or the
   2564    remote_state::starting_up flag) is true then the new thread is added
   2565    silently, otherwise the new thread will be announced to the user.  */
   2566 
   2567 thread_info *
   2568 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
   2569 				  bool silent_p)
   2570 {
   2571   struct remote_state *rs = get_remote_state ();
   2572   struct thread_info *thread;
   2573 
   2574   /* GDB historically didn't pull threads in the initial connection
   2575      setup.  If the remote target doesn't even have a concept of
   2576      threads (e.g., a bare-metal target), even if internally we
   2577      consider that a single-threaded target, mentioning a new thread
   2578      might be confusing to the user.  Be silent then, preserving the
   2579      age old behavior.  */
   2580   if (rs->starting_up || silent_p)
   2581     thread = add_thread_silent (this, ptid);
   2582   else
   2583     thread = add_thread (this, ptid);
   2584 
   2585   /* We start by assuming threads are resumed.  That state then gets updated
   2586      when we process a matching stop reply.  */
   2587   get_remote_thread_info (thread)->set_resumed ();
   2588 
   2589   set_executing (this, ptid, executing);
   2590   set_running (this, ptid, running);
   2591 
   2592   return thread;
   2593 }
   2594 
   2595 /* Come here when we learn about a thread id from the remote target.
   2596    It may be the first time we hear about such thread, so take the
   2597    opportunity to add it to GDB's thread list.  In case this is the
   2598    first time we're noticing its corresponding inferior, add it to
   2599    GDB's inferior list as well.  EXECUTING indicates whether the
   2600    thread is (internally) executing or stopped.  */
   2601 
   2602 void
   2603 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
   2604 {
   2605   /* In non-stop mode, we assume new found threads are (externally)
   2606      running until proven otherwise with a stop reply.  In all-stop,
   2607      we can only get here if all threads are stopped.  */
   2608   bool running = target_is_non_stop_p ();
   2609 
   2610   /* If this is a new thread, add it to GDB's thread list.
   2611      If we leave it up to WFI to do this, bad things will happen.  */
   2612 
   2613   thread_info *tp = find_thread_ptid (this, currthread);
   2614   if (tp != NULL && tp->state == THREAD_EXITED)
   2615     {
   2616       /* We're seeing an event on a thread id we knew had exited.
   2617 	 This has to be a new thread reusing the old id.  Add it.  */
   2618       remote_add_thread (currthread, running, executing, false);
   2619       return;
   2620     }
   2621 
   2622   if (!in_thread_list (this, currthread))
   2623     {
   2624       struct inferior *inf = NULL;
   2625       int pid = currthread.pid ();
   2626 
   2627       if (inferior_ptid.is_pid ()
   2628 	  && pid == inferior_ptid.pid ())
   2629 	{
   2630 	  /* inferior_ptid has no thread member yet.  This can happen
   2631 	     with the vAttach -> remote_wait,"TAAthread:" path if the
   2632 	     stub doesn't support qC.  This is the first stop reported
   2633 	     after an attach, so this is the main thread.  Update the
   2634 	     ptid in the thread list.  */
   2635 	  if (in_thread_list (this, ptid_t (pid)))
   2636 	    thread_change_ptid (this, inferior_ptid, currthread);
   2637 	  else
   2638 	    {
   2639 	      thread_info *thr
   2640 		= remote_add_thread (currthread, running, executing, false);
   2641 	      switch_to_thread (thr);
   2642 	    }
   2643 	  return;
   2644 	}
   2645 
   2646       if (magic_null_ptid == inferior_ptid)
   2647 	{
   2648 	  /* inferior_ptid is not set yet.  This can happen with the
   2649 	     vRun -> remote_wait,"TAAthread:" path if the stub
   2650 	     doesn't support qC.  This is the first stop reported
   2651 	     after an attach, so this is the main thread.  Update the
   2652 	     ptid in the thread list.  */
   2653 	  thread_change_ptid (this, inferior_ptid, currthread);
   2654 	  return;
   2655 	}
   2656 
   2657       /* When connecting to a target remote, or to a target
   2658 	 extended-remote which already was debugging an inferior, we
   2659 	 may not know about it yet.  Add it before adding its child
   2660 	 thread, so notifications are emitted in a sensible order.  */
   2661       if (find_inferior_pid (this, currthread.pid ()) == NULL)
   2662 	{
   2663 	  struct remote_state *rs = get_remote_state ();
   2664 	  bool fake_pid_p = !remote_multi_process_p (rs);
   2665 
   2666 	  inf = remote_add_inferior (fake_pid_p,
   2667 				     currthread.pid (), -1, 1);
   2668 	}
   2669 
   2670       /* This is really a new thread.  Add it.  */
   2671       thread_info *new_thr
   2672 	= remote_add_thread (currthread, running, executing, false);
   2673 
   2674       /* If we found a new inferior, let the common code do whatever
   2675 	 it needs to with it (e.g., read shared libraries, insert
   2676 	 breakpoints), unless we're just setting up an all-stop
   2677 	 connection.  */
   2678       if (inf != NULL)
   2679 	{
   2680 	  struct remote_state *rs = get_remote_state ();
   2681 
   2682 	  if (!rs->starting_up)
   2683 	    notice_new_inferior (new_thr, executing, 0);
   2684 	}
   2685     }
   2686 }
   2687 
   2688 /* Return THREAD's private thread data, creating it if necessary.  */
   2689 
   2690 static remote_thread_info *
   2691 get_remote_thread_info (thread_info *thread)
   2692 {
   2693   gdb_assert (thread != NULL);
   2694 
   2695   if (thread->priv == NULL)
   2696     thread->priv.reset (new remote_thread_info);
   2697 
   2698   return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
   2699 }
   2700 
   2701 /* Return PTID's private thread data, creating it if necessary.  */
   2702 
   2703 static remote_thread_info *
   2704 get_remote_thread_info (remote_target *target, ptid_t ptid)
   2705 {
   2706   thread_info *thr = find_thread_ptid (target, ptid);
   2707   return get_remote_thread_info (thr);
   2708 }
   2709 
   2710 /* Call this function as a result of
   2711    1) A halt indication (T packet) containing a thread id
   2712    2) A direct query of currthread
   2713    3) Successful execution of set thread */
   2714 
   2715 static void
   2716 record_currthread (struct remote_state *rs, ptid_t currthread)
   2717 {
   2718   rs->general_thread = currthread;
   2719 }
   2720 
   2721 /* If 'QPassSignals' is supported, tell the remote stub what signals
   2722    it can simply pass through to the inferior without reporting.  */
   2723 
   2724 void
   2725 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
   2726 {
   2727   if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
   2728     {
   2729       char *pass_packet, *p;
   2730       int count = 0;
   2731       struct remote_state *rs = get_remote_state ();
   2732 
   2733       gdb_assert (pass_signals.size () < 256);
   2734       for (size_t i = 0; i < pass_signals.size (); i++)
   2735 	{
   2736 	  if (pass_signals[i])
   2737 	    count++;
   2738 	}
   2739       pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
   2740       strcpy (pass_packet, "QPassSignals:");
   2741       p = pass_packet + strlen (pass_packet);
   2742       for (size_t i = 0; i < pass_signals.size (); i++)
   2743 	{
   2744 	  if (pass_signals[i])
   2745 	    {
   2746 	      if (i >= 16)
   2747 		*p++ = tohex (i >> 4);
   2748 	      *p++ = tohex (i & 15);
   2749 	      if (count)
   2750 		*p++ = ';';
   2751 	      else
   2752 		break;
   2753 	      count--;
   2754 	    }
   2755 	}
   2756       *p = 0;
   2757       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
   2758 	{
   2759 	  putpkt (pass_packet);
   2760 	  getpkt (&rs->buf, 0);
   2761 	  packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
   2762 	  xfree (rs->last_pass_packet);
   2763 	  rs->last_pass_packet = pass_packet;
   2764 	}
   2765       else
   2766 	xfree (pass_packet);
   2767     }
   2768 }
   2769 
   2770 /* If 'QCatchSyscalls' is supported, tell the remote stub
   2771    to report syscalls to GDB.  */
   2772 
   2773 int
   2774 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
   2775 				       gdb::array_view<const int> syscall_counts)
   2776 {
   2777   const char *catch_packet;
   2778   enum packet_result result;
   2779   int n_sysno = 0;
   2780 
   2781   if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
   2782     {
   2783       /* Not supported.  */
   2784       return 1;
   2785     }
   2786 
   2787   if (needed && any_count == 0)
   2788     {
   2789       /* Count how many syscalls are to be caught.  */
   2790       for (size_t i = 0; i < syscall_counts.size (); i++)
   2791 	{
   2792 	  if (syscall_counts[i] != 0)
   2793 	    n_sysno++;
   2794 	}
   2795     }
   2796 
   2797   remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
   2798 		       pid, needed, any_count, n_sysno);
   2799 
   2800   std::string built_packet;
   2801   if (needed)
   2802     {
   2803       /* Prepare a packet with the sysno list, assuming max 8+1
   2804 	 characters for a sysno.  If the resulting packet size is too
   2805 	 big, fallback on the non-selective packet.  */
   2806       const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
   2807       built_packet.reserve (maxpktsz);
   2808       built_packet = "QCatchSyscalls:1";
   2809       if (any_count == 0)
   2810 	{
   2811 	  /* Add in each syscall to be caught.  */
   2812 	  for (size_t i = 0; i < syscall_counts.size (); i++)
   2813 	    {
   2814 	      if (syscall_counts[i] != 0)
   2815 		string_appendf (built_packet, ";%zx", i);
   2816 	    }
   2817 	}
   2818       if (built_packet.size () > get_remote_packet_size ())
   2819 	{
   2820 	  /* catch_packet too big.  Fallback to less efficient
   2821 	     non selective mode, with GDB doing the filtering.  */
   2822 	  catch_packet = "QCatchSyscalls:1";
   2823 	}
   2824       else
   2825 	catch_packet = built_packet.c_str ();
   2826     }
   2827   else
   2828     catch_packet = "QCatchSyscalls:0";
   2829 
   2830   struct remote_state *rs = get_remote_state ();
   2831 
   2832   putpkt (catch_packet);
   2833   getpkt (&rs->buf, 0);
   2834   result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
   2835   if (result == PACKET_OK)
   2836     return 0;
   2837   else
   2838     return -1;
   2839 }
   2840 
   2841 /* If 'QProgramSignals' is supported, tell the remote stub what
   2842    signals it should pass through to the inferior when detaching.  */
   2843 
   2844 void
   2845 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
   2846 {
   2847   if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
   2848     {
   2849       char *packet, *p;
   2850       int count = 0;
   2851       struct remote_state *rs = get_remote_state ();
   2852 
   2853       gdb_assert (signals.size () < 256);
   2854       for (size_t i = 0; i < signals.size (); i++)
   2855 	{
   2856 	  if (signals[i])
   2857 	    count++;
   2858 	}
   2859       packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
   2860       strcpy (packet, "QProgramSignals:");
   2861       p = packet + strlen (packet);
   2862       for (size_t i = 0; i < signals.size (); i++)
   2863 	{
   2864 	  if (signal_pass_state (i))
   2865 	    {
   2866 	      if (i >= 16)
   2867 		*p++ = tohex (i >> 4);
   2868 	      *p++ = tohex (i & 15);
   2869 	      if (count)
   2870 		*p++ = ';';
   2871 	      else
   2872 		break;
   2873 	      count--;
   2874 	    }
   2875 	}
   2876       *p = 0;
   2877       if (!rs->last_program_signals_packet
   2878 	  || strcmp (rs->last_program_signals_packet, packet) != 0)
   2879 	{
   2880 	  putpkt (packet);
   2881 	  getpkt (&rs->buf, 0);
   2882 	  packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
   2883 	  xfree (rs->last_program_signals_packet);
   2884 	  rs->last_program_signals_packet = packet;
   2885 	}
   2886       else
   2887 	xfree (packet);
   2888     }
   2889 }
   2890 
   2891 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
   2892    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
   2893    thread.  If GEN is set, set the general thread, if not, then set
   2894    the step/continue thread.  */
   2895 void
   2896 remote_target::set_thread (ptid_t ptid, int gen)
   2897 {
   2898   struct remote_state *rs = get_remote_state ();
   2899   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
   2900   char *buf = rs->buf.data ();
   2901   char *endbuf = buf + get_remote_packet_size ();
   2902 
   2903   if (state == ptid)
   2904     return;
   2905 
   2906   *buf++ = 'H';
   2907   *buf++ = gen ? 'g' : 'c';
   2908   if (ptid == magic_null_ptid)
   2909     xsnprintf (buf, endbuf - buf, "0");
   2910   else if (ptid == any_thread_ptid)
   2911     xsnprintf (buf, endbuf - buf, "0");
   2912   else if (ptid == minus_one_ptid)
   2913     xsnprintf (buf, endbuf - buf, "-1");
   2914   else
   2915     write_ptid (buf, endbuf, ptid);
   2916   putpkt (rs->buf);
   2917   getpkt (&rs->buf, 0);
   2918   if (gen)
   2919     rs->general_thread = ptid;
   2920   else
   2921     rs->continue_thread = ptid;
   2922 }
   2923 
   2924 void
   2925 remote_target::set_general_thread (ptid_t ptid)
   2926 {
   2927   set_thread (ptid, 1);
   2928 }
   2929 
   2930 void
   2931 remote_target::set_continue_thread (ptid_t ptid)
   2932 {
   2933   set_thread (ptid, 0);
   2934 }
   2935 
   2936 /* Change the remote current process.  Which thread within the process
   2937    ends up selected isn't important, as long as it is the same process
   2938    as what INFERIOR_PTID points to.
   2939 
   2940    This comes from that fact that there is no explicit notion of
   2941    "selected process" in the protocol.  The selected process for
   2942    general operations is the process the selected general thread
   2943    belongs to.  */
   2944 
   2945 void
   2946 remote_target::set_general_process ()
   2947 {
   2948   struct remote_state *rs = get_remote_state ();
   2949 
   2950   /* If the remote can't handle multiple processes, don't bother.  */
   2951   if (!remote_multi_process_p (rs))
   2952     return;
   2953 
   2954   /* We only need to change the remote current thread if it's pointing
   2955      at some other process.  */
   2956   if (rs->general_thread.pid () != inferior_ptid.pid ())
   2957     set_general_thread (inferior_ptid);
   2958 }
   2959 
   2960 
   2961 /* Return nonzero if this is the main thread that we made up ourselves
   2963    to model non-threaded targets as single-threaded.  */
   2964 
   2965 static int
   2966 remote_thread_always_alive (ptid_t ptid)
   2967 {
   2968   if (ptid == magic_null_ptid)
   2969     /* The main thread is always alive.  */
   2970     return 1;
   2971 
   2972   if (ptid.pid () != 0 && ptid.lwp () == 0)
   2973     /* The main thread is always alive.  This can happen after a
   2974        vAttach, if the remote side doesn't support
   2975        multi-threading.  */
   2976     return 1;
   2977 
   2978   return 0;
   2979 }
   2980 
   2981 /* Return nonzero if the thread PTID is still alive on the remote
   2982    system.  */
   2983 
   2984 bool
   2985 remote_target::thread_alive (ptid_t ptid)
   2986 {
   2987   struct remote_state *rs = get_remote_state ();
   2988   char *p, *endp;
   2989 
   2990   /* Check if this is a thread that we made up ourselves to model
   2991      non-threaded targets as single-threaded.  */
   2992   if (remote_thread_always_alive (ptid))
   2993     return 1;
   2994 
   2995   p = rs->buf.data ();
   2996   endp = p + get_remote_packet_size ();
   2997 
   2998   *p++ = 'T';
   2999   write_ptid (p, endp, ptid);
   3000 
   3001   putpkt (rs->buf);
   3002   getpkt (&rs->buf, 0);
   3003   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
   3004 }
   3005 
   3006 /* Return a pointer to a thread name if we know it and NULL otherwise.
   3007    The thread_info object owns the memory for the name.  */
   3008 
   3009 const char *
   3010 remote_target::thread_name (struct thread_info *info)
   3011 {
   3012   if (info->priv != NULL)
   3013     {
   3014       const std::string &name = get_remote_thread_info (info)->name;
   3015       return !name.empty () ? name.c_str () : NULL;
   3016     }
   3017 
   3018   return NULL;
   3019 }
   3020 
   3021 /* About these extended threadlist and threadinfo packets.  They are
   3022    variable length packets but, the fields within them are often fixed
   3023    length.  They are redundant enough to send over UDP as is the
   3024    remote protocol in general.  There is a matching unit test module
   3025    in libstub.  */
   3026 
   3027 /* WARNING: This threadref data structure comes from the remote O.S.,
   3028    libstub protocol encoding, and remote.c.  It is not particularly
   3029    changable.  */
   3030 
   3031 /* Right now, the internal structure is int. We want it to be bigger.
   3032    Plan to fix this.  */
   3033 
   3034 typedef int gdb_threadref;	/* Internal GDB thread reference.  */
   3035 
   3036 /* gdb_ext_thread_info is an internal GDB data structure which is
   3037    equivalent to the reply of the remote threadinfo packet.  */
   3038 
   3039 struct gdb_ext_thread_info
   3040   {
   3041     threadref threadid;		/* External form of thread reference.  */
   3042     int active;			/* Has state interesting to GDB?
   3043 				   regs, stack.  */
   3044     char display[256];		/* Brief state display, name,
   3045 				   blocked/suspended.  */
   3046     char shortname[32];		/* To be used to name threads.  */
   3047     char more_display[256];	/* Long info, statistics, queue depth,
   3048 				   whatever.  */
   3049   };
   3050 
   3051 /* The volume of remote transfers can be limited by submitting
   3052    a mask containing bits specifying the desired information.
   3053    Use a union of these values as the 'selection' parameter to
   3054    get_thread_info.  FIXME: Make these TAG names more thread specific.  */
   3055 
   3056 #define TAG_THREADID 1
   3057 #define TAG_EXISTS 2
   3058 #define TAG_DISPLAY 4
   3059 #define TAG_THREADNAME 8
   3060 #define TAG_MOREDISPLAY 16
   3061 
   3062 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
   3063 
   3064 static const char *unpack_nibble (const char *buf, int *val);
   3065 
   3066 static const char *unpack_byte (const char *buf, int *value);
   3067 
   3068 static char *pack_int (char *buf, int value);
   3069 
   3070 static const char *unpack_int (const char *buf, int *value);
   3071 
   3072 static const char *unpack_string (const char *src, char *dest, int length);
   3073 
   3074 static char *pack_threadid (char *pkt, threadref *id);
   3075 
   3076 static const char *unpack_threadid (const char *inbuf, threadref *id);
   3077 
   3078 void int_to_threadref (threadref *id, int value);
   3079 
   3080 static int threadref_to_int (threadref *ref);
   3081 
   3082 static void copy_threadref (threadref *dest, threadref *src);
   3083 
   3084 static int threadmatch (threadref *dest, threadref *src);
   3085 
   3086 static char *pack_threadinfo_request (char *pkt, int mode,
   3087 				      threadref *id);
   3088 
   3089 static char *pack_threadlist_request (char *pkt, int startflag,
   3090 				      int threadcount,
   3091 				      threadref *nextthread);
   3092 
   3093 static int remote_newthread_step (threadref *ref, void *context);
   3094 
   3095 
   3096 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
   3097    buffer we're allowed to write to.  Returns
   3098    BUF+CHARACTERS_WRITTEN.  */
   3099 
   3100 char *
   3101 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
   3102 {
   3103   int pid, tid;
   3104   struct remote_state *rs = get_remote_state ();
   3105 
   3106   if (remote_multi_process_p (rs))
   3107     {
   3108       pid = ptid.pid ();
   3109       if (pid < 0)
   3110 	buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
   3111       else
   3112 	buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
   3113     }
   3114   tid = ptid.lwp ();
   3115   if (tid < 0)
   3116     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
   3117   else
   3118     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
   3119 
   3120   return buf;
   3121 }
   3122 
   3123 /* Extract a PTID from BUF.  If non-null, OBUF is set to one past the
   3124    last parsed char.  Returns null_ptid if no thread id is found, and
   3125    throws an error if the thread id has an invalid format.  */
   3126 
   3127 static ptid_t
   3128 read_ptid (const char *buf, const char **obuf)
   3129 {
   3130   const char *p = buf;
   3131   const char *pp;
   3132   ULONGEST pid = 0, tid = 0;
   3133 
   3134   if (*p == 'p')
   3135     {
   3136       /* Multi-process ptid.  */
   3137       pp = unpack_varlen_hex (p + 1, &pid);
   3138       if (*pp != '.')
   3139 	error (_("invalid remote ptid: %s"), p);
   3140 
   3141       p = pp;
   3142       pp = unpack_varlen_hex (p + 1, &tid);
   3143       if (obuf)
   3144 	*obuf = pp;
   3145       return ptid_t (pid, tid);
   3146     }
   3147 
   3148   /* No multi-process.  Just a tid.  */
   3149   pp = unpack_varlen_hex (p, &tid);
   3150 
   3151   /* Return null_ptid when no thread id is found.  */
   3152   if (p == pp)
   3153     {
   3154       if (obuf)
   3155 	*obuf = pp;
   3156       return null_ptid;
   3157     }
   3158 
   3159   /* Since the stub is not sending a process id, default to what's
   3160      current_inferior, unless it doesn't have a PID yet.  If so,
   3161      then since there's no way to know the pid of the reported
   3162      threads, use the magic number.  */
   3163   inferior *inf = current_inferior ();
   3164   if (inf->pid == 0)
   3165     pid = magic_null_ptid.pid ();
   3166   else
   3167     pid = inf->pid;
   3168 
   3169   if (obuf)
   3170     *obuf = pp;
   3171   return ptid_t (pid, tid);
   3172 }
   3173 
   3174 static int
   3175 stubhex (int ch)
   3176 {
   3177   if (ch >= 'a' && ch <= 'f')
   3178     return ch - 'a' + 10;
   3179   if (ch >= '0' && ch <= '9')
   3180     return ch - '0';
   3181   if (ch >= 'A' && ch <= 'F')
   3182     return ch - 'A' + 10;
   3183   return -1;
   3184 }
   3185 
   3186 static int
   3187 stub_unpack_int (const char *buff, int fieldlength)
   3188 {
   3189   int nibble;
   3190   int retval = 0;
   3191 
   3192   while (fieldlength)
   3193     {
   3194       nibble = stubhex (*buff++);
   3195       retval |= nibble;
   3196       fieldlength--;
   3197       if (fieldlength)
   3198 	retval = retval << 4;
   3199     }
   3200   return retval;
   3201 }
   3202 
   3203 static const char *
   3204 unpack_nibble (const char *buf, int *val)
   3205 {
   3206   *val = fromhex (*buf++);
   3207   return buf;
   3208 }
   3209 
   3210 static const char *
   3211 unpack_byte (const char *buf, int *value)
   3212 {
   3213   *value = stub_unpack_int (buf, 2);
   3214   return buf + 2;
   3215 }
   3216 
   3217 static char *
   3218 pack_int (char *buf, int value)
   3219 {
   3220   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
   3221   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
   3222   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
   3223   buf = pack_hex_byte (buf, (value & 0xff));
   3224   return buf;
   3225 }
   3226 
   3227 static const char *
   3228 unpack_int (const char *buf, int *value)
   3229 {
   3230   *value = stub_unpack_int (buf, 8);
   3231   return buf + 8;
   3232 }
   3233 
   3234 #if 0			/* Currently unused, uncomment when needed.  */
   3235 static char *pack_string (char *pkt, char *string);
   3236 
   3237 static char *
   3238 pack_string (char *pkt, char *string)
   3239 {
   3240   char ch;
   3241   int len;
   3242 
   3243   len = strlen (string);
   3244   if (len > 200)
   3245     len = 200;		/* Bigger than most GDB packets, junk???  */
   3246   pkt = pack_hex_byte (pkt, len);
   3247   while (len-- > 0)
   3248     {
   3249       ch = *string++;
   3250       if ((ch == '\0') || (ch == '#'))
   3251 	ch = '*';		/* Protect encapsulation.  */
   3252       *pkt++ = ch;
   3253     }
   3254   return pkt;
   3255 }
   3256 #endif /* 0 (unused) */
   3257 
   3258 static const char *
   3259 unpack_string (const char *src, char *dest, int length)
   3260 {
   3261   while (length--)
   3262     *dest++ = *src++;
   3263   *dest = '\0';
   3264   return src;
   3265 }
   3266 
   3267 static char *
   3268 pack_threadid (char *pkt, threadref *id)
   3269 {
   3270   char *limit;
   3271   unsigned char *altid;
   3272 
   3273   altid = (unsigned char *) id;
   3274   limit = pkt + BUF_THREAD_ID_SIZE;
   3275   while (pkt < limit)
   3276     pkt = pack_hex_byte (pkt, *altid++);
   3277   return pkt;
   3278 }
   3279 
   3280 
   3281 static const char *
   3282 unpack_threadid (const char *inbuf, threadref *id)
   3283 {
   3284   char *altref;
   3285   const char *limit = inbuf + BUF_THREAD_ID_SIZE;
   3286   int x, y;
   3287 
   3288   altref = (char *) id;
   3289 
   3290   while (inbuf < limit)
   3291     {
   3292       x = stubhex (*inbuf++);
   3293       y = stubhex (*inbuf++);
   3294       *altref++ = (x << 4) | y;
   3295     }
   3296   return inbuf;
   3297 }
   3298 
   3299 /* Externally, threadrefs are 64 bits but internally, they are still
   3300    ints.  This is due to a mismatch of specifications.  We would like
   3301    to use 64bit thread references internally.  This is an adapter
   3302    function.  */
   3303 
   3304 void
   3305 int_to_threadref (threadref *id, int value)
   3306 {
   3307   unsigned char *scan;
   3308 
   3309   scan = (unsigned char *) id;
   3310   {
   3311     int i = 4;
   3312     while (i--)
   3313       *scan++ = 0;
   3314   }
   3315   *scan++ = (value >> 24) & 0xff;
   3316   *scan++ = (value >> 16) & 0xff;
   3317   *scan++ = (value >> 8) & 0xff;
   3318   *scan++ = (value & 0xff);
   3319 }
   3320 
   3321 static int
   3322 threadref_to_int (threadref *ref)
   3323 {
   3324   int i, value = 0;
   3325   unsigned char *scan;
   3326 
   3327   scan = *ref;
   3328   scan += 4;
   3329   i = 4;
   3330   while (i-- > 0)
   3331     value = (value << 8) | ((*scan++) & 0xff);
   3332   return value;
   3333 }
   3334 
   3335 static void
   3336 copy_threadref (threadref *dest, threadref *src)
   3337 {
   3338   int i;
   3339   unsigned char *csrc, *cdest;
   3340 
   3341   csrc = (unsigned char *) src;
   3342   cdest = (unsigned char *) dest;
   3343   i = 8;
   3344   while (i--)
   3345     *cdest++ = *csrc++;
   3346 }
   3347 
   3348 static int
   3349 threadmatch (threadref *dest, threadref *src)
   3350 {
   3351   /* Things are broken right now, so just assume we got a match.  */
   3352 #if 0
   3353   unsigned char *srcp, *destp;
   3354   int i, result;
   3355   srcp = (char *) src;
   3356   destp = (char *) dest;
   3357 
   3358   result = 1;
   3359   while (i-- > 0)
   3360     result &= (*srcp++ == *destp++) ? 1 : 0;
   3361   return result;
   3362 #endif
   3363   return 1;
   3364 }
   3365 
   3366 /*
   3367    threadid:1,        # always request threadid
   3368    context_exists:2,
   3369    display:4,
   3370    unique_name:8,
   3371    more_display:16
   3372  */
   3373 
   3374 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
   3375 
   3376 static char *
   3377 pack_threadinfo_request (char *pkt, int mode, threadref *id)
   3378 {
   3379   *pkt++ = 'q';				/* Info Query */
   3380   *pkt++ = 'P';				/* process or thread info */
   3381   pkt = pack_int (pkt, mode);		/* mode */
   3382   pkt = pack_threadid (pkt, id);	/* threadid */
   3383   *pkt = '\0';				/* terminate */
   3384   return pkt;
   3385 }
   3386 
   3387 /* These values tag the fields in a thread info response packet.  */
   3388 /* Tagging the fields allows us to request specific fields and to
   3389    add more fields as time goes by.  */
   3390 
   3391 #define TAG_THREADID 1		/* Echo the thread identifier.  */
   3392 #define TAG_EXISTS 2		/* Is this process defined enough to
   3393 				   fetch registers and its stack?  */
   3394 #define TAG_DISPLAY 4		/* A short thing maybe to put on a window */
   3395 #define TAG_THREADNAME 8	/* string, maps 1-to-1 with a thread is.  */
   3396 #define TAG_MOREDISPLAY 16	/* Whatever the kernel wants to say about
   3397 				   the process.  */
   3398 
   3399 int
   3400 remote_target::remote_unpack_thread_info_response (const char *pkt,
   3401 						   threadref *expectedref,
   3402 						   gdb_ext_thread_info *info)
   3403 {
   3404   struct remote_state *rs = get_remote_state ();
   3405   int mask, length;
   3406   int tag;
   3407   threadref ref;
   3408   const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit.  */
   3409   int retval = 1;
   3410 
   3411   /* info->threadid = 0; FIXME: implement zero_threadref.  */
   3412   info->active = 0;
   3413   info->display[0] = '\0';
   3414   info->shortname[0] = '\0';
   3415   info->more_display[0] = '\0';
   3416 
   3417   /* Assume the characters indicating the packet type have been
   3418      stripped.  */
   3419   pkt = unpack_int (pkt, &mask);	/* arg mask */
   3420   pkt = unpack_threadid (pkt, &ref);
   3421 
   3422   if (mask == 0)
   3423     warning (_("Incomplete response to threadinfo request."));
   3424   if (!threadmatch (&ref, expectedref))
   3425     {			/* This is an answer to a different request.  */
   3426       warning (_("ERROR RMT Thread info mismatch."));
   3427       return 0;
   3428     }
   3429   copy_threadref (&info->threadid, &ref);
   3430 
   3431   /* Loop on tagged fields , try to bail if something goes wrong.  */
   3432 
   3433   /* Packets are terminated with nulls.  */
   3434   while ((pkt < limit) && mask && *pkt)
   3435     {
   3436       pkt = unpack_int (pkt, &tag);	/* tag */
   3437       pkt = unpack_byte (pkt, &length);	/* length */
   3438       if (!(tag & mask))		/* Tags out of synch with mask.  */
   3439 	{
   3440 	  warning (_("ERROR RMT: threadinfo tag mismatch."));
   3441 	  retval = 0;
   3442 	  break;
   3443 	}
   3444       if (tag == TAG_THREADID)
   3445 	{
   3446 	  if (length != 16)
   3447 	    {
   3448 	      warning (_("ERROR RMT: length of threadid is not 16."));
   3449 	      retval = 0;
   3450 	      break;
   3451 	    }
   3452 	  pkt = unpack_threadid (pkt, &ref);
   3453 	  mask = mask & ~TAG_THREADID;
   3454 	  continue;
   3455 	}
   3456       if (tag == TAG_EXISTS)
   3457 	{
   3458 	  info->active = stub_unpack_int (pkt, length);
   3459 	  pkt += length;
   3460 	  mask = mask & ~(TAG_EXISTS);
   3461 	  if (length > 8)
   3462 	    {
   3463 	      warning (_("ERROR RMT: 'exists' length too long."));
   3464 	      retval = 0;
   3465 	      break;
   3466 	    }
   3467 	  continue;
   3468 	}
   3469       if (tag == TAG_THREADNAME)
   3470 	{
   3471 	  pkt = unpack_string (pkt, &info->shortname[0], length);
   3472 	  mask = mask & ~TAG_THREADNAME;
   3473 	  continue;
   3474 	}
   3475       if (tag == TAG_DISPLAY)
   3476 	{
   3477 	  pkt = unpack_string (pkt, &info->display[0], length);
   3478 	  mask = mask & ~TAG_DISPLAY;
   3479 	  continue;
   3480 	}
   3481       if (tag == TAG_MOREDISPLAY)
   3482 	{
   3483 	  pkt = unpack_string (pkt, &info->more_display[0], length);
   3484 	  mask = mask & ~TAG_MOREDISPLAY;
   3485 	  continue;
   3486 	}
   3487       warning (_("ERROR RMT: unknown thread info tag."));
   3488       break;			/* Not a tag we know about.  */
   3489     }
   3490   return retval;
   3491 }
   3492 
   3493 int
   3494 remote_target::remote_get_threadinfo (threadref *threadid,
   3495 				      int fieldset,
   3496 				      gdb_ext_thread_info *info)
   3497 {
   3498   struct remote_state *rs = get_remote_state ();
   3499   int result;
   3500 
   3501   pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
   3502   putpkt (rs->buf);
   3503   getpkt (&rs->buf, 0);
   3504 
   3505   if (rs->buf[0] == '\0')
   3506     return 0;
   3507 
   3508   result = remote_unpack_thread_info_response (&rs->buf[2],
   3509 					       threadid, info);
   3510   return result;
   3511 }
   3512 
   3513 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
   3514 
   3515 static char *
   3516 pack_threadlist_request (char *pkt, int startflag, int threadcount,
   3517 			 threadref *nextthread)
   3518 {
   3519   *pkt++ = 'q';			/* info query packet */
   3520   *pkt++ = 'L';			/* Process LIST or threadLIST request */
   3521   pkt = pack_nibble (pkt, startflag);		/* initflag 1 bytes */
   3522   pkt = pack_hex_byte (pkt, threadcount);	/* threadcount 2 bytes */
   3523   pkt = pack_threadid (pkt, nextthread);	/* 64 bit thread identifier */
   3524   *pkt = '\0';
   3525   return pkt;
   3526 }
   3527 
   3528 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
   3529 
   3530 int
   3531 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
   3532 					  threadref *original_echo,
   3533 					  threadref *resultlist,
   3534 					  int *doneflag)
   3535 {
   3536   struct remote_state *rs = get_remote_state ();
   3537   int count, resultcount, done;
   3538 
   3539   resultcount = 0;
   3540   /* Assume the 'q' and 'M chars have been stripped.  */
   3541   const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
   3542   /* done parse past here */
   3543   pkt = unpack_byte (pkt, &count);	/* count field */
   3544   pkt = unpack_nibble (pkt, &done);
   3545   /* The first threadid is the argument threadid.  */
   3546   pkt = unpack_threadid (pkt, original_echo);	/* should match query packet */
   3547   while ((count-- > 0) && (pkt < limit))
   3548     {
   3549       pkt = unpack_threadid (pkt, resultlist++);
   3550       if (resultcount++ >= result_limit)
   3551 	break;
   3552     }
   3553   if (doneflag)
   3554     *doneflag = done;
   3555   return resultcount;
   3556 }
   3557 
   3558 /* Fetch the next batch of threads from the remote.  Returns -1 if the
   3559    qL packet is not supported, 0 on error and 1 on success.  */
   3560 
   3561 int
   3562 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
   3563 				      int result_limit, int *done, int *result_count,
   3564 				      threadref *threadlist)
   3565 {
   3566   struct remote_state *rs = get_remote_state ();
   3567   int result = 1;
   3568 
   3569   /* Truncate result limit to be smaller than the packet size.  */
   3570   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
   3571       >= get_remote_packet_size ())
   3572     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
   3573 
   3574   pack_threadlist_request (rs->buf.data (), startflag, result_limit,
   3575 			   nextthread);
   3576   putpkt (rs->buf);
   3577   getpkt (&rs->buf, 0);
   3578   if (rs->buf[0] == '\0')
   3579     {
   3580       /* Packet not supported.  */
   3581       return -1;
   3582     }
   3583 
   3584   *result_count =
   3585     parse_threadlist_response (&rs->buf[2], result_limit,
   3586 			       &rs->echo_nextthread, threadlist, done);
   3587 
   3588   if (!threadmatch (&rs->echo_nextthread, nextthread))
   3589     {
   3590       /* FIXME: This is a good reason to drop the packet.  */
   3591       /* Possibly, there is a duplicate response.  */
   3592       /* Possibilities :
   3593 	 retransmit immediatly - race conditions
   3594 	 retransmit after timeout - yes
   3595 	 exit
   3596 	 wait for packet, then exit
   3597        */
   3598       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
   3599       return 0;			/* I choose simply exiting.  */
   3600     }
   3601   if (*result_count <= 0)
   3602     {
   3603       if (*done != 1)
   3604 	{
   3605 	  warning (_("RMT ERROR : failed to get remote thread list."));
   3606 	  result = 0;
   3607 	}
   3608       return result;		/* break; */
   3609     }
   3610   if (*result_count > result_limit)
   3611     {
   3612       *result_count = 0;
   3613       warning (_("RMT ERROR: threadlist response longer than requested."));
   3614       return 0;
   3615     }
   3616   return result;
   3617 }
   3618 
   3619 /* Fetch the list of remote threads, with the qL packet, and call
   3620    STEPFUNCTION for each thread found.  Stops iterating and returns 1
   3621    if STEPFUNCTION returns true.  Stops iterating and returns 0 if the
   3622    STEPFUNCTION returns false.  If the packet is not supported,
   3623    returns -1.  */
   3624 
   3625 int
   3626 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
   3627 					   void *context, int looplimit)
   3628 {
   3629   struct remote_state *rs = get_remote_state ();
   3630   int done, i, result_count;
   3631   int startflag = 1;
   3632   int result = 1;
   3633   int loopcount = 0;
   3634 
   3635   done = 0;
   3636   while (!done)
   3637     {
   3638       if (loopcount++ > looplimit)
   3639 	{
   3640 	  result = 0;
   3641 	  warning (_("Remote fetch threadlist -infinite loop-."));
   3642 	  break;
   3643 	}
   3644       result = remote_get_threadlist (startflag, &rs->nextthread,
   3645 				      MAXTHREADLISTRESULTS,
   3646 				      &done, &result_count,
   3647 				      rs->resultthreadlist);
   3648       if (result <= 0)
   3649 	break;
   3650       /* Clear for later iterations.  */
   3651       startflag = 0;
   3652       /* Setup to resume next batch of thread references, set nextthread.  */
   3653       if (result_count >= 1)
   3654 	copy_threadref (&rs->nextthread,
   3655 			&rs->resultthreadlist[result_count - 1]);
   3656       i = 0;
   3657       while (result_count--)
   3658 	{
   3659 	  if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
   3660 	    {
   3661 	      result = 0;
   3662 	      break;
   3663 	    }
   3664 	}
   3665     }
   3666   return result;
   3667 }
   3668 
   3669 /* A thread found on the remote target.  */
   3670 
   3671 struct thread_item
   3672 {
   3673   explicit thread_item (ptid_t ptid_)
   3674   : ptid (ptid_)
   3675   {}
   3676 
   3677   thread_item (thread_item &&other) = default;
   3678   thread_item &operator= (thread_item &&other) = default;
   3679 
   3680   DISABLE_COPY_AND_ASSIGN (thread_item);
   3681 
   3682   /* The thread's PTID.  */
   3683   ptid_t ptid;
   3684 
   3685   /* The thread's extra info.  */
   3686   std::string extra;
   3687 
   3688   /* The thread's name.  */
   3689   std::string name;
   3690 
   3691   /* The core the thread was running on.  -1 if not known.  */
   3692   int core = -1;
   3693 
   3694   /* The thread handle associated with the thread.  */
   3695   gdb::byte_vector thread_handle;
   3696 };
   3697 
   3698 /* Context passed around to the various methods listing remote
   3699    threads.  As new threads are found, they're added to the ITEMS
   3700    vector.  */
   3701 
   3702 struct threads_listing_context
   3703 {
   3704   /* Return true if this object contains an entry for a thread with ptid
   3705      PTID.  */
   3706 
   3707   bool contains_thread (ptid_t ptid) const
   3708   {
   3709     auto match_ptid = [&] (const thread_item &item)
   3710       {
   3711 	return item.ptid == ptid;
   3712       };
   3713 
   3714     auto it = std::find_if (this->items.begin (),
   3715 			    this->items.end (),
   3716 			    match_ptid);
   3717 
   3718     return it != this->items.end ();
   3719   }
   3720 
   3721   /* Remove the thread with ptid PTID.  */
   3722 
   3723   void remove_thread (ptid_t ptid)
   3724   {
   3725     auto match_ptid = [&] (const thread_item &item)
   3726       {
   3727 	return item.ptid == ptid;
   3728       };
   3729 
   3730     auto it = std::remove_if (this->items.begin (),
   3731 			      this->items.end (),
   3732 			      match_ptid);
   3733 
   3734     if (it != this->items.end ())
   3735       this->items.erase (it);
   3736   }
   3737 
   3738   /* The threads found on the remote target.  */
   3739   std::vector<thread_item> items;
   3740 };
   3741 
   3742 static int
   3743 remote_newthread_step (threadref *ref, void *data)
   3744 {
   3745   struct threads_listing_context *context
   3746     = (struct threads_listing_context *) data;
   3747   int pid = inferior_ptid.pid ();
   3748   int lwp = threadref_to_int (ref);
   3749   ptid_t ptid (pid, lwp);
   3750 
   3751   context->items.emplace_back (ptid);
   3752 
   3753   return 1;			/* continue iterator */
   3754 }
   3755 
   3756 #define CRAZY_MAX_THREADS 1000
   3757 
   3758 ptid_t
   3759 remote_target::remote_current_thread (ptid_t oldpid)
   3760 {
   3761   struct remote_state *rs = get_remote_state ();
   3762 
   3763   putpkt ("qC");
   3764   getpkt (&rs->buf, 0);
   3765   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
   3766     {
   3767       const char *obuf;
   3768       ptid_t result;
   3769 
   3770       result = read_ptid (&rs->buf[2], &obuf);
   3771       if (*obuf != '\0')
   3772 	remote_debug_printf ("warning: garbage in qC reply");
   3773 
   3774       return result;
   3775     }
   3776   else
   3777     return oldpid;
   3778 }
   3779 
   3780 /* List remote threads using the deprecated qL packet.  */
   3781 
   3782 int
   3783 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
   3784 {
   3785   if (remote_threadlist_iterator (remote_newthread_step, context,
   3786 				  CRAZY_MAX_THREADS) >= 0)
   3787     return 1;
   3788 
   3789   return 0;
   3790 }
   3791 
   3792 #if defined(HAVE_LIBEXPAT)
   3793 
   3794 static void
   3795 start_thread (struct gdb_xml_parser *parser,
   3796 	      const struct gdb_xml_element *element,
   3797 	      void *user_data,
   3798 	      std::vector<gdb_xml_value> &attributes)
   3799 {
   3800   struct threads_listing_context *data
   3801     = (struct threads_listing_context *) user_data;
   3802   struct gdb_xml_value *attr;
   3803 
   3804   char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
   3805   ptid_t ptid = read_ptid (id, NULL);
   3806 
   3807   data->items.emplace_back (ptid);
   3808   thread_item &item = data->items.back ();
   3809 
   3810   attr = xml_find_attribute (attributes, "core");
   3811   if (attr != NULL)
   3812     item.core = *(ULONGEST *) attr->value.get ();
   3813 
   3814   attr = xml_find_attribute (attributes, "name");
   3815   if (attr != NULL)
   3816     item.name = (const char *) attr->value.get ();
   3817 
   3818   attr = xml_find_attribute (attributes, "handle");
   3819   if (attr != NULL)
   3820     item.thread_handle = hex2bin ((const char *) attr->value.get ());
   3821 }
   3822 
   3823 static void
   3824 end_thread (struct gdb_xml_parser *parser,
   3825 	    const struct gdb_xml_element *element,
   3826 	    void *user_data, const char *body_text)
   3827 {
   3828   struct threads_listing_context *data
   3829     = (struct threads_listing_context *) user_data;
   3830 
   3831   if (body_text != NULL && *body_text != '\0')
   3832     data->items.back ().extra = body_text;
   3833 }
   3834 
   3835 const struct gdb_xml_attribute thread_attributes[] = {
   3836   { "id", GDB_XML_AF_NONE, NULL, NULL },
   3837   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
   3838   { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
   3839   { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
   3840   { NULL, GDB_XML_AF_NONE, NULL, NULL }
   3841 };
   3842 
   3843 const struct gdb_xml_element thread_children[] = {
   3844   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
   3845 };
   3846 
   3847 const struct gdb_xml_element threads_children[] = {
   3848   { "thread", thread_attributes, thread_children,
   3849     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
   3850     start_thread, end_thread },
   3851   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
   3852 };
   3853 
   3854 const struct gdb_xml_element threads_elements[] = {
   3855   { "threads", NULL, threads_children,
   3856     GDB_XML_EF_NONE, NULL, NULL },
   3857   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
   3858 };
   3859 
   3860 #endif
   3861 
   3862 /* List remote threads using qXfer:threads:read.  */
   3863 
   3864 int
   3865 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
   3866 {
   3867 #if defined(HAVE_LIBEXPAT)
   3868   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
   3869     {
   3870       gdb::optional<gdb::char_vector> xml
   3871 	= target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
   3872 
   3873       if (xml && (*xml)[0] != '\0')
   3874 	{
   3875 	  gdb_xml_parse_quick (_("threads"), "threads.dtd",
   3876 			       threads_elements, xml->data (), context);
   3877 	}
   3878 
   3879       return 1;
   3880     }
   3881 #endif
   3882 
   3883   return 0;
   3884 }
   3885 
   3886 /* List remote threads using qfThreadInfo/qsThreadInfo.  */
   3887 
   3888 int
   3889 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
   3890 {
   3891   struct remote_state *rs = get_remote_state ();
   3892 
   3893   if (rs->use_threadinfo_query)
   3894     {
   3895       const char *bufp;
   3896 
   3897       putpkt ("qfThreadInfo");
   3898       getpkt (&rs->buf, 0);
   3899       bufp = rs->buf.data ();
   3900       if (bufp[0] != '\0')		/* q packet recognized */
   3901 	{
   3902 	  while (*bufp++ == 'm')	/* reply contains one or more TID */
   3903 	    {
   3904 	      do
   3905 		{
   3906 		  ptid_t ptid = read_ptid (bufp, &bufp);
   3907 		  context->items.emplace_back (ptid);
   3908 		}
   3909 	      while (*bufp++ == ',');	/* comma-separated list */
   3910 	      putpkt ("qsThreadInfo");
   3911 	      getpkt (&rs->buf, 0);
   3912 	      bufp = rs->buf.data ();
   3913 	    }
   3914 	  return 1;
   3915 	}
   3916       else
   3917 	{
   3918 	  /* Packet not recognized.  */
   3919 	  rs->use_threadinfo_query = 0;
   3920 	}
   3921     }
   3922 
   3923   return 0;
   3924 }
   3925 
   3926 /* Return true if INF only has one non-exited thread.  */
   3927 
   3928 static bool
   3929 has_single_non_exited_thread (inferior *inf)
   3930 {
   3931   int count = 0;
   3932   for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
   3933     if (++count > 1)
   3934       break;
   3935   return count == 1;
   3936 }
   3937 
   3938 /* Implement the to_update_thread_list function for the remote
   3939    targets.  */
   3940 
   3941 void
   3942 remote_target::update_thread_list ()
   3943 {
   3944   struct threads_listing_context context;
   3945   int got_list = 0;
   3946 
   3947   /* We have a few different mechanisms to fetch the thread list.  Try
   3948      them all, starting with the most preferred one first, falling
   3949      back to older methods.  */
   3950   if (remote_get_threads_with_qxfer (&context)
   3951       || remote_get_threads_with_qthreadinfo (&context)
   3952       || remote_get_threads_with_ql (&context))
   3953     {
   3954       got_list = 1;
   3955 
   3956       if (context.items.empty ()
   3957 	  && remote_thread_always_alive (inferior_ptid))
   3958 	{
   3959 	  /* Some targets don't really support threads, but still
   3960 	     reply an (empty) thread list in response to the thread
   3961 	     listing packets, instead of replying "packet not
   3962 	     supported".  Exit early so we don't delete the main
   3963 	     thread.  */
   3964 	  return;
   3965 	}
   3966 
   3967       /* CONTEXT now holds the current thread list on the remote
   3968 	 target end.  Delete GDB-side threads no longer found on the
   3969 	 target.  */
   3970       for (thread_info *tp : all_threads_safe ())
   3971 	{
   3972 	  if (tp->inf->process_target () != this)
   3973 	    continue;
   3974 
   3975 	  if (!context.contains_thread (tp->ptid))
   3976 	    {
   3977 	      /* Do not remove the thread if it is the last thread in
   3978 		 the inferior.  This situation happens when we have a
   3979 		 pending exit process status to process.  Otherwise we
   3980 		 may end up with a seemingly live inferior (i.e.  pid
   3981 		 != 0) that has no threads.  */
   3982 	      if (has_single_non_exited_thread (tp->inf))
   3983 		continue;
   3984 
   3985 	      /* Not found.  */
   3986 	      delete_thread (tp);
   3987 	    }
   3988 	}
   3989 
   3990       /* Remove any unreported fork child threads from CONTEXT so
   3991 	 that we don't interfere with follow fork, which is where
   3992 	 creation of such threads is handled.  */
   3993       remove_new_fork_children (&context);
   3994 
   3995       /* And now add threads we don't know about yet to our list.  */
   3996       for (thread_item &item : context.items)
   3997 	{
   3998 	  if (item.ptid != null_ptid)
   3999 	    {
   4000 	      /* In non-stop mode, we assume new found threads are
   4001 		 executing until proven otherwise with a stop reply.
   4002 		 In all-stop, we can only get here if all threads are
   4003 		 stopped.  */
   4004 	      bool executing = target_is_non_stop_p ();
   4005 
   4006 	      remote_notice_new_inferior (item.ptid, executing);
   4007 
   4008 	      thread_info *tp = find_thread_ptid (this, item.ptid);
   4009 	      remote_thread_info *info = get_remote_thread_info (tp);
   4010 	      info->core = item.core;
   4011 	      info->extra = std::move (item.extra);
   4012 	      info->name = std::move (item.name);
   4013 	      info->thread_handle = std::move (item.thread_handle);
   4014 	    }
   4015 	}
   4016     }
   4017 
   4018   if (!got_list)
   4019     {
   4020       /* If no thread listing method is supported, then query whether
   4021 	 each known thread is alive, one by one, with the T packet.
   4022 	 If the target doesn't support threads at all, then this is a
   4023 	 no-op.  See remote_thread_alive.  */
   4024       prune_threads ();
   4025     }
   4026 }
   4027 
   4028 /*
   4029  * Collect a descriptive string about the given thread.
   4030  * The target may say anything it wants to about the thread
   4031  * (typically info about its blocked / runnable state, name, etc.).
   4032  * This string will appear in the info threads display.
   4033  *
   4034  * Optional: targets are not required to implement this function.
   4035  */
   4036 
   4037 const char *
   4038 remote_target::extra_thread_info (thread_info *tp)
   4039 {
   4040   struct remote_state *rs = get_remote_state ();
   4041   int set;
   4042   threadref id;
   4043   struct gdb_ext_thread_info threadinfo;
   4044 
   4045   if (rs->remote_desc == 0)		/* paranoia */
   4046     internal_error (_("remote_threads_extra_info"));
   4047 
   4048   if (tp->ptid == magic_null_ptid
   4049       || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
   4050     /* This is the main thread which was added by GDB.  The remote
   4051        server doesn't know about it.  */
   4052     return NULL;
   4053 
   4054   std::string &extra = get_remote_thread_info (tp)->extra;
   4055 
   4056   /* If already have cached info, use it.  */
   4057   if (!extra.empty ())
   4058     return extra.c_str ();
   4059 
   4060   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
   4061     {
   4062       /* If we're using qXfer:threads:read, then the extra info is
   4063 	 included in the XML.  So if we didn't have anything cached,
   4064 	 it's because there's really no extra info.  */
   4065       return NULL;
   4066     }
   4067 
   4068   if (rs->use_threadextra_query)
   4069     {
   4070       char *b = rs->buf.data ();
   4071       char *endb = b + get_remote_packet_size ();
   4072 
   4073       xsnprintf (b, endb - b, "qThreadExtraInfo,");
   4074       b += strlen (b);
   4075       write_ptid (b, endb, tp->ptid);
   4076 
   4077       putpkt (rs->buf);
   4078       getpkt (&rs->buf, 0);
   4079       if (rs->buf[0] != 0)
   4080 	{
   4081 	  extra.resize (strlen (rs->buf.data ()) / 2);
   4082 	  hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
   4083 	  return extra.c_str ();
   4084 	}
   4085     }
   4086 
   4087   /* If the above query fails, fall back to the old method.  */
   4088   rs->use_threadextra_query = 0;
   4089   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
   4090     | TAG_MOREDISPLAY | TAG_DISPLAY;
   4091   int_to_threadref (&id, tp->ptid.lwp ());
   4092   if (remote_get_threadinfo (&id, set, &threadinfo))
   4093     if (threadinfo.active)
   4094       {
   4095 	if (*threadinfo.shortname)
   4096 	  string_appendf (extra, " Name: %s", threadinfo.shortname);
   4097 	if (*threadinfo.display)
   4098 	  {
   4099 	    if (!extra.empty ())
   4100 	      extra += ',';
   4101 	    string_appendf (extra, " State: %s", threadinfo.display);
   4102 	  }
   4103 	if (*threadinfo.more_display)
   4104 	  {
   4105 	    if (!extra.empty ())
   4106 	      extra += ',';
   4107 	    string_appendf (extra, " Priority: %s", threadinfo.more_display);
   4108 	  }
   4109 	return extra.c_str ();
   4110       }
   4111   return NULL;
   4112 }
   4113 
   4114 
   4116 bool
   4117 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
   4118 					    struct static_tracepoint_marker *marker)
   4119 {
   4120   struct remote_state *rs = get_remote_state ();
   4121   char *p = rs->buf.data ();
   4122 
   4123   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
   4124   p += strlen (p);
   4125   p += hexnumstr (p, addr);
   4126   putpkt (rs->buf);
   4127   getpkt (&rs->buf, 0);
   4128   p = rs->buf.data ();
   4129 
   4130   if (*p == 'E')
   4131     error (_("Remote failure reply: %s"), p);
   4132 
   4133   if (*p++ == 'm')
   4134     {
   4135       parse_static_tracepoint_marker_definition (p, NULL, marker);
   4136       return true;
   4137     }
   4138 
   4139   return false;
   4140 }
   4141 
   4142 std::vector<static_tracepoint_marker>
   4143 remote_target::static_tracepoint_markers_by_strid (const char *strid)
   4144 {
   4145   struct remote_state *rs = get_remote_state ();
   4146   std::vector<static_tracepoint_marker> markers;
   4147   const char *p;
   4148   static_tracepoint_marker marker;
   4149 
   4150   /* Ask for a first packet of static tracepoint marker
   4151      definition.  */
   4152   putpkt ("qTfSTM");
   4153   getpkt (&rs->buf, 0);
   4154   p = rs->buf.data ();
   4155   if (*p == 'E')
   4156     error (_("Remote failure reply: %s"), p);
   4157 
   4158   while (*p++ == 'm')
   4159     {
   4160       do
   4161 	{
   4162 	  parse_static_tracepoint_marker_definition (p, &p, &marker);
   4163 
   4164 	  if (strid == NULL || marker.str_id == strid)
   4165 	    markers.push_back (std::move (marker));
   4166 	}
   4167       while (*p++ == ',');	/* comma-separated list */
   4168       /* Ask for another packet of static tracepoint definition.  */
   4169       putpkt ("qTsSTM");
   4170       getpkt (&rs->buf, 0);
   4171       p = rs->buf.data ();
   4172     }
   4173 
   4174   return markers;
   4175 }
   4176 
   4177 
   4178 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
   4180 
   4181 ptid_t
   4182 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
   4183 {
   4184   return ptid_t (inferior_ptid.pid (), lwp);
   4185 }
   4186 
   4187 
   4189 /* Restart the remote side; this is an extended protocol operation.  */
   4190 
   4191 void
   4192 remote_target::extended_remote_restart ()
   4193 {
   4194   struct remote_state *rs = get_remote_state ();
   4195 
   4196   /* Send the restart command; for reasons I don't understand the
   4197      remote side really expects a number after the "R".  */
   4198   xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
   4199   putpkt (rs->buf);
   4200 
   4201   remote_fileio_reset ();
   4202 }
   4203 
   4204 /* Clean up connection to a remote debugger.  */
   4206 
   4207 void
   4208 remote_target::close ()
   4209 {
   4210   /* Make sure we leave stdin registered in the event loop.  */
   4211   terminal_ours ();
   4212 
   4213   trace_reset_local_state ();
   4214 
   4215   delete this;
   4216 }
   4217 
   4218 remote_target::~remote_target ()
   4219 {
   4220   struct remote_state *rs = get_remote_state ();
   4221 
   4222   /* Check for NULL because we may get here with a partially
   4223      constructed target/connection.  */
   4224   if (rs->remote_desc == nullptr)
   4225     return;
   4226 
   4227   serial_close (rs->remote_desc);
   4228 
   4229   /* We are destroying the remote target, so we should discard
   4230      everything of this target.  */
   4231   discard_pending_stop_replies_in_queue ();
   4232 
   4233   if (rs->remote_async_inferior_event_token)
   4234     delete_async_event_handler (&rs->remote_async_inferior_event_token);
   4235 
   4236   delete rs->notif_state;
   4237 }
   4238 
   4239 /* Query the remote side for the text, data and bss offsets.  */
   4240 
   4241 void
   4242 remote_target::get_offsets ()
   4243 {
   4244   struct remote_state *rs = get_remote_state ();
   4245   char *buf;
   4246   char *ptr;
   4247   int lose, num_segments = 0, do_sections, do_segments;
   4248   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
   4249 
   4250   if (current_program_space->symfile_object_file == NULL)
   4251     return;
   4252 
   4253   putpkt ("qOffsets");
   4254   getpkt (&rs->buf, 0);
   4255   buf = rs->buf.data ();
   4256 
   4257   if (buf[0] == '\000')
   4258     return;			/* Return silently.  Stub doesn't support
   4259 				   this command.  */
   4260   if (buf[0] == 'E')
   4261     {
   4262       warning (_("Remote failure reply: %s"), buf);
   4263       return;
   4264     }
   4265 
   4266   /* Pick up each field in turn.  This used to be done with scanf, but
   4267      scanf will make trouble if CORE_ADDR size doesn't match
   4268      conversion directives correctly.  The following code will work
   4269      with any size of CORE_ADDR.  */
   4270   text_addr = data_addr = bss_addr = 0;
   4271   ptr = buf;
   4272   lose = 0;
   4273 
   4274   if (startswith (ptr, "Text="))
   4275     {
   4276       ptr += 5;
   4277       /* Don't use strtol, could lose on big values.  */
   4278       while (*ptr && *ptr != ';')
   4279 	text_addr = (text_addr << 4) + fromhex (*ptr++);
   4280 
   4281       if (startswith (ptr, ";Data="))
   4282 	{
   4283 	  ptr += 6;
   4284 	  while (*ptr && *ptr != ';')
   4285 	    data_addr = (data_addr << 4) + fromhex (*ptr++);
   4286 	}
   4287       else
   4288 	lose = 1;
   4289 
   4290       if (!lose && startswith (ptr, ";Bss="))
   4291 	{
   4292 	  ptr += 5;
   4293 	  while (*ptr && *ptr != ';')
   4294 	    bss_addr = (bss_addr << 4) + fromhex (*ptr++);
   4295 
   4296 	  if (bss_addr != data_addr)
   4297 	    warning (_("Target reported unsupported offsets: %s"), buf);
   4298 	}
   4299       else
   4300 	lose = 1;
   4301     }
   4302   else if (startswith (ptr, "TextSeg="))
   4303     {
   4304       ptr += 8;
   4305       /* Don't use strtol, could lose on big values.  */
   4306       while (*ptr && *ptr != ';')
   4307 	text_addr = (text_addr << 4) + fromhex (*ptr++);
   4308       num_segments = 1;
   4309 
   4310       if (startswith (ptr, ";DataSeg="))
   4311 	{
   4312 	  ptr += 9;
   4313 	  while (*ptr && *ptr != ';')
   4314 	    data_addr = (data_addr << 4) + fromhex (*ptr++);
   4315 	  num_segments++;
   4316 	}
   4317     }
   4318   else
   4319     lose = 1;
   4320 
   4321   if (lose)
   4322     error (_("Malformed response to offset query, %s"), buf);
   4323   else if (*ptr != '\0')
   4324     warning (_("Target reported unsupported offsets: %s"), buf);
   4325 
   4326   objfile *objf = current_program_space->symfile_object_file;
   4327   section_offsets offs = objf->section_offsets;
   4328 
   4329   symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
   4330   do_segments = (data != NULL);
   4331   do_sections = num_segments == 0;
   4332 
   4333   if (num_segments > 0)
   4334     {
   4335       segments[0] = text_addr;
   4336       segments[1] = data_addr;
   4337     }
   4338   /* If we have two segments, we can still try to relocate everything
   4339      by assuming that the .text and .data offsets apply to the whole
   4340      text and data segments.  Convert the offsets given in the packet
   4341      to base addresses for symfile_map_offsets_to_segments.  */
   4342   else if (data != nullptr && data->segments.size () == 2)
   4343     {
   4344       segments[0] = data->segments[0].base + text_addr;
   4345       segments[1] = data->segments[1].base + data_addr;
   4346       num_segments = 2;
   4347     }
   4348   /* If the object file has only one segment, assume that it is text
   4349      rather than data; main programs with no writable data are rare,
   4350      but programs with no code are useless.  Of course the code might
   4351      have ended up in the data segment... to detect that we would need
   4352      the permissions here.  */
   4353   else if (data && data->segments.size () == 1)
   4354     {
   4355       segments[0] = data->segments[0].base + text_addr;
   4356       num_segments = 1;
   4357     }
   4358   /* There's no way to relocate by segment.  */
   4359   else
   4360     do_segments = 0;
   4361 
   4362   if (do_segments)
   4363     {
   4364       int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
   4365 						 data.get (), offs,
   4366 						 num_segments, segments);
   4367 
   4368       if (ret == 0 && !do_sections)
   4369 	error (_("Can not handle qOffsets TextSeg "
   4370 		 "response with this symbol file"));
   4371 
   4372       if (ret > 0)
   4373 	do_sections = 0;
   4374     }
   4375 
   4376   if (do_sections)
   4377     {
   4378       offs[SECT_OFF_TEXT (objf)] = text_addr;
   4379 
   4380       /* This is a temporary kludge to force data and bss to use the
   4381 	 same offsets because that's what nlmconv does now.  The real
   4382 	 solution requires changes to the stub and remote.c that I
   4383 	 don't have time to do right now.  */
   4384 
   4385       offs[SECT_OFF_DATA (objf)] = data_addr;
   4386       offs[SECT_OFF_BSS (objf)] = data_addr;
   4387     }
   4388 
   4389   objfile_relocate (objf, offs);
   4390 }
   4391 
   4392 /* Send interrupt_sequence to remote target.  */
   4393 
   4394 void
   4395 remote_target::send_interrupt_sequence ()
   4396 {
   4397   struct remote_state *rs = get_remote_state ();
   4398 
   4399   if (interrupt_sequence_mode == interrupt_sequence_control_c)
   4400     remote_serial_write ("\x03", 1);
   4401   else if (interrupt_sequence_mode == interrupt_sequence_break)
   4402     serial_send_break (rs->remote_desc);
   4403   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
   4404     {
   4405       serial_send_break (rs->remote_desc);
   4406       remote_serial_write ("g", 1);
   4407     }
   4408   else
   4409     internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
   4410 		    interrupt_sequence_mode);
   4411 }
   4412 
   4413 
   4414 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
   4415    and extract the PTID.  Returns NULL_PTID if not found.  */
   4416 
   4417 static ptid_t
   4418 stop_reply_extract_thread (const char *stop_reply)
   4419 {
   4420   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
   4421     {
   4422       const char *p;
   4423 
   4424       /* Txx r:val ; r:val (...)  */
   4425       p = &stop_reply[3];
   4426 
   4427       /* Look for "register" named "thread".  */
   4428       while (*p != '\0')
   4429 	{
   4430 	  const char *p1;
   4431 
   4432 	  p1 = strchr (p, ':');
   4433 	  if (p1 == NULL)
   4434 	    return null_ptid;
   4435 
   4436 	  if (strncmp (p, "thread", p1 - p) == 0)
   4437 	    return read_ptid (++p1, &p);
   4438 
   4439 	  p1 = strchr (p, ';');
   4440 	  if (p1 == NULL)
   4441 	    return null_ptid;
   4442 	  p1++;
   4443 
   4444 	  p = p1;
   4445 	}
   4446     }
   4447 
   4448   return null_ptid;
   4449 }
   4450 
   4451 /* Determine the remote side's current thread.  If we have a stop
   4452    reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
   4453    "thread" register we can extract the current thread from.  If not,
   4454    ask the remote which is the current thread with qC.  The former
   4455    method avoids a roundtrip.  */
   4456 
   4457 ptid_t
   4458 remote_target::get_current_thread (const char *wait_status)
   4459 {
   4460   ptid_t ptid = null_ptid;
   4461 
   4462   /* Note we don't use remote_parse_stop_reply as that makes use of
   4463      the target architecture, which we haven't yet fully determined at
   4464      this point.  */
   4465   if (wait_status != NULL)
   4466     ptid = stop_reply_extract_thread (wait_status);
   4467   if (ptid == null_ptid)
   4468     ptid = remote_current_thread (inferior_ptid);
   4469 
   4470   return ptid;
   4471 }
   4472 
   4473 /* Query the remote target for which is the current thread/process,
   4474    add it to our tables, and update INFERIOR_PTID.  The caller is
   4475    responsible for setting the state such that the remote end is ready
   4476    to return the current thread.
   4477 
   4478    This function is called after handling the '?' or 'vRun' packets,
   4479    whose response is a stop reply from which we can also try
   4480    extracting the thread.  If the target doesn't support the explicit
   4481    qC query, we infer the current thread from that stop reply, passed
   4482    in in WAIT_STATUS, which may be NULL.
   4483 
   4484    The function returns pointer to the main thread of the inferior. */
   4485 
   4486 thread_info *
   4487 remote_target::add_current_inferior_and_thread (const char *wait_status)
   4488 {
   4489   struct remote_state *rs = get_remote_state ();
   4490   bool fake_pid_p = false;
   4491 
   4492   switch_to_no_thread ();
   4493 
   4494   /* Now, if we have thread information, update the current thread's
   4495      ptid.  */
   4496   ptid_t curr_ptid = get_current_thread (wait_status);
   4497 
   4498   if (curr_ptid != null_ptid)
   4499     {
   4500       if (!remote_multi_process_p (rs))
   4501 	fake_pid_p = true;
   4502     }
   4503   else
   4504     {
   4505       /* Without this, some commands which require an active target
   4506 	 (such as kill) won't work.  This variable serves (at least)
   4507 	 double duty as both the pid of the target process (if it has
   4508 	 such), and as a flag indicating that a target is active.  */
   4509       curr_ptid = magic_null_ptid;
   4510       fake_pid_p = true;
   4511     }
   4512 
   4513   remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
   4514 
   4515   /* Add the main thread and switch to it.  Don't try reading
   4516      registers yet, since we haven't fetched the target description
   4517      yet.  */
   4518   thread_info *tp = add_thread_silent (this, curr_ptid);
   4519   switch_to_thread_no_regs (tp);
   4520 
   4521   return tp;
   4522 }
   4523 
   4524 /* Print info about a thread that was found already stopped on
   4525    connection.  */
   4526 
   4527 void
   4528 remote_target::print_one_stopped_thread (thread_info *thread)
   4529 {
   4530   target_waitstatus ws;
   4531 
   4532   /* If there is a pending waitstatus, use it.  If there isn't it's because
   4533      the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
   4534      and process_initial_stop_replies decided it wasn't interesting to save
   4535      and report to the core.  */
   4536   if (thread->has_pending_waitstatus ())
   4537     {
   4538       ws = thread->pending_waitstatus ();
   4539       thread->clear_pending_waitstatus ();
   4540     }
   4541   else
   4542     {
   4543       ws.set_stopped (GDB_SIGNAL_0);
   4544     }
   4545 
   4546   switch_to_thread (thread);
   4547   thread->set_stop_pc (get_frame_pc (get_current_frame ()));
   4548   set_current_sal_from_frame (get_current_frame ());
   4549 
   4550   /* For "info program".  */
   4551   set_last_target_status (this, thread->ptid, ws);
   4552 
   4553   if (ws.kind () == TARGET_WAITKIND_STOPPED)
   4554     {
   4555       enum gdb_signal sig = ws.sig ();
   4556 
   4557       if (signal_print_state (sig))
   4558 	gdb::observers::signal_received.notify (sig);
   4559     }
   4560   gdb::observers::normal_stop.notify (NULL, 1);
   4561 }
   4562 
   4563 /* Process all initial stop replies the remote side sent in response
   4564    to the ? packet.  These indicate threads that were already stopped
   4565    on initial connection.  We mark these threads as stopped and print
   4566    their current frame before giving the user the prompt.  */
   4567 
   4568 void
   4569 remote_target::process_initial_stop_replies (int from_tty)
   4570 {
   4571   int pending_stop_replies = stop_reply_queue_length ();
   4572   struct thread_info *selected = NULL;
   4573   struct thread_info *lowest_stopped = NULL;
   4574   struct thread_info *first = NULL;
   4575 
   4576   /* This is only used when the target is non-stop.  */
   4577   gdb_assert (target_is_non_stop_p ());
   4578 
   4579   /* Consume the initial pending events.  */
   4580   while (pending_stop_replies-- > 0)
   4581     {
   4582       ptid_t waiton_ptid = minus_one_ptid;
   4583       ptid_t event_ptid;
   4584       struct target_waitstatus ws;
   4585       int ignore_event = 0;
   4586 
   4587       event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
   4588       if (remote_debug)
   4589 	print_target_wait_results (waiton_ptid, event_ptid, ws);
   4590 
   4591       switch (ws.kind ())
   4592 	{
   4593 	case TARGET_WAITKIND_IGNORE:
   4594 	case TARGET_WAITKIND_NO_RESUMED:
   4595 	case TARGET_WAITKIND_SIGNALLED:
   4596 	case TARGET_WAITKIND_EXITED:
   4597 	  /* We shouldn't see these, but if we do, just ignore.  */
   4598 	  remote_debug_printf ("event ignored");
   4599 	  ignore_event = 1;
   4600 	  break;
   4601 
   4602 	default:
   4603 	  break;
   4604 	}
   4605 
   4606       if (ignore_event)
   4607 	continue;
   4608 
   4609       thread_info *evthread = find_thread_ptid (this, event_ptid);
   4610 
   4611       if (ws.kind () == TARGET_WAITKIND_STOPPED)
   4612 	{
   4613 	  enum gdb_signal sig = ws.sig ();
   4614 
   4615 	  /* Stubs traditionally report SIGTRAP as initial signal,
   4616 	     instead of signal 0.  Suppress it.  */
   4617 	  if (sig == GDB_SIGNAL_TRAP)
   4618 	    sig = GDB_SIGNAL_0;
   4619 	  evthread->set_stop_signal (sig);
   4620 	  ws.set_stopped (sig);
   4621 	}
   4622 
   4623       if (ws.kind () != TARGET_WAITKIND_STOPPED
   4624 	  || ws.sig () != GDB_SIGNAL_0)
   4625 	evthread->set_pending_waitstatus (ws);
   4626 
   4627       set_executing (this, event_ptid, false);
   4628       set_running (this, event_ptid, false);
   4629       get_remote_thread_info (evthread)->set_not_resumed ();
   4630     }
   4631 
   4632   /* "Notice" the new inferiors before anything related to
   4633      registers/memory.  */
   4634   for (inferior *inf : all_non_exited_inferiors (this))
   4635     {
   4636       inf->needs_setup = true;
   4637 
   4638       if (non_stop)
   4639 	{
   4640 	  thread_info *thread = any_live_thread_of_inferior (inf);
   4641 	  notice_new_inferior (thread, thread->state == THREAD_RUNNING,
   4642 			       from_tty);
   4643 	}
   4644     }
   4645 
   4646   /* If all-stop on top of non-stop, pause all threads.  Note this
   4647      records the threads' stop pc, so must be done after "noticing"
   4648      the inferiors.  */
   4649   if (!non_stop)
   4650     {
   4651       {
   4652 	/* At this point, the remote target is not async.  It needs to be for
   4653 	   the poll in stop_all_threads to consider events from it, so enable
   4654 	   it temporarily.  */
   4655 	gdb_assert (!this->is_async_p ());
   4656 	SCOPE_EXIT { target_async (false); };
   4657 	target_async (true);
   4658 	stop_all_threads ("remote connect in all-stop");
   4659       }
   4660 
   4661       /* If all threads of an inferior were already stopped, we
   4662 	 haven't setup the inferior yet.  */
   4663       for (inferior *inf : all_non_exited_inferiors (this))
   4664 	{
   4665 	  if (inf->needs_setup)
   4666 	    {
   4667 	      thread_info *thread = any_live_thread_of_inferior (inf);
   4668 	      switch_to_thread_no_regs (thread);
   4669 	      setup_inferior (0);
   4670 	    }
   4671 	}
   4672     }
   4673 
   4674   /* Now go over all threads that are stopped, and print their current
   4675      frame.  If all-stop, then if there's a signalled thread, pick
   4676      that as current.  */
   4677   for (thread_info *thread : all_non_exited_threads (this))
   4678     {
   4679       if (first == NULL)
   4680 	first = thread;
   4681 
   4682       if (!non_stop)
   4683 	thread->set_running (false);
   4684       else if (thread->state != THREAD_STOPPED)
   4685 	continue;
   4686 
   4687       if (selected == nullptr && thread->has_pending_waitstatus ())
   4688 	selected = thread;
   4689 
   4690       if (lowest_stopped == NULL
   4691 	  || thread->inf->num < lowest_stopped->inf->num
   4692 	  || thread->per_inf_num < lowest_stopped->per_inf_num)
   4693 	lowest_stopped = thread;
   4694 
   4695       if (non_stop)
   4696 	print_one_stopped_thread (thread);
   4697     }
   4698 
   4699   /* In all-stop, we only print the status of one thread, and leave
   4700      others with their status pending.  */
   4701   if (!non_stop)
   4702     {
   4703       thread_info *thread = selected;
   4704       if (thread == NULL)
   4705 	thread = lowest_stopped;
   4706       if (thread == NULL)
   4707 	thread = first;
   4708 
   4709       print_one_stopped_thread (thread);
   4710     }
   4711 }
   4712 
   4713 /* Mark a remote_target as starting (by setting the starting_up flag within
   4714    its remote_state) for the lifetime of this object.  The reference count
   4715    on the remote target is temporarily incremented, to prevent the target
   4716    being deleted under our feet.  */
   4717 
   4718 struct scoped_mark_target_starting
   4719 {
   4720   /* Constructor, TARGET is the target to be marked as starting, its
   4721      reference count will be incremented.  */
   4722   scoped_mark_target_starting (remote_target *target)
   4723     : m_remote_target (remote_target_ref::new_reference (target)),
   4724       m_restore_starting_up (set_starting_up_flag (target))
   4725   { /* Nothing.  */ }
   4726 
   4727 private:
   4728 
   4729   /* Helper function, set the starting_up flag on TARGET and return an
   4730      object which, when it goes out of scope, will restore the previous
   4731      value of the starting_up flag.  */
   4732   static scoped_restore_tmpl<bool>
   4733   set_starting_up_flag (remote_target *target)
   4734   {
   4735     remote_state *rs = target->get_remote_state ();
   4736     gdb_assert (!rs->starting_up);
   4737     return make_scoped_restore (&rs->starting_up, true);
   4738   }
   4739 
   4740   /* A gdb::ref_ptr pointer to a remote_target.  */
   4741   using remote_target_ref = gdb::ref_ptr<remote_target, target_ops_ref_policy>;
   4742 
   4743   /* A reference to the target on which we are operating.  */
   4744   remote_target_ref m_remote_target;
   4745 
   4746   /* An object which restores the previous value of the starting_up flag
   4747      when it goes out of scope.  */
   4748   scoped_restore_tmpl<bool> m_restore_starting_up;
   4749 };
   4750 
   4751 /* Helper for remote_target::start_remote, start the remote connection and
   4752    sync state.  Return true if everything goes OK, otherwise, return false.
   4753    This function exists so that the scoped_restore created within it will
   4754    expire before we return to remote_target::start_remote.  */
   4755 
   4756 bool
   4757 remote_target::start_remote_1 (int from_tty, int extended_p)
   4758 {
   4759   REMOTE_SCOPED_DEBUG_ENTER_EXIT;
   4760 
   4761   struct remote_state *rs = get_remote_state ();
   4762   struct packet_config *noack_config;
   4763 
   4764   /* Signal other parts that we're going through the initial setup,
   4765      and so things may not be stable yet.  E.g., we don't try to
   4766      install tracepoints until we've relocated symbols.  Also, a
   4767      Ctrl-C before we're connected and synced up can't interrupt the
   4768      target.  Instead, it offers to drop the (potentially wedged)
   4769      connection.  */
   4770   scoped_mark_target_starting target_is_starting (this);
   4771 
   4772   QUIT;
   4773 
   4774   if (interrupt_on_connect)
   4775     send_interrupt_sequence ();
   4776 
   4777   /* Ack any packet which the remote side has already sent.  */
   4778   remote_serial_write ("+", 1);
   4779 
   4780   /* The first packet we send to the target is the optional "supported
   4781      packets" request.  If the target can answer this, it will tell us
   4782      which later probes to skip.  */
   4783   remote_query_supported ();
   4784 
   4785   /* If the stub wants to get a QAllow, compose one and send it.  */
   4786   if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
   4787     set_permissions ();
   4788 
   4789   /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
   4790      unknown 'v' packet with string "OK".  "OK" gets interpreted by GDB
   4791      as a reply to known packet.  For packet "vFile:setfs:" it is an
   4792      invalid reply and GDB would return error in
   4793      remote_hostio_set_filesystem, making remote files access impossible.
   4794      Disable "vFile:setfs:" in such case.  Do not disable other 'v' packets as
   4795      other "vFile" packets get correctly detected even on gdbserver < 7.7.  */
   4796   {
   4797     const char v_mustreplyempty[] = "vMustReplyEmpty";
   4798 
   4799     putpkt (v_mustreplyempty);
   4800     getpkt (&rs->buf, 0);
   4801     if (strcmp (rs->buf.data (), "OK") == 0)
   4802       remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
   4803     else if (strcmp (rs->buf.data (), "") != 0)
   4804       error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
   4805 	     rs->buf.data ());
   4806   }
   4807 
   4808   /* Next, we possibly activate noack mode.
   4809 
   4810      If the QStartNoAckMode packet configuration is set to AUTO,
   4811      enable noack mode if the stub reported a wish for it with
   4812      qSupported.
   4813 
   4814      If set to TRUE, then enable noack mode even if the stub didn't
   4815      report it in qSupported.  If the stub doesn't reply OK, the
   4816      session ends with an error.
   4817 
   4818      If FALSE, then don't activate noack mode, regardless of what the
   4819      stub claimed should be the default with qSupported.  */
   4820 
   4821   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
   4822   if (packet_config_support (noack_config) != PACKET_DISABLE)
   4823     {
   4824       putpkt ("QStartNoAckMode");
   4825       getpkt (&rs->buf, 0);
   4826       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
   4827 	rs->noack_mode = 1;
   4828     }
   4829 
   4830   if (extended_p)
   4831     {
   4832       /* Tell the remote that we are using the extended protocol.  */
   4833       putpkt ("!");
   4834       getpkt (&rs->buf, 0);
   4835     }
   4836 
   4837   /* Let the target know which signals it is allowed to pass down to
   4838      the program.  */
   4839   update_signals_program_target ();
   4840 
   4841   /* Next, if the target can specify a description, read it.  We do
   4842      this before anything involving memory or registers.  */
   4843   target_find_description ();
   4844 
   4845   /* Next, now that we know something about the target, update the
   4846      address spaces in the program spaces.  */
   4847   update_address_spaces ();
   4848 
   4849   /* On OSs where the list of libraries is global to all
   4850      processes, we fetch them early.  */
   4851   if (gdbarch_has_global_solist (target_gdbarch ()))
   4852     solib_add (NULL, from_tty, auto_solib_add);
   4853 
   4854   if (target_is_non_stop_p ())
   4855     {
   4856       if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
   4857 	error (_("Non-stop mode requested, but remote "
   4858 		 "does not support non-stop"));
   4859 
   4860       putpkt ("QNonStop:1");
   4861       getpkt (&rs->buf, 0);
   4862 
   4863       if (strcmp (rs->buf.data (), "OK") != 0)
   4864 	error (_("Remote refused setting non-stop mode with: %s"),
   4865 	       rs->buf.data ());
   4866 
   4867       /* Find about threads and processes the stub is already
   4868 	 controlling.  We default to adding them in the running state.
   4869 	 The '?' query below will then tell us about which threads are
   4870 	 stopped.  */
   4871       this->update_thread_list ();
   4872     }
   4873   else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
   4874     {
   4875       /* Don't assume that the stub can operate in all-stop mode.
   4876 	 Request it explicitly.  */
   4877       putpkt ("QNonStop:0");
   4878       getpkt (&rs->buf, 0);
   4879 
   4880       if (strcmp (rs->buf.data (), "OK") != 0)
   4881 	error (_("Remote refused setting all-stop mode with: %s"),
   4882 	       rs->buf.data ());
   4883     }
   4884 
   4885   /* Upload TSVs regardless of whether the target is running or not.  The
   4886      remote stub, such as GDBserver, may have some predefined or builtin
   4887      TSVs, even if the target is not running.  */
   4888   if (get_trace_status (current_trace_status ()) != -1)
   4889     {
   4890       struct uploaded_tsv *uploaded_tsvs = NULL;
   4891 
   4892       upload_trace_state_variables (&uploaded_tsvs);
   4893       merge_uploaded_trace_state_variables (&uploaded_tsvs);
   4894     }
   4895 
   4896   /* Check whether the target is running now.  */
   4897   putpkt ("?");
   4898   getpkt (&rs->buf, 0);
   4899 
   4900   if (!target_is_non_stop_p ())
   4901     {
   4902       char *wait_status = NULL;
   4903 
   4904       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
   4905 	{
   4906 	  if (!extended_p)
   4907 	    error (_("The target is not running (try extended-remote?)"));
   4908 	  return false;
   4909 	}
   4910       else
   4911 	{
   4912 	  /* Save the reply for later.  */
   4913 	  wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
   4914 	  strcpy (wait_status, rs->buf.data ());
   4915 	}
   4916 
   4917       /* Fetch thread list.  */
   4918       target_update_thread_list ();
   4919 
   4920       /* Let the stub know that we want it to return the thread.  */
   4921       set_continue_thread (minus_one_ptid);
   4922 
   4923       if (thread_count (this) == 0)
   4924 	{
   4925 	  /* Target has no concept of threads at all.  GDB treats
   4926 	     non-threaded target as single-threaded; add a main
   4927 	     thread.  */
   4928 	  thread_info *tp = add_current_inferior_and_thread (wait_status);
   4929 	  get_remote_thread_info (tp)->set_resumed ();
   4930 	}
   4931       else
   4932 	{
   4933 	  /* We have thread information; select the thread the target
   4934 	     says should be current.  If we're reconnecting to a
   4935 	     multi-threaded program, this will ideally be the thread
   4936 	     that last reported an event before GDB disconnected.  */
   4937 	  ptid_t curr_thread = get_current_thread (wait_status);
   4938 	  if (curr_thread == null_ptid)
   4939 	    {
   4940 	      /* Odd... The target was able to list threads, but not
   4941 		 tell us which thread was current (no "thread"
   4942 		 register in T stop reply?).  Just pick the first
   4943 		 thread in the thread list then.  */
   4944 
   4945 	      remote_debug_printf ("warning: couldn't determine remote "
   4946 				   "current thread; picking first in list.");
   4947 
   4948 	      for (thread_info *tp : all_non_exited_threads (this,
   4949 							     minus_one_ptid))
   4950 		{
   4951 		  switch_to_thread (tp);
   4952 		  break;
   4953 		}
   4954 	    }
   4955 	  else
   4956 	    switch_to_thread (find_thread_ptid (this, curr_thread));
   4957 	}
   4958 
   4959       /* init_wait_for_inferior should be called before get_offsets in order
   4960 	 to manage `inserted' flag in bp loc in a correct state.
   4961 	 breakpoint_init_inferior, called from init_wait_for_inferior, set
   4962 	 `inserted' flag to 0, while before breakpoint_re_set, called from
   4963 	 start_remote, set `inserted' flag to 1.  In the initialization of
   4964 	 inferior, breakpoint_init_inferior should be called first, and then
   4965 	 breakpoint_re_set can be called.  If this order is broken, state of
   4966 	 `inserted' flag is wrong, and cause some problems on breakpoint
   4967 	 manipulation.  */
   4968       init_wait_for_inferior ();
   4969 
   4970       get_offsets ();		/* Get text, data & bss offsets.  */
   4971 
   4972       /* If we could not find a description using qXfer, and we know
   4973 	 how to do it some other way, try again.  This is not
   4974 	 supported for non-stop; it could be, but it is tricky if
   4975 	 there are no stopped threads when we connect.  */
   4976       if (remote_read_description_p (this)
   4977 	  && gdbarch_target_desc (target_gdbarch ()) == NULL)
   4978 	{
   4979 	  target_clear_description ();
   4980 	  target_find_description ();
   4981 	}
   4982 
   4983       /* Use the previously fetched status.  */
   4984       gdb_assert (wait_status != NULL);
   4985       struct notif_event *reply
   4986 	= remote_notif_parse (this, &notif_client_stop, wait_status);
   4987       push_stop_reply ((struct stop_reply *) reply);
   4988 
   4989       ::start_remote (from_tty); /* Initialize gdb process mechanisms.  */
   4990     }
   4991   else
   4992     {
   4993       /* Clear WFI global state.  Do this before finding about new
   4994 	 threads and inferiors, and setting the current inferior.
   4995 	 Otherwise we would clear the proceed status of the current
   4996 	 inferior when we want its stop_soon state to be preserved
   4997 	 (see notice_new_inferior).  */
   4998       init_wait_for_inferior ();
   4999 
   5000       /* In non-stop, we will either get an "OK", meaning that there
   5001 	 are no stopped threads at this time; or, a regular stop
   5002 	 reply.  In the latter case, there may be more than one thread
   5003 	 stopped --- we pull them all out using the vStopped
   5004 	 mechanism.  */
   5005       if (strcmp (rs->buf.data (), "OK") != 0)
   5006 	{
   5007 	  struct notif_client *notif = &notif_client_stop;
   5008 
   5009 	  /* remote_notif_get_pending_replies acks this one, and gets
   5010 	     the rest out.  */
   5011 	  rs->notif_state->pending_event[notif_client_stop.id]
   5012 	    = remote_notif_parse (this, notif, rs->buf.data ());
   5013 	  remote_notif_get_pending_events (notif);
   5014 	}
   5015 
   5016       if (thread_count (this) == 0)
   5017 	{
   5018 	  if (!extended_p)
   5019 	    error (_("The target is not running (try extended-remote?)"));
   5020 	  return false;
   5021 	}
   5022 
   5023       /* Report all signals during attach/startup.  */
   5024       pass_signals ({});
   5025 
   5026       /* If there are already stopped threads, mark them stopped and
   5027 	 report their stops before giving the prompt to the user.  */
   5028       process_initial_stop_replies (from_tty);
   5029 
   5030       if (target_can_async_p ())
   5031 	target_async (true);
   5032     }
   5033 
   5034   /* Give the target a chance to look up symbols.  */
   5035   for (inferior *inf : all_inferiors (this))
   5036     {
   5037       /* The inferiors that exist at this point were created from what
   5038 	 was found already running on the remote side, so we know they
   5039 	 have execution.  */
   5040       gdb_assert (this->has_execution (inf));
   5041 
   5042       /* No use without a symbol-file.  */
   5043       if (inf->pspace->symfile_object_file == nullptr)
   5044 	continue;
   5045 
   5046       /* Need to switch to a specific thread, because remote_check_symbols
   5047          uses INFERIOR_PTID to set the general thread.  */
   5048       scoped_restore_current_thread restore_thread;
   5049       thread_info *thread = any_thread_of_inferior (inf);
   5050       switch_to_thread (thread);
   5051       this->remote_check_symbols ();
   5052     }
   5053 
   5054   /* Possibly the target has been engaged in a trace run started
   5055      previously; find out where things are at.  */
   5056   if (get_trace_status (current_trace_status ()) != -1)
   5057     {
   5058       struct uploaded_tp *uploaded_tps = NULL;
   5059 
   5060       if (current_trace_status ()->running)
   5061 	gdb_printf (_("Trace is already running on the target.\n"));
   5062 
   5063       upload_tracepoints (&uploaded_tps);
   5064 
   5065       merge_uploaded_tracepoints (&uploaded_tps);
   5066     }
   5067 
   5068   /* Possibly the target has been engaged in a btrace record started
   5069      previously; find out where things are at.  */
   5070   remote_btrace_maybe_reopen ();
   5071 
   5072   return true;
   5073 }
   5074 
   5075 /* Start the remote connection and sync state.  */
   5076 
   5077 void
   5078 remote_target::start_remote (int from_tty, int extended_p)
   5079 {
   5080   if (start_remote_1 (from_tty, extended_p)
   5081       && breakpoints_should_be_inserted_now ())
   5082     insert_breakpoints ();
   5083 }
   5084 
   5085 const char *
   5086 remote_target::connection_string ()
   5087 {
   5088   remote_state *rs = get_remote_state ();
   5089 
   5090   if (rs->remote_desc->name != NULL)
   5091     return rs->remote_desc->name;
   5092   else
   5093     return NULL;
   5094 }
   5095 
   5096 /* Open a connection to a remote debugger.
   5097    NAME is the filename used for communication.  */
   5098 
   5099 void
   5100 remote_target::open (const char *name, int from_tty)
   5101 {
   5102   open_1 (name, from_tty, 0);
   5103 }
   5104 
   5105 /* Open a connection to a remote debugger using the extended
   5106    remote gdb protocol.  NAME is the filename used for communication.  */
   5107 
   5108 void
   5109 extended_remote_target::open (const char *name, int from_tty)
   5110 {
   5111   open_1 (name, from_tty, 1 /*extended_p */);
   5112 }
   5113 
   5114 /* Reset all packets back to "unknown support".  Called when opening a
   5115    new connection to a remote target.  */
   5116 
   5117 static void
   5118 reset_all_packet_configs_support (void)
   5119 {
   5120   int i;
   5121 
   5122   for (i = 0; i < PACKET_MAX; i++)
   5123     remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
   5124 }
   5125 
   5126 /* Initialize all packet configs.  */
   5127 
   5128 static void
   5129 init_all_packet_configs (void)
   5130 {
   5131   int i;
   5132 
   5133   for (i = 0; i < PACKET_MAX; i++)
   5134     {
   5135       remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
   5136       remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
   5137     }
   5138 }
   5139 
   5140 /* Symbol look-up.  */
   5141 
   5142 void
   5143 remote_target::remote_check_symbols ()
   5144 {
   5145   char *tmp;
   5146   int end;
   5147 
   5148   /* It doesn't make sense to send a qSymbol packet for an inferior that
   5149      doesn't have execution, because the remote side doesn't know about
   5150      inferiors without execution.  */
   5151   gdb_assert (target_has_execution ());
   5152 
   5153   if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
   5154     return;
   5155 
   5156   /* Make sure the remote is pointing at the right process.  Note
   5157      there's no way to select "no process".  */
   5158   set_general_process ();
   5159 
   5160   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
   5161      because we need both at the same time.  */
   5162   gdb::char_vector msg (get_remote_packet_size ());
   5163   gdb::char_vector reply (get_remote_packet_size ());
   5164 
   5165   /* Invite target to request symbol lookups.  */
   5166 
   5167   putpkt ("qSymbol::");
   5168   getpkt (&reply, 0);
   5169   packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
   5170 
   5171   while (startswith (reply.data (), "qSymbol:"))
   5172     {
   5173       struct bound_minimal_symbol sym;
   5174 
   5175       tmp = &reply[8];
   5176       end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
   5177 		     strlen (tmp) / 2);
   5178       msg[end] = '\0';
   5179       sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
   5180       if (sym.minsym == NULL)
   5181 	xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
   5182 		   &reply[8]);
   5183       else
   5184 	{
   5185 	  int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
   5186 	  CORE_ADDR sym_addr = sym.value_address ();
   5187 
   5188 	  /* If this is a function address, return the start of code
   5189 	     instead of any data function descriptor.  */
   5190 	  sym_addr = gdbarch_convert_from_func_ptr_addr
   5191 	    (target_gdbarch (), sym_addr, current_inferior ()->top_target ());
   5192 
   5193 	  xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
   5194 		     phex_nz (sym_addr, addr_size), &reply[8]);
   5195 	}
   5196 
   5197       putpkt (msg.data ());
   5198       getpkt (&reply, 0);
   5199     }
   5200 }
   5201 
   5202 static struct serial *
   5203 remote_serial_open (const char *name)
   5204 {
   5205   static int udp_warning = 0;
   5206 
   5207   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
   5208      of in ser-tcp.c, because it is the remote protocol assuming that the
   5209      serial connection is reliable and not the serial connection promising
   5210      to be.  */
   5211   if (!udp_warning && startswith (name, "udp:"))
   5212     {
   5213       warning (_("The remote protocol may be unreliable over UDP.\n"
   5214 		 "Some events may be lost, rendering further debugging "
   5215 		 "impossible."));
   5216       udp_warning = 1;
   5217     }
   5218 
   5219   return serial_open (name);
   5220 }
   5221 
   5222 /* Inform the target of our permission settings.  The permission flags
   5223    work without this, but if the target knows the settings, it can do
   5224    a couple things.  First, it can add its own check, to catch cases
   5225    that somehow manage to get by the permissions checks in target
   5226    methods.  Second, if the target is wired to disallow particular
   5227    settings (for instance, a system in the field that is not set up to
   5228    be able to stop at a breakpoint), it can object to any unavailable
   5229    permissions.  */
   5230 
   5231 void
   5232 remote_target::set_permissions ()
   5233 {
   5234   struct remote_state *rs = get_remote_state ();
   5235 
   5236   xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
   5237 	     "WriteReg:%x;WriteMem:%x;"
   5238 	     "InsertBreak:%x;InsertTrace:%x;"
   5239 	     "InsertFastTrace:%x;Stop:%x",
   5240 	     may_write_registers, may_write_memory,
   5241 	     may_insert_breakpoints, may_insert_tracepoints,
   5242 	     may_insert_fast_tracepoints, may_stop);
   5243   putpkt (rs->buf);
   5244   getpkt (&rs->buf, 0);
   5245 
   5246   /* If the target didn't like the packet, warn the user.  Do not try
   5247      to undo the user's settings, that would just be maddening.  */
   5248   if (strcmp (rs->buf.data (), "OK") != 0)
   5249     warning (_("Remote refused setting permissions with: %s"),
   5250 	     rs->buf.data ());
   5251 }
   5252 
   5253 /* This type describes each known response to the qSupported
   5254    packet.  */
   5255 struct protocol_feature
   5256 {
   5257   /* The name of this protocol feature.  */
   5258   const char *name;
   5259 
   5260   /* The default for this protocol feature.  */
   5261   enum packet_support default_support;
   5262 
   5263   /* The function to call when this feature is reported, or after
   5264      qSupported processing if the feature is not supported.
   5265      The first argument points to this structure.  The second
   5266      argument indicates whether the packet requested support be
   5267      enabled, disabled, or probed (or the default, if this function
   5268      is being called at the end of processing and this feature was
   5269      not reported).  The third argument may be NULL; if not NULL, it
   5270      is a NUL-terminated string taken from the packet following
   5271      this feature's name and an equals sign.  */
   5272   void (*func) (remote_target *remote, const struct protocol_feature *,
   5273 		enum packet_support, const char *);
   5274 
   5275   /* The corresponding packet for this feature.  Only used if
   5276      FUNC is remote_supported_packet.  */
   5277   int packet;
   5278 };
   5279 
   5280 static void
   5281 remote_supported_packet (remote_target *remote,
   5282 			 const struct protocol_feature *feature,
   5283 			 enum packet_support support,
   5284 			 const char *argument)
   5285 {
   5286   if (argument)
   5287     {
   5288       warning (_("Remote qSupported response supplied an unexpected value for"
   5289 		 " \"%s\"."), feature->name);
   5290       return;
   5291     }
   5292 
   5293   remote_protocol_packets[feature->packet].support = support;
   5294 }
   5295 
   5296 void
   5297 remote_target::remote_packet_size (const protocol_feature *feature,
   5298 				   enum packet_support support, const char *value)
   5299 {
   5300   struct remote_state *rs = get_remote_state ();
   5301 
   5302   int packet_size;
   5303   char *value_end;
   5304 
   5305   if (support != PACKET_ENABLE)
   5306     return;
   5307 
   5308   if (value == NULL || *value == '\0')
   5309     {
   5310       warning (_("Remote target reported \"%s\" without a size."),
   5311 	       feature->name);
   5312       return;
   5313     }
   5314 
   5315   errno = 0;
   5316   packet_size = strtol (value, &value_end, 16);
   5317   if (errno != 0 || *value_end != '\0' || packet_size < 0)
   5318     {
   5319       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
   5320 	       feature->name, value);
   5321       return;
   5322     }
   5323 
   5324   /* Record the new maximum packet size.  */
   5325   rs->explicit_packet_size = packet_size;
   5326 }
   5327 
   5328 static void
   5329 remote_packet_size (remote_target *remote, const protocol_feature *feature,
   5330 		    enum packet_support support, const char *value)
   5331 {
   5332   remote->remote_packet_size (feature, support, value);
   5333 }
   5334 
   5335 static const struct protocol_feature remote_protocol_features[] = {
   5336   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
   5337   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
   5338     PACKET_qXfer_auxv },
   5339   { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
   5340     PACKET_qXfer_exec_file },
   5341   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
   5342     PACKET_qXfer_features },
   5343   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
   5344     PACKET_qXfer_libraries },
   5345   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
   5346     PACKET_qXfer_libraries_svr4 },
   5347   { "augmented-libraries-svr4-read", PACKET_DISABLE,
   5348     remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
   5349   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
   5350     PACKET_qXfer_memory_map },
   5351   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
   5352     PACKET_qXfer_osdata },
   5353   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
   5354     PACKET_qXfer_threads },
   5355   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
   5356     PACKET_qXfer_traceframe_info },
   5357   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
   5358     PACKET_QPassSignals },
   5359   { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
   5360     PACKET_QCatchSyscalls },
   5361   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
   5362     PACKET_QProgramSignals },
   5363   { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
   5364     PACKET_QSetWorkingDir },
   5365   { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
   5366     PACKET_QStartupWithShell },
   5367   { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
   5368     PACKET_QEnvironmentHexEncoded },
   5369   { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
   5370     PACKET_QEnvironmentReset },
   5371   { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
   5372     PACKET_QEnvironmentUnset },
   5373   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
   5374     PACKET_QStartNoAckMode },
   5375   { "multiprocess", PACKET_DISABLE, remote_supported_packet,
   5376     PACKET_multiprocess_feature },
   5377   { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
   5378   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
   5379     PACKET_qXfer_siginfo_read },
   5380   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
   5381     PACKET_qXfer_siginfo_write },
   5382   { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
   5383     PACKET_ConditionalTracepoints },
   5384   { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
   5385     PACKET_ConditionalBreakpoints },
   5386   { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
   5387     PACKET_BreakpointCommands },
   5388   { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
   5389     PACKET_FastTracepoints },
   5390   { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
   5391     PACKET_StaticTracepoints },
   5392   {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
   5393    PACKET_InstallInTrace},
   5394   { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
   5395     PACKET_DisconnectedTracing_feature },
   5396   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
   5397     PACKET_bc },
   5398   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
   5399     PACKET_bs },
   5400   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
   5401     PACKET_TracepointSource },
   5402   { "QAllow", PACKET_DISABLE, remote_supported_packet,
   5403     PACKET_QAllow },
   5404   { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
   5405     PACKET_EnableDisableTracepoints_feature },
   5406   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
   5407     PACKET_qXfer_fdpic },
   5408   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
   5409     PACKET_qXfer_uib },
   5410   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
   5411     PACKET_QDisableRandomization },
   5412   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
   5413   { "QTBuffer:size", PACKET_DISABLE,
   5414     remote_supported_packet, PACKET_QTBuffer_size},
   5415   { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
   5416   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
   5417   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
   5418   { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
   5419   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
   5420     PACKET_qXfer_btrace },
   5421   { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
   5422     PACKET_qXfer_btrace_conf },
   5423   { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
   5424     PACKET_Qbtrace_conf_bts_size },
   5425   { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
   5426   { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
   5427   { "fork-events", PACKET_DISABLE, remote_supported_packet,
   5428     PACKET_fork_event_feature },
   5429   { "vfork-events", PACKET_DISABLE, remote_supported_packet,
   5430     PACKET_vfork_event_feature },
   5431   { "exec-events", PACKET_DISABLE, remote_supported_packet,
   5432     PACKET_exec_event_feature },
   5433   { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
   5434     PACKET_Qbtrace_conf_pt_size },
   5435   { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
   5436   { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
   5437   { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
   5438   { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
   5439     PACKET_memory_tagging_feature },
   5440 };
   5441 
   5442 static char *remote_support_xml;
   5443 
   5444 /* Register string appended to "xmlRegisters=" in qSupported query.  */
   5445 
   5446 void
   5447 register_remote_support_xml (const char *xml)
   5448 {
   5449 #if defined(HAVE_LIBEXPAT)
   5450   if (remote_support_xml == NULL)
   5451     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
   5452   else
   5453     {
   5454       char *copy = xstrdup (remote_support_xml + 13);
   5455       char *saveptr;
   5456       char *p = strtok_r (copy, ",", &saveptr);
   5457 
   5458       do
   5459 	{
   5460 	  if (strcmp (p, xml) == 0)
   5461 	    {
   5462 	      /* already there */
   5463 	      xfree (copy);
   5464 	      return;
   5465 	    }
   5466 	}
   5467       while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
   5468       xfree (copy);
   5469 
   5470       remote_support_xml = reconcat (remote_support_xml,
   5471 				     remote_support_xml, ",", xml,
   5472 				     (char *) NULL);
   5473     }
   5474 #endif
   5475 }
   5476 
   5477 static void
   5478 remote_query_supported_append (std::string *msg, const char *append)
   5479 {
   5480   if (!msg->empty ())
   5481     msg->append (";");
   5482   msg->append (append);
   5483 }
   5484 
   5485 void
   5486 remote_target::remote_query_supported ()
   5487 {
   5488   struct remote_state *rs = get_remote_state ();
   5489   char *next;
   5490   int i;
   5491   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
   5492 
   5493   /* The packet support flags are handled differently for this packet
   5494      than for most others.  We treat an error, a disabled packet, and
   5495      an empty response identically: any features which must be reported
   5496      to be used will be automatically disabled.  An empty buffer
   5497      accomplishes this, since that is also the representation for a list
   5498      containing no features.  */
   5499 
   5500   rs->buf[0] = 0;
   5501   if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
   5502     {
   5503       std::string q;
   5504 
   5505       if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
   5506 	remote_query_supported_append (&q, "multiprocess+");
   5507 
   5508       if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
   5509 	remote_query_supported_append (&q, "swbreak+");
   5510       if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
   5511 	remote_query_supported_append (&q, "hwbreak+");
   5512 
   5513       remote_query_supported_append (&q, "qRelocInsn+");
   5514 
   5515       if (packet_set_cmd_state (PACKET_fork_event_feature)
   5516 	  != AUTO_BOOLEAN_FALSE)
   5517 	remote_query_supported_append (&q, "fork-events+");
   5518       if (packet_set_cmd_state (PACKET_vfork_event_feature)
   5519 	  != AUTO_BOOLEAN_FALSE)
   5520 	remote_query_supported_append (&q, "vfork-events+");
   5521       if (packet_set_cmd_state (PACKET_exec_event_feature)
   5522 	  != AUTO_BOOLEAN_FALSE)
   5523 	remote_query_supported_append (&q, "exec-events+");
   5524 
   5525       if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
   5526 	remote_query_supported_append (&q, "vContSupported+");
   5527 
   5528       if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
   5529 	remote_query_supported_append (&q, "QThreadEvents+");
   5530 
   5531       if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
   5532 	remote_query_supported_append (&q, "no-resumed+");
   5533 
   5534       if (packet_set_cmd_state (PACKET_memory_tagging_feature)
   5535 	  != AUTO_BOOLEAN_FALSE)
   5536 	remote_query_supported_append (&q, "memory-tagging+");
   5537 
   5538       /* Keep this one last to work around a gdbserver <= 7.10 bug in
   5539 	 the qSupported:xmlRegisters=i386 handling.  */
   5540       if (remote_support_xml != NULL
   5541 	  && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
   5542 	remote_query_supported_append (&q, remote_support_xml);
   5543 
   5544       q = "qSupported:" + q;
   5545       putpkt (q.c_str ());
   5546 
   5547       getpkt (&rs->buf, 0);
   5548 
   5549       /* If an error occured, warn, but do not return - just reset the
   5550 	 buffer to empty and go on to disable features.  */
   5551       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
   5552 	  == PACKET_ERROR)
   5553 	{
   5554 	  warning (_("Remote failure reply: %s"), rs->buf.data ());
   5555 	  rs->buf[0] = 0;
   5556 	}
   5557     }
   5558 
   5559   memset (seen, 0, sizeof (seen));
   5560 
   5561   next = rs->buf.data ();
   5562   while (*next)
   5563     {
   5564       enum packet_support is_supported;
   5565       char *p, *end, *name_end, *value;
   5566 
   5567       /* First separate out this item from the rest of the packet.  If
   5568 	 there's another item after this, we overwrite the separator
   5569 	 (terminated strings are much easier to work with).  */
   5570       p = next;
   5571       end = strchr (p, ';');
   5572       if (end == NULL)
   5573 	{
   5574 	  end = p + strlen (p);
   5575 	  next = end;
   5576 	}
   5577       else
   5578 	{
   5579 	  *end = '\0';
   5580 	  next = end + 1;
   5581 
   5582 	  if (end == p)
   5583 	    {
   5584 	      warning (_("empty item in \"qSupported\" response"));
   5585 	      continue;
   5586 	    }
   5587 	}
   5588 
   5589       name_end = strchr (p, '=');
   5590       if (name_end)
   5591 	{
   5592 	  /* This is a name=value entry.  */
   5593 	  is_supported = PACKET_ENABLE;
   5594 	  value = name_end + 1;
   5595 	  *name_end = '\0';
   5596 	}
   5597       else
   5598 	{
   5599 	  value = NULL;
   5600 	  switch (end[-1])
   5601 	    {
   5602 	    case '+':
   5603 	      is_supported = PACKET_ENABLE;
   5604 	      break;
   5605 
   5606 	    case '-':
   5607 	      is_supported = PACKET_DISABLE;
   5608 	      break;
   5609 
   5610 	    case '?':
   5611 	      is_supported = PACKET_SUPPORT_UNKNOWN;
   5612 	      break;
   5613 
   5614 	    default:
   5615 	      warning (_("unrecognized item \"%s\" "
   5616 			 "in \"qSupported\" response"), p);
   5617 	      continue;
   5618 	    }
   5619 	  end[-1] = '\0';
   5620 	}
   5621 
   5622       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
   5623 	if (strcmp (remote_protocol_features[i].name, p) == 0)
   5624 	  {
   5625 	    const struct protocol_feature *feature;
   5626 
   5627 	    seen[i] = 1;
   5628 	    feature = &remote_protocol_features[i];
   5629 	    feature->func (this, feature, is_supported, value);
   5630 	    break;
   5631 	  }
   5632     }
   5633 
   5634   /* If we increased the packet size, make sure to increase the global
   5635      buffer size also.  We delay this until after parsing the entire
   5636      qSupported packet, because this is the same buffer we were
   5637      parsing.  */
   5638   if (rs->buf.size () < rs->explicit_packet_size)
   5639     rs->buf.resize (rs->explicit_packet_size);
   5640 
   5641   /* Handle the defaults for unmentioned features.  */
   5642   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
   5643     if (!seen[i])
   5644       {
   5645 	const struct protocol_feature *feature;
   5646 
   5647 	feature = &remote_protocol_features[i];
   5648 	feature->func (this, feature, feature->default_support, NULL);
   5649       }
   5650 }
   5651 
   5652 /* Serial QUIT handler for the remote serial descriptor.
   5653 
   5654    Defers handling a Ctrl-C until we're done with the current
   5655    command/response packet sequence, unless:
   5656 
   5657    - We're setting up the connection.  Don't send a remote interrupt
   5658      request, as we're not fully synced yet.  Quit immediately
   5659      instead.
   5660 
   5661    - The target has been resumed in the foreground
   5662      (target_terminal::is_ours is false) with a synchronous resume
   5663      packet, and we're blocked waiting for the stop reply, thus a
   5664      Ctrl-C should be immediately sent to the target.
   5665 
   5666    - We get a second Ctrl-C while still within the same serial read or
   5667      write.  In that case the serial is seemingly wedged --- offer to
   5668      quit/disconnect.
   5669 
   5670    - We see a second Ctrl-C without target response, after having
   5671      previously interrupted the target.  In that case the target/stub
   5672      is probably wedged --- offer to quit/disconnect.
   5673 */
   5674 
   5675 void
   5676 remote_target::remote_serial_quit_handler ()
   5677 {
   5678   struct remote_state *rs = get_remote_state ();
   5679 
   5680   if (check_quit_flag ())
   5681     {
   5682       /* If we're starting up, we're not fully synced yet.  Quit
   5683 	 immediately.  */
   5684       if (rs->starting_up)
   5685 	quit ();
   5686       else if (rs->got_ctrlc_during_io)
   5687 	{
   5688 	  if (query (_("The target is not responding to GDB commands.\n"
   5689 		       "Stop debugging it? ")))
   5690 	    remote_unpush_and_throw (this);
   5691 	}
   5692       /* If ^C has already been sent once, offer to disconnect.  */
   5693       else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
   5694 	interrupt_query ();
   5695       /* All-stop protocol, and blocked waiting for stop reply.  Send
   5696 	 an interrupt request.  */
   5697       else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
   5698 	target_interrupt ();
   5699       else
   5700 	rs->got_ctrlc_during_io = 1;
   5701     }
   5702 }
   5703 
   5704 /* The remote_target that is current while the quit handler is
   5705    overridden with remote_serial_quit_handler.  */
   5706 static remote_target *curr_quit_handler_target;
   5707 
   5708 static void
   5709 remote_serial_quit_handler ()
   5710 {
   5711   curr_quit_handler_target->remote_serial_quit_handler ();
   5712 }
   5713 
   5714 /* Remove the remote target from the target stack of each inferior
   5715    that is using it.  Upper targets depend on it so remove them
   5716    first.  */
   5717 
   5718 static void
   5719 remote_unpush_target (remote_target *target)
   5720 {
   5721   /* We have to unpush the target from all inferiors, even those that
   5722      aren't running.  */
   5723   scoped_restore_current_inferior restore_current_inferior;
   5724 
   5725   for (inferior *inf : all_inferiors (target))
   5726     {
   5727       switch_to_inferior_no_thread (inf);
   5728       inf->pop_all_targets_at_and_above (process_stratum);
   5729       generic_mourn_inferior ();
   5730     }
   5731 
   5732   /* Don't rely on target_close doing this when the target is popped
   5733      from the last remote inferior above, because something may be
   5734      holding a reference to the target higher up on the stack, meaning
   5735      target_close won't be called yet.  We lost the connection to the
   5736      target, so clear these now, otherwise we may later throw
   5737      TARGET_CLOSE_ERROR while trying to tell the remote target to
   5738      close the file.  */
   5739   fileio_handles_invalidate_target (target);
   5740 }
   5741 
   5742 static void
   5743 remote_unpush_and_throw (remote_target *target)
   5744 {
   5745   remote_unpush_target (target);
   5746   throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
   5747 }
   5748 
   5749 void
   5750 remote_target::open_1 (const char *name, int from_tty, int extended_p)
   5751 {
   5752   remote_target *curr_remote = get_current_remote_target ();
   5753 
   5754   if (name == 0)
   5755     error (_("To open a remote debug connection, you need to specify what\n"
   5756 	   "serial device is attached to the remote system\n"
   5757 	   "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
   5758 
   5759   /* If we're connected to a running target, target_preopen will kill it.
   5760      Ask this question first, before target_preopen has a chance to kill
   5761      anything.  */
   5762   if (curr_remote != NULL && !target_has_execution ())
   5763     {
   5764       if (from_tty
   5765 	  && !query (_("Already connected to a remote target.  Disconnect? ")))
   5766 	error (_("Still connected."));
   5767     }
   5768 
   5769   /* Here the possibly existing remote target gets unpushed.  */
   5770   target_preopen (from_tty);
   5771 
   5772   remote_fileio_reset ();
   5773   reopen_exec_file ();
   5774   reread_symbols (from_tty);
   5775 
   5776   remote_target *remote
   5777     = (extended_p ? new extended_remote_target () : new remote_target ());
   5778   target_ops_up target_holder (remote);
   5779 
   5780   remote_state *rs = remote->get_remote_state ();
   5781 
   5782   /* See FIXME above.  */
   5783   if (!target_async_permitted)
   5784     rs->wait_forever_enabled_p = 1;
   5785 
   5786   rs->remote_desc = remote_serial_open (name);
   5787   if (!rs->remote_desc)
   5788     perror_with_name (name);
   5789 
   5790   if (baud_rate != -1)
   5791     {
   5792       if (serial_setbaudrate (rs->remote_desc, baud_rate))
   5793 	{
   5794 	  /* The requested speed could not be set.  Error out to
   5795 	     top level after closing remote_desc.  Take care to
   5796 	     set remote_desc to NULL to avoid closing remote_desc
   5797 	     more than once.  */
   5798 	  serial_close (rs->remote_desc);
   5799 	  rs->remote_desc = NULL;
   5800 	  perror_with_name (name);
   5801 	}
   5802     }
   5803 
   5804   serial_setparity (rs->remote_desc, serial_parity);
   5805   serial_raw (rs->remote_desc);
   5806 
   5807   /* If there is something sitting in the buffer we might take it as a
   5808      response to a command, which would be bad.  */
   5809   serial_flush_input (rs->remote_desc);
   5810 
   5811   if (from_tty)
   5812     {
   5813       gdb_puts ("Remote debugging using ");
   5814       gdb_puts (name);
   5815       gdb_puts ("\n");
   5816     }
   5817 
   5818   /* Switch to using the remote target now.  */
   5819   current_inferior ()->push_target (std::move (target_holder));
   5820 
   5821   /* Register extra event sources in the event loop.  */
   5822   rs->remote_async_inferior_event_token
   5823     = create_async_event_handler (remote_async_inferior_event_handler, nullptr,
   5824 				  "remote");
   5825   rs->notif_state = remote_notif_state_allocate (remote);
   5826 
   5827   /* Reset the target state; these things will be queried either by
   5828      remote_query_supported or as they are needed.  */
   5829   reset_all_packet_configs_support ();
   5830   rs->explicit_packet_size = 0;
   5831   rs->noack_mode = 0;
   5832   rs->extended = extended_p;
   5833   rs->waiting_for_stop_reply = 0;
   5834   rs->ctrlc_pending_p = 0;
   5835   rs->got_ctrlc_during_io = 0;
   5836 
   5837   rs->general_thread = not_sent_ptid;
   5838   rs->continue_thread = not_sent_ptid;
   5839   rs->remote_traceframe_number = -1;
   5840 
   5841   rs->last_resume_exec_dir = EXEC_FORWARD;
   5842 
   5843   /* Probe for ability to use "ThreadInfo" query, as required.  */
   5844   rs->use_threadinfo_query = 1;
   5845   rs->use_threadextra_query = 1;
   5846 
   5847   rs->readahead_cache.invalidate ();
   5848 
   5849   if (target_async_permitted)
   5850     {
   5851       /* FIXME: cagney/1999-09-23: During the initial connection it is
   5852 	 assumed that the target is already ready and able to respond to
   5853 	 requests.  Unfortunately remote_start_remote() eventually calls
   5854 	 wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
   5855 	 around this.  Eventually a mechanism that allows
   5856 	 wait_for_inferior() to expect/get timeouts will be
   5857 	 implemented.  */
   5858       rs->wait_forever_enabled_p = 0;
   5859     }
   5860 
   5861   /* First delete any symbols previously loaded from shared libraries.  */
   5862   no_shared_libraries (NULL, 0);
   5863 
   5864   /* Start the remote connection.  If error() or QUIT, discard this
   5865      target (we'd otherwise be in an inconsistent state) and then
   5866      propogate the error on up the exception chain.  This ensures that
   5867      the caller doesn't stumble along blindly assuming that the
   5868      function succeeded.  The CLI doesn't have this problem but other
   5869      UI's, such as MI do.
   5870 
   5871      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
   5872      this function should return an error indication letting the
   5873      caller restore the previous state.  Unfortunately the command
   5874      ``target remote'' is directly wired to this function making that
   5875      impossible.  On a positive note, the CLI side of this problem has
   5876      been fixed - the function set_cmd_context() makes it possible for
   5877      all the ``target ....'' commands to share a common callback
   5878      function.  See cli-dump.c.  */
   5879   {
   5880 
   5881     try
   5882       {
   5883 	remote->start_remote (from_tty, extended_p);
   5884       }
   5885     catch (const gdb_exception &ex)
   5886       {
   5887 	/* Pop the partially set up target - unless something else did
   5888 	   already before throwing the exception.  */
   5889 	if (ex.error != TARGET_CLOSE_ERROR)
   5890 	  remote_unpush_target (remote);
   5891 	throw;
   5892       }
   5893   }
   5894 
   5895   remote_btrace_reset (rs);
   5896 
   5897   if (target_async_permitted)
   5898     rs->wait_forever_enabled_p = 1;
   5899 }
   5900 
   5901 /* Determine if WS represents a fork status.  */
   5902 
   5903 static bool
   5904 is_fork_status (target_waitkind kind)
   5905 {
   5906   return (kind == TARGET_WAITKIND_FORKED
   5907 	  || kind == TARGET_WAITKIND_VFORKED);
   5908 }
   5909 
   5910 /* Return THREAD's pending status if it is a pending fork parent, else
   5911    return nullptr.  */
   5912 
   5913 static const target_waitstatus *
   5914 thread_pending_fork_status (struct thread_info *thread)
   5915 {
   5916   const target_waitstatus &ws
   5917     = (thread->has_pending_waitstatus ()
   5918        ? thread->pending_waitstatus ()
   5919        : thread->pending_follow);
   5920 
   5921   if (!is_fork_status (ws.kind ()))
   5922     return nullptr;
   5923 
   5924   return &ws;
   5925 }
   5926 
   5927 /* Detach the specified process.  */
   5928 
   5929 void
   5930 remote_target::remote_detach_pid (int pid)
   5931 {
   5932   struct remote_state *rs = get_remote_state ();
   5933 
   5934   /* This should not be necessary, but the handling for D;PID in
   5935      GDBserver versions prior to 8.2 incorrectly assumes that the
   5936      selected process points to the same process we're detaching,
   5937      leading to misbehavior (and possibly GDBserver crashing) when it
   5938      does not.  Since it's easy and cheap, work around it by forcing
   5939      GDBserver to select GDB's current process.  */
   5940   set_general_process ();
   5941 
   5942   if (remote_multi_process_p (rs))
   5943     xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
   5944   else
   5945     strcpy (rs->buf.data (), "D");
   5946 
   5947   putpkt (rs->buf);
   5948   getpkt (&rs->buf, 0);
   5949 
   5950   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
   5951     ;
   5952   else if (rs->buf[0] == '\0')
   5953     error (_("Remote doesn't know how to detach"));
   5954   else
   5955     error (_("Can't detach process."));
   5956 }
   5957 
   5958 /* This detaches a program to which we previously attached, using
   5959    inferior_ptid to identify the process.  After this is done, GDB
   5960    can be used to debug some other program.  We better not have left
   5961    any breakpoints in the target program or it'll die when it hits
   5962    one.  */
   5963 
   5964 void
   5965 remote_target::remote_detach_1 (inferior *inf, int from_tty)
   5966 {
   5967   int pid = inferior_ptid.pid ();
   5968   struct remote_state *rs = get_remote_state ();
   5969   int is_fork_parent;
   5970 
   5971   if (!target_has_execution ())
   5972     error (_("No process to detach from."));
   5973 
   5974   target_announce_detach (from_tty);
   5975 
   5976   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
   5977     {
   5978       /* If we're in breakpoints-always-inserted mode, or the inferior
   5979 	 is running, we have to remove breakpoints before detaching.
   5980 	 We don't do this in common code instead because not all
   5981 	 targets support removing breakpoints while the target is
   5982 	 running.  The remote target / gdbserver does, though.  */
   5983       remove_breakpoints_inf (current_inferior ());
   5984     }
   5985 
   5986   /* Tell the remote target to detach.  */
   5987   remote_detach_pid (pid);
   5988 
   5989   /* Exit only if this is the only active inferior.  */
   5990   if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
   5991     gdb_puts (_("Ending remote debugging.\n"));
   5992 
   5993   /* See if any thread of the inferior we are detaching has a pending fork
   5994      status.  In that case, we must detach from the child resulting from
   5995      that fork.  */
   5996   for (thread_info *thread : inf->non_exited_threads ())
   5997     {
   5998       const target_waitstatus *ws = thread_pending_fork_status (thread);
   5999 
   6000       if (ws == nullptr)
   6001 	continue;
   6002 
   6003       remote_detach_pid (ws->child_ptid ().pid ());
   6004     }
   6005 
   6006   /* Check also for any pending fork events in the stop reply queue.  */
   6007   remote_notif_get_pending_events (&notif_client_stop);
   6008   for (stop_reply_up &reply : rs->stop_reply_queue)
   6009     {
   6010       if (reply->ptid.pid () != pid)
   6011 	continue;
   6012 
   6013       if (!is_fork_status (reply->ws.kind ()))
   6014 	continue;
   6015 
   6016       remote_detach_pid (reply->ws.child_ptid ().pid ());
   6017     }
   6018 
   6019   thread_info *tp = find_thread_ptid (this, inferior_ptid);
   6020 
   6021   /* Check to see if we are detaching a fork parent.  Note that if we
   6022      are detaching a fork child, tp == NULL.  */
   6023   is_fork_parent = (tp != NULL
   6024 		    && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
   6025 
   6026   /* If doing detach-on-fork, we don't mourn, because that will delete
   6027      breakpoints that should be available for the followed inferior.  */
   6028   if (!is_fork_parent)
   6029     {
   6030       /* Save the pid as a string before mourning, since that will
   6031 	 unpush the remote target, and we need the string after.  */
   6032       std::string infpid = target_pid_to_str (ptid_t (pid));
   6033 
   6034       target_mourn_inferior (inferior_ptid);
   6035       if (print_inferior_events)
   6036 	gdb_printf (_("[Inferior %d (%s) detached]\n"),
   6037 		    inf->num, infpid.c_str ());
   6038     }
   6039   else
   6040     {
   6041       switch_to_no_thread ();
   6042       detach_inferior (current_inferior ());
   6043     }
   6044 }
   6045 
   6046 void
   6047 remote_target::detach (inferior *inf, int from_tty)
   6048 {
   6049   remote_detach_1 (inf, from_tty);
   6050 }
   6051 
   6052 void
   6053 extended_remote_target::detach (inferior *inf, int from_tty)
   6054 {
   6055   remote_detach_1 (inf, from_tty);
   6056 }
   6057 
   6058 /* Target follow-fork function for remote targets.  On entry, and
   6059    at return, the current inferior is the fork parent.
   6060 
   6061    Note that although this is currently only used for extended-remote,
   6062    it is named remote_follow_fork in anticipation of using it for the
   6063    remote target as well.  */
   6064 
   6065 void
   6066 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
   6067 			    target_waitkind fork_kind, bool follow_child,
   6068 			    bool detach_fork)
   6069 {
   6070   process_stratum_target::follow_fork (child_inf, child_ptid,
   6071 				       fork_kind, follow_child, detach_fork);
   6072 
   6073   struct remote_state *rs = get_remote_state ();
   6074 
   6075   if ((fork_kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
   6076       || (fork_kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
   6077     {
   6078       /* When following the parent and detaching the child, we detach
   6079 	 the child here.  For the case of following the child and
   6080 	 detaching the parent, the detach is done in the target-
   6081 	 independent follow fork code in infrun.c.  We can't use
   6082 	 target_detach when detaching an unfollowed child because
   6083 	 the client side doesn't know anything about the child.  */
   6084       if (detach_fork && !follow_child)
   6085 	{
   6086 	  /* Detach the fork child.  */
   6087 	  remote_detach_pid (child_ptid.pid ());
   6088 	}
   6089     }
   6090 }
   6091 
   6092 /* Target follow-exec function for remote targets.  Save EXECD_PATHNAME
   6093    in the program space of the new inferior.  */
   6094 
   6095 void
   6096 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
   6097 			    const char *execd_pathname)
   6098 {
   6099   process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
   6100 
   6101   /* We know that this is a target file name, so if it has the "target:"
   6102      prefix we strip it off before saving it in the program space.  */
   6103   if (is_target_filename (execd_pathname))
   6104     execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
   6105 
   6106   set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
   6107 }
   6108 
   6109 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
   6110 
   6111 void
   6112 remote_target::disconnect (const char *args, int from_tty)
   6113 {
   6114   if (args)
   6115     error (_("Argument given to \"disconnect\" when remotely debugging."));
   6116 
   6117   /* Make sure we unpush even the extended remote targets.  Calling
   6118      target_mourn_inferior won't unpush, and
   6119      remote_target::mourn_inferior won't unpush if there is more than
   6120      one inferior left.  */
   6121   remote_unpush_target (this);
   6122 
   6123   if (from_tty)
   6124     gdb_puts ("Ending remote debugging.\n");
   6125 }
   6126 
   6127 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
   6128    be chatty about it.  */
   6129 
   6130 void
   6131 extended_remote_target::attach (const char *args, int from_tty)
   6132 {
   6133   struct remote_state *rs = get_remote_state ();
   6134   int pid;
   6135   char *wait_status = NULL;
   6136 
   6137   pid = parse_pid_to_attach (args);
   6138 
   6139   /* Remote PID can be freely equal to getpid, do not check it here the same
   6140      way as in other targets.  */
   6141 
   6142   if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
   6143     error (_("This target does not support attaching to a process"));
   6144 
   6145   target_announce_attach (from_tty, pid);
   6146 
   6147   xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
   6148   putpkt (rs->buf);
   6149   getpkt (&rs->buf, 0);
   6150 
   6151   switch (packet_ok (rs->buf,
   6152 		     &remote_protocol_packets[PACKET_vAttach]))
   6153     {
   6154     case PACKET_OK:
   6155       if (!target_is_non_stop_p ())
   6156 	{
   6157 	  /* Save the reply for later.  */
   6158 	  wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
   6159 	  strcpy (wait_status, rs->buf.data ());
   6160 	}
   6161       else if (strcmp (rs->buf.data (), "OK") != 0)
   6162 	error (_("Attaching to %s failed with: %s"),
   6163 	       target_pid_to_str (ptid_t (pid)).c_str (),
   6164 	       rs->buf.data ());
   6165       break;
   6166     case PACKET_UNKNOWN:
   6167       error (_("This target does not support attaching to a process"));
   6168     default:
   6169       error (_("Attaching to %s failed"),
   6170 	     target_pid_to_str (ptid_t (pid)).c_str ());
   6171     }
   6172 
   6173   switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
   6174 
   6175   inferior_ptid = ptid_t (pid);
   6176 
   6177   if (target_is_non_stop_p ())
   6178     {
   6179       /* Get list of threads.  */
   6180       update_thread_list ();
   6181 
   6182       thread_info *thread = first_thread_of_inferior (current_inferior ());
   6183       if (thread != nullptr)
   6184 	switch_to_thread (thread);
   6185 
   6186       /* Invalidate our notion of the remote current thread.  */
   6187       record_currthread (rs, minus_one_ptid);
   6188     }
   6189   else
   6190     {
   6191       /* Now, if we have thread information, update the main thread's
   6192 	 ptid.  */
   6193       ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
   6194 
   6195       /* Add the main thread to the thread list.  We add the thread
   6196 	 silently in this case (the final true parameter).  */
   6197       thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
   6198 
   6199       switch_to_thread (thr);
   6200     }
   6201 
   6202   /* Next, if the target can specify a description, read it.  We do
   6203      this before anything involving memory or registers.  */
   6204   target_find_description ();
   6205 
   6206   if (!target_is_non_stop_p ())
   6207     {
   6208       /* Use the previously fetched status.  */
   6209       gdb_assert (wait_status != NULL);
   6210 
   6211       struct notif_event *reply
   6212 	=  remote_notif_parse (this, &notif_client_stop, wait_status);
   6213 
   6214       push_stop_reply ((struct stop_reply *) reply);
   6215     }
   6216   else
   6217     {
   6218       gdb_assert (wait_status == NULL);
   6219 
   6220       gdb_assert (target_can_async_p ());
   6221     }
   6222 }
   6223 
   6224 /* Implementation of the to_post_attach method.  */
   6225 
   6226 void
   6227 extended_remote_target::post_attach (int pid)
   6228 {
   6229   /* Get text, data & bss offsets.  */
   6230   get_offsets ();
   6231 
   6232   /* In certain cases GDB might not have had the chance to start
   6233      symbol lookup up until now.  This could happen if the debugged
   6234      binary is not using shared libraries, the vsyscall page is not
   6235      present (on Linux) and the binary itself hadn't changed since the
   6236      debugging process was started.  */
   6237   if (current_program_space->symfile_object_file != NULL)
   6238     remote_check_symbols();
   6239 }
   6240 
   6241 
   6242 /* Check for the availability of vCont.  This function should also check
   6244    the response.  */
   6245 
   6246 void
   6247 remote_target::remote_vcont_probe ()
   6248 {
   6249   remote_state *rs = get_remote_state ();
   6250   char *buf;
   6251 
   6252   strcpy (rs->buf.data (), "vCont?");
   6253   putpkt (rs->buf);
   6254   getpkt (&rs->buf, 0);
   6255   buf = rs->buf.data ();
   6256 
   6257   /* Make sure that the features we assume are supported.  */
   6258   if (startswith (buf, "vCont"))
   6259     {
   6260       char *p = &buf[5];
   6261       int support_c, support_C;
   6262 
   6263       rs->supports_vCont.s = 0;
   6264       rs->supports_vCont.S = 0;
   6265       support_c = 0;
   6266       support_C = 0;
   6267       rs->supports_vCont.t = 0;
   6268       rs->supports_vCont.r = 0;
   6269       while (p && *p == ';')
   6270 	{
   6271 	  p++;
   6272 	  if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
   6273 	    rs->supports_vCont.s = 1;
   6274 	  else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
   6275 	    rs->supports_vCont.S = 1;
   6276 	  else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
   6277 	    support_c = 1;
   6278 	  else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
   6279 	    support_C = 1;
   6280 	  else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
   6281 	    rs->supports_vCont.t = 1;
   6282 	  else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
   6283 	    rs->supports_vCont.r = 1;
   6284 
   6285 	  p = strchr (p, ';');
   6286 	}
   6287 
   6288       /* If c, and C are not all supported, we can't use vCont.  Clearing
   6289 	 BUF will make packet_ok disable the packet.  */
   6290       if (!support_c || !support_C)
   6291 	buf[0] = 0;
   6292     }
   6293 
   6294   packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCont]);
   6295   rs->supports_vCont_probed = true;
   6296 }
   6297 
   6298 /* Helper function for building "vCont" resumptions.  Write a
   6299    resumption to P.  ENDP points to one-passed-the-end of the buffer
   6300    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
   6301    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
   6302    resumed thread should be single-stepped and/or signalled.  If PTID
   6303    equals minus_one_ptid, then all threads are resumed; if PTID
   6304    represents a process, then all threads of the process are
   6305    resumed.  */
   6306 
   6307 char *
   6308 remote_target::append_resumption (char *p, char *endp,
   6309 				  ptid_t ptid, int step, gdb_signal siggnal)
   6310 {
   6311   struct remote_state *rs = get_remote_state ();
   6312 
   6313   if (step && siggnal != GDB_SIGNAL_0)
   6314     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
   6315   else if (step
   6316 	   /* GDB is willing to range step.  */
   6317 	   && use_range_stepping
   6318 	   /* Target supports range stepping.  */
   6319 	   && rs->supports_vCont.r
   6320 	   /* We don't currently support range stepping multiple
   6321 	      threads with a wildcard (though the protocol allows it,
   6322 	      so stubs shouldn't make an active effort to forbid
   6323 	      it).  */
   6324 	   && !(remote_multi_process_p (rs) && ptid.is_pid ()))
   6325     {
   6326       struct thread_info *tp;
   6327 
   6328       if (ptid == minus_one_ptid)
   6329 	{
   6330 	  /* If we don't know about the target thread's tid, then
   6331 	     we're resuming magic_null_ptid (see caller).  */
   6332 	  tp = find_thread_ptid (this, magic_null_ptid);
   6333 	}
   6334       else
   6335 	tp = find_thread_ptid (this, ptid);
   6336       gdb_assert (tp != NULL);
   6337 
   6338       if (tp->control.may_range_step)
   6339 	{
   6340 	  int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
   6341 
   6342 	  p += xsnprintf (p, endp - p, ";r%s,%s",
   6343 			  phex_nz (tp->control.step_range_start,
   6344 				   addr_size),
   6345 			  phex_nz (tp->control.step_range_end,
   6346 				   addr_size));
   6347 	}
   6348       else
   6349 	p += xsnprintf (p, endp - p, ";s");
   6350     }
   6351   else if (step)
   6352     p += xsnprintf (p, endp - p, ";s");
   6353   else if (siggnal != GDB_SIGNAL_0)
   6354     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
   6355   else
   6356     p += xsnprintf (p, endp - p, ";c");
   6357 
   6358   if (remote_multi_process_p (rs) && ptid.is_pid ())
   6359     {
   6360       ptid_t nptid;
   6361 
   6362       /* All (-1) threads of process.  */
   6363       nptid = ptid_t (ptid.pid (), -1);
   6364 
   6365       p += xsnprintf (p, endp - p, ":");
   6366       p = write_ptid (p, endp, nptid);
   6367     }
   6368   else if (ptid != minus_one_ptid)
   6369     {
   6370       p += xsnprintf (p, endp - p, ":");
   6371       p = write_ptid (p, endp, ptid);
   6372     }
   6373 
   6374   return p;
   6375 }
   6376 
   6377 /* Clear the thread's private info on resume.  */
   6378 
   6379 static void
   6380 resume_clear_thread_private_info (struct thread_info *thread)
   6381 {
   6382   if (thread->priv != NULL)
   6383     {
   6384       remote_thread_info *priv = get_remote_thread_info (thread);
   6385 
   6386       priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
   6387       priv->watch_data_address = 0;
   6388     }
   6389 }
   6390 
   6391 /* Append a vCont continue-with-signal action for threads that have a
   6392    non-zero stop signal.  */
   6393 
   6394 char *
   6395 remote_target::append_pending_thread_resumptions (char *p, char *endp,
   6396 						  ptid_t ptid)
   6397 {
   6398   for (thread_info *thread : all_non_exited_threads (this, ptid))
   6399     if (inferior_ptid != thread->ptid
   6400 	&& thread->stop_signal () != GDB_SIGNAL_0)
   6401       {
   6402 	p = append_resumption (p, endp, thread->ptid,
   6403 			       0, thread->stop_signal ());
   6404 	thread->set_stop_signal (GDB_SIGNAL_0);
   6405 	resume_clear_thread_private_info (thread);
   6406       }
   6407 
   6408   return p;
   6409 }
   6410 
   6411 /* Set the target running, using the packets that use Hc
   6412    (c/s/C/S).  */
   6413 
   6414 void
   6415 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
   6416 				      gdb_signal siggnal)
   6417 {
   6418   struct remote_state *rs = get_remote_state ();
   6419   char *buf;
   6420 
   6421   rs->last_sent_signal = siggnal;
   6422   rs->last_sent_step = step;
   6423 
   6424   /* The c/s/C/S resume packets use Hc, so set the continue
   6425      thread.  */
   6426   if (ptid == minus_one_ptid)
   6427     set_continue_thread (any_thread_ptid);
   6428   else
   6429     set_continue_thread (ptid);
   6430 
   6431   for (thread_info *thread : all_non_exited_threads (this))
   6432     resume_clear_thread_private_info (thread);
   6433 
   6434   buf = rs->buf.data ();
   6435   if (::execution_direction == EXEC_REVERSE)
   6436     {
   6437       /* We don't pass signals to the target in reverse exec mode.  */
   6438       if (info_verbose && siggnal != GDB_SIGNAL_0)
   6439 	warning (_(" - Can't pass signal %d to target in reverse: ignored."),
   6440 		 siggnal);
   6441 
   6442       if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
   6443 	error (_("Remote reverse-step not supported."));
   6444       if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
   6445 	error (_("Remote reverse-continue not supported."));
   6446 
   6447       strcpy (buf, step ? "bs" : "bc");
   6448     }
   6449   else if (siggnal != GDB_SIGNAL_0)
   6450     {
   6451       buf[0] = step ? 'S' : 'C';
   6452       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
   6453       buf[2] = tohex (((int) siggnal) & 0xf);
   6454       buf[3] = '\0';
   6455     }
   6456   else
   6457     strcpy (buf, step ? "s" : "c");
   6458 
   6459   putpkt (buf);
   6460 }
   6461 
   6462 /* Resume the remote inferior by using a "vCont" packet.  SCOPE_PTID,
   6463    STEP, and SIGGNAL have the same meaning as in target_resume.  This
   6464    function returns non-zero iff it resumes the inferior.
   6465 
   6466    This function issues a strict subset of all possible vCont commands
   6467    at the moment.  */
   6468 
   6469 int
   6470 remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
   6471 					 enum gdb_signal siggnal)
   6472 {
   6473   struct remote_state *rs = get_remote_state ();
   6474   char *p;
   6475   char *endp;
   6476 
   6477   /* No reverse execution actions defined for vCont.  */
   6478   if (::execution_direction == EXEC_REVERSE)
   6479     return 0;
   6480 
   6481   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
   6482     remote_vcont_probe ();
   6483 
   6484   if (packet_support (PACKET_vCont) == PACKET_DISABLE)
   6485     return 0;
   6486 
   6487   p = rs->buf.data ();
   6488   endp = p + get_remote_packet_size ();
   6489 
   6490   /* If we could generate a wider range of packets, we'd have to worry
   6491      about overflowing BUF.  Should there be a generic
   6492      "multi-part-packet" packet?  */
   6493 
   6494   p += xsnprintf (p, endp - p, "vCont");
   6495 
   6496   if (scope_ptid == magic_null_ptid)
   6497     {
   6498       /* MAGIC_NULL_PTID means that we don't have any active threads,
   6499 	 so we don't have any TID numbers the inferior will
   6500 	 understand.  Make sure to only send forms that do not specify
   6501 	 a TID.  */
   6502       append_resumption (p, endp, minus_one_ptid, step, siggnal);
   6503     }
   6504   else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
   6505     {
   6506       /* Resume all threads (of all processes, or of a single
   6507 	 process), with preference for INFERIOR_PTID.  This assumes
   6508 	 inferior_ptid belongs to the set of all threads we are about
   6509 	 to resume.  */
   6510       if (step || siggnal != GDB_SIGNAL_0)
   6511 	{
   6512 	  /* Step inferior_ptid, with or without signal.  */
   6513 	  p = append_resumption (p, endp, inferior_ptid, step, siggnal);
   6514 	}
   6515 
   6516       /* Also pass down any pending signaled resumption for other
   6517 	 threads not the current.  */
   6518       p = append_pending_thread_resumptions (p, endp, scope_ptid);
   6519 
   6520       /* And continue others without a signal.  */
   6521       append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
   6522     }
   6523   else
   6524     {
   6525       /* Scheduler locking; resume only SCOPE_PTID.  */
   6526       append_resumption (p, endp, scope_ptid, step, siggnal);
   6527     }
   6528 
   6529   gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
   6530   putpkt (rs->buf);
   6531 
   6532   if (target_is_non_stop_p ())
   6533     {
   6534       /* In non-stop, the stub replies to vCont with "OK".  The stop
   6535 	 reply will be reported asynchronously by means of a `%Stop'
   6536 	 notification.  */
   6537       getpkt (&rs->buf, 0);
   6538       if (strcmp (rs->buf.data (), "OK") != 0)
   6539 	error (_("Unexpected vCont reply in non-stop mode: %s"),
   6540 	       rs->buf.data ());
   6541     }
   6542 
   6543   return 1;
   6544 }
   6545 
   6546 /* Tell the remote machine to resume.  */
   6547 
   6548 void
   6549 remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
   6550 {
   6551   struct remote_state *rs = get_remote_state ();
   6552 
   6553   /* When connected in non-stop mode, the core resumes threads
   6554      individually.  Resuming remote threads directly in target_resume
   6555      would thus result in sending one packet per thread.  Instead, to
   6556      minimize roundtrip latency, here we just store the resume
   6557      request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
   6558      resumption will be done in remote_target::commit_resume, where we'll be
   6559      able to do vCont action coalescing.  */
   6560   if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
   6561     {
   6562       remote_thread_info *remote_thr
   6563 	= get_remote_thread_info (inferior_thread ());
   6564 
   6565       /* We don't expect the core to ask to resume an already resumed (from
   6566          its point of view) thread.  */
   6567       gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
   6568 
   6569       remote_thr->set_resumed_pending_vcont (step, siggnal);
   6570 
   6571       /* There's actually nothing that says that the core can't
   6572 	 request a wildcard resume in non-stop mode, though.  It's
   6573 	 just that we know it doesn't currently, so we don't bother
   6574 	 with it.  */
   6575       gdb_assert (scope_ptid == inferior_ptid);
   6576       return;
   6577     }
   6578 
   6579   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
   6580      (explained in remote-notif.c:handle_notification) so
   6581      remote_notif_process is not called.  We need find a place where
   6582      it is safe to start a 'vNotif' sequence.  It is good to do it
   6583      before resuming inferior, because inferior was stopped and no RSP
   6584      traffic at that moment.  */
   6585   if (!target_is_non_stop_p ())
   6586     remote_notif_process (rs->notif_state, &notif_client_stop);
   6587 
   6588   rs->last_resume_exec_dir = ::execution_direction;
   6589 
   6590   /* Prefer vCont, and fallback to s/c/S/C, which use Hc.  */
   6591   if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
   6592     remote_resume_with_hc (scope_ptid, step, siggnal);
   6593 
   6594   /* Update resumed state tracked by the remote target.  */
   6595   for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
   6596     get_remote_thread_info (tp)->set_resumed ();
   6597 
   6598   /* We've just told the target to resume.  The remote server will
   6599      wait for the inferior to stop, and then send a stop reply.  In
   6600      the mean time, we can't start another command/query ourselves
   6601      because the stub wouldn't be ready to process it.  This applies
   6602      only to the base all-stop protocol, however.  In non-stop (which
   6603      only supports vCont), the stub replies with an "OK", and is
   6604      immediate able to process further serial input.  */
   6605   if (!target_is_non_stop_p ())
   6606     rs->waiting_for_stop_reply = 1;
   6607 }
   6608 
   6609 /* Private per-inferior info for target remote processes.  */
   6610 
   6611 struct remote_inferior : public private_inferior
   6612 {
   6613   /* Whether we can send a wildcard vCont for this process.  */
   6614   bool may_wildcard_vcont = true;
   6615 };
   6616 
   6617 /* Get the remote private inferior data associated to INF.  */
   6618 
   6619 static remote_inferior *
   6620 get_remote_inferior (inferior *inf)
   6621 {
   6622   if (inf->priv == NULL)
   6623     inf->priv.reset (new remote_inferior);
   6624 
   6625   return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
   6626 }
   6627 
   6628 /* Class used to track the construction of a vCont packet in the
   6629    outgoing packet buffer.  This is used to send multiple vCont
   6630    packets if we have more actions than would fit a single packet.  */
   6631 
   6632 class vcont_builder
   6633 {
   6634 public:
   6635   explicit vcont_builder (remote_target *remote)
   6636     : m_remote (remote)
   6637   {
   6638     restart ();
   6639   }
   6640 
   6641   void flush ();
   6642   void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
   6643 
   6644 private:
   6645   void restart ();
   6646 
   6647   /* The remote target.  */
   6648   remote_target *m_remote;
   6649 
   6650   /* Pointer to the first action.  P points here if no action has been
   6651      appended yet.  */
   6652   char *m_first_action;
   6653 
   6654   /* Where the next action will be appended.  */
   6655   char *m_p;
   6656 
   6657   /* The end of the buffer.  Must never write past this.  */
   6658   char *m_endp;
   6659 };
   6660 
   6661 /* Prepare the outgoing buffer for a new vCont packet.  */
   6662 
   6663 void
   6664 vcont_builder::restart ()
   6665 {
   6666   struct remote_state *rs = m_remote->get_remote_state ();
   6667 
   6668   m_p = rs->buf.data ();
   6669   m_endp = m_p + m_remote->get_remote_packet_size ();
   6670   m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
   6671   m_first_action = m_p;
   6672 }
   6673 
   6674 /* If the vCont packet being built has any action, send it to the
   6675    remote end.  */
   6676 
   6677 void
   6678 vcont_builder::flush ()
   6679 {
   6680   struct remote_state *rs;
   6681 
   6682   if (m_p == m_first_action)
   6683     return;
   6684 
   6685   rs = m_remote->get_remote_state ();
   6686   m_remote->putpkt (rs->buf);
   6687   m_remote->getpkt (&rs->buf, 0);
   6688   if (strcmp (rs->buf.data (), "OK") != 0)
   6689     error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
   6690 }
   6691 
   6692 /* The largest action is range-stepping, with its two addresses.  This
   6693    is more than sufficient.  If a new, bigger action is created, it'll
   6694    quickly trigger a failed assertion in append_resumption (and we'll
   6695    just bump this).  */
   6696 #define MAX_ACTION_SIZE 200
   6697 
   6698 /* Append a new vCont action in the outgoing packet being built.  If
   6699    the action doesn't fit the packet along with previous actions, push
   6700    what we've got so far to the remote end and start over a new vCont
   6701    packet (with the new action).  */
   6702 
   6703 void
   6704 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
   6705 {
   6706   char buf[MAX_ACTION_SIZE + 1];
   6707 
   6708   char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
   6709 					    ptid, step, siggnal);
   6710 
   6711   /* Check whether this new action would fit in the vCont packet along
   6712      with previous actions.  If not, send what we've got so far and
   6713      start a new vCont packet.  */
   6714   size_t rsize = endp - buf;
   6715   if (rsize > m_endp - m_p)
   6716     {
   6717       flush ();
   6718       restart ();
   6719 
   6720       /* Should now fit.  */
   6721       gdb_assert (rsize <= m_endp - m_p);
   6722     }
   6723 
   6724   memcpy (m_p, buf, rsize);
   6725   m_p += rsize;
   6726   *m_p = '\0';
   6727 }
   6728 
   6729 /* to_commit_resume implementation.  */
   6730 
   6731 void
   6732 remote_target::commit_resumed ()
   6733 {
   6734   /* If connected in all-stop mode, we'd send the remote resume
   6735      request directly from remote_resume.  Likewise if
   6736      reverse-debugging, as there are no defined vCont actions for
   6737      reverse execution.  */
   6738   if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
   6739     return;
   6740 
   6741   /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
   6742      instead of resuming all threads of each process individually.
   6743      However, if any thread of a process must remain halted, we can't
   6744      send wildcard resumes and must send one action per thread.
   6745 
   6746      Care must be taken to not resume threads/processes the server
   6747      side already told us are stopped, but the core doesn't know about
   6748      yet, because the events are still in the vStopped notification
   6749      queue.  For example:
   6750 
   6751        #1 => vCont s:p1.1;c
   6752        #2 <= OK
   6753        #3 <= %Stopped T05 p1.1
   6754        #4 => vStopped
   6755        #5 <= T05 p1.2
   6756        #6 => vStopped
   6757        #7 <= OK
   6758        #8 (infrun handles the stop for p1.1 and continues stepping)
   6759        #9 => vCont s:p1.1;c
   6760 
   6761      The last vCont above would resume thread p1.2 by mistake, because
   6762      the server has no idea that the event for p1.2 had not been
   6763      handled yet.
   6764 
   6765      The server side must similarly ignore resume actions for the
   6766      thread that has a pending %Stopped notification (and any other
   6767      threads with events pending), until GDB acks the notification
   6768      with vStopped.  Otherwise, e.g., the following case is
   6769      mishandled:
   6770 
   6771        #1 => g  (or any other packet)
   6772        #2 <= [registers]
   6773        #3 <= %Stopped T05 p1.2
   6774        #4 => vCont s:p1.1;c
   6775        #5 <= OK
   6776 
   6777      Above, the server must not resume thread p1.2.  GDB can't know
   6778      that p1.2 stopped until it acks the %Stopped notification, and
   6779      since from GDB's perspective all threads should be running, it
   6780      sends a "c" action.
   6781 
   6782      Finally, special care must also be given to handling fork/vfork
   6783      events.  A (v)fork event actually tells us that two processes
   6784      stopped -- the parent and the child.  Until we follow the fork,
   6785      we must not resume the child.  Therefore, if we have a pending
   6786      fork follow, we must not send a global wildcard resume action
   6787      (vCont;c).  We can still send process-wide wildcards though.  */
   6788 
   6789   /* Start by assuming a global wildcard (vCont;c) is possible.  */
   6790   bool may_global_wildcard_vcont = true;
   6791 
   6792   /* And assume every process is individually wildcard-able too.  */
   6793   for (inferior *inf : all_non_exited_inferiors (this))
   6794     {
   6795       remote_inferior *priv = get_remote_inferior (inf);
   6796 
   6797       priv->may_wildcard_vcont = true;
   6798     }
   6799 
   6800   /* Check for any pending events (not reported or processed yet) and
   6801      disable process and global wildcard resumes appropriately.  */
   6802   check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
   6803 
   6804   bool any_pending_vcont_resume = false;
   6805 
   6806   for (thread_info *tp : all_non_exited_threads (this))
   6807     {
   6808       remote_thread_info *priv = get_remote_thread_info (tp);
   6809 
   6810       /* If a thread of a process is not meant to be resumed, then we
   6811 	 can't wildcard that process.  */
   6812       if (priv->get_resume_state () == resume_state::NOT_RESUMED)
   6813 	{
   6814 	  get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
   6815 
   6816 	  /* And if we can't wildcard a process, we can't wildcard
   6817 	     everything either.  */
   6818 	  may_global_wildcard_vcont = false;
   6819 	  continue;
   6820 	}
   6821 
   6822       if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
   6823 	any_pending_vcont_resume = true;
   6824 
   6825       /* If a thread is the parent of an unfollowed fork, then we
   6826 	 can't do a global wildcard, as that would resume the fork
   6827 	 child.  */
   6828       if (thread_pending_fork_status (tp) != nullptr)
   6829 	may_global_wildcard_vcont = false;
   6830     }
   6831 
   6832   /* We didn't have any resumed thread pending a vCont resume, so nothing to
   6833      do.  */
   6834   if (!any_pending_vcont_resume)
   6835     return;
   6836 
   6837   /* Now let's build the vCont packet(s).  Actions must be appended
   6838      from narrower to wider scopes (thread -> process -> global).  If
   6839      we end up with too many actions for a single packet vcont_builder
   6840      flushes the current vCont packet to the remote side and starts a
   6841      new one.  */
   6842   struct vcont_builder vcont_builder (this);
   6843 
   6844   /* Threads first.  */
   6845   for (thread_info *tp : all_non_exited_threads (this))
   6846     {
   6847       remote_thread_info *remote_thr = get_remote_thread_info (tp);
   6848 
   6849       /* If the thread was previously vCont-resumed, no need to send a specific
   6850 	 action for it.  If we didn't receive a resume request for it, don't
   6851 	 send an action for it either.  */
   6852       if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
   6853 	continue;
   6854 
   6855       gdb_assert (!thread_is_in_step_over_chain (tp));
   6856 
   6857       /* We should never be commit-resuming a thread that has a stop reply.
   6858          Otherwise, we would end up reporting a stop event for a thread while
   6859 	 it is running on the remote target.  */
   6860       remote_state *rs = get_remote_state ();
   6861       for (const auto &stop_reply : rs->stop_reply_queue)
   6862 	gdb_assert (stop_reply->ptid != tp->ptid);
   6863 
   6864       const resumed_pending_vcont_info &info
   6865 	= remote_thr->resumed_pending_vcont_info ();
   6866 
   6867       /* Check if we need to send a specific action for this thread.  If not,
   6868          it will be included in a wildcard resume instead.  */
   6869       if (info.step || info.sig != GDB_SIGNAL_0
   6870 	  || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
   6871 	vcont_builder.push_action (tp->ptid, info.step, info.sig);
   6872 
   6873       remote_thr->set_resumed ();
   6874     }
   6875 
   6876   /* Now check whether we can send any process-wide wildcard.  This is
   6877      to avoid sending a global wildcard in the case nothing is
   6878      supposed to be resumed.  */
   6879   bool any_process_wildcard = false;
   6880 
   6881   for (inferior *inf : all_non_exited_inferiors (this))
   6882     {
   6883       if (get_remote_inferior (inf)->may_wildcard_vcont)
   6884 	{
   6885 	  any_process_wildcard = true;
   6886 	  break;
   6887 	}
   6888     }
   6889 
   6890   if (any_process_wildcard)
   6891     {
   6892       /* If all processes are wildcard-able, then send a single "c"
   6893 	 action, otherwise, send an "all (-1) threads of process"
   6894 	 continue action for each running process, if any.  */
   6895       if (may_global_wildcard_vcont)
   6896 	{
   6897 	  vcont_builder.push_action (minus_one_ptid,
   6898 				     false, GDB_SIGNAL_0);
   6899 	}
   6900       else
   6901 	{
   6902 	  for (inferior *inf : all_non_exited_inferiors (this))
   6903 	    {
   6904 	      if (get_remote_inferior (inf)->may_wildcard_vcont)
   6905 		{
   6906 		  vcont_builder.push_action (ptid_t (inf->pid),
   6907 					     false, GDB_SIGNAL_0);
   6908 		}
   6909 	    }
   6910 	}
   6911     }
   6912 
   6913   vcont_builder.flush ();
   6914 }
   6915 
   6916 /* Implementation of target_has_pending_events.  */
   6917 
   6918 bool
   6919 remote_target::has_pending_events ()
   6920 {
   6921   if (target_can_async_p ())
   6922     {
   6923       remote_state *rs = get_remote_state ();
   6924 
   6925       if (async_event_handler_marked (rs->remote_async_inferior_event_token))
   6926 	return true;
   6927 
   6928       /* Note that BUFCNT can be negative, indicating sticky
   6929 	 error.  */
   6930       if (rs->remote_desc->bufcnt != 0)
   6931 	return true;
   6932     }
   6933   return false;
   6934 }
   6935 
   6936 
   6937 
   6939 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
   6940    thread, all threads of a remote process, or all threads of all
   6941    processes.  */
   6942 
   6943 void
   6944 remote_target::remote_stop_ns (ptid_t ptid)
   6945 {
   6946   struct remote_state *rs = get_remote_state ();
   6947   char *p = rs->buf.data ();
   6948   char *endp = p + get_remote_packet_size ();
   6949 
   6950   /* If any thread that needs to stop was resumed but pending a vCont
   6951      resume, generate a phony stop_reply.  However, first check
   6952      whether the thread wasn't resumed with a signal.  Generating a
   6953      phony stop in that case would result in losing the signal.  */
   6954   bool needs_commit = false;
   6955   for (thread_info *tp : all_non_exited_threads (this, ptid))
   6956     {
   6957       remote_thread_info *remote_thr = get_remote_thread_info (tp);
   6958 
   6959       if (remote_thr->get_resume_state ()
   6960 	  == resume_state::RESUMED_PENDING_VCONT)
   6961 	{
   6962 	  const resumed_pending_vcont_info &info
   6963 	    = remote_thr->resumed_pending_vcont_info ();
   6964 	  if (info.sig != GDB_SIGNAL_0)
   6965 	    {
   6966 	      /* This signal must be forwarded to the inferior.  We
   6967 		 could commit-resume just this thread, but its simpler
   6968 		 to just commit-resume everything.  */
   6969 	      needs_commit = true;
   6970 	      break;
   6971 	    }
   6972 	}
   6973     }
   6974 
   6975   if (needs_commit)
   6976     commit_resumed ();
   6977   else
   6978     for (thread_info *tp : all_non_exited_threads (this, ptid))
   6979       {
   6980 	remote_thread_info *remote_thr = get_remote_thread_info (tp);
   6981 
   6982 	if (remote_thr->get_resume_state ()
   6983 	    == resume_state::RESUMED_PENDING_VCONT)
   6984 	  {
   6985 	    remote_debug_printf ("Enqueueing phony stop reply for thread pending "
   6986 				 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
   6987 				 tp->ptid.lwp (),
   6988 				 pulongest (tp->ptid.tid ()));
   6989 
   6990 	    /* Check that the thread wasn't resumed with a signal.
   6991 	       Generating a phony stop would result in losing the
   6992 	       signal.  */
   6993 	    const resumed_pending_vcont_info &info
   6994 	      = remote_thr->resumed_pending_vcont_info ();
   6995 	    gdb_assert (info.sig == GDB_SIGNAL_0);
   6996 
   6997 	    stop_reply *sr = new stop_reply ();
   6998 	    sr->ptid = tp->ptid;
   6999 	    sr->rs = rs;
   7000 	    sr->ws.set_stopped (GDB_SIGNAL_0);
   7001 	    sr->arch = tp->inf->gdbarch;
   7002 	    sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
   7003 	    sr->watch_data_address = 0;
   7004 	    sr->core = 0;
   7005 	    this->push_stop_reply (sr);
   7006 
   7007 	    /* Pretend that this thread was actually resumed on the
   7008 	       remote target, then stopped.  If we leave it in the
   7009 	       RESUMED_PENDING_VCONT state and the commit_resumed
   7010 	       method is called while the stop reply is still in the
   7011 	       queue, we'll end up reporting a stop event to the core
   7012 	       for that thread while it is running on the remote
   7013 	       target... that would be bad.  */
   7014 	    remote_thr->set_resumed ();
   7015 	  }
   7016       }
   7017 
   7018   /* FIXME: This supports_vCont_probed check is a workaround until
   7019      packet_support is per-connection.  */
   7020   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN
   7021       || !rs->supports_vCont_probed)
   7022     remote_vcont_probe ();
   7023 
   7024   if (!rs->supports_vCont.t)
   7025     error (_("Remote server does not support stopping threads"));
   7026 
   7027   if (ptid == minus_one_ptid
   7028       || (!remote_multi_process_p (rs) && ptid.is_pid ()))
   7029     p += xsnprintf (p, endp - p, "vCont;t");
   7030   else
   7031     {
   7032       ptid_t nptid;
   7033 
   7034       p += xsnprintf (p, endp - p, "vCont;t:");
   7035 
   7036       if (ptid.is_pid ())
   7037 	  /* All (-1) threads of process.  */
   7038 	nptid = ptid_t (ptid.pid (), -1);
   7039       else
   7040 	{
   7041 	  /* Small optimization: if we already have a stop reply for
   7042 	     this thread, no use in telling the stub we want this
   7043 	     stopped.  */
   7044 	  if (peek_stop_reply (ptid))
   7045 	    return;
   7046 
   7047 	  nptid = ptid;
   7048 	}
   7049 
   7050       write_ptid (p, endp, nptid);
   7051     }
   7052 
   7053   /* In non-stop, we get an immediate OK reply.  The stop reply will
   7054      come in asynchronously by notification.  */
   7055   putpkt (rs->buf);
   7056   getpkt (&rs->buf, 0);
   7057   if (strcmp (rs->buf.data (), "OK") != 0)
   7058     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
   7059 	   rs->buf.data ());
   7060 }
   7061 
   7062 /* All-stop version of target_interrupt.  Sends a break or a ^C to
   7063    interrupt the remote target.  It is undefined which thread of which
   7064    process reports the interrupt.  */
   7065 
   7066 void
   7067 remote_target::remote_interrupt_as ()
   7068 {
   7069   struct remote_state *rs = get_remote_state ();
   7070 
   7071   rs->ctrlc_pending_p = 1;
   7072 
   7073   /* If the inferior is stopped already, but the core didn't know
   7074      about it yet, just ignore the request.  The pending stop events
   7075      will be collected in remote_wait.  */
   7076   if (stop_reply_queue_length () > 0)
   7077     return;
   7078 
   7079   /* Send interrupt_sequence to remote target.  */
   7080   send_interrupt_sequence ();
   7081 }
   7082 
   7083 /* Non-stop version of target_interrupt.  Uses `vCtrlC' to interrupt
   7084    the remote target.  It is undefined which thread of which process
   7085    reports the interrupt.  Throws an error if the packet is not
   7086    supported by the server.  */
   7087 
   7088 void
   7089 remote_target::remote_interrupt_ns ()
   7090 {
   7091   struct remote_state *rs = get_remote_state ();
   7092   char *p = rs->buf.data ();
   7093   char *endp = p + get_remote_packet_size ();
   7094 
   7095   xsnprintf (p, endp - p, "vCtrlC");
   7096 
   7097   /* In non-stop, we get an immediate OK reply.  The stop reply will
   7098      come in asynchronously by notification.  */
   7099   putpkt (rs->buf);
   7100   getpkt (&rs->buf, 0);
   7101 
   7102   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
   7103     {
   7104     case PACKET_OK:
   7105       break;
   7106     case PACKET_UNKNOWN:
   7107       error (_("No support for interrupting the remote target."));
   7108     case PACKET_ERROR:
   7109       error (_("Interrupting target failed: %s"), rs->buf.data ());
   7110     }
   7111 }
   7112 
   7113 /* Implement the to_stop function for the remote targets.  */
   7114 
   7115 void
   7116 remote_target::stop (ptid_t ptid)
   7117 {
   7118   REMOTE_SCOPED_DEBUG_ENTER_EXIT;
   7119 
   7120   if (target_is_non_stop_p ())
   7121     remote_stop_ns (ptid);
   7122   else
   7123     {
   7124       /* We don't currently have a way to transparently pause the
   7125 	 remote target in all-stop mode.  Interrupt it instead.  */
   7126       remote_interrupt_as ();
   7127     }
   7128 }
   7129 
   7130 /* Implement the to_interrupt function for the remote targets.  */
   7131 
   7132 void
   7133 remote_target::interrupt ()
   7134 {
   7135   REMOTE_SCOPED_DEBUG_ENTER_EXIT;
   7136 
   7137   if (target_is_non_stop_p ())
   7138     remote_interrupt_ns ();
   7139   else
   7140     remote_interrupt_as ();
   7141 }
   7142 
   7143 /* Implement the to_pass_ctrlc function for the remote targets.  */
   7144 
   7145 void
   7146 remote_target::pass_ctrlc ()
   7147 {
   7148   REMOTE_SCOPED_DEBUG_ENTER_EXIT;
   7149 
   7150   struct remote_state *rs = get_remote_state ();
   7151 
   7152   /* If we're starting up, we're not fully synced yet.  Quit
   7153      immediately.  */
   7154   if (rs->starting_up)
   7155     quit ();
   7156   /* If ^C has already been sent once, offer to disconnect.  */
   7157   else if (rs->ctrlc_pending_p)
   7158     interrupt_query ();
   7159   else
   7160     target_interrupt ();
   7161 }
   7162 
   7163 /* Ask the user what to do when an interrupt is received.  */
   7164 
   7165 void
   7166 remote_target::interrupt_query ()
   7167 {
   7168   struct remote_state *rs = get_remote_state ();
   7169 
   7170   if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
   7171     {
   7172       if (query (_("The target is not responding to interrupt requests.\n"
   7173 		   "Stop debugging it? ")))
   7174 	{
   7175 	  remote_unpush_target (this);
   7176 	  throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
   7177 	}
   7178     }
   7179   else
   7180     {
   7181       if (query (_("Interrupted while waiting for the program.\n"
   7182 		   "Give up waiting? ")))
   7183 	quit ();
   7184     }
   7185 }
   7186 
   7187 /* Enable/disable target terminal ownership.  Most targets can use
   7188    terminal groups to control terminal ownership.  Remote targets are
   7189    different in that explicit transfer of ownership to/from GDB/target
   7190    is required.  */
   7191 
   7192 void
   7193 remote_target::terminal_inferior ()
   7194 {
   7195   /* NOTE: At this point we could also register our selves as the
   7196      recipient of all input.  Any characters typed could then be
   7197      passed on down to the target.  */
   7198 }
   7199 
   7200 void
   7201 remote_target::terminal_ours ()
   7202 {
   7203 }
   7204 
   7205 static void
   7206 remote_console_output (const char *msg)
   7207 {
   7208   const char *p;
   7209 
   7210   for (p = msg; p[0] && p[1]; p += 2)
   7211     {
   7212       char tb[2];
   7213       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
   7214 
   7215       tb[0] = c;
   7216       tb[1] = 0;
   7217       gdb_stdtarg->puts (tb);
   7218     }
   7219   gdb_stdtarg->flush ();
   7220 }
   7221 
   7222 /* Return the length of the stop reply queue.  */
   7223 
   7224 int
   7225 remote_target::stop_reply_queue_length ()
   7226 {
   7227   remote_state *rs = get_remote_state ();
   7228   return rs->stop_reply_queue.size ();
   7229 }
   7230 
   7231 static void
   7232 remote_notif_stop_parse (remote_target *remote,
   7233 			 struct notif_client *self, const char *buf,
   7234 			 struct notif_event *event)
   7235 {
   7236   remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
   7237 }
   7238 
   7239 static void
   7240 remote_notif_stop_ack (remote_target *remote,
   7241 		       struct notif_client *self, const char *buf,
   7242 		       struct notif_event *event)
   7243 {
   7244   struct stop_reply *stop_reply = (struct stop_reply *) event;
   7245 
   7246   /* acknowledge */
   7247   putpkt (remote, self->ack_command);
   7248 
   7249   /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
   7250      the notification.  It was left in the queue because we need to
   7251      acknowledge it and pull the rest of the notifications out.  */
   7252   if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
   7253     remote->push_stop_reply (stop_reply);
   7254 }
   7255 
   7256 static int
   7257 remote_notif_stop_can_get_pending_events (remote_target *remote,
   7258 					  struct notif_client *self)
   7259 {
   7260   /* We can't get pending events in remote_notif_process for
   7261      notification stop, and we have to do this in remote_wait_ns
   7262      instead.  If we fetch all queued events from stub, remote stub
   7263      may exit and we have no chance to process them back in
   7264      remote_wait_ns.  */
   7265   remote_state *rs = remote->get_remote_state ();
   7266   mark_async_event_handler (rs->remote_async_inferior_event_token);
   7267   return 0;
   7268 }
   7269 
   7270 stop_reply::~stop_reply ()
   7271 {
   7272   for (cached_reg_t &reg : regcache)
   7273     xfree (reg.data);
   7274 }
   7275 
   7276 static notif_event_up
   7277 remote_notif_stop_alloc_reply ()
   7278 {
   7279   return notif_event_up (new struct stop_reply ());
   7280 }
   7281 
   7282 /* A client of notification Stop.  */
   7283 
   7284 struct notif_client notif_client_stop =
   7285 {
   7286   "Stop",
   7287   "vStopped",
   7288   remote_notif_stop_parse,
   7289   remote_notif_stop_ack,
   7290   remote_notif_stop_can_get_pending_events,
   7291   remote_notif_stop_alloc_reply,
   7292   REMOTE_NOTIF_STOP,
   7293 };
   7294 
   7295 /* If CONTEXT contains any fork child threads that have not been
   7296    reported yet, remove them from the CONTEXT list.  If such a
   7297    thread exists it is because we are stopped at a fork catchpoint
   7298    and have not yet called follow_fork, which will set up the
   7299    host-side data structures for the new process.  */
   7300 
   7301 void
   7302 remote_target::remove_new_fork_children (threads_listing_context *context)
   7303 {
   7304   struct notif_client *notif = &notif_client_stop;
   7305 
   7306   /* For any threads stopped at a fork event, remove the corresponding
   7307      fork child threads from the CONTEXT list.  */
   7308   for (thread_info *thread : all_non_exited_threads (this))
   7309     {
   7310       const target_waitstatus *ws = thread_pending_fork_status (thread);
   7311 
   7312       if (ws == nullptr)
   7313 	continue;
   7314 
   7315       context->remove_thread (ws->child_ptid ());
   7316     }
   7317 
   7318   /* Check for any pending fork events (not reported or processed yet)
   7319      in process PID and remove those fork child threads from the
   7320      CONTEXT list as well.  */
   7321   remote_notif_get_pending_events (notif);
   7322   for (auto &event : get_remote_state ()->stop_reply_queue)
   7323     if (event->ws.kind () == TARGET_WAITKIND_FORKED
   7324 	|| event->ws.kind () == TARGET_WAITKIND_VFORKED)
   7325       context->remove_thread (event->ws.child_ptid ());
   7326     else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
   7327       context->remove_thread (event->ptid);
   7328 }
   7329 
   7330 /* Check whether any event pending in the vStopped queue would prevent a
   7331    global or process wildcard vCont action.  Set *may_global_wildcard to
   7332    false if we can't do a global wildcard (vCont;c), and clear the event
   7333    inferior's may_wildcard_vcont flag if we can't do a process-wide
   7334    wildcard resume (vCont;c:pPID.-1).  */
   7335 
   7336 void
   7337 remote_target::check_pending_events_prevent_wildcard_vcont
   7338   (bool *may_global_wildcard)
   7339 {
   7340   struct notif_client *notif = &notif_client_stop;
   7341 
   7342   remote_notif_get_pending_events (notif);
   7343   for (auto &event : get_remote_state ()->stop_reply_queue)
   7344     {
   7345       if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
   7346 	  || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
   7347 	continue;
   7348 
   7349       if (event->ws.kind () == TARGET_WAITKIND_FORKED
   7350 	  || event->ws.kind () == TARGET_WAITKIND_VFORKED)
   7351 	*may_global_wildcard = false;
   7352 
   7353       /* This may be the first time we heard about this process.
   7354 	 Regardless, we must not do a global wildcard resume, otherwise
   7355 	 we'd resume this process too.  */
   7356       *may_global_wildcard = false;
   7357       if (event->ptid != null_ptid)
   7358 	{
   7359 	  inferior *inf = find_inferior_ptid (this, event->ptid);
   7360 	  if (inf != NULL)
   7361 	    get_remote_inferior (inf)->may_wildcard_vcont = false;
   7362 	}
   7363     }
   7364 }
   7365 
   7366 /* Discard all pending stop replies of inferior INF.  */
   7367 
   7368 void
   7369 remote_target::discard_pending_stop_replies (struct inferior *inf)
   7370 {
   7371   struct stop_reply *reply;
   7372   struct remote_state *rs = get_remote_state ();
   7373   struct remote_notif_state *rns = rs->notif_state;
   7374 
   7375   /* This function can be notified when an inferior exists.  When the
   7376      target is not remote, the notification state is NULL.  */
   7377   if (rs->remote_desc == NULL)
   7378     return;
   7379 
   7380   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
   7381 
   7382   /* Discard the in-flight notification.  */
   7383   if (reply != NULL && reply->ptid.pid () == inf->pid)
   7384     {
   7385       /* Leave the notification pending, since the server expects that
   7386 	 we acknowledge it with vStopped.  But clear its contents, so
   7387 	 that later on when we acknowledge it, we also discard it.  */
   7388       remote_debug_printf
   7389 	("discarding in-flight notification: ptid: %s, ws: %s\n",
   7390 	 reply->ptid.to_string().c_str(),
   7391 	 reply->ws.to_string ().c_str ());
   7392       reply->ws.set_ignore ();
   7393     }
   7394 
   7395   /* Discard the stop replies we have already pulled with
   7396      vStopped.  */
   7397   auto iter = std::remove_if (rs->stop_reply_queue.begin (),
   7398 			      rs->stop_reply_queue.end (),
   7399 			      [=] (const stop_reply_up &event)
   7400 			      {
   7401 				return event->ptid.pid () == inf->pid;
   7402 			      });
   7403   for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
   7404     remote_debug_printf
   7405       ("discarding queued stop reply: ptid: %s, ws: %s\n",
   7406        reply->ptid.to_string().c_str(),
   7407        reply->ws.to_string ().c_str ());
   7408   rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
   7409 }
   7410 
   7411 /* Discard the stop replies for RS in stop_reply_queue.  */
   7412 
   7413 void
   7414 remote_target::discard_pending_stop_replies_in_queue ()
   7415 {
   7416   remote_state *rs = get_remote_state ();
   7417 
   7418   /* Discard the stop replies we have already pulled with
   7419      vStopped.  */
   7420   auto iter = std::remove_if (rs->stop_reply_queue.begin (),
   7421 			      rs->stop_reply_queue.end (),
   7422 			      [=] (const stop_reply_up &event)
   7423 			      {
   7424 				return event->rs == rs;
   7425 			      });
   7426   rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
   7427 }
   7428 
   7429 /* Remove the first reply in 'stop_reply_queue' which matches
   7430    PTID.  */
   7431 
   7432 struct stop_reply *
   7433 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
   7434 {
   7435   remote_state *rs = get_remote_state ();
   7436 
   7437   auto iter = std::find_if (rs->stop_reply_queue.begin (),
   7438 			    rs->stop_reply_queue.end (),
   7439 			    [=] (const stop_reply_up &event)
   7440 			    {
   7441 			      return event->ptid.matches (ptid);
   7442 			    });
   7443   struct stop_reply *result;
   7444   if (iter == rs->stop_reply_queue.end ())
   7445     result = nullptr;
   7446   else
   7447     {
   7448       result = iter->release ();
   7449       rs->stop_reply_queue.erase (iter);
   7450     }
   7451 
   7452   if (notif_debug)
   7453     gdb_printf (gdb_stdlog,
   7454 		"notif: discard queued event: 'Stop' in %s\n",
   7455 		ptid.to_string ().c_str ());
   7456 
   7457   return result;
   7458 }
   7459 
   7460 /* Look for a queued stop reply belonging to PTID.  If one is found,
   7461    remove it from the queue, and return it.  Returns NULL if none is
   7462    found.  If there are still queued events left to process, tell the
   7463    event loop to get back to target_wait soon.  */
   7464 
   7465 struct stop_reply *
   7466 remote_target::queued_stop_reply (ptid_t ptid)
   7467 {
   7468   remote_state *rs = get_remote_state ();
   7469   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
   7470 
   7471   if (!rs->stop_reply_queue.empty () && target_can_async_p ())
   7472     {
   7473       /* There's still at least an event left.  */
   7474       mark_async_event_handler (rs->remote_async_inferior_event_token);
   7475     }
   7476 
   7477   return r;
   7478 }
   7479 
   7480 /* Push a fully parsed stop reply in the stop reply queue.  Since we
   7481    know that we now have at least one queued event left to pass to the
   7482    core side, tell the event loop to get back to target_wait soon.  */
   7483 
   7484 void
   7485 remote_target::push_stop_reply (struct stop_reply *new_event)
   7486 {
   7487   remote_state *rs = get_remote_state ();
   7488   rs->stop_reply_queue.push_back (stop_reply_up (new_event));
   7489 
   7490   if (notif_debug)
   7491     gdb_printf (gdb_stdlog,
   7492 		"notif: push 'Stop' %s to queue %d\n",
   7493 		new_event->ptid.to_string ().c_str (),
   7494 		int (rs->stop_reply_queue.size ()));
   7495 
   7496   /* Mark the pending event queue only if async mode is currently enabled.
   7497      If async mode is not currently enabled, then, if it later becomes
   7498      enabled, and there are events in this queue, we will mark the event
   7499      token at that point, see remote_target::async.  */
   7500   if (target_is_async_p ())
   7501     mark_async_event_handler (rs->remote_async_inferior_event_token);
   7502 }
   7503 
   7504 /* Returns true if we have a stop reply for PTID.  */
   7505 
   7506 int
   7507 remote_target::peek_stop_reply (ptid_t ptid)
   7508 {
   7509   remote_state *rs = get_remote_state ();
   7510   for (auto &event : rs->stop_reply_queue)
   7511     if (ptid == event->ptid
   7512 	&& event->ws.kind () == TARGET_WAITKIND_STOPPED)
   7513       return 1;
   7514   return 0;
   7515 }
   7516 
   7517 /* Helper for remote_parse_stop_reply.  Return nonzero if the substring
   7518    starting with P and ending with PEND matches PREFIX.  */
   7519 
   7520 static int
   7521 strprefix (const char *p, const char *pend, const char *prefix)
   7522 {
   7523   for ( ; p < pend; p++, prefix++)
   7524     if (*p != *prefix)
   7525       return 0;
   7526   return *prefix == '\0';
   7527 }
   7528 
   7529 /* Parse the stop reply in BUF.  Either the function succeeds, and the
   7530    result is stored in EVENT, or throws an error.  */
   7531 
   7532 void
   7533 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
   7534 {
   7535   remote_arch_state *rsa = NULL;
   7536   ULONGEST addr;
   7537   const char *p;
   7538   int skipregs = 0;
   7539 
   7540   event->ptid = null_ptid;
   7541   event->rs = get_remote_state ();
   7542   event->ws.set_ignore ();
   7543   event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
   7544   event->regcache.clear ();
   7545   event->core = -1;
   7546 
   7547   switch (buf[0])
   7548     {
   7549     case 'T':		/* Status with PC, SP, FP, ...	*/
   7550       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
   7551       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
   7552 	    ss = signal number
   7553 	    n... = register number
   7554 	    r... = register contents
   7555       */
   7556 
   7557       p = &buf[3];	/* after Txx */
   7558       while (*p)
   7559 	{
   7560 	  const char *p1;
   7561 	  int fieldsize;
   7562 
   7563 	  p1 = strchr (p, ':');
   7564 	  if (p1 == NULL)
   7565 	    error (_("Malformed packet(a) (missing colon): %s\n\
   7566 Packet: '%s'\n"),
   7567 		   p, buf);
   7568 	  if (p == p1)
   7569 	    error (_("Malformed packet(a) (missing register number): %s\n\
   7570 Packet: '%s'\n"),
   7571 		   p, buf);
   7572 
   7573 	  /* Some "registers" are actually extended stop information.
   7574 	     Note if you're adding a new entry here: GDB 7.9 and
   7575 	     earlier assume that all register "numbers" that start
   7576 	     with an hex digit are real register numbers.  Make sure
   7577 	     the server only sends such a packet if it knows the
   7578 	     client understands it.  */
   7579 
   7580 	  if (strprefix (p, p1, "thread"))
   7581 	    event->ptid = read_ptid (++p1, &p);
   7582 	  else if (strprefix (p, p1, "syscall_entry"))
   7583 	    {
   7584 	      ULONGEST sysno;
   7585 
   7586 	      p = unpack_varlen_hex (++p1, &sysno);
   7587 	      event->ws.set_syscall_entry ((int) sysno);
   7588 	    }
   7589 	  else if (strprefix (p, p1, "syscall_return"))
   7590 	    {
   7591 	      ULONGEST sysno;
   7592 
   7593 	      p = unpack_varlen_hex (++p1, &sysno);
   7594 	      event->ws.set_syscall_return ((int) sysno);
   7595 	    }
   7596 	  else if (strprefix (p, p1, "watch")
   7597 		   || strprefix (p, p1, "rwatch")
   7598 		   || strprefix (p, p1, "awatch"))
   7599 	    {
   7600 	      event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
   7601 	      p = unpack_varlen_hex (++p1, &addr);
   7602 	      event->watch_data_address = (CORE_ADDR) addr;
   7603 	    }
   7604 	  else if (strprefix (p, p1, "swbreak"))
   7605 	    {
   7606 	      event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
   7607 
   7608 	      /* Make sure the stub doesn't forget to indicate support
   7609 		 with qSupported.  */
   7610 	      if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
   7611 		error (_("Unexpected swbreak stop reason"));
   7612 
   7613 	      /* The value part is documented as "must be empty",
   7614 		 though we ignore it, in case we ever decide to make
   7615 		 use of it in a backward compatible way.  */
   7616 	      p = strchrnul (p1 + 1, ';');
   7617 	    }
   7618 	  else if (strprefix (p, p1, "hwbreak"))
   7619 	    {
   7620 	      event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
   7621 
   7622 	      /* Make sure the stub doesn't forget to indicate support
   7623 		 with qSupported.  */
   7624 	      if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
   7625 		error (_("Unexpected hwbreak stop reason"));
   7626 
   7627 	      /* See above.  */
   7628 	      p = strchrnul (p1 + 1, ';');
   7629 	    }
   7630 	  else if (strprefix (p, p1, "library"))
   7631 	    {
   7632 	      event->ws.set_loaded ();
   7633 	      p = strchrnul (p1 + 1, ';');
   7634 	    }
   7635 	  else if (strprefix (p, p1, "replaylog"))
   7636 	    {
   7637 	      event->ws.set_no_history ();
   7638 	      /* p1 will indicate "begin" or "end", but it makes
   7639 		 no difference for now, so ignore it.  */
   7640 	      p = strchrnul (p1 + 1, ';');
   7641 	    }
   7642 	  else if (strprefix (p, p1, "core"))
   7643 	    {
   7644 	      ULONGEST c;
   7645 
   7646 	      p = unpack_varlen_hex (++p1, &c);
   7647 	      event->core = c;
   7648 	    }
   7649 	  else if (strprefix (p, p1, "fork"))
   7650 	    event->ws.set_forked (read_ptid (++p1, &p));
   7651 	  else if (strprefix (p, p1, "vfork"))
   7652 	    event->ws.set_vforked (read_ptid (++p1, &p));
   7653 	  else if (strprefix (p, p1, "vforkdone"))
   7654 	    {
   7655 	      event->ws.set_vfork_done ();
   7656 	      p = strchrnul (p1 + 1, ';');
   7657 	    }
   7658 	  else if (strprefix (p, p1, "exec"))
   7659 	    {
   7660 	      ULONGEST ignored;
   7661 	      int pathlen;
   7662 
   7663 	      /* Determine the length of the execd pathname.  */
   7664 	      p = unpack_varlen_hex (++p1, &ignored);
   7665 	      pathlen = (p - p1) / 2;
   7666 
   7667 	      /* Save the pathname for event reporting and for
   7668 		 the next run command.  */
   7669 	      gdb::unique_xmalloc_ptr<char> pathname
   7670 		((char *) xmalloc (pathlen + 1));
   7671 	      hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
   7672 	      pathname.get ()[pathlen] = '\0';
   7673 
   7674 	      /* This is freed during event handling.  */
   7675 	      event->ws.set_execd (std::move (pathname));
   7676 
   7677 	      /* Skip the registers included in this packet, since
   7678 		 they may be for an architecture different from the
   7679 		 one used by the original program.  */
   7680 	      skipregs = 1;
   7681 	    }
   7682 	  else if (strprefix (p, p1, "create"))
   7683 	    {
   7684 	      event->ws.set_thread_created ();
   7685 	      p = strchrnul (p1 + 1, ';');
   7686 	    }
   7687 	  else
   7688 	    {
   7689 	      ULONGEST pnum;
   7690 	      const char *p_temp;
   7691 
   7692 	      if (skipregs)
   7693 		{
   7694 		  p = strchrnul (p1 + 1, ';');
   7695 		  p++;
   7696 		  continue;
   7697 		}
   7698 
   7699 	      /* Maybe a real ``P'' register number.  */
   7700 	      p_temp = unpack_varlen_hex (p, &pnum);
   7701 	      /* If the first invalid character is the colon, we got a
   7702 		 register number.  Otherwise, it's an unknown stop
   7703 		 reason.  */
   7704 	      if (p_temp == p1)
   7705 		{
   7706 		  /* If we haven't parsed the event's thread yet, find
   7707 		     it now, in order to find the architecture of the
   7708 		     reported expedited registers.  */
   7709 		  if (event->ptid == null_ptid)
   7710 		    {
   7711 		      /* If there is no thread-id information then leave
   7712 			 the event->ptid as null_ptid.  Later in
   7713 			 process_stop_reply we will pick a suitable
   7714 			 thread.  */
   7715 		      const char *thr = strstr (p1 + 1, ";thread:");
   7716 		      if (thr != NULL)
   7717 			event->ptid = read_ptid (thr + strlen (";thread:"),
   7718 						 NULL);
   7719 		    }
   7720 
   7721 		  if (rsa == NULL)
   7722 		    {
   7723 		      inferior *inf
   7724 			= (event->ptid == null_ptid
   7725 			   ? NULL
   7726 			   : find_inferior_ptid (this, event->ptid));
   7727 		      /* If this is the first time we learn anything
   7728 			 about this process, skip the registers
   7729 			 included in this packet, since we don't yet
   7730 			 know which architecture to use to parse them.
   7731 			 We'll determine the architecture later when
   7732 			 we process the stop reply and retrieve the
   7733 			 target description, via
   7734 			 remote_notice_new_inferior ->
   7735 			 post_create_inferior.  */
   7736 		      if (inf == NULL)
   7737 			{
   7738 			  p = strchrnul (p1 + 1, ';');
   7739 			  p++;
   7740 			  continue;
   7741 			}
   7742 
   7743 		      event->arch = inf->gdbarch;
   7744 		      rsa = event->rs->get_remote_arch_state (event->arch);
   7745 		    }
   7746 
   7747 		  packet_reg *reg
   7748 		    = packet_reg_from_pnum (event->arch, rsa, pnum);
   7749 		  cached_reg_t cached_reg;
   7750 
   7751 		  if (reg == NULL)
   7752 		    error (_("Remote sent bad register number %s: %s\n\
   7753 Packet: '%s'\n"),
   7754 			   hex_string (pnum), p, buf);
   7755 
   7756 		  cached_reg.num = reg->regnum;
   7757 		  cached_reg.data = (gdb_byte *)
   7758 		    xmalloc (register_size (event->arch, reg->regnum));
   7759 
   7760 		  p = p1 + 1;
   7761 		  fieldsize = hex2bin (p, cached_reg.data,
   7762 				       register_size (event->arch, reg->regnum));
   7763 		  p += 2 * fieldsize;
   7764 		  if (fieldsize < register_size (event->arch, reg->regnum))
   7765 		    warning (_("Remote reply is too short: %s"), buf);
   7766 
   7767 		  event->regcache.push_back (cached_reg);
   7768 		}
   7769 	      else
   7770 		{
   7771 		  /* Not a number.  Silently skip unknown optional
   7772 		     info.  */
   7773 		  p = strchrnul (p1 + 1, ';');
   7774 		}
   7775 	    }
   7776 
   7777 	  if (*p != ';')
   7778 	    error (_("Remote register badly formatted: %s\nhere: %s"),
   7779 		   buf, p);
   7780 	  ++p;
   7781 	}
   7782 
   7783       if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
   7784 	break;
   7785 
   7786       /* fall through */
   7787     case 'S':		/* Old style status, just signal only.  */
   7788       {
   7789 	int sig;
   7790 
   7791 	sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
   7792 	if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
   7793 	  event->ws.set_stopped ((enum gdb_signal) sig);
   7794 	else
   7795 	  event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
   7796       }
   7797       break;
   7798     case 'w':		/* Thread exited.  */
   7799       {
   7800 	ULONGEST value;
   7801 
   7802 	p = unpack_varlen_hex (&buf[1], &value);
   7803 	event->ws.set_thread_exited (value);
   7804 	if (*p != ';')
   7805 	  error (_("stop reply packet badly formatted: %s"), buf);
   7806 	event->ptid = read_ptid (++p, NULL);
   7807 	break;
   7808       }
   7809     case 'W':		/* Target exited.  */
   7810     case 'X':
   7811       {
   7812 	ULONGEST value;
   7813 
   7814 	/* GDB used to accept only 2 hex chars here.  Stubs should
   7815 	   only send more if they detect GDB supports multi-process
   7816 	   support.  */
   7817 	p = unpack_varlen_hex (&buf[1], &value);
   7818 
   7819 	if (buf[0] == 'W')
   7820 	  {
   7821 	    /* The remote process exited.  */
   7822 	    event->ws.set_exited (value);
   7823 	  }
   7824 	else
   7825 	  {
   7826 	    /* The remote process exited with a signal.  */
   7827 	    if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
   7828 	      event->ws.set_signalled ((enum gdb_signal) value);
   7829 	    else
   7830 	      event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
   7831 	  }
   7832 
   7833 	/* If no process is specified, return null_ptid, and let the
   7834 	   caller figure out the right process to use.  */
   7835 	int pid = 0;
   7836 	if (*p == '\0')
   7837 	  ;
   7838 	else if (*p == ';')
   7839 	  {
   7840 	    p++;
   7841 
   7842 	    if (*p == '\0')
   7843 	      ;
   7844 	    else if (startswith (p, "process:"))
   7845 	      {
   7846 		ULONGEST upid;
   7847 
   7848 		p += sizeof ("process:") - 1;
   7849 		unpack_varlen_hex (p, &upid);
   7850 		pid = upid;
   7851 	      }
   7852 	    else
   7853 	      error (_("unknown stop reply packet: %s"), buf);
   7854 	  }
   7855 	else
   7856 	  error (_("unknown stop reply packet: %s"), buf);
   7857 	event->ptid = ptid_t (pid);
   7858       }
   7859       break;
   7860     case 'N':
   7861       event->ws.set_no_resumed ();
   7862       event->ptid = minus_one_ptid;
   7863       break;
   7864     }
   7865 }
   7866 
   7867 /* When the stub wants to tell GDB about a new notification reply, it
   7868    sends a notification (%Stop, for example).  Those can come it at
   7869    any time, hence, we have to make sure that any pending
   7870    putpkt/getpkt sequence we're making is finished, before querying
   7871    the stub for more events with the corresponding ack command
   7872    (vStopped, for example).  E.g., if we started a vStopped sequence
   7873    immediately upon receiving the notification, something like this
   7874    could happen:
   7875 
   7876     1.1) --> Hg 1
   7877     1.2) <-- OK
   7878     1.3) --> g
   7879     1.4) <-- %Stop
   7880     1.5) --> vStopped
   7881     1.6) <-- (registers reply to step #1.3)
   7882 
   7883    Obviously, the reply in step #1.6 would be unexpected to a vStopped
   7884    query.
   7885 
   7886    To solve this, whenever we parse a %Stop notification successfully,
   7887    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
   7888    doing whatever we were doing:
   7889 
   7890     2.1) --> Hg 1
   7891     2.2) <-- OK
   7892     2.3) --> g
   7893     2.4) <-- %Stop
   7894       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
   7895     2.5) <-- (registers reply to step #2.3)
   7896 
   7897    Eventually after step #2.5, we return to the event loop, which
   7898    notices there's an event on the
   7899    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
   7900    associated callback --- the function below.  At this point, we're
   7901    always safe to start a vStopped sequence. :
   7902 
   7903     2.6) --> vStopped
   7904     2.7) <-- T05 thread:2
   7905     2.8) --> vStopped
   7906     2.9) --> OK
   7907 */
   7908 
   7909 void
   7910 remote_target::remote_notif_get_pending_events (notif_client *nc)
   7911 {
   7912   struct remote_state *rs = get_remote_state ();
   7913 
   7914   if (rs->notif_state->pending_event[nc->id] != NULL)
   7915     {
   7916       if (notif_debug)
   7917 	gdb_printf (gdb_stdlog,
   7918 		    "notif: process: '%s' ack pending event\n",
   7919 		    nc->name);
   7920 
   7921       /* acknowledge */
   7922       nc->ack (this, nc, rs->buf.data (),
   7923 	       rs->notif_state->pending_event[nc->id]);
   7924       rs->notif_state->pending_event[nc->id] = NULL;
   7925 
   7926       while (1)
   7927 	{
   7928 	  getpkt (&rs->buf, 0);
   7929 	  if (strcmp (rs->buf.data (), "OK") == 0)
   7930 	    break;
   7931 	  else
   7932 	    remote_notif_ack (this, nc, rs->buf.data ());
   7933 	}
   7934     }
   7935   else
   7936     {
   7937       if (notif_debug)
   7938 	gdb_printf (gdb_stdlog,
   7939 		    "notif: process: '%s' no pending reply\n",
   7940 		    nc->name);
   7941     }
   7942 }
   7943 
   7944 /* Wrapper around remote_target::remote_notif_get_pending_events to
   7945    avoid having to export the whole remote_target class.  */
   7946 
   7947 void
   7948 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
   7949 {
   7950   remote->remote_notif_get_pending_events (nc);
   7951 }
   7952 
   7953 /* Called from process_stop_reply when the stop packet we are responding
   7954    to didn't include a process-id or thread-id.  STATUS is the stop event
   7955    we are responding to.
   7956 
   7957    It is the task of this function to select a suitable thread (or process)
   7958    and return its ptid, this is the thread (or process) we will assume the
   7959    stop event came from.
   7960 
   7961    In some cases there isn't really any choice about which thread (or
   7962    process) is selected, a basic remote with a single process containing a
   7963    single thread might choose not to send any process-id or thread-id in
   7964    its stop packets, this function will select and return the one and only
   7965    thread.
   7966 
   7967    However, if a target supports multiple threads (or processes) and still
   7968    doesn't include a thread-id (or process-id) in its stop packet then
   7969    first, this is a badly behaving target, and second, we're going to have
   7970    to select a thread (or process) at random and use that.  This function
   7971    will print a warning to the user if it detects that there is the
   7972    possibility that GDB is guessing which thread (or process) to
   7973    report.
   7974 
   7975    Note that this is called before GDB fetches the updated thread list from the
   7976    target.  So it's possible for the stop reply to be ambiguous and for GDB to
   7977    not realize it.  For example, if there's initially one thread, the target
   7978    spawns a second thread, and then sends a stop reply without an id that
   7979    concerns the first thread.  GDB will assume the stop reply is about the
   7980    first thread - the only thread it knows about - without printing a warning.
   7981    Anyway, if the remote meant for the stop reply to be about the second thread,
   7982    then it would be really broken, because GDB doesn't know about that thread
   7983    yet.  */
   7984 
   7985 ptid_t
   7986 remote_target::select_thread_for_ambiguous_stop_reply
   7987   (const target_waitstatus &status)
   7988 {
   7989   REMOTE_SCOPED_DEBUG_ENTER_EXIT;
   7990 
   7991   /* Some stop events apply to all threads in an inferior, while others
   7992      only apply to a single thread.  */
   7993   bool process_wide_stop
   7994     = (status.kind () == TARGET_WAITKIND_EXITED
   7995        || status.kind () == TARGET_WAITKIND_SIGNALLED);
   7996 
   7997   remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
   7998 
   7999   thread_info *first_resumed_thread = nullptr;
   8000   bool ambiguous = false;
   8001 
   8002   /* Consider all non-exited threads of the target, find the first resumed
   8003      one.  */
   8004   for (thread_info *thr : all_non_exited_threads (this))
   8005     {
   8006       remote_thread_info *remote_thr = get_remote_thread_info (thr);
   8007 
   8008       if (remote_thr->get_resume_state () != resume_state::RESUMED)
   8009 	continue;
   8010 
   8011       if (first_resumed_thread == nullptr)
   8012 	first_resumed_thread = thr;
   8013       else if (!process_wide_stop
   8014 	       || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
   8015 	ambiguous = true;
   8016     }
   8017 
   8018   gdb_assert (first_resumed_thread != nullptr);
   8019 
   8020   remote_debug_printf ("first resumed thread is %s",
   8021 		       pid_to_str (first_resumed_thread->ptid).c_str ());
   8022   remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
   8023 
   8024   /* Warn if the remote target is sending ambiguous stop replies.  */
   8025   if (ambiguous)
   8026     {
   8027       static bool warned = false;
   8028 
   8029       if (!warned)
   8030 	{
   8031 	  /* If you are seeing this warning then the remote target has
   8032 	     stopped without specifying a thread-id, but the target
   8033 	     does have multiple threads (or inferiors), and so GDB is
   8034 	     having to guess which thread stopped.
   8035 
   8036 	     Examples of what might cause this are the target sending
   8037 	     and 'S' stop packet, or a 'T' stop packet and not
   8038 	     including a thread-id.
   8039 
   8040 	     Additionally, the target might send a 'W' or 'X packet
   8041 	     without including a process-id, when the target has
   8042 	     multiple running inferiors.  */
   8043 	  if (process_wide_stop)
   8044 	    warning (_("multi-inferior target stopped without "
   8045 		       "sending a process-id, using first "
   8046 		       "non-exited inferior"));
   8047 	  else
   8048 	    warning (_("multi-threaded target stopped without "
   8049 		       "sending a thread-id, using first "
   8050 		       "non-exited thread"));
   8051 	  warned = true;
   8052 	}
   8053     }
   8054 
   8055   /* If this is a stop for all threads then don't use a particular threads
   8056      ptid, instead create a new ptid where only the pid field is set.  */
   8057   if (process_wide_stop)
   8058     return ptid_t (first_resumed_thread->ptid.pid ());
   8059   else
   8060     return first_resumed_thread->ptid;
   8061 }
   8062 
   8063 /* Called when it is decided that STOP_REPLY holds the info of the
   8064    event that is to be returned to the core.  This function always
   8065    destroys STOP_REPLY.  */
   8066 
   8067 ptid_t
   8068 remote_target::process_stop_reply (struct stop_reply *stop_reply,
   8069 				   struct target_waitstatus *status)
   8070 {
   8071   *status = stop_reply->ws;
   8072   ptid_t ptid = stop_reply->ptid;
   8073 
   8074   /* If no thread/process was reported by the stub then select a suitable
   8075      thread/process.  */
   8076   if (ptid == null_ptid)
   8077     ptid = select_thread_for_ambiguous_stop_reply (*status);
   8078   gdb_assert (ptid != null_ptid);
   8079 
   8080   if (status->kind () != TARGET_WAITKIND_EXITED
   8081       && status->kind () != TARGET_WAITKIND_SIGNALLED
   8082       && status->kind () != TARGET_WAITKIND_NO_RESUMED)
   8083     {
   8084       /* Expedited registers.  */
   8085       if (!stop_reply->regcache.empty ())
   8086 	{
   8087 	  struct regcache *regcache
   8088 	    = get_thread_arch_regcache (this, ptid, stop_reply->arch);
   8089 
   8090 	  for (cached_reg_t &reg : stop_reply->regcache)
   8091 	    {
   8092 	      regcache->raw_supply (reg.num, reg.data);
   8093 	      xfree (reg.data);
   8094 	    }
   8095 
   8096 	  stop_reply->regcache.clear ();
   8097 	}
   8098 
   8099       remote_notice_new_inferior (ptid, false);
   8100       remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
   8101       remote_thr->core = stop_reply->core;
   8102       remote_thr->stop_reason = stop_reply->stop_reason;
   8103       remote_thr->watch_data_address = stop_reply->watch_data_address;
   8104 
   8105       if (target_is_non_stop_p ())
   8106 	{
   8107 	  /* If the target works in non-stop mode, a stop-reply indicates that
   8108 	     only this thread stopped.  */
   8109 	  remote_thr->set_not_resumed ();
   8110 	}
   8111       else
   8112 	{
   8113 	  /* If the target works in all-stop mode, a stop-reply indicates that
   8114 	     all the target's threads stopped.  */
   8115 	  for (thread_info *tp : all_non_exited_threads (this))
   8116 	    get_remote_thread_info (tp)->set_not_resumed ();
   8117 	}
   8118     }
   8119 
   8120   delete stop_reply;
   8121   return ptid;
   8122 }
   8123 
   8124 /* The non-stop mode version of target_wait.  */
   8125 
   8126 ptid_t
   8127 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
   8128 			target_wait_flags options)
   8129 {
   8130   struct remote_state *rs = get_remote_state ();
   8131   struct stop_reply *stop_reply;
   8132   int ret;
   8133   int is_notif = 0;
   8134 
   8135   /* If in non-stop mode, get out of getpkt even if a
   8136      notification is received.	*/
   8137 
   8138   ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
   8139   while (1)
   8140     {
   8141       if (ret != -1 && !is_notif)
   8142 	switch (rs->buf[0])
   8143 	  {
   8144 	  case 'E':		/* Error of some sort.	*/
   8145 	    /* We're out of sync with the target now.  Did it continue
   8146 	       or not?  We can't tell which thread it was in non-stop,
   8147 	       so just ignore this.  */
   8148 	    warning (_("Remote failure reply: %s"), rs->buf.data ());
   8149 	    break;
   8150 	  case 'O':		/* Console output.  */
   8151 	    remote_console_output (&rs->buf[1]);
   8152 	    break;
   8153 	  default:
   8154 	    warning (_("Invalid remote reply: %s"), rs->buf.data ());
   8155 	    break;
   8156 	  }
   8157 
   8158       /* Acknowledge a pending stop reply that may have arrived in the
   8159 	 mean time.  */
   8160       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
   8161 	remote_notif_get_pending_events (&notif_client_stop);
   8162 
   8163       /* If indeed we noticed a stop reply, we're done.  */
   8164       stop_reply = queued_stop_reply (ptid);
   8165       if (stop_reply != NULL)
   8166 	return process_stop_reply (stop_reply, status);
   8167 
   8168       /* Still no event.  If we're just polling for an event, then
   8169 	 return to the event loop.  */
   8170       if (options & TARGET_WNOHANG)
   8171 	{
   8172 	  status->set_ignore ();
   8173 	  return minus_one_ptid;
   8174 	}
   8175 
   8176       /* Otherwise do a blocking wait.  */
   8177       ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
   8178     }
   8179 }
   8180 
   8181 /* Return the first resumed thread.  */
   8182 
   8183 static ptid_t
   8184 first_remote_resumed_thread (remote_target *target)
   8185 {
   8186   for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
   8187     if (tp->resumed ())
   8188       return tp->ptid;
   8189   return null_ptid;
   8190 }
   8191 
   8192 /* Wait until the remote machine stops, then return, storing status in
   8193    STATUS just as `wait' would.  */
   8194 
   8195 ptid_t
   8196 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
   8197 			target_wait_flags options)
   8198 {
   8199   struct remote_state *rs = get_remote_state ();
   8200   ptid_t event_ptid = null_ptid;
   8201   char *buf;
   8202   struct stop_reply *stop_reply;
   8203 
   8204  again:
   8205 
   8206   status->set_ignore ();
   8207 
   8208   stop_reply = queued_stop_reply (ptid);
   8209   if (stop_reply != NULL)
   8210     {
   8211       /* None of the paths that push a stop reply onto the queue should
   8212 	 have set the waiting_for_stop_reply flag.  */
   8213       gdb_assert (!rs->waiting_for_stop_reply);
   8214       event_ptid = process_stop_reply (stop_reply, status);
   8215     }
   8216   else
   8217     {
   8218       int forever = ((options & TARGET_WNOHANG) == 0
   8219 		     && rs->wait_forever_enabled_p);
   8220 
   8221       if (!rs->waiting_for_stop_reply)
   8222 	{
   8223 	  status->set_no_resumed ();
   8224 	  return minus_one_ptid;
   8225 	}
   8226 
   8227       /* FIXME: cagney/1999-09-27: If we're in async mode we should
   8228 	 _never_ wait for ever -> test on target_is_async_p().
   8229 	 However, before we do that we need to ensure that the caller
   8230 	 knows how to take the target into/out of async mode.  */
   8231       int is_notif;
   8232       int ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
   8233 
   8234       /* GDB gets a notification.  Return to core as this event is
   8235 	 not interesting.  */
   8236       if (ret != -1 && is_notif)
   8237 	return minus_one_ptid;
   8238 
   8239       if (ret == -1 && (options & TARGET_WNOHANG) != 0)
   8240 	return minus_one_ptid;
   8241 
   8242       buf = rs->buf.data ();
   8243 
   8244       /* Assume that the target has acknowledged Ctrl-C unless we receive
   8245 	 an 'F' or 'O' packet.  */
   8246       if (buf[0] != 'F' && buf[0] != 'O')
   8247 	rs->ctrlc_pending_p = 0;
   8248 
   8249       switch (buf[0])
   8250 	{
   8251 	case 'E':		/* Error of some sort.	*/
   8252 	  /* We're out of sync with the target now.  Did it continue or
   8253 	     not?  Not is more likely, so report a stop.  */
   8254 	  rs->waiting_for_stop_reply = 0;
   8255 
   8256 	  warning (_("Remote failure reply: %s"), buf);
   8257 	  status->set_stopped (GDB_SIGNAL_0);
   8258 	  break;
   8259 	case 'F':		/* File-I/O request.  */
   8260 	  /* GDB may access the inferior memory while handling the File-I/O
   8261 	     request, but we don't want GDB accessing memory while waiting
   8262 	     for a stop reply.  See the comments in putpkt_binary.  Set
   8263 	     waiting_for_stop_reply to 0 temporarily.  */
   8264 	  rs->waiting_for_stop_reply = 0;
   8265 	  remote_fileio_request (this, buf, rs->ctrlc_pending_p);
   8266 	  rs->ctrlc_pending_p = 0;
   8267 	  /* GDB handled the File-I/O request, and the target is running
   8268 	     again.  Keep waiting for events.  */
   8269 	  rs->waiting_for_stop_reply = 1;
   8270 	  break;
   8271 	case 'N': case 'T': case 'S': case 'X': case 'W':
   8272 	  {
   8273 	    /* There is a stop reply to handle.  */
   8274 	    rs->waiting_for_stop_reply = 0;
   8275 
   8276 	    stop_reply
   8277 	      = (struct stop_reply *) remote_notif_parse (this,
   8278 							  &notif_client_stop,
   8279 							  rs->buf.data ());
   8280 
   8281 	    event_ptid = process_stop_reply (stop_reply, status);
   8282 	    break;
   8283 	  }
   8284 	case 'O':		/* Console output.  */
   8285 	  remote_console_output (buf + 1);
   8286 	  break;
   8287 	case '\0':
   8288 	  if (rs->last_sent_signal != GDB_SIGNAL_0)
   8289 	    {
   8290 	      /* Zero length reply means that we tried 'S' or 'C' and the
   8291 		 remote system doesn't support it.  */
   8292 	      target_terminal::ours_for_output ();
   8293 	      gdb_printf
   8294 		("Can't send signals to this remote system.  %s not sent.\n",
   8295 		 gdb_signal_to_name (rs->last_sent_signal));
   8296 	      rs->last_sent_signal = GDB_SIGNAL_0;
   8297 	      target_terminal::inferior ();
   8298 
   8299 	      strcpy (buf, rs->last_sent_step ? "s" : "c");
   8300 	      putpkt (buf);
   8301 	      break;
   8302 	    }
   8303 	  /* fallthrough */
   8304 	default:
   8305 	  warning (_("Invalid remote reply: %s"), buf);
   8306 	  break;
   8307 	}
   8308     }
   8309 
   8310   if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
   8311     return minus_one_ptid;
   8312   else if (status->kind () == TARGET_WAITKIND_IGNORE)
   8313     {
   8314       /* Nothing interesting happened.  If we're doing a non-blocking
   8315 	 poll, we're done.  Otherwise, go back to waiting.  */
   8316       if (options & TARGET_WNOHANG)
   8317 	return minus_one_ptid;
   8318       else
   8319 	goto again;
   8320     }
   8321   else if (status->kind () != TARGET_WAITKIND_EXITED
   8322 	   && status->kind () != TARGET_WAITKIND_SIGNALLED)
   8323     {
   8324       if (event_ptid != null_ptid)
   8325 	record_currthread (rs, event_ptid);
   8326       else
   8327 	event_ptid = first_remote_resumed_thread (this);
   8328     }
   8329   else
   8330     {
   8331       /* A process exit.  Invalidate our notion of current thread.  */
   8332       record_currthread (rs, minus_one_ptid);
   8333       /* It's possible that the packet did not include a pid.  */
   8334       if (event_ptid == null_ptid)
   8335 	event_ptid = first_remote_resumed_thread (this);
   8336       /* EVENT_PTID could still be NULL_PTID.  Double-check.  */
   8337       if (event_ptid == null_ptid)
   8338 	event_ptid = magic_null_ptid;
   8339     }
   8340 
   8341   return event_ptid;
   8342 }
   8343 
   8344 /* Wait until the remote machine stops, then return, storing status in
   8345    STATUS just as `wait' would.  */
   8346 
   8347 ptid_t
   8348 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
   8349 		     target_wait_flags options)
   8350 {
   8351   REMOTE_SCOPED_DEBUG_ENTER_EXIT;
   8352 
   8353   remote_state *rs = get_remote_state ();
   8354 
   8355   /* Start by clearing the flag that asks for our wait method to be called,
   8356      we'll mark it again at the end if needed.  If the target is not in
   8357      async mode then the async token should not be marked.  */
   8358   if (target_is_async_p ())
   8359     clear_async_event_handler (rs->remote_async_inferior_event_token);
   8360   else
   8361     gdb_assert (!async_event_handler_marked
   8362 		(rs->remote_async_inferior_event_token));
   8363 
   8364   ptid_t event_ptid;
   8365 
   8366   if (target_is_non_stop_p ())
   8367     event_ptid = wait_ns (ptid, status, options);
   8368   else
   8369     event_ptid = wait_as (ptid, status, options);
   8370 
   8371   if (target_is_async_p ())
   8372     {
   8373       /* If there are events left in the queue, or unacknowledged
   8374 	 notifications, then tell the event loop to call us again.  */
   8375       if (!rs->stop_reply_queue.empty ()
   8376 	  || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
   8377 	mark_async_event_handler (rs->remote_async_inferior_event_token);
   8378     }
   8379 
   8380   return event_ptid;
   8381 }
   8382 
   8383 /* Fetch a single register using a 'p' packet.  */
   8384 
   8385 int
   8386 remote_target::fetch_register_using_p (struct regcache *regcache,
   8387 				       packet_reg *reg)
   8388 {
   8389   struct gdbarch *gdbarch = regcache->arch ();
   8390   struct remote_state *rs = get_remote_state ();
   8391   char *buf, *p;
   8392   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
   8393   int i;
   8394 
   8395   if (packet_support (PACKET_p) == PACKET_DISABLE)
   8396     return 0;
   8397 
   8398   if (reg->pnum == -1)
   8399     return 0;
   8400 
   8401   p = rs->buf.data ();
   8402   *p++ = 'p';
   8403   p += hexnumstr (p, reg->pnum);
   8404   *p++ = '\0';
   8405   putpkt (rs->buf);
   8406   getpkt (&rs->buf, 0);
   8407 
   8408   buf = rs->buf.data ();
   8409 
   8410   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_p]))
   8411     {
   8412     case PACKET_OK:
   8413       break;
   8414     case PACKET_UNKNOWN:
   8415       return 0;
   8416     case PACKET_ERROR:
   8417       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
   8418 	     gdbarch_register_name (regcache->arch (),
   8419 				    reg->regnum),
   8420 	     buf);
   8421     }
   8422 
   8423   /* If this register is unfetchable, tell the regcache.  */
   8424   if (buf[0] == 'x')
   8425     {
   8426       regcache->raw_supply (reg->regnum, NULL);
   8427       return 1;
   8428     }
   8429 
   8430   /* Otherwise, parse and supply the value.  */
   8431   p = buf;
   8432   i = 0;
   8433   while (p[0] != 0)
   8434     {
   8435       if (p[1] == 0)
   8436 	error (_("fetch_register_using_p: early buf termination"));
   8437 
   8438       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
   8439       p += 2;
   8440     }
   8441   regcache->raw_supply (reg->regnum, regp);
   8442   return 1;
   8443 }
   8444 
   8445 /* Fetch the registers included in the target's 'g' packet.  */
   8446 
   8447 int
   8448 remote_target::send_g_packet ()
   8449 {
   8450   struct remote_state *rs = get_remote_state ();
   8451   int buf_len;
   8452 
   8453   xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
   8454   putpkt (rs->buf);
   8455   getpkt (&rs->buf, 0);
   8456   if (packet_check_result (rs->buf) == PACKET_ERROR)
   8457     error (_("Could not read registers; remote failure reply '%s'"),
   8458 	   rs->buf.data ());
   8459 
   8460   /* We can get out of synch in various cases.  If the first character
   8461      in the buffer is not a hex character, assume that has happened
   8462      and try to fetch another packet to read.  */
   8463   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
   8464 	 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
   8465 	 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
   8466 	 && rs->buf[0] != 'x')	/* New: unavailable register value.  */
   8467     {
   8468       remote_debug_printf ("Bad register packet; fetching a new packet");
   8469       getpkt (&rs->buf, 0);
   8470     }
   8471 
   8472   buf_len = strlen (rs->buf.data ());
   8473 
   8474   /* Sanity check the received packet.  */
   8475   if (buf_len % 2 != 0)
   8476     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
   8477 
   8478   return buf_len / 2;
   8479 }
   8480 
   8481 void
   8482 remote_target::process_g_packet (struct regcache *regcache)
   8483 {
   8484   struct gdbarch *gdbarch = regcache->arch ();
   8485   struct remote_state *rs = get_remote_state ();
   8486   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
   8487   int i, buf_len;
   8488   char *p;
   8489   char *regs;
   8490 
   8491   buf_len = strlen (rs->buf.data ());
   8492 
   8493   /* Further sanity checks, with knowledge of the architecture.  */
   8494   if (buf_len > 2 * rsa->sizeof_g_packet)
   8495     error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
   8496 	     "bytes): %s"),
   8497 	   rsa->sizeof_g_packet, buf_len / 2,
   8498 	   rs->buf.data ());
   8499 
   8500   /* Save the size of the packet sent to us by the target.  It is used
   8501      as a heuristic when determining the max size of packets that the
   8502      target can safely receive.  */
   8503   if (rsa->actual_register_packet_size == 0)
   8504     rsa->actual_register_packet_size = buf_len;
   8505 
   8506   /* If this is smaller than we guessed the 'g' packet would be,
   8507      update our records.  A 'g' reply that doesn't include a register's
   8508      value implies either that the register is not available, or that
   8509      the 'p' packet must be used.  */
   8510   if (buf_len < 2 * rsa->sizeof_g_packet)
   8511     {
   8512       long sizeof_g_packet = buf_len / 2;
   8513 
   8514       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
   8515 	{
   8516 	  long offset = rsa->regs[i].offset;
   8517 	  long reg_size = register_size (gdbarch, i);
   8518 
   8519 	  if (rsa->regs[i].pnum == -1)
   8520 	    continue;
   8521 
   8522 	  if (offset >= sizeof_g_packet)
   8523 	    rsa->regs[i].in_g_packet = 0;
   8524 	  else if (offset + reg_size > sizeof_g_packet)
   8525 	    error (_("Truncated register %d in remote 'g' packet"), i);
   8526 	  else
   8527 	    rsa->regs[i].in_g_packet = 1;
   8528 	}
   8529 
   8530       /* Looks valid enough, we can assume this is the correct length
   8531 	 for a 'g' packet.  It's important not to adjust
   8532 	 rsa->sizeof_g_packet if we have truncated registers otherwise
   8533 	 this "if" won't be run the next time the method is called
   8534 	 with a packet of the same size and one of the internal errors
   8535 	 below will trigger instead.  */
   8536       rsa->sizeof_g_packet = sizeof_g_packet;
   8537     }
   8538 
   8539   regs = (char *) alloca (rsa->sizeof_g_packet);
   8540 
   8541   /* Unimplemented registers read as all bits zero.  */
   8542   memset (regs, 0, rsa->sizeof_g_packet);
   8543 
   8544   /* Reply describes registers byte by byte, each byte encoded as two
   8545      hex characters.  Suck them all up, then supply them to the
   8546      register cacheing/storage mechanism.  */
   8547 
   8548   p = rs->buf.data ();
   8549   for (i = 0; i < rsa->sizeof_g_packet; i++)
   8550     {
   8551       if (p[0] == 0 || p[1] == 0)
   8552 	/* This shouldn't happen - we adjusted sizeof_g_packet above.  */
   8553 	internal_error (_("unexpected end of 'g' packet reply"));
   8554 
   8555       if (p[0] == 'x' && p[1] == 'x')
   8556 	regs[i] = 0;		/* 'x' */
   8557       else
   8558 	regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
   8559       p += 2;
   8560     }
   8561 
   8562   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
   8563     {
   8564       struct packet_reg *r = &rsa->regs[i];
   8565       long reg_size = register_size (gdbarch, i);
   8566 
   8567       if (r->in_g_packet)
   8568 	{
   8569 	  if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
   8570 	    /* This shouldn't happen - we adjusted in_g_packet above.  */
   8571 	    internal_error (_("unexpected end of 'g' packet reply"));
   8572 	  else if (rs->buf[r->offset * 2] == 'x')
   8573 	    {
   8574 	      gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
   8575 	      /* The register isn't available, mark it as such (at
   8576 		 the same time setting the value to zero).  */
   8577 	      regcache->raw_supply (r->regnum, NULL);
   8578 	    }
   8579 	  else
   8580 	    regcache->raw_supply (r->regnum, regs + r->offset);
   8581 	}
   8582     }
   8583 }
   8584 
   8585 void
   8586 remote_target::fetch_registers_using_g (struct regcache *regcache)
   8587 {
   8588   send_g_packet ();
   8589   process_g_packet (regcache);
   8590 }
   8591 
   8592 /* Make the remote selected traceframe match GDB's selected
   8593    traceframe.  */
   8594 
   8595 void
   8596 remote_target::set_remote_traceframe ()
   8597 {
   8598   int newnum;
   8599   struct remote_state *rs = get_remote_state ();
   8600 
   8601   if (rs->remote_traceframe_number == get_traceframe_number ())
   8602     return;
   8603 
   8604   /* Avoid recursion, remote_trace_find calls us again.  */
   8605   rs->remote_traceframe_number = get_traceframe_number ();
   8606 
   8607   newnum = target_trace_find (tfind_number,
   8608 			      get_traceframe_number (), 0, 0, NULL);
   8609 
   8610   /* Should not happen.  If it does, all bets are off.  */
   8611   if (newnum != get_traceframe_number ())
   8612     warning (_("could not set remote traceframe"));
   8613 }
   8614 
   8615 void
   8616 remote_target::fetch_registers (struct regcache *regcache, int regnum)
   8617 {
   8618   struct gdbarch *gdbarch = regcache->arch ();
   8619   struct remote_state *rs = get_remote_state ();
   8620   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
   8621   int i;
   8622 
   8623   set_remote_traceframe ();
   8624   set_general_thread (regcache->ptid ());
   8625 
   8626   if (regnum >= 0)
   8627     {
   8628       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
   8629 
   8630       gdb_assert (reg != NULL);
   8631 
   8632       /* If this register might be in the 'g' packet, try that first -
   8633 	 we are likely to read more than one register.  If this is the
   8634 	 first 'g' packet, we might be overly optimistic about its
   8635 	 contents, so fall back to 'p'.  */
   8636       if (reg->in_g_packet)
   8637 	{
   8638 	  fetch_registers_using_g (regcache);
   8639 	  if (reg->in_g_packet)
   8640 	    return;
   8641 	}
   8642 
   8643       if (fetch_register_using_p (regcache, reg))
   8644 	return;
   8645 
   8646       /* This register is not available.  */
   8647       regcache->raw_supply (reg->regnum, NULL);
   8648 
   8649       return;
   8650     }
   8651 
   8652   fetch_registers_using_g (regcache);
   8653 
   8654   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
   8655     if (!rsa->regs[i].in_g_packet)
   8656       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
   8657 	{
   8658 	  /* This register is not available.  */
   8659 	  regcache->raw_supply (i, NULL);
   8660 	}
   8661 }
   8662 
   8663 /* Prepare to store registers.  Since we may send them all (using a
   8664    'G' request), we have to read out the ones we don't want to change
   8665    first.  */
   8666 
   8667 void
   8668 remote_target::prepare_to_store (struct regcache *regcache)
   8669 {
   8670   struct remote_state *rs = get_remote_state ();
   8671   remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
   8672   int i;
   8673 
   8674   /* Make sure the entire registers array is valid.  */
   8675   switch (packet_support (PACKET_P))
   8676     {
   8677     case PACKET_DISABLE:
   8678     case PACKET_SUPPORT_UNKNOWN:
   8679       /* Make sure all the necessary registers are cached.  */
   8680       for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
   8681 	if (rsa->regs[i].in_g_packet)
   8682 	  regcache->raw_update (rsa->regs[i].regnum);
   8683       break;
   8684     case PACKET_ENABLE:
   8685       break;
   8686     }
   8687 }
   8688 
   8689 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
   8690    packet was not recognized.  */
   8691 
   8692 int
   8693 remote_target::store_register_using_P (const struct regcache *regcache,
   8694 				       packet_reg *reg)
   8695 {
   8696   struct gdbarch *gdbarch = regcache->arch ();
   8697   struct remote_state *rs = get_remote_state ();
   8698   /* Try storing a single register.  */
   8699   char *buf = rs->buf.data ();
   8700   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
   8701   char *p;
   8702 
   8703   if (packet_support (PACKET_P) == PACKET_DISABLE)
   8704     return 0;
   8705 
   8706   if (reg->pnum == -1)
   8707     return 0;
   8708 
   8709   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
   8710   p = buf + strlen (buf);
   8711   regcache->raw_collect (reg->regnum, regp);
   8712   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
   8713   putpkt (rs->buf);
   8714   getpkt (&rs->buf, 0);
   8715 
   8716   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
   8717     {
   8718     case PACKET_OK:
   8719       return 1;
   8720     case PACKET_ERROR:
   8721       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
   8722 	     gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
   8723     case PACKET_UNKNOWN:
   8724       return 0;
   8725     default:
   8726       internal_error (_("Bad result from packet_ok"));
   8727     }
   8728 }
   8729 
   8730 /* Store register REGNUM, or all registers if REGNUM == -1, from the
   8731    contents of the register cache buffer.  FIXME: ignores errors.  */
   8732 
   8733 void
   8734 remote_target::store_registers_using_G (const struct regcache *regcache)
   8735 {
   8736   struct remote_state *rs = get_remote_state ();
   8737   remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
   8738   gdb_byte *regs;
   8739   char *p;
   8740 
   8741   /* Extract all the registers in the regcache copying them into a
   8742      local buffer.  */
   8743   {
   8744     int i;
   8745 
   8746     regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
   8747     memset (regs, 0, rsa->sizeof_g_packet);
   8748     for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
   8749       {
   8750 	struct packet_reg *r = &rsa->regs[i];
   8751 
   8752 	if (r->in_g_packet)
   8753 	  regcache->raw_collect (r->regnum, regs + r->offset);
   8754       }
   8755   }
   8756 
   8757   /* Command describes registers byte by byte,
   8758      each byte encoded as two hex characters.  */
   8759   p = rs->buf.data ();
   8760   *p++ = 'G';
   8761   bin2hex (regs, p, rsa->sizeof_g_packet);
   8762   putpkt (rs->buf);
   8763   getpkt (&rs->buf, 0);
   8764   if (packet_check_result (rs->buf) == PACKET_ERROR)
   8765     error (_("Could not write registers; remote failure reply '%s'"),
   8766 	   rs->buf.data ());
   8767 }
   8768 
   8769 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
   8770    of the register cache buffer.  FIXME: ignores errors.  */
   8771 
   8772 void
   8773 remote_target::store_registers (struct regcache *regcache, int regnum)
   8774 {
   8775   struct gdbarch *gdbarch = regcache->arch ();
   8776   struct remote_state *rs = get_remote_state ();
   8777   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
   8778   int i;
   8779 
   8780   set_remote_traceframe ();
   8781   set_general_thread (regcache->ptid ());
   8782 
   8783   if (regnum >= 0)
   8784     {
   8785       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
   8786 
   8787       gdb_assert (reg != NULL);
   8788 
   8789       /* Always prefer to store registers using the 'P' packet if
   8790 	 possible; we often change only a small number of registers.
   8791 	 Sometimes we change a larger number; we'd need help from a
   8792 	 higher layer to know to use 'G'.  */
   8793       if (store_register_using_P (regcache, reg))
   8794 	return;
   8795 
   8796       /* For now, don't complain if we have no way to write the
   8797 	 register.  GDB loses track of unavailable registers too
   8798 	 easily.  Some day, this may be an error.  We don't have
   8799 	 any way to read the register, either...  */
   8800       if (!reg->in_g_packet)
   8801 	return;
   8802 
   8803       store_registers_using_G (regcache);
   8804       return;
   8805     }
   8806 
   8807   store_registers_using_G (regcache);
   8808 
   8809   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
   8810     if (!rsa->regs[i].in_g_packet)
   8811       if (!store_register_using_P (regcache, &rsa->regs[i]))
   8812 	/* See above for why we do not issue an error here.  */
   8813 	continue;
   8814 }
   8815 
   8816 
   8818 /* Return the number of hex digits in num.  */
   8819 
   8820 static int
   8821 hexnumlen (ULONGEST num)
   8822 {
   8823   int i;
   8824 
   8825   for (i = 0; num != 0; i++)
   8826     num >>= 4;
   8827 
   8828   return std::max (i, 1);
   8829 }
   8830 
   8831 /* Set BUF to the minimum number of hex digits representing NUM.  */
   8832 
   8833 static int
   8834 hexnumstr (char *buf, ULONGEST num)
   8835 {
   8836   int len = hexnumlen (num);
   8837 
   8838   return hexnumnstr (buf, num, len);
   8839 }
   8840 
   8841 
   8842 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
   8843 
   8844 static int
   8845 hexnumnstr (char *buf, ULONGEST num, int width)
   8846 {
   8847   int i;
   8848 
   8849   buf[width] = '\0';
   8850 
   8851   for (i = width - 1; i >= 0; i--)
   8852     {
   8853       buf[i] = "0123456789abcdef"[(num & 0xf)];
   8854       num >>= 4;
   8855     }
   8856 
   8857   return width;
   8858 }
   8859 
   8860 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
   8861 
   8862 static CORE_ADDR
   8863 remote_address_masked (CORE_ADDR addr)
   8864 {
   8865   unsigned int address_size = remote_address_size;
   8866 
   8867   /* If "remoteaddresssize" was not set, default to target address size.  */
   8868   if (!address_size)
   8869     address_size = gdbarch_addr_bit (target_gdbarch ());
   8870 
   8871   if (address_size > 0
   8872       && address_size < (sizeof (ULONGEST) * 8))
   8873     {
   8874       /* Only create a mask when that mask can safely be constructed
   8875 	 in a ULONGEST variable.  */
   8876       ULONGEST mask = 1;
   8877 
   8878       mask = (mask << address_size) - 1;
   8879       addr &= mask;
   8880     }
   8881   return addr;
   8882 }
   8883 
   8884 /* Determine whether the remote target supports binary downloading.
   8885    This is accomplished by sending a no-op memory write of zero length
   8886    to the target at the specified address. It does not suffice to send
   8887    the whole packet, since many stubs strip the eighth bit and
   8888    subsequently compute a wrong checksum, which causes real havoc with
   8889    remote_write_bytes.
   8890 
   8891    NOTE: This can still lose if the serial line is not eight-bit
   8892    clean.  In cases like this, the user should clear "remote
   8893    X-packet".  */
   8894 
   8895 void
   8896 remote_target::check_binary_download (CORE_ADDR addr)
   8897 {
   8898   struct remote_state *rs = get_remote_state ();
   8899 
   8900   switch (packet_support (PACKET_X))
   8901     {
   8902     case PACKET_DISABLE:
   8903       break;
   8904     case PACKET_ENABLE:
   8905       break;
   8906     case PACKET_SUPPORT_UNKNOWN:
   8907       {
   8908 	char *p;
   8909 
   8910 	p = rs->buf.data ();
   8911 	*p++ = 'X';
   8912 	p += hexnumstr (p, (ULONGEST) addr);
   8913 	*p++ = ',';
   8914 	p += hexnumstr (p, (ULONGEST) 0);
   8915 	*p++ = ':';
   8916 	*p = '\0';
   8917 
   8918 	putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
   8919 	getpkt (&rs->buf, 0);
   8920 
   8921 	if (rs->buf[0] == '\0')
   8922 	  {
   8923 	    remote_debug_printf ("binary downloading NOT supported by target");
   8924 	    remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
   8925 	  }
   8926 	else
   8927 	  {
   8928 	    remote_debug_printf ("binary downloading supported by target");
   8929 	    remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
   8930 	  }
   8931 	break;
   8932       }
   8933     }
   8934 }
   8935 
   8936 /* Helper function to resize the payload in order to try to get a good
   8937    alignment.  We try to write an amount of data such that the next write will
   8938    start on an address aligned on REMOTE_ALIGN_WRITES.  */
   8939 
   8940 static int
   8941 align_for_efficient_write (int todo, CORE_ADDR memaddr)
   8942 {
   8943   return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
   8944 }
   8945 
   8946 /* Write memory data directly to the remote machine.
   8947    This does not inform the data cache; the data cache uses this.
   8948    HEADER is the starting part of the packet.
   8949    MEMADDR is the address in the remote memory space.
   8950    MYADDR is the address of the buffer in our space.
   8951    LEN_UNITS is the number of addressable units to write.
   8952    UNIT_SIZE is the length in bytes of an addressable unit.
   8953    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
   8954    should send data as binary ('X'), or hex-encoded ('M').
   8955 
   8956    The function creates packet of the form
   8957        <HEADER><ADDRESS>,<LENGTH>:<DATA>
   8958 
   8959    where encoding of <DATA> is terminated by PACKET_FORMAT.
   8960 
   8961    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
   8962    are omitted.
   8963 
   8964    Return the transferred status, error or OK (an
   8965    'enum target_xfer_status' value).  Save the number of addressable units
   8966    transferred in *XFERED_LEN_UNITS.  Only transfer a single packet.
   8967 
   8968    On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
   8969    exchange between gdb and the stub could look like (?? in place of the
   8970    checksum):
   8971 
   8972    -> $m1000,4#??
   8973    <- aaaabbbbccccdddd
   8974 
   8975    -> $M1000,3:eeeeffffeeee#??
   8976    <- OK
   8977 
   8978    -> $m1000,4#??
   8979    <- eeeeffffeeeedddd  */
   8980 
   8981 target_xfer_status
   8982 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
   8983 				       const gdb_byte *myaddr,
   8984 				       ULONGEST len_units,
   8985 				       int unit_size,
   8986 				       ULONGEST *xfered_len_units,
   8987 				       char packet_format, int use_length)
   8988 {
   8989   struct remote_state *rs = get_remote_state ();
   8990   char *p;
   8991   char *plen = NULL;
   8992   int plenlen = 0;
   8993   int todo_units;
   8994   int units_written;
   8995   int payload_capacity_bytes;
   8996   int payload_length_bytes;
   8997 
   8998   if (packet_format != 'X' && packet_format != 'M')
   8999     internal_error (_("remote_write_bytes_aux: bad packet format"));
   9000 
   9001   if (len_units == 0)
   9002     return TARGET_XFER_EOF;
   9003 
   9004   payload_capacity_bytes = get_memory_write_packet_size ();
   9005 
   9006   /* The packet buffer will be large enough for the payload;
   9007      get_memory_packet_size ensures this.  */
   9008   rs->buf[0] = '\0';
   9009 
   9010   /* Compute the size of the actual payload by subtracting out the
   9011      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
   9012 
   9013   payload_capacity_bytes -= strlen ("$,:#NN");
   9014   if (!use_length)
   9015     /* The comma won't be used.  */
   9016     payload_capacity_bytes += 1;
   9017   payload_capacity_bytes -= strlen (header);
   9018   payload_capacity_bytes -= hexnumlen (memaddr);
   9019 
   9020   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
   9021 
   9022   strcat (rs->buf.data (), header);
   9023   p = rs->buf.data () + strlen (header);
   9024 
   9025   /* Compute a best guess of the number of bytes actually transfered.  */
   9026   if (packet_format == 'X')
   9027     {
   9028       /* Best guess at number of bytes that will fit.  */
   9029       todo_units = std::min (len_units,
   9030 			     (ULONGEST) payload_capacity_bytes / unit_size);
   9031       if (use_length)
   9032 	payload_capacity_bytes -= hexnumlen (todo_units);
   9033       todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
   9034     }
   9035   else
   9036     {
   9037       /* Number of bytes that will fit.  */
   9038       todo_units
   9039 	= std::min (len_units,
   9040 		    (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
   9041       if (use_length)
   9042 	payload_capacity_bytes -= hexnumlen (todo_units);
   9043       todo_units = std::min (todo_units,
   9044 			     (payload_capacity_bytes / unit_size) / 2);
   9045     }
   9046 
   9047   if (todo_units <= 0)
   9048     internal_error (_("minimum packet size too small to write data"));
   9049 
   9050   /* If we already need another packet, then try to align the end
   9051      of this packet to a useful boundary.  */
   9052   if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
   9053     todo_units = align_for_efficient_write (todo_units, memaddr);
   9054 
   9055   /* Append "<memaddr>".  */
   9056   memaddr = remote_address_masked (memaddr);
   9057   p += hexnumstr (p, (ULONGEST) memaddr);
   9058 
   9059   if (use_length)
   9060     {
   9061       /* Append ",".  */
   9062       *p++ = ',';
   9063 
   9064       /* Append the length and retain its location and size.  It may need to be
   9065 	 adjusted once the packet body has been created.  */
   9066       plen = p;
   9067       plenlen = hexnumstr (p, (ULONGEST) todo_units);
   9068       p += plenlen;
   9069     }
   9070 
   9071   /* Append ":".  */
   9072   *p++ = ':';
   9073   *p = '\0';
   9074 
   9075   /* Append the packet body.  */
   9076   if (packet_format == 'X')
   9077     {
   9078       /* Binary mode.  Send target system values byte by byte, in
   9079 	 increasing byte addresses.  Only escape certain critical
   9080 	 characters.  */
   9081       payload_length_bytes =
   9082 	  remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
   9083 				&units_written, payload_capacity_bytes);
   9084 
   9085       /* If not all TODO units fit, then we'll need another packet.  Make
   9086 	 a second try to keep the end of the packet aligned.  Don't do
   9087 	 this if the packet is tiny.  */
   9088       if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
   9089 	{
   9090 	  int new_todo_units;
   9091 
   9092 	  new_todo_units = align_for_efficient_write (units_written, memaddr);
   9093 
   9094 	  if (new_todo_units != units_written)
   9095 	    payload_length_bytes =
   9096 		remote_escape_output (myaddr, new_todo_units, unit_size,
   9097 				      (gdb_byte *) p, &units_written,
   9098 				      payload_capacity_bytes);
   9099 	}
   9100 
   9101       p += payload_length_bytes;
   9102       if (use_length && units_written < todo_units)
   9103 	{
   9104 	  /* Escape chars have filled up the buffer prematurely,
   9105 	     and we have actually sent fewer units than planned.
   9106 	     Fix-up the length field of the packet.  Use the same
   9107 	     number of characters as before.  */
   9108 	  plen += hexnumnstr (plen, (ULONGEST) units_written,
   9109 			      plenlen);
   9110 	  *plen = ':';  /* overwrite \0 from hexnumnstr() */
   9111 	}
   9112     }
   9113   else
   9114     {
   9115       /* Normal mode: Send target system values byte by byte, in
   9116 	 increasing byte addresses.  Each byte is encoded as a two hex
   9117 	 value.  */
   9118       p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
   9119       units_written = todo_units;
   9120     }
   9121 
   9122   putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
   9123   getpkt (&rs->buf, 0);
   9124 
   9125   if (rs->buf[0] == 'E')
   9126     return TARGET_XFER_E_IO;
   9127 
   9128   /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
   9129      send fewer units than we'd planned.  */
   9130   *xfered_len_units = (ULONGEST) units_written;
   9131   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
   9132 }
   9133 
   9134 /* Write memory data directly to the remote machine.
   9135    This does not inform the data cache; the data cache uses this.
   9136    MEMADDR is the address in the remote memory space.
   9137    MYADDR is the address of the buffer in our space.
   9138    LEN is the number of bytes.
   9139 
   9140    Return the transferred status, error or OK (an
   9141    'enum target_xfer_status' value).  Save the number of bytes
   9142    transferred in *XFERED_LEN.  Only transfer a single packet.  */
   9143 
   9144 target_xfer_status
   9145 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
   9146 				   ULONGEST len, int unit_size,
   9147 				   ULONGEST *xfered_len)
   9148 {
   9149   const char *packet_format = NULL;
   9150 
   9151   /* Check whether the target supports binary download.  */
   9152   check_binary_download (memaddr);
   9153 
   9154   switch (packet_support (PACKET_X))
   9155     {
   9156     case PACKET_ENABLE:
   9157       packet_format = "X";
   9158       break;
   9159     case PACKET_DISABLE:
   9160       packet_format = "M";
   9161       break;
   9162     case PACKET_SUPPORT_UNKNOWN:
   9163       internal_error (_("remote_write_bytes: bad internal state"));
   9164     default:
   9165       internal_error (_("bad switch"));
   9166     }
   9167 
   9168   return remote_write_bytes_aux (packet_format,
   9169 				 memaddr, myaddr, len, unit_size, xfered_len,
   9170 				 packet_format[0], 1);
   9171 }
   9172 
   9173 /* Read memory data directly from the remote machine.
   9174    This does not use the data cache; the data cache uses this.
   9175    MEMADDR is the address in the remote memory space.
   9176    MYADDR is the address of the buffer in our space.
   9177    LEN_UNITS is the number of addressable memory units to read..
   9178    UNIT_SIZE is the length in bytes of an addressable unit.
   9179 
   9180    Return the transferred status, error or OK (an
   9181    'enum target_xfer_status' value).  Save the number of bytes
   9182    transferred in *XFERED_LEN_UNITS.
   9183 
   9184    See the comment of remote_write_bytes_aux for an example of
   9185    memory read/write exchange between gdb and the stub.  */
   9186 
   9187 target_xfer_status
   9188 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
   9189 				    ULONGEST len_units,
   9190 				    int unit_size, ULONGEST *xfered_len_units)
   9191 {
   9192   struct remote_state *rs = get_remote_state ();
   9193   int buf_size_bytes;		/* Max size of packet output buffer.  */
   9194   char *p;
   9195   int todo_units;
   9196   int decoded_bytes;
   9197 
   9198   buf_size_bytes = get_memory_read_packet_size ();
   9199   /* The packet buffer will be large enough for the payload;
   9200      get_memory_packet_size ensures this.  */
   9201 
   9202   /* Number of units that will fit.  */
   9203   todo_units = std::min (len_units,
   9204 			 (ULONGEST) (buf_size_bytes / unit_size) / 2);
   9205 
   9206   /* Construct "m"<memaddr>","<len>".  */
   9207   memaddr = remote_address_masked (memaddr);
   9208   p = rs->buf.data ();
   9209   *p++ = 'm';
   9210   p += hexnumstr (p, (ULONGEST) memaddr);
   9211   *p++ = ',';
   9212   p += hexnumstr (p, (ULONGEST) todo_units);
   9213   *p = '\0';
   9214   putpkt (rs->buf);
   9215   getpkt (&rs->buf, 0);
   9216   if (rs->buf[0] == 'E'
   9217       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
   9218       && rs->buf[3] == '\0')
   9219     return TARGET_XFER_E_IO;
   9220   /* Reply describes memory byte by byte, each byte encoded as two hex
   9221      characters.  */
   9222   p = rs->buf.data ();
   9223   decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
   9224   /* Return what we have.  Let higher layers handle partial reads.  */
   9225   *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
   9226   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
   9227 }
   9228 
   9229 /* Using the set of read-only target sections of remote, read live
   9230    read-only memory.
   9231 
   9232    For interface/parameters/return description see target.h,
   9233    to_xfer_partial.  */
   9234 
   9235 target_xfer_status
   9236 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
   9237 						  ULONGEST memaddr,
   9238 						  ULONGEST len,
   9239 						  int unit_size,
   9240 						  ULONGEST *xfered_len)
   9241 {
   9242   const struct target_section *secp;
   9243 
   9244   secp = target_section_by_addr (this, memaddr);
   9245   if (secp != NULL
   9246       && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
   9247     {
   9248       ULONGEST memend = memaddr + len;
   9249 
   9250       const target_section_table *table = target_get_section_table (this);
   9251       for (const target_section &p : *table)
   9252 	{
   9253 	  if (memaddr >= p.addr)
   9254 	    {
   9255 	      if (memend <= p.endaddr)
   9256 		{
   9257 		  /* Entire transfer is within this section.  */
   9258 		  return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
   9259 					      xfered_len);
   9260 		}
   9261 	      else if (memaddr >= p.endaddr)
   9262 		{
   9263 		  /* This section ends before the transfer starts.  */
   9264 		  continue;
   9265 		}
   9266 	      else
   9267 		{
   9268 		  /* This section overlaps the transfer.  Just do half.  */
   9269 		  len = p.endaddr - memaddr;
   9270 		  return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
   9271 					      xfered_len);
   9272 		}
   9273 	    }
   9274 	}
   9275     }
   9276 
   9277   return TARGET_XFER_EOF;
   9278 }
   9279 
   9280 /* Similar to remote_read_bytes_1, but it reads from the remote stub
   9281    first if the requested memory is unavailable in traceframe.
   9282    Otherwise, fall back to remote_read_bytes_1.  */
   9283 
   9284 target_xfer_status
   9285 remote_target::remote_read_bytes (CORE_ADDR memaddr,
   9286 				  gdb_byte *myaddr, ULONGEST len, int unit_size,
   9287 				  ULONGEST *xfered_len)
   9288 {
   9289   if (len == 0)
   9290     return TARGET_XFER_EOF;
   9291 
   9292   if (get_traceframe_number () != -1)
   9293     {
   9294       std::vector<mem_range> available;
   9295 
   9296       /* If we fail to get the set of available memory, then the
   9297 	 target does not support querying traceframe info, and so we
   9298 	 attempt reading from the traceframe anyway (assuming the
   9299 	 target implements the old QTro packet then).  */
   9300       if (traceframe_available_memory (&available, memaddr, len))
   9301 	{
   9302 	  if (available.empty () || available[0].start != memaddr)
   9303 	    {
   9304 	      enum target_xfer_status res;
   9305 
   9306 	      /* Don't read into the traceframe's available
   9307 		 memory.  */
   9308 	      if (!available.empty ())
   9309 		{
   9310 		  LONGEST oldlen = len;
   9311 
   9312 		  len = available[0].start - memaddr;
   9313 		  gdb_assert (len <= oldlen);
   9314 		}
   9315 
   9316 	      /* This goes through the topmost target again.  */
   9317 	      res = remote_xfer_live_readonly_partial (myaddr, memaddr,
   9318 						       len, unit_size, xfered_len);
   9319 	      if (res == TARGET_XFER_OK)
   9320 		return TARGET_XFER_OK;
   9321 	      else
   9322 		{
   9323 		  /* No use trying further, we know some memory starting
   9324 		     at MEMADDR isn't available.  */
   9325 		  *xfered_len = len;
   9326 		  return (*xfered_len != 0) ?
   9327 		    TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
   9328 		}
   9329 	    }
   9330 
   9331 	  /* Don't try to read more than how much is available, in
   9332 	     case the target implements the deprecated QTro packet to
   9333 	     cater for older GDBs (the target's knowledge of read-only
   9334 	     sections may be outdated by now).  */
   9335 	  len = available[0].length;
   9336 	}
   9337     }
   9338 
   9339   return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
   9340 }
   9341 
   9342 
   9343 
   9345 /* Sends a packet with content determined by the printf format string
   9346    FORMAT and the remaining arguments, then gets the reply.  Returns
   9347    whether the packet was a success, a failure, or unknown.  */
   9348 
   9349 packet_result
   9350 remote_target::remote_send_printf (const char *format, ...)
   9351 {
   9352   struct remote_state *rs = get_remote_state ();
   9353   int max_size = get_remote_packet_size ();
   9354   va_list ap;
   9355 
   9356   va_start (ap, format);
   9357 
   9358   rs->buf[0] = '\0';
   9359   int size = vsnprintf (rs->buf.data (), max_size, format, ap);
   9360 
   9361   va_end (ap);
   9362 
   9363   if (size >= max_size)
   9364     internal_error (_("Too long remote packet."));
   9365 
   9366   if (putpkt (rs->buf) < 0)
   9367     error (_("Communication problem with target."));
   9368 
   9369   rs->buf[0] = '\0';
   9370   getpkt (&rs->buf, 0);
   9371 
   9372   return packet_check_result (rs->buf);
   9373 }
   9374 
   9375 /* Flash writing can take quite some time.  We'll set
   9376    effectively infinite timeout for flash operations.
   9377    In future, we'll need to decide on a better approach.  */
   9378 static const int remote_flash_timeout = 1000;
   9379 
   9380 void
   9381 remote_target::flash_erase (ULONGEST address, LONGEST length)
   9382 {
   9383   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
   9384   enum packet_result ret;
   9385   scoped_restore restore_timeout
   9386     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
   9387 
   9388   ret = remote_send_printf ("vFlashErase:%s,%s",
   9389 			    phex (address, addr_size),
   9390 			    phex (length, 4));
   9391   switch (ret)
   9392     {
   9393     case PACKET_UNKNOWN:
   9394       error (_("Remote target does not support flash erase"));
   9395     case PACKET_ERROR:
   9396       error (_("Error erasing flash with vFlashErase packet"));
   9397     default:
   9398       break;
   9399     }
   9400 }
   9401 
   9402 target_xfer_status
   9403 remote_target::remote_flash_write (ULONGEST address,
   9404 				   ULONGEST length, ULONGEST *xfered_len,
   9405 				   const gdb_byte *data)
   9406 {
   9407   scoped_restore restore_timeout
   9408     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
   9409   return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
   9410 				 xfered_len,'X', 0);
   9411 }
   9412 
   9413 void
   9414 remote_target::flash_done ()
   9415 {
   9416   int ret;
   9417 
   9418   scoped_restore restore_timeout
   9419     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
   9420 
   9421   ret = remote_send_printf ("vFlashDone");
   9422 
   9423   switch (ret)
   9424     {
   9425     case PACKET_UNKNOWN:
   9426       error (_("Remote target does not support vFlashDone"));
   9427     case PACKET_ERROR:
   9428       error (_("Error finishing flash operation"));
   9429     default:
   9430       break;
   9431     }
   9432 }
   9433 
   9434 
   9435 /* Stuff for dealing with the packets which are part of this protocol.
   9437    See comment at top of file for details.  */
   9438 
   9439 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
   9440    error to higher layers.  Called when a serial error is detected.
   9441    The exception message is STRING, followed by a colon and a blank,
   9442    the system error message for errno at function entry and final dot
   9443    for output compatibility with throw_perror_with_name.  */
   9444 
   9445 static void
   9446 unpush_and_perror (remote_target *target, const char *string)
   9447 {
   9448   int saved_errno = errno;
   9449 
   9450   remote_unpush_target (target);
   9451   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
   9452 	       safe_strerror (saved_errno));
   9453 }
   9454 
   9455 /* Read a single character from the remote end.  The current quit
   9456    handler is overridden to avoid quitting in the middle of packet
   9457    sequence, as that would break communication with the remote server.
   9458    See remote_serial_quit_handler for more detail.  */
   9459 
   9460 int
   9461 remote_target::readchar (int timeout)
   9462 {
   9463   int ch;
   9464   struct remote_state *rs = get_remote_state ();
   9465 
   9466   {
   9467     scoped_restore restore_quit_target
   9468       = make_scoped_restore (&curr_quit_handler_target, this);
   9469     scoped_restore restore_quit
   9470       = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
   9471 
   9472     rs->got_ctrlc_during_io = 0;
   9473 
   9474     ch = serial_readchar (rs->remote_desc, timeout);
   9475 
   9476     if (rs->got_ctrlc_during_io)
   9477       set_quit_flag ();
   9478   }
   9479 
   9480   if (ch >= 0)
   9481     return ch;
   9482 
   9483   switch ((enum serial_rc) ch)
   9484     {
   9485     case SERIAL_EOF:
   9486       remote_unpush_target (this);
   9487       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
   9488       /* no return */
   9489     case SERIAL_ERROR:
   9490       unpush_and_perror (this, _("Remote communication error.  "
   9491 				 "Target disconnected."));
   9492       /* no return */
   9493     case SERIAL_TIMEOUT:
   9494       break;
   9495     }
   9496   return ch;
   9497 }
   9498 
   9499 /* Wrapper for serial_write that closes the target and throws if
   9500    writing fails.  The current quit handler is overridden to avoid
   9501    quitting in the middle of packet sequence, as that would break
   9502    communication with the remote server.  See
   9503    remote_serial_quit_handler for more detail.  */
   9504 
   9505 void
   9506 remote_target::remote_serial_write (const char *str, int len)
   9507 {
   9508   struct remote_state *rs = get_remote_state ();
   9509 
   9510   scoped_restore restore_quit_target
   9511     = make_scoped_restore (&curr_quit_handler_target, this);
   9512   scoped_restore restore_quit
   9513     = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
   9514 
   9515   rs->got_ctrlc_during_io = 0;
   9516 
   9517   if (serial_write (rs->remote_desc, str, len))
   9518     {
   9519       unpush_and_perror (this, _("Remote communication error.  "
   9520 				 "Target disconnected."));
   9521     }
   9522 
   9523   if (rs->got_ctrlc_during_io)
   9524     set_quit_flag ();
   9525 }
   9526 
   9527 /* Return a string representing an escaped version of BUF, of len N.
   9528    E.g. \n is converted to \\n, \t to \\t, etc.  */
   9529 
   9530 static std::string
   9531 escape_buffer (const char *buf, int n)
   9532 {
   9533   string_file stb;
   9534 
   9535   stb.putstrn (buf, n, '\\');
   9536   return stb.release ();
   9537 }
   9538 
   9539 int
   9540 remote_target::putpkt (const char *buf)
   9541 {
   9542   return putpkt_binary (buf, strlen (buf));
   9543 }
   9544 
   9545 /* Wrapper around remote_target::putpkt to avoid exporting
   9546    remote_target.  */
   9547 
   9548 int
   9549 putpkt (remote_target *remote, const char *buf)
   9550 {
   9551   return remote->putpkt (buf);
   9552 }
   9553 
   9554 /* Send a packet to the remote machine, with error checking.  The data
   9555    of the packet is in BUF.  The string in BUF can be at most
   9556    get_remote_packet_size () - 5 to account for the $, # and checksum,
   9557    and for a possible /0 if we are debugging (remote_debug) and want
   9558    to print the sent packet as a string.  */
   9559 
   9560 int
   9561 remote_target::putpkt_binary (const char *buf, int cnt)
   9562 {
   9563   struct remote_state *rs = get_remote_state ();
   9564   int i;
   9565   unsigned char csum = 0;
   9566   gdb::def_vector<char> data (cnt + 6);
   9567   char *buf2 = data.data ();
   9568 
   9569   int ch;
   9570   int tcount = 0;
   9571   char *p;
   9572 
   9573   /* Catch cases like trying to read memory or listing threads while
   9574      we're waiting for a stop reply.  The remote server wouldn't be
   9575      ready to handle this request, so we'd hang and timeout.  We don't
   9576      have to worry about this in synchronous mode, because in that
   9577      case it's not possible to issue a command while the target is
   9578      running.  This is not a problem in non-stop mode, because in that
   9579      case, the stub is always ready to process serial input.  */
   9580   if (!target_is_non_stop_p ()
   9581       && target_is_async_p ()
   9582       && rs->waiting_for_stop_reply)
   9583     {
   9584       error (_("Cannot execute this command while the target is running.\n"
   9585 	       "Use the \"interrupt\" command to stop the target\n"
   9586 	       "and then try again."));
   9587     }
   9588 
   9589   /* Copy the packet into buffer BUF2, encapsulating it
   9590      and giving it a checksum.  */
   9591 
   9592   p = buf2;
   9593   *p++ = '$';
   9594 
   9595   for (i = 0; i < cnt; i++)
   9596     {
   9597       csum += buf[i];
   9598       *p++ = buf[i];
   9599     }
   9600   *p++ = '#';
   9601   *p++ = tohex ((csum >> 4) & 0xf);
   9602   *p++ = tohex (csum & 0xf);
   9603 
   9604   /* Send it over and over until we get a positive ack.  */
   9605 
   9606   while (1)
   9607     {
   9608       if (remote_debug)
   9609 	{
   9610 	  *p = '\0';
   9611 
   9612 	  int len = (int) (p - buf2);
   9613 	  int max_chars;
   9614 
   9615 	  if (remote_packet_max_chars < 0)
   9616 	    max_chars = len;
   9617 	  else
   9618 	    max_chars = remote_packet_max_chars;
   9619 
   9620 	  std::string str
   9621 	    = escape_buffer (buf2, std::min (len, max_chars));
   9622 
   9623 	  if (len > max_chars)
   9624 	    remote_debug_printf_nofunc
   9625 	      ("Sending packet: %s [%d bytes omitted]", str.c_str (),
   9626 	       len - max_chars);
   9627 	  else
   9628 	    remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
   9629 	}
   9630       remote_serial_write (buf2, p - buf2);
   9631 
   9632       /* If this is a no acks version of the remote protocol, send the
   9633 	 packet and move on.  */
   9634       if (rs->noack_mode)
   9635 	break;
   9636 
   9637       /* Read until either a timeout occurs (-2) or '+' is read.
   9638 	 Handle any notification that arrives in the mean time.  */
   9639       while (1)
   9640 	{
   9641 	  ch = readchar (remote_timeout);
   9642 
   9643 	  switch (ch)
   9644 	    {
   9645 	    case '+':
   9646 	      remote_debug_printf_nofunc ("Received Ack");
   9647 	      return 1;
   9648 	    case '-':
   9649 	      remote_debug_printf_nofunc ("Received Nak");
   9650 	      /* FALLTHROUGH */
   9651 	    case SERIAL_TIMEOUT:
   9652 	      tcount++;
   9653 	      if (tcount > 3)
   9654 		return 0;
   9655 	      break;		/* Retransmit buffer.  */
   9656 	    case '$':
   9657 	      {
   9658 		remote_debug_printf ("Packet instead of Ack, ignoring it");
   9659 		/* It's probably an old response sent because an ACK
   9660 		   was lost.  Gobble up the packet and ack it so it
   9661 		   doesn't get retransmitted when we resend this
   9662 		   packet.  */
   9663 		skip_frame ();
   9664 		remote_serial_write ("+", 1);
   9665 		continue;	/* Now, go look for +.  */
   9666 	      }
   9667 
   9668 	    case '%':
   9669 	      {
   9670 		int val;
   9671 
   9672 		/* If we got a notification, handle it, and go back to looking
   9673 		   for an ack.  */
   9674 		/* We've found the start of a notification.  Now
   9675 		   collect the data.  */
   9676 		val = read_frame (&rs->buf);
   9677 		if (val >= 0)
   9678 		  {
   9679 		    remote_debug_printf_nofunc
   9680 		      ("  Notification received: %s",
   9681 		       escape_buffer (rs->buf.data (), val).c_str ());
   9682 
   9683 		    handle_notification (rs->notif_state, rs->buf.data ());
   9684 		    /* We're in sync now, rewait for the ack.  */
   9685 		    tcount = 0;
   9686 		  }
   9687 		else
   9688 		  remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
   9689 					      rs->buf.data ());
   9690 		continue;
   9691 	      }
   9692 	      /* fall-through */
   9693 	    default:
   9694 	      remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
   9695 					  rs->buf.data ());
   9696 	      continue;
   9697 	    }
   9698 	  break;		/* Here to retransmit.  */
   9699 	}
   9700 
   9701 #if 0
   9702       /* This is wrong.  If doing a long backtrace, the user should be
   9703 	 able to get out next time we call QUIT, without anything as
   9704 	 violent as interrupt_query.  If we want to provide a way out of
   9705 	 here without getting to the next QUIT, it should be based on
   9706 	 hitting ^C twice as in remote_wait.  */
   9707       if (quit_flag)
   9708 	{
   9709 	  quit_flag = 0;
   9710 	  interrupt_query ();
   9711 	}
   9712 #endif
   9713     }
   9714 
   9715   return 0;
   9716 }
   9717 
   9718 /* Come here after finding the start of a frame when we expected an
   9719    ack.  Do our best to discard the rest of this packet.  */
   9720 
   9721 void
   9722 remote_target::skip_frame ()
   9723 {
   9724   int c;
   9725 
   9726   while (1)
   9727     {
   9728       c = readchar (remote_timeout);
   9729       switch (c)
   9730 	{
   9731 	case SERIAL_TIMEOUT:
   9732 	  /* Nothing we can do.  */
   9733 	  return;
   9734 	case '#':
   9735 	  /* Discard the two bytes of checksum and stop.  */
   9736 	  c = readchar (remote_timeout);
   9737 	  if (c >= 0)
   9738 	    c = readchar (remote_timeout);
   9739 
   9740 	  return;
   9741 	case '*':		/* Run length encoding.  */
   9742 	  /* Discard the repeat count.  */
   9743 	  c = readchar (remote_timeout);
   9744 	  if (c < 0)
   9745 	    return;
   9746 	  break;
   9747 	default:
   9748 	  /* A regular character.  */
   9749 	  break;
   9750 	}
   9751     }
   9752 }
   9753 
   9754 /* Come here after finding the start of the frame.  Collect the rest
   9755    into *BUF, verifying the checksum, length, and handling run-length
   9756    compression.  NUL terminate the buffer.  If there is not enough room,
   9757    expand *BUF.
   9758 
   9759    Returns -1 on error, number of characters in buffer (ignoring the
   9760    trailing NULL) on success. (could be extended to return one of the
   9761    SERIAL status indications).  */
   9762 
   9763 long
   9764 remote_target::read_frame (gdb::char_vector *buf_p)
   9765 {
   9766   unsigned char csum;
   9767   long bc;
   9768   int c;
   9769   char *buf = buf_p->data ();
   9770   struct remote_state *rs = get_remote_state ();
   9771 
   9772   csum = 0;
   9773   bc = 0;
   9774 
   9775   while (1)
   9776     {
   9777       c = readchar (remote_timeout);
   9778       switch (c)
   9779 	{
   9780 	case SERIAL_TIMEOUT:
   9781 	  remote_debug_printf ("Timeout in mid-packet, retrying");
   9782 	  return -1;
   9783 
   9784 	case '$':
   9785 	  remote_debug_printf ("Saw new packet start in middle of old one");
   9786 	  return -1;		/* Start a new packet, count retries.  */
   9787 
   9788 	case '#':
   9789 	  {
   9790 	    unsigned char pktcsum;
   9791 	    int check_0 = 0;
   9792 	    int check_1 = 0;
   9793 
   9794 	    buf[bc] = '\0';
   9795 
   9796 	    check_0 = readchar (remote_timeout);
   9797 	    if (check_0 >= 0)
   9798 	      check_1 = readchar (remote_timeout);
   9799 
   9800 	    if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
   9801 	      {
   9802 		remote_debug_printf ("Timeout in checksum, retrying");
   9803 		return -1;
   9804 	      }
   9805 	    else if (check_0 < 0 || check_1 < 0)
   9806 	      {
   9807 		remote_debug_printf ("Communication error in checksum");
   9808 		return -1;
   9809 	      }
   9810 
   9811 	    /* Don't recompute the checksum; with no ack packets we
   9812 	       don't have any way to indicate a packet retransmission
   9813 	       is necessary.  */
   9814 	    if (rs->noack_mode)
   9815 	      return bc;
   9816 
   9817 	    pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
   9818 	    if (csum == pktcsum)
   9819 	      return bc;
   9820 
   9821 	    remote_debug_printf
   9822 	      ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
   9823 	       pktcsum, csum, escape_buffer (buf, bc).c_str ());
   9824 
   9825 	    /* Number of characters in buffer ignoring trailing
   9826 	       NULL.  */
   9827 	    return -1;
   9828 	  }
   9829 	case '*':		/* Run length encoding.  */
   9830 	  {
   9831 	    int repeat;
   9832 
   9833 	    csum += c;
   9834 	    c = readchar (remote_timeout);
   9835 	    csum += c;
   9836 	    repeat = c - ' ' + 3;	/* Compute repeat count.  */
   9837 
   9838 	    /* The character before ``*'' is repeated.  */
   9839 
   9840 	    if (repeat > 0 && repeat <= 255 && bc > 0)
   9841 	      {
   9842 		if (bc + repeat - 1 >= buf_p->size () - 1)
   9843 		  {
   9844 		    /* Make some more room in the buffer.  */
   9845 		    buf_p->resize (buf_p->size () + repeat);
   9846 		    buf = buf_p->data ();
   9847 		  }
   9848 
   9849 		memset (&buf[bc], buf[bc - 1], repeat);
   9850 		bc += repeat;
   9851 		continue;
   9852 	      }
   9853 
   9854 	    buf[bc] = '\0';
   9855 	    gdb_printf (_("Invalid run length encoding: %s\n"), buf);
   9856 	    return -1;
   9857 	  }
   9858 	default:
   9859 	  if (bc >= buf_p->size () - 1)
   9860 	    {
   9861 	      /* Make some more room in the buffer.  */
   9862 	      buf_p->resize (buf_p->size () * 2);
   9863 	      buf = buf_p->data ();
   9864 	    }
   9865 
   9866 	  buf[bc++] = c;
   9867 	  csum += c;
   9868 	  continue;
   9869 	}
   9870     }
   9871 }
   9872 
   9873 /* Set this to the maximum number of seconds to wait instead of waiting forever
   9874    in target_wait().  If this timer times out, then it generates an error and
   9875    the command is aborted.  This replaces most of the need for timeouts in the
   9876    GDB test suite, and makes it possible to distinguish between a hung target
   9877    and one with slow communications.  */
   9878 
   9879 static int watchdog = 0;
   9880 static void
   9881 show_watchdog (struct ui_file *file, int from_tty,
   9882 	       struct cmd_list_element *c, const char *value)
   9883 {
   9884   gdb_printf (file, _("Watchdog timer is %s.\n"), value);
   9885 }
   9886 
   9887 /* Read a packet from the remote machine, with error checking, and
   9888    store it in *BUF.  Resize *BUF if necessary to hold the result.  If
   9889    FOREVER, wait forever rather than timing out; this is used (in
   9890    synchronous mode) to wait for a target that is is executing user
   9891    code to stop.  */
   9892 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
   9893    don't have to change all the calls to getpkt to deal with the
   9894    return value, because at the moment I don't know what the right
   9895    thing to do it for those.  */
   9896 
   9897 void
   9898 remote_target::getpkt (gdb::char_vector *buf, int forever)
   9899 {
   9900   getpkt_sane (buf, forever);
   9901 }
   9902 
   9903 
   9904 /* Read a packet from the remote machine, with error checking, and
   9905    store it in *BUF.  Resize *BUF if necessary to hold the result.  If
   9906    FOREVER, wait forever rather than timing out; this is used (in
   9907    synchronous mode) to wait for a target that is is executing user
   9908    code to stop.  If FOREVER == 0, this function is allowed to time
   9909    out gracefully and return an indication of this to the caller.
   9910    Otherwise return the number of bytes read.  If EXPECTING_NOTIF,
   9911    consider receiving a notification enough reason to return to the
   9912    caller.  *IS_NOTIF is an output boolean that indicates whether *BUF
   9913    holds a notification or not (a regular packet).  */
   9914 
   9915 int
   9916 remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
   9917 				       int forever, int expecting_notif,
   9918 				       int *is_notif)
   9919 {
   9920   struct remote_state *rs = get_remote_state ();
   9921   int c;
   9922   int tries;
   9923   int timeout;
   9924   int val = -1;
   9925 
   9926   strcpy (buf->data (), "timeout");
   9927 
   9928   if (forever)
   9929     timeout = watchdog > 0 ? watchdog : -1;
   9930   else if (expecting_notif)
   9931     timeout = 0; /* There should already be a char in the buffer.  If
   9932 		    not, bail out.  */
   9933   else
   9934     timeout = remote_timeout;
   9935 
   9936 #define MAX_TRIES 3
   9937 
   9938   /* Process any number of notifications, and then return when
   9939      we get a packet.  */
   9940   for (;;)
   9941     {
   9942       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
   9943 	 times.  */
   9944       for (tries = 1; tries <= MAX_TRIES; tries++)
   9945 	{
   9946 	  /* This can loop forever if the remote side sends us
   9947 	     characters continuously, but if it pauses, we'll get
   9948 	     SERIAL_TIMEOUT from readchar because of timeout.  Then
   9949 	     we'll count that as a retry.
   9950 
   9951 	     Note that even when forever is set, we will only wait
   9952 	     forever prior to the start of a packet.  After that, we
   9953 	     expect characters to arrive at a brisk pace.  They should
   9954 	     show up within remote_timeout intervals.  */
   9955 	  do
   9956 	    c = readchar (timeout);
   9957 	  while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
   9958 
   9959 	  if (c == SERIAL_TIMEOUT)
   9960 	    {
   9961 	      if (expecting_notif)
   9962 		return -1; /* Don't complain, it's normal to not get
   9963 			      anything in this case.  */
   9964 
   9965 	      if (forever)	/* Watchdog went off?  Kill the target.  */
   9966 		{
   9967 		  remote_unpush_target (this);
   9968 		  throw_error (TARGET_CLOSE_ERROR,
   9969 			       _("Watchdog timeout has expired.  "
   9970 				 "Target detached."));
   9971 		}
   9972 
   9973 	      remote_debug_printf ("Timed out.");
   9974 	    }
   9975 	  else
   9976 	    {
   9977 	      /* We've found the start of a packet or notification.
   9978 		 Now collect the data.  */
   9979 	      val = read_frame (buf);
   9980 	      if (val >= 0)
   9981 		break;
   9982 	    }
   9983 
   9984 	  remote_serial_write ("-", 1);
   9985 	}
   9986 
   9987       if (tries > MAX_TRIES)
   9988 	{
   9989 	  /* We have tried hard enough, and just can't receive the
   9990 	     packet/notification.  Give up.  */
   9991 	  gdb_printf (_("Ignoring packet error, continuing...\n"));
   9992 
   9993 	  /* Skip the ack char if we're in no-ack mode.  */
   9994 	  if (!rs->noack_mode)
   9995 	    remote_serial_write ("+", 1);
   9996 	  return -1;
   9997 	}
   9998 
   9999       /* If we got an ordinary packet, return that to our caller.  */
   10000       if (c == '$')
   10001 	{
   10002 	  if (remote_debug)
   10003 	    {
   10004 	      int max_chars;
   10005 
   10006 	      if (remote_packet_max_chars < 0)
   10007 		max_chars = val;
   10008 	      else
   10009 		max_chars = remote_packet_max_chars;
   10010 
   10011 	      std::string str
   10012 		= escape_buffer (buf->data (),
   10013 				 std::min (val, max_chars));
   10014 
   10015 	      if (val > max_chars)
   10016 		remote_debug_printf_nofunc
   10017 		  ("Packet received: %s [%d bytes omitted]", str.c_str (),
   10018 		   val - max_chars);
   10019 	      else
   10020 		remote_debug_printf_nofunc ("Packet received: %s",
   10021 					    str.c_str ());
   10022 	    }
   10023 
   10024 	  /* Skip the ack char if we're in no-ack mode.  */
   10025 	  if (!rs->noack_mode)
   10026 	    remote_serial_write ("+", 1);
   10027 	  if (is_notif != NULL)
   10028 	    *is_notif = 0;
   10029 	  return val;
   10030 	}
   10031 
   10032        /* If we got a notification, handle it, and go back to looking
   10033 	 for a packet.  */
   10034       else
   10035 	{
   10036 	  gdb_assert (c == '%');
   10037 
   10038 	  remote_debug_printf_nofunc
   10039 	    ("  Notification received: %s",
   10040 	     escape_buffer (buf->data (), val).c_str ());
   10041 
   10042 	  if (is_notif != NULL)
   10043 	    *is_notif = 1;
   10044 
   10045 	  handle_notification (rs->notif_state, buf->data ());
   10046 
   10047 	  /* Notifications require no acknowledgement.  */
   10048 
   10049 	  if (expecting_notif)
   10050 	    return val;
   10051 	}
   10052     }
   10053 }
   10054 
   10055 int
   10056 remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
   10057 {
   10058   return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
   10059 }
   10060 
   10061 int
   10062 remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
   10063 				     int *is_notif)
   10064 {
   10065   return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
   10066 }
   10067 
   10068 /* Kill any new fork children of inferior INF that haven't been
   10069    processed by follow_fork.  */
   10070 
   10071 void
   10072 remote_target::kill_new_fork_children (inferior *inf)
   10073 {
   10074   remote_state *rs = get_remote_state ();
   10075   struct notif_client *notif = &notif_client_stop;
   10076 
   10077   /* Kill the fork child threads of any threads in inferior INF that are stopped
   10078      at a fork event.  */
   10079   for (thread_info *thread : inf->non_exited_threads ())
   10080     {
   10081       const target_waitstatus *ws = thread_pending_fork_status (thread);
   10082 
   10083       if (ws == nullptr)
   10084 	continue;
   10085 
   10086       int child_pid = ws->child_ptid ().pid ();
   10087       int res = remote_vkill (child_pid);
   10088 
   10089       if (res != 0)
   10090 	error (_("Can't kill fork child process %d"), child_pid);
   10091     }
   10092 
   10093   /* Check for any pending fork events (not reported or processed yet)
   10094      in inferior INF and kill those fork child threads as well.  */
   10095   remote_notif_get_pending_events (notif);
   10096   for (auto &event : rs->stop_reply_queue)
   10097     {
   10098       if (event->ptid.pid () != inf->pid)
   10099 	continue;
   10100 
   10101       if (!is_fork_status (event->ws.kind ()))
   10102 	continue;
   10103 
   10104       int child_pid = event->ws.child_ptid ().pid ();
   10105       int res = remote_vkill (child_pid);
   10106 
   10107       if (res != 0)
   10108 	error (_("Can't kill fork child process %d"), child_pid);
   10109     }
   10110 }
   10111 
   10112 
   10113 /* Target hook to kill the current inferior.  */
   10115 
   10116 void
   10117 remote_target::kill ()
   10118 {
   10119   int res = -1;
   10120   inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
   10121   struct remote_state *rs = get_remote_state ();
   10122 
   10123   gdb_assert (inf != nullptr);
   10124 
   10125   if (packet_support (PACKET_vKill) != PACKET_DISABLE)
   10126     {
   10127       /* If we're stopped while forking and we haven't followed yet,
   10128 	 kill the child task.  We need to do this before killing the
   10129 	 parent task because if this is a vfork then the parent will
   10130 	 be sleeping.  */
   10131       kill_new_fork_children (inf);
   10132 
   10133       res = remote_vkill (inf->pid);
   10134       if (res == 0)
   10135 	{
   10136 	  target_mourn_inferior (inferior_ptid);
   10137 	  return;
   10138 	}
   10139     }
   10140 
   10141   /* If we are in 'target remote' mode and we are killing the only
   10142      inferior, then we will tell gdbserver to exit and unpush the
   10143      target.  */
   10144   if (res == -1 && !remote_multi_process_p (rs)
   10145       && number_of_live_inferiors (this) == 1)
   10146     {
   10147       remote_kill_k ();
   10148 
   10149       /* We've killed the remote end, we get to mourn it.  If we are
   10150 	 not in extended mode, mourning the inferior also unpushes
   10151 	 remote_ops from the target stack, which closes the remote
   10152 	 connection.  */
   10153       target_mourn_inferior (inferior_ptid);
   10154 
   10155       return;
   10156     }
   10157 
   10158   error (_("Can't kill process"));
   10159 }
   10160 
   10161 /* Send a kill request to the target using the 'vKill' packet.  */
   10162 
   10163 int
   10164 remote_target::remote_vkill (int pid)
   10165 {
   10166   if (packet_support (PACKET_vKill) == PACKET_DISABLE)
   10167     return -1;
   10168 
   10169   remote_state *rs = get_remote_state ();
   10170 
   10171   /* Tell the remote target to detach.  */
   10172   xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
   10173   putpkt (rs->buf);
   10174   getpkt (&rs->buf, 0);
   10175 
   10176   switch (packet_ok (rs->buf,
   10177 		     &remote_protocol_packets[PACKET_vKill]))
   10178     {
   10179     case PACKET_OK:
   10180       return 0;
   10181     case PACKET_ERROR:
   10182       return 1;
   10183     case PACKET_UNKNOWN:
   10184       return -1;
   10185     default:
   10186       internal_error (_("Bad result from packet_ok"));
   10187     }
   10188 }
   10189 
   10190 /* Send a kill request to the target using the 'k' packet.  */
   10191 
   10192 void
   10193 remote_target::remote_kill_k ()
   10194 {
   10195   /* Catch errors so the user can quit from gdb even when we
   10196      aren't on speaking terms with the remote system.  */
   10197   try
   10198     {
   10199       putpkt ("k");
   10200     }
   10201   catch (const gdb_exception_error &ex)
   10202     {
   10203       if (ex.error == TARGET_CLOSE_ERROR)
   10204 	{
   10205 	  /* If we got an (EOF) error that caused the target
   10206 	     to go away, then we're done, that's what we wanted.
   10207 	     "k" is susceptible to cause a premature EOF, given
   10208 	     that the remote server isn't actually required to
   10209 	     reply to "k", and it can happen that it doesn't
   10210 	     even get to reply ACK to the "k".  */
   10211 	  return;
   10212 	}
   10213 
   10214       /* Otherwise, something went wrong.  We didn't actually kill
   10215 	 the target.  Just propagate the exception, and let the
   10216 	 user or higher layers decide what to do.  */
   10217       throw;
   10218     }
   10219 }
   10220 
   10221 void
   10222 remote_target::mourn_inferior ()
   10223 {
   10224   struct remote_state *rs = get_remote_state ();
   10225 
   10226   /* We're no longer interested in notification events of an inferior
   10227      that exited or was killed/detached.  */
   10228   discard_pending_stop_replies (current_inferior ());
   10229 
   10230   /* In 'target remote' mode with one inferior, we close the connection.  */
   10231   if (!rs->extended && number_of_live_inferiors (this) <= 1)
   10232     {
   10233       remote_unpush_target (this);
   10234       return;
   10235     }
   10236 
   10237   /* In case we got here due to an error, but we're going to stay
   10238      connected.  */
   10239   rs->waiting_for_stop_reply = 0;
   10240 
   10241   /* If the current general thread belonged to the process we just
   10242      detached from or has exited, the remote side current general
   10243      thread becomes undefined.  Considering a case like this:
   10244 
   10245      - We just got here due to a detach.
   10246      - The process that we're detaching from happens to immediately
   10247        report a global breakpoint being hit in non-stop mode, in the
   10248        same thread we had selected before.
   10249      - GDB attaches to this process again.
   10250      - This event happens to be the next event we handle.
   10251 
   10252      GDB would consider that the current general thread didn't need to
   10253      be set on the stub side (with Hg), since for all it knew,
   10254      GENERAL_THREAD hadn't changed.
   10255 
   10256      Notice that although in all-stop mode, the remote server always
   10257      sets the current thread to the thread reporting the stop event,
   10258      that doesn't happen in non-stop mode; in non-stop, the stub *must
   10259      not* change the current thread when reporting a breakpoint hit,
   10260      due to the decoupling of event reporting and event handling.
   10261 
   10262      To keep things simple, we always invalidate our notion of the
   10263      current thread.  */
   10264   record_currthread (rs, minus_one_ptid);
   10265 
   10266   /* Call common code to mark the inferior as not running.  */
   10267   generic_mourn_inferior ();
   10268 }
   10269 
   10270 bool
   10271 extended_remote_target::supports_disable_randomization ()
   10272 {
   10273   return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
   10274 }
   10275 
   10276 void
   10277 remote_target::extended_remote_disable_randomization (int val)
   10278 {
   10279   struct remote_state *rs = get_remote_state ();
   10280   char *reply;
   10281 
   10282   xsnprintf (rs->buf.data (), get_remote_packet_size (),
   10283 	     "QDisableRandomization:%x", val);
   10284   putpkt (rs->buf);
   10285   reply = remote_get_noisy_reply ();
   10286   if (*reply == '\0')
   10287     error (_("Target does not support QDisableRandomization."));
   10288   if (strcmp (reply, "OK") != 0)
   10289     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
   10290 }
   10291 
   10292 int
   10293 remote_target::extended_remote_run (const std::string &args)
   10294 {
   10295   struct remote_state *rs = get_remote_state ();
   10296   int len;
   10297   const char *remote_exec_file = get_remote_exec_file ();
   10298 
   10299   /* If the user has disabled vRun support, or we have detected that
   10300      support is not available, do not try it.  */
   10301   if (packet_support (PACKET_vRun) == PACKET_DISABLE)
   10302     return -1;
   10303 
   10304   strcpy (rs->buf.data (), "vRun;");
   10305   len = strlen (rs->buf.data ());
   10306 
   10307   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
   10308     error (_("Remote file name too long for run packet"));
   10309   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
   10310 		      strlen (remote_exec_file));
   10311 
   10312   if (!args.empty ())
   10313     {
   10314       int i;
   10315 
   10316       gdb_argv argv (args.c_str ());
   10317       for (i = 0; argv[i] != NULL; i++)
   10318 	{
   10319 	  if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
   10320 	    error (_("Argument list too long for run packet"));
   10321 	  rs->buf[len++] = ';';
   10322 	  len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
   10323 			      strlen (argv[i]));
   10324 	}
   10325     }
   10326 
   10327   rs->buf[len++] = '\0';
   10328 
   10329   putpkt (rs->buf);
   10330   getpkt (&rs->buf, 0);
   10331 
   10332   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
   10333     {
   10334     case PACKET_OK:
   10335       /* We have a wait response.  All is well.  */
   10336       return 0;
   10337     case PACKET_UNKNOWN:
   10338       return -1;
   10339     case PACKET_ERROR:
   10340       if (remote_exec_file[0] == '\0')
   10341 	error (_("Running the default executable on the remote target failed; "
   10342 		 "try \"set remote exec-file\"?"));
   10343       else
   10344 	error (_("Running \"%s\" on the remote target failed"),
   10345 	       remote_exec_file);
   10346     default:
   10347       gdb_assert_not_reached ("bad switch");
   10348     }
   10349 }
   10350 
   10351 /* Helper function to send set/unset environment packets.  ACTION is
   10352    either "set" or "unset".  PACKET is either "QEnvironmentHexEncoded"
   10353    or "QEnvironmentUnsetVariable".  VALUE is the variable to be
   10354    sent.  */
   10355 
   10356 void
   10357 remote_target::send_environment_packet (const char *action,
   10358 					const char *packet,
   10359 					const char *value)
   10360 {
   10361   remote_state *rs = get_remote_state ();
   10362 
   10363   /* Convert the environment variable to an hex string, which
   10364      is the best format to be transmitted over the wire.  */
   10365   std::string encoded_value = bin2hex ((const gdb_byte *) value,
   10366 					 strlen (value));
   10367 
   10368   xsnprintf (rs->buf.data (), get_remote_packet_size (),
   10369 	     "%s:%s", packet, encoded_value.c_str ());
   10370 
   10371   putpkt (rs->buf);
   10372   getpkt (&rs->buf, 0);
   10373   if (strcmp (rs->buf.data (), "OK") != 0)
   10374     warning (_("Unable to %s environment variable '%s' on remote."),
   10375 	     action, value);
   10376 }
   10377 
   10378 /* Helper function to handle the QEnvironment* packets.  */
   10379 
   10380 void
   10381 remote_target::extended_remote_environment_support ()
   10382 {
   10383   remote_state *rs = get_remote_state ();
   10384 
   10385   if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
   10386     {
   10387       putpkt ("QEnvironmentReset");
   10388       getpkt (&rs->buf, 0);
   10389       if (strcmp (rs->buf.data (), "OK") != 0)
   10390 	warning (_("Unable to reset environment on remote."));
   10391     }
   10392 
   10393   gdb_environ *e = &current_inferior ()->environment;
   10394 
   10395   if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
   10396     for (const std::string &el : e->user_set_env ())
   10397       send_environment_packet ("set", "QEnvironmentHexEncoded",
   10398 			       el.c_str ());
   10399 
   10400   if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
   10401     for (const std::string &el : e->user_unset_env ())
   10402       send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
   10403 }
   10404 
   10405 /* Helper function to set the current working directory for the
   10406    inferior in the remote target.  */
   10407 
   10408 void
   10409 remote_target::extended_remote_set_inferior_cwd ()
   10410 {
   10411   if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
   10412     {
   10413       const std::string &inferior_cwd = current_inferior ()->cwd ();
   10414       remote_state *rs = get_remote_state ();
   10415 
   10416       if (!inferior_cwd.empty ())
   10417 	{
   10418 	  std::string hexpath
   10419 	    = bin2hex ((const gdb_byte *) inferior_cwd.data (),
   10420 		       inferior_cwd.size ());
   10421 
   10422 	  xsnprintf (rs->buf.data (), get_remote_packet_size (),
   10423 		     "QSetWorkingDir:%s", hexpath.c_str ());
   10424 	}
   10425       else
   10426 	{
   10427 	  /* An empty inferior_cwd means that the user wants us to
   10428 	     reset the remote server's inferior's cwd.  */
   10429 	  xsnprintf (rs->buf.data (), get_remote_packet_size (),
   10430 		     "QSetWorkingDir:");
   10431 	}
   10432 
   10433       putpkt (rs->buf);
   10434       getpkt (&rs->buf, 0);
   10435       if (packet_ok (rs->buf,
   10436 		     &remote_protocol_packets[PACKET_QSetWorkingDir])
   10437 	  != PACKET_OK)
   10438 	error (_("\
   10439 Remote replied unexpectedly while setting the inferior's working\n\
   10440 directory: %s"),
   10441 	       rs->buf.data ());
   10442 
   10443     }
   10444 }
   10445 
   10446 /* In the extended protocol we want to be able to do things like
   10447    "run" and have them basically work as expected.  So we need
   10448    a special create_inferior function.  We support changing the
   10449    executable file and the command line arguments, but not the
   10450    environment.  */
   10451 
   10452 void
   10453 extended_remote_target::create_inferior (const char *exec_file,
   10454 					 const std::string &args,
   10455 					 char **env, int from_tty)
   10456 {
   10457   int run_worked;
   10458   char *stop_reply;
   10459   struct remote_state *rs = get_remote_state ();
   10460   const char *remote_exec_file = get_remote_exec_file ();
   10461 
   10462   /* If running asynchronously, register the target file descriptor
   10463      with the event loop.  */
   10464   if (target_can_async_p ())
   10465     target_async (true);
   10466 
   10467   /* Disable address space randomization if requested (and supported).  */
   10468   if (supports_disable_randomization ())
   10469     extended_remote_disable_randomization (disable_randomization);
   10470 
   10471   /* If startup-with-shell is on, we inform gdbserver to start the
   10472      remote inferior using a shell.  */
   10473   if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
   10474     {
   10475       xsnprintf (rs->buf.data (), get_remote_packet_size (),
   10476 		 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
   10477       putpkt (rs->buf);
   10478       getpkt (&rs->buf, 0);
   10479       if (strcmp (rs->buf.data (), "OK") != 0)
   10480 	error (_("\
   10481 Remote replied unexpectedly while setting startup-with-shell: %s"),
   10482 	       rs->buf.data ());
   10483     }
   10484 
   10485   extended_remote_environment_support ();
   10486 
   10487   extended_remote_set_inferior_cwd ();
   10488 
   10489   /* Now restart the remote server.  */
   10490   run_worked = extended_remote_run (args) != -1;
   10491   if (!run_worked)
   10492     {
   10493       /* vRun was not supported.  Fail if we need it to do what the
   10494 	 user requested.  */
   10495       if (remote_exec_file[0])
   10496 	error (_("Remote target does not support \"set remote exec-file\""));
   10497       if (!args.empty ())
   10498 	error (_("Remote target does not support \"set args\" or run ARGS"));
   10499 
   10500       /* Fall back to "R".  */
   10501       extended_remote_restart ();
   10502     }
   10503 
   10504   /* vRun's success return is a stop reply.  */
   10505   stop_reply = run_worked ? rs->buf.data () : NULL;
   10506   add_current_inferior_and_thread (stop_reply);
   10507 
   10508   /* Get updated offsets, if the stub uses qOffsets.  */
   10509   get_offsets ();
   10510 }
   10511 
   10512 
   10514 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
   10515    the list of conditions (in agent expression bytecode format), if any, the
   10516    target needs to evaluate.  The output is placed into the packet buffer
   10517    started from BUF and ended at BUF_END.  */
   10518 
   10519 static int
   10520 remote_add_target_side_condition (struct gdbarch *gdbarch,
   10521 				  struct bp_target_info *bp_tgt, char *buf,
   10522 				  char *buf_end)
   10523 {
   10524   if (bp_tgt->conditions.empty ())
   10525     return 0;
   10526 
   10527   buf += strlen (buf);
   10528   xsnprintf (buf, buf_end - buf, "%s", ";");
   10529   buf++;
   10530 
   10531   /* Send conditions to the target.  */
   10532   for (agent_expr *aexpr : bp_tgt->conditions)
   10533     {
   10534       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
   10535       buf += strlen (buf);
   10536       for (int i = 0; i < aexpr->len; ++i)
   10537 	buf = pack_hex_byte (buf, aexpr->buf[i]);
   10538       *buf = '\0';
   10539     }
   10540   return 0;
   10541 }
   10542 
   10543 static void
   10544 remote_add_target_side_commands (struct gdbarch *gdbarch,
   10545 				 struct bp_target_info *bp_tgt, char *buf)
   10546 {
   10547   if (bp_tgt->tcommands.empty ())
   10548     return;
   10549 
   10550   buf += strlen (buf);
   10551 
   10552   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
   10553   buf += strlen (buf);
   10554 
   10555   /* Concatenate all the agent expressions that are commands into the
   10556      cmds parameter.  */
   10557   for (agent_expr *aexpr : bp_tgt->tcommands)
   10558     {
   10559       sprintf (buf, "X%x,", aexpr->len);
   10560       buf += strlen (buf);
   10561       for (int i = 0; i < aexpr->len; ++i)
   10562 	buf = pack_hex_byte (buf, aexpr->buf[i]);
   10563       *buf = '\0';
   10564     }
   10565 }
   10566 
   10567 /* Insert a breakpoint.  On targets that have software breakpoint
   10568    support, we ask the remote target to do the work; on targets
   10569    which don't, we insert a traditional memory breakpoint.  */
   10570 
   10571 int
   10572 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
   10573 				  struct bp_target_info *bp_tgt)
   10574 {
   10575   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
   10576      If it succeeds, then set the support to PACKET_ENABLE.  If it
   10577      fails, and the user has explicitly requested the Z support then
   10578      report an error, otherwise, mark it disabled and go on.  */
   10579 
   10580   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
   10581     {
   10582       CORE_ADDR addr = bp_tgt->reqstd_address;
   10583       struct remote_state *rs;
   10584       char *p, *endbuf;
   10585 
   10586       /* Make sure the remote is pointing at the right process, if
   10587 	 necessary.  */
   10588       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
   10589 	set_general_process ();
   10590 
   10591       rs = get_remote_state ();
   10592       p = rs->buf.data ();
   10593       endbuf = p + get_remote_packet_size ();
   10594 
   10595       *(p++) = 'Z';
   10596       *(p++) = '0';
   10597       *(p++) = ',';
   10598       addr = (ULONGEST) remote_address_masked (addr);
   10599       p += hexnumstr (p, addr);
   10600       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
   10601 
   10602       if (supports_evaluation_of_breakpoint_conditions ())
   10603 	remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
   10604 
   10605       if (can_run_breakpoint_commands ())
   10606 	remote_add_target_side_commands (gdbarch, bp_tgt, p);
   10607 
   10608       putpkt (rs->buf);
   10609       getpkt (&rs->buf, 0);
   10610 
   10611       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
   10612 	{
   10613 	case PACKET_ERROR:
   10614 	  return -1;
   10615 	case PACKET_OK:
   10616 	  return 0;
   10617 	case PACKET_UNKNOWN:
   10618 	  break;
   10619 	}
   10620     }
   10621 
   10622   /* If this breakpoint has target-side commands but this stub doesn't
   10623      support Z0 packets, throw error.  */
   10624   if (!bp_tgt->tcommands.empty ())
   10625     throw_error (NOT_SUPPORTED_ERROR, _("\
   10626 Target doesn't support breakpoints that have target side commands."));
   10627 
   10628   return memory_insert_breakpoint (this, gdbarch, bp_tgt);
   10629 }
   10630 
   10631 int
   10632 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
   10633 				  struct bp_target_info *bp_tgt,
   10634 				  enum remove_bp_reason reason)
   10635 {
   10636   CORE_ADDR addr = bp_tgt->placed_address;
   10637   struct remote_state *rs = get_remote_state ();
   10638 
   10639   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
   10640     {
   10641       char *p = rs->buf.data ();
   10642       char *endbuf = p + get_remote_packet_size ();
   10643 
   10644       /* Make sure the remote is pointing at the right process, if
   10645 	 necessary.  */
   10646       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
   10647 	set_general_process ();
   10648 
   10649       *(p++) = 'z';
   10650       *(p++) = '0';
   10651       *(p++) = ',';
   10652 
   10653       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
   10654       p += hexnumstr (p, addr);
   10655       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
   10656 
   10657       putpkt (rs->buf);
   10658       getpkt (&rs->buf, 0);
   10659 
   10660       return (rs->buf[0] == 'E');
   10661     }
   10662 
   10663   return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
   10664 }
   10665 
   10666 static enum Z_packet_type
   10667 watchpoint_to_Z_packet (int type)
   10668 {
   10669   switch (type)
   10670     {
   10671     case hw_write:
   10672       return Z_PACKET_WRITE_WP;
   10673       break;
   10674     case hw_read:
   10675       return Z_PACKET_READ_WP;
   10676       break;
   10677     case hw_access:
   10678       return Z_PACKET_ACCESS_WP;
   10679       break;
   10680     default:
   10681       internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
   10682     }
   10683 }
   10684 
   10685 int
   10686 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
   10687 				  enum target_hw_bp_type type, struct expression *cond)
   10688 {
   10689   struct remote_state *rs = get_remote_state ();
   10690   char *endbuf = rs->buf.data () + get_remote_packet_size ();
   10691   char *p;
   10692   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
   10693 
   10694   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
   10695     return 1;
   10696 
   10697   /* Make sure the remote is pointing at the right process, if
   10698      necessary.  */
   10699   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
   10700     set_general_process ();
   10701 
   10702   xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
   10703   p = strchr (rs->buf.data (), '\0');
   10704   addr = remote_address_masked (addr);
   10705   p += hexnumstr (p, (ULONGEST) addr);
   10706   xsnprintf (p, endbuf - p, ",%x", len);
   10707 
   10708   putpkt (rs->buf);
   10709   getpkt (&rs->buf, 0);
   10710 
   10711   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
   10712     {
   10713     case PACKET_ERROR:
   10714       return -1;
   10715     case PACKET_UNKNOWN:
   10716       return 1;
   10717     case PACKET_OK:
   10718       return 0;
   10719     }
   10720   internal_error (_("remote_insert_watchpoint: reached end of function"));
   10721 }
   10722 
   10723 bool
   10724 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
   10725 					     CORE_ADDR start, int length)
   10726 {
   10727   CORE_ADDR diff = remote_address_masked (addr - start);
   10728 
   10729   return diff < length;
   10730 }
   10731 
   10732 
   10733 int
   10734 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
   10735 				  enum target_hw_bp_type type, struct expression *cond)
   10736 {
   10737   struct remote_state *rs = get_remote_state ();
   10738   char *endbuf = rs->buf.data () + get_remote_packet_size ();
   10739   char *p;
   10740   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
   10741 
   10742   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
   10743     return -1;
   10744 
   10745   /* Make sure the remote is pointing at the right process, if
   10746      necessary.  */
   10747   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
   10748     set_general_process ();
   10749 
   10750   xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
   10751   p = strchr (rs->buf.data (), '\0');
   10752   addr = remote_address_masked (addr);
   10753   p += hexnumstr (p, (ULONGEST) addr);
   10754   xsnprintf (p, endbuf - p, ",%x", len);
   10755   putpkt (rs->buf);
   10756   getpkt (&rs->buf, 0);
   10757 
   10758   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
   10759     {
   10760     case PACKET_ERROR:
   10761     case PACKET_UNKNOWN:
   10762       return -1;
   10763     case PACKET_OK:
   10764       return 0;
   10765     }
   10766   internal_error (_("remote_remove_watchpoint: reached end of function"));
   10767 }
   10768 
   10769 
   10770 static int remote_hw_watchpoint_limit = -1;
   10771 static int remote_hw_watchpoint_length_limit = -1;
   10772 static int remote_hw_breakpoint_limit = -1;
   10773 
   10774 int
   10775 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
   10776 {
   10777   if (remote_hw_watchpoint_length_limit == 0)
   10778     return 0;
   10779   else if (remote_hw_watchpoint_length_limit < 0)
   10780     return 1;
   10781   else if (len <= remote_hw_watchpoint_length_limit)
   10782     return 1;
   10783   else
   10784     return 0;
   10785 }
   10786 
   10787 int
   10788 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
   10789 {
   10790   if (type == bp_hardware_breakpoint)
   10791     {
   10792       if (remote_hw_breakpoint_limit == 0)
   10793 	return 0;
   10794       else if (remote_hw_breakpoint_limit < 0)
   10795 	return 1;
   10796       else if (cnt <= remote_hw_breakpoint_limit)
   10797 	return 1;
   10798     }
   10799   else
   10800     {
   10801       if (remote_hw_watchpoint_limit == 0)
   10802 	return 0;
   10803       else if (remote_hw_watchpoint_limit < 0)
   10804 	return 1;
   10805       else if (ot)
   10806 	return -1;
   10807       else if (cnt <= remote_hw_watchpoint_limit)
   10808 	return 1;
   10809     }
   10810   return -1;
   10811 }
   10812 
   10813 /* The to_stopped_by_sw_breakpoint method of target remote.  */
   10814 
   10815 bool
   10816 remote_target::stopped_by_sw_breakpoint ()
   10817 {
   10818   struct thread_info *thread = inferior_thread ();
   10819 
   10820   return (thread->priv != NULL
   10821 	  && (get_remote_thread_info (thread)->stop_reason
   10822 	      == TARGET_STOPPED_BY_SW_BREAKPOINT));
   10823 }
   10824 
   10825 /* The to_supports_stopped_by_sw_breakpoint method of target
   10826    remote.  */
   10827 
   10828 bool
   10829 remote_target::supports_stopped_by_sw_breakpoint ()
   10830 {
   10831   return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
   10832 }
   10833 
   10834 /* The to_stopped_by_hw_breakpoint method of target remote.  */
   10835 
   10836 bool
   10837 remote_target::stopped_by_hw_breakpoint ()
   10838 {
   10839   struct thread_info *thread = inferior_thread ();
   10840 
   10841   return (thread->priv != NULL
   10842 	  && (get_remote_thread_info (thread)->stop_reason
   10843 	      == TARGET_STOPPED_BY_HW_BREAKPOINT));
   10844 }
   10845 
   10846 /* The to_supports_stopped_by_hw_breakpoint method of target
   10847    remote.  */
   10848 
   10849 bool
   10850 remote_target::supports_stopped_by_hw_breakpoint ()
   10851 {
   10852   return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
   10853 }
   10854 
   10855 bool
   10856 remote_target::stopped_by_watchpoint ()
   10857 {
   10858   struct thread_info *thread = inferior_thread ();
   10859 
   10860   return (thread->priv != NULL
   10861 	  && (get_remote_thread_info (thread)->stop_reason
   10862 	      == TARGET_STOPPED_BY_WATCHPOINT));
   10863 }
   10864 
   10865 bool
   10866 remote_target::stopped_data_address (CORE_ADDR *addr_p)
   10867 {
   10868   struct thread_info *thread = inferior_thread ();
   10869 
   10870   if (thread->priv != NULL
   10871       && (get_remote_thread_info (thread)->stop_reason
   10872 	  == TARGET_STOPPED_BY_WATCHPOINT))
   10873     {
   10874       *addr_p = get_remote_thread_info (thread)->watch_data_address;
   10875       return true;
   10876     }
   10877 
   10878   return false;
   10879 }
   10880 
   10881 
   10882 int
   10883 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
   10884 				     struct bp_target_info *bp_tgt)
   10885 {
   10886   CORE_ADDR addr = bp_tgt->reqstd_address;
   10887   struct remote_state *rs;
   10888   char *p, *endbuf;
   10889   char *message;
   10890 
   10891   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
   10892     return -1;
   10893 
   10894   /* Make sure the remote is pointing at the right process, if
   10895      necessary.  */
   10896   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
   10897     set_general_process ();
   10898 
   10899   rs = get_remote_state ();
   10900   p = rs->buf.data ();
   10901   endbuf = p + get_remote_packet_size ();
   10902 
   10903   *(p++) = 'Z';
   10904   *(p++) = '1';
   10905   *(p++) = ',';
   10906 
   10907   addr = remote_address_masked (addr);
   10908   p += hexnumstr (p, (ULONGEST) addr);
   10909   xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
   10910 
   10911   if (supports_evaluation_of_breakpoint_conditions ())
   10912     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
   10913 
   10914   if (can_run_breakpoint_commands ())
   10915     remote_add_target_side_commands (gdbarch, bp_tgt, p);
   10916 
   10917   putpkt (rs->buf);
   10918   getpkt (&rs->buf, 0);
   10919 
   10920   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
   10921     {
   10922     case PACKET_ERROR:
   10923       if (rs->buf[1] == '.')
   10924 	{
   10925 	  message = strchr (&rs->buf[2], '.');
   10926 	  if (message)
   10927 	    error (_("Remote failure reply: %s"), message + 1);
   10928 	}
   10929       return -1;
   10930     case PACKET_UNKNOWN:
   10931       return -1;
   10932     case PACKET_OK:
   10933       return 0;
   10934     }
   10935   internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
   10936 }
   10937 
   10938 
   10939 int
   10940 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
   10941 				     struct bp_target_info *bp_tgt)
   10942 {
   10943   CORE_ADDR addr;
   10944   struct remote_state *rs = get_remote_state ();
   10945   char *p = rs->buf.data ();
   10946   char *endbuf = p + get_remote_packet_size ();
   10947 
   10948   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
   10949     return -1;
   10950 
   10951   /* Make sure the remote is pointing at the right process, if
   10952      necessary.  */
   10953   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
   10954     set_general_process ();
   10955 
   10956   *(p++) = 'z';
   10957   *(p++) = '1';
   10958   *(p++) = ',';
   10959 
   10960   addr = remote_address_masked (bp_tgt->placed_address);
   10961   p += hexnumstr (p, (ULONGEST) addr);
   10962   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->kind);
   10963 
   10964   putpkt (rs->buf);
   10965   getpkt (&rs->buf, 0);
   10966 
   10967   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
   10968     {
   10969     case PACKET_ERROR:
   10970     case PACKET_UNKNOWN:
   10971       return -1;
   10972     case PACKET_OK:
   10973       return 0;
   10974     }
   10975   internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
   10976 }
   10977 
   10978 /* Verify memory using the "qCRC:" request.  */
   10979 
   10980 int
   10981 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
   10982 {
   10983   struct remote_state *rs = get_remote_state ();
   10984   unsigned long host_crc, target_crc;
   10985   char *tmp;
   10986 
   10987   /* It doesn't make sense to use qCRC if the remote target is
   10988      connected but not running.  */
   10989   if (target_has_execution ()
   10990       && packet_support (PACKET_qCRC) != PACKET_DISABLE)
   10991     {
   10992       enum packet_result result;
   10993 
   10994       /* Make sure the remote is pointing at the right process.  */
   10995       set_general_process ();
   10996 
   10997       /* FIXME: assumes lma can fit into long.  */
   10998       xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
   10999 		 (long) lma, (long) size);
   11000       putpkt (rs->buf);
   11001 
   11002       /* Be clever; compute the host_crc before waiting for target
   11003 	 reply.  */
   11004       host_crc = xcrc32 (data, size, 0xffffffff);
   11005 
   11006       getpkt (&rs->buf, 0);
   11007 
   11008       result = packet_ok (rs->buf,
   11009 			  &remote_protocol_packets[PACKET_qCRC]);
   11010       if (result == PACKET_ERROR)
   11011 	return -1;
   11012       else if (result == PACKET_OK)
   11013 	{
   11014 	  for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
   11015 	    target_crc = target_crc * 16 + fromhex (*tmp);
   11016 
   11017 	  return (host_crc == target_crc);
   11018 	}
   11019     }
   11020 
   11021   return simple_verify_memory (this, data, lma, size);
   11022 }
   11023 
   11024 /* compare-sections command
   11025 
   11026    With no arguments, compares each loadable section in the exec bfd
   11027    with the same memory range on the target, and reports mismatches.
   11028    Useful for verifying the image on the target against the exec file.  */
   11029 
   11030 static void
   11031 compare_sections_command (const char *args, int from_tty)
   11032 {
   11033   asection *s;
   11034   const char *sectname;
   11035   bfd_size_type size;
   11036   bfd_vma lma;
   11037   int matched = 0;
   11038   int mismatched = 0;
   11039   int res;
   11040   int read_only = 0;
   11041 
   11042   if (!current_program_space->exec_bfd ())
   11043     error (_("command cannot be used without an exec file"));
   11044 
   11045   if (args != NULL && strcmp (args, "-r") == 0)
   11046     {
   11047       read_only = 1;
   11048       args = NULL;
   11049     }
   11050 
   11051   for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
   11052     {
   11053       if (!(s->flags & SEC_LOAD))
   11054 	continue;		/* Skip non-loadable section.  */
   11055 
   11056       if (read_only && (s->flags & SEC_READONLY) == 0)
   11057 	continue;		/* Skip writeable sections */
   11058 
   11059       size = bfd_section_size (s);
   11060       if (size == 0)
   11061 	continue;		/* Skip zero-length section.  */
   11062 
   11063       sectname = bfd_section_name (s);
   11064       if (args && strcmp (args, sectname) != 0)
   11065 	continue;		/* Not the section selected by user.  */
   11066 
   11067       matched = 1;		/* Do this section.  */
   11068       lma = s->lma;
   11069 
   11070       gdb::byte_vector sectdata (size);
   11071       bfd_get_section_contents (current_program_space->exec_bfd (), s,
   11072 				sectdata.data (), 0, size);
   11073 
   11074       res = target_verify_memory (sectdata.data (), lma, size);
   11075 
   11076       if (res == -1)
   11077 	error (_("target memory fault, section %s, range %s -- %s"), sectname,
   11078 	       paddress (target_gdbarch (), lma),
   11079 	       paddress (target_gdbarch (), lma + size));
   11080 
   11081       gdb_printf ("Section %s, range %s -- %s: ", sectname,
   11082 		  paddress (target_gdbarch (), lma),
   11083 		  paddress (target_gdbarch (), lma + size));
   11084       if (res)
   11085 	gdb_printf ("matched.\n");
   11086       else
   11087 	{
   11088 	  gdb_printf ("MIS-MATCHED!\n");
   11089 	  mismatched++;
   11090 	}
   11091     }
   11092   if (mismatched > 0)
   11093     warning (_("One or more sections of the target image does not match\n\
   11094 the loaded file\n"));
   11095   if (args && !matched)
   11096     gdb_printf (_("No loaded section named '%s'.\n"), args);
   11097 }
   11098 
   11099 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
   11100    into remote target.  The number of bytes written to the remote
   11101    target is returned, or -1 for error.  */
   11102 
   11103 target_xfer_status
   11104 remote_target::remote_write_qxfer (const char *object_name,
   11105 				   const char *annex, const gdb_byte *writebuf,
   11106 				   ULONGEST offset, LONGEST len,
   11107 				   ULONGEST *xfered_len,
   11108 				   struct packet_config *packet)
   11109 {
   11110   int i, buf_len;
   11111   ULONGEST n;
   11112   struct remote_state *rs = get_remote_state ();
   11113   int max_size = get_memory_write_packet_size ();
   11114 
   11115   if (packet_config_support (packet) == PACKET_DISABLE)
   11116     return TARGET_XFER_E_IO;
   11117 
   11118   /* Insert header.  */
   11119   i = snprintf (rs->buf.data (), max_size,
   11120 		"qXfer:%s:write:%s:%s:",
   11121 		object_name, annex ? annex : "",
   11122 		phex_nz (offset, sizeof offset));
   11123   max_size -= (i + 1);
   11124 
   11125   /* Escape as much data as fits into rs->buf.  */
   11126   buf_len = remote_escape_output
   11127     (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
   11128 
   11129   if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
   11130       || getpkt_sane (&rs->buf, 0) < 0
   11131       || packet_ok (rs->buf, packet) != PACKET_OK)
   11132     return TARGET_XFER_E_IO;
   11133 
   11134   unpack_varlen_hex (rs->buf.data (), &n);
   11135 
   11136   *xfered_len = n;
   11137   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
   11138 }
   11139 
   11140 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
   11141    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
   11142    number of bytes read is returned, or 0 for EOF, or -1 for error.
   11143    The number of bytes read may be less than LEN without indicating an
   11144    EOF.  PACKET is checked and updated to indicate whether the remote
   11145    target supports this object.  */
   11146 
   11147 target_xfer_status
   11148 remote_target::remote_read_qxfer (const char *object_name,
   11149 				  const char *annex,
   11150 				  gdb_byte *readbuf, ULONGEST offset,
   11151 				  LONGEST len,
   11152 				  ULONGEST *xfered_len,
   11153 				  struct packet_config *packet)
   11154 {
   11155   struct remote_state *rs = get_remote_state ();
   11156   LONGEST i, n, packet_len;
   11157 
   11158   if (packet_config_support (packet) == PACKET_DISABLE)
   11159     return TARGET_XFER_E_IO;
   11160 
   11161   /* Check whether we've cached an end-of-object packet that matches
   11162      this request.  */
   11163   if (rs->finished_object)
   11164     {
   11165       if (strcmp (object_name, rs->finished_object) == 0
   11166 	  && strcmp (annex ? annex : "", rs->finished_annex) == 0
   11167 	  && offset == rs->finished_offset)
   11168 	return TARGET_XFER_EOF;
   11169 
   11170 
   11171       /* Otherwise, we're now reading something different.  Discard
   11172 	 the cache.  */
   11173       xfree (rs->finished_object);
   11174       xfree (rs->finished_annex);
   11175       rs->finished_object = NULL;
   11176       rs->finished_annex = NULL;
   11177     }
   11178 
   11179   /* Request only enough to fit in a single packet.  The actual data
   11180      may not, since we don't know how much of it will need to be escaped;
   11181      the target is free to respond with slightly less data.  We subtract
   11182      five to account for the response type and the protocol frame.  */
   11183   n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
   11184   snprintf (rs->buf.data (), get_remote_packet_size () - 4,
   11185 	    "qXfer:%s:read:%s:%s,%s",
   11186 	    object_name, annex ? annex : "",
   11187 	    phex_nz (offset, sizeof offset),
   11188 	    phex_nz (n, sizeof n));
   11189   i = putpkt (rs->buf);
   11190   if (i < 0)
   11191     return TARGET_XFER_E_IO;
   11192 
   11193   rs->buf[0] = '\0';
   11194   packet_len = getpkt_sane (&rs->buf, 0);
   11195   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
   11196     return TARGET_XFER_E_IO;
   11197 
   11198   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
   11199     error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
   11200 
   11201   /* 'm' means there is (or at least might be) more data after this
   11202      batch.  That does not make sense unless there's at least one byte
   11203      of data in this reply.  */
   11204   if (rs->buf[0] == 'm' && packet_len == 1)
   11205     error (_("Remote qXfer reply contained no data."));
   11206 
   11207   /* Got some data.  */
   11208   i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
   11209 			     packet_len - 1, readbuf, n);
   11210 
   11211   /* 'l' is an EOF marker, possibly including a final block of data,
   11212      or possibly empty.  If we have the final block of a non-empty
   11213      object, record this fact to bypass a subsequent partial read.  */
   11214   if (rs->buf[0] == 'l' && offset + i > 0)
   11215     {
   11216       rs->finished_object = xstrdup (object_name);
   11217       rs->finished_annex = xstrdup (annex ? annex : "");
   11218       rs->finished_offset = offset + i;
   11219     }
   11220 
   11221   if (i == 0)
   11222     return TARGET_XFER_EOF;
   11223   else
   11224     {
   11225       *xfered_len = i;
   11226       return TARGET_XFER_OK;
   11227     }
   11228 }
   11229 
   11230 enum target_xfer_status
   11231 remote_target::xfer_partial (enum target_object object,
   11232 			     const char *annex, gdb_byte *readbuf,
   11233 			     const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
   11234 			     ULONGEST *xfered_len)
   11235 {
   11236   struct remote_state *rs;
   11237   int i;
   11238   char *p2;
   11239   char query_type;
   11240   int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
   11241 
   11242   set_remote_traceframe ();
   11243   set_general_thread (inferior_ptid);
   11244 
   11245   rs = get_remote_state ();
   11246 
   11247   /* Handle memory using the standard memory routines.  */
   11248   if (object == TARGET_OBJECT_MEMORY)
   11249     {
   11250       /* If the remote target is connected but not running, we should
   11251 	 pass this request down to a lower stratum (e.g. the executable
   11252 	 file).  */
   11253       if (!target_has_execution ())
   11254 	return TARGET_XFER_EOF;
   11255 
   11256       if (writebuf != NULL)
   11257 	return remote_write_bytes (offset, writebuf, len, unit_size,
   11258 				   xfered_len);
   11259       else
   11260 	return remote_read_bytes (offset, readbuf, len, unit_size,
   11261 				  xfered_len);
   11262     }
   11263 
   11264   /* Handle extra signal info using qxfer packets.  */
   11265   if (object == TARGET_OBJECT_SIGNAL_INFO)
   11266     {
   11267       if (readbuf)
   11268 	return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
   11269 				  xfered_len, &remote_protocol_packets
   11270 				  [PACKET_qXfer_siginfo_read]);
   11271       else
   11272 	return remote_write_qxfer ("siginfo", annex,
   11273 				   writebuf, offset, len, xfered_len,
   11274 				   &remote_protocol_packets
   11275 				   [PACKET_qXfer_siginfo_write]);
   11276     }
   11277 
   11278   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
   11279     {
   11280       if (readbuf)
   11281 	return remote_read_qxfer ("statictrace", annex,
   11282 				  readbuf, offset, len, xfered_len,
   11283 				  &remote_protocol_packets
   11284 				  [PACKET_qXfer_statictrace_read]);
   11285       else
   11286 	return TARGET_XFER_E_IO;
   11287     }
   11288 
   11289   /* Only handle flash writes.  */
   11290   if (writebuf != NULL)
   11291     {
   11292       switch (object)
   11293 	{
   11294 	case TARGET_OBJECT_FLASH:
   11295 	  return remote_flash_write (offset, len, xfered_len,
   11296 				     writebuf);
   11297 
   11298 	default:
   11299 	  return TARGET_XFER_E_IO;
   11300 	}
   11301     }
   11302 
   11303   /* Map pre-existing objects onto letters.  DO NOT do this for new
   11304      objects!!!  Instead specify new query packets.  */
   11305   switch (object)
   11306     {
   11307     case TARGET_OBJECT_AVR:
   11308       query_type = 'R';
   11309       break;
   11310 
   11311     case TARGET_OBJECT_AUXV:
   11312       gdb_assert (annex == NULL);
   11313       return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
   11314 				xfered_len,
   11315 				&remote_protocol_packets[PACKET_qXfer_auxv]);
   11316 
   11317     case TARGET_OBJECT_AVAILABLE_FEATURES:
   11318       return remote_read_qxfer
   11319 	("features", annex, readbuf, offset, len, xfered_len,
   11320 	 &remote_protocol_packets[PACKET_qXfer_features]);
   11321 
   11322     case TARGET_OBJECT_LIBRARIES:
   11323       return remote_read_qxfer
   11324 	("libraries", annex, readbuf, offset, len, xfered_len,
   11325 	 &remote_protocol_packets[PACKET_qXfer_libraries]);
   11326 
   11327     case TARGET_OBJECT_LIBRARIES_SVR4:
   11328       return remote_read_qxfer
   11329 	("libraries-svr4", annex, readbuf, offset, len, xfered_len,
   11330 	 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
   11331 
   11332     case TARGET_OBJECT_MEMORY_MAP:
   11333       gdb_assert (annex == NULL);
   11334       return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
   11335 				 xfered_len,
   11336 				&remote_protocol_packets[PACKET_qXfer_memory_map]);
   11337 
   11338     case TARGET_OBJECT_OSDATA:
   11339       /* Should only get here if we're connected.  */
   11340       gdb_assert (rs->remote_desc);
   11341       return remote_read_qxfer
   11342 	("osdata", annex, readbuf, offset, len, xfered_len,
   11343 	&remote_protocol_packets[PACKET_qXfer_osdata]);
   11344 
   11345     case TARGET_OBJECT_THREADS:
   11346       gdb_assert (annex == NULL);
   11347       return remote_read_qxfer ("threads", annex, readbuf, offset, len,
   11348 				xfered_len,
   11349 				&remote_protocol_packets[PACKET_qXfer_threads]);
   11350 
   11351     case TARGET_OBJECT_TRACEFRAME_INFO:
   11352       gdb_assert (annex == NULL);
   11353       return remote_read_qxfer
   11354 	("traceframe-info", annex, readbuf, offset, len, xfered_len,
   11355 	 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
   11356 
   11357     case TARGET_OBJECT_FDPIC:
   11358       return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
   11359 				xfered_len,
   11360 				&remote_protocol_packets[PACKET_qXfer_fdpic]);
   11361 
   11362     case TARGET_OBJECT_OPENVMS_UIB:
   11363       return remote_read_qxfer ("uib", annex, readbuf, offset, len,
   11364 				xfered_len,
   11365 				&remote_protocol_packets[PACKET_qXfer_uib]);
   11366 
   11367     case TARGET_OBJECT_BTRACE:
   11368       return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
   11369 				xfered_len,
   11370 	&remote_protocol_packets[PACKET_qXfer_btrace]);
   11371 
   11372     case TARGET_OBJECT_BTRACE_CONF:
   11373       return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
   11374 				len, xfered_len,
   11375 	&remote_protocol_packets[PACKET_qXfer_btrace_conf]);
   11376 
   11377     case TARGET_OBJECT_EXEC_FILE:
   11378       return remote_read_qxfer ("exec-file", annex, readbuf, offset,
   11379 				len, xfered_len,
   11380 	&remote_protocol_packets[PACKET_qXfer_exec_file]);
   11381 
   11382     default:
   11383       return TARGET_XFER_E_IO;
   11384     }
   11385 
   11386   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
   11387      large enough let the caller deal with it.  */
   11388   if (len < get_remote_packet_size ())
   11389     return TARGET_XFER_E_IO;
   11390   len = get_remote_packet_size ();
   11391 
   11392   /* Except for querying the minimum buffer size, target must be open.  */
   11393   if (!rs->remote_desc)
   11394     error (_("remote query is only available after target open"));
   11395 
   11396   gdb_assert (annex != NULL);
   11397   gdb_assert (readbuf != NULL);
   11398 
   11399   p2 = rs->buf.data ();
   11400   *p2++ = 'q';
   11401   *p2++ = query_type;
   11402 
   11403   /* We used one buffer char for the remote protocol q command and
   11404      another for the query type.  As the remote protocol encapsulation
   11405      uses 4 chars plus one extra in case we are debugging
   11406      (remote_debug), we have PBUFZIZ - 7 left to pack the query
   11407      string.  */
   11408   i = 0;
   11409   while (annex[i] && (i < (get_remote_packet_size () - 8)))
   11410     {
   11411       /* Bad caller may have sent forbidden characters.  */
   11412       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
   11413       *p2++ = annex[i];
   11414       i++;
   11415     }
   11416   *p2 = '\0';
   11417   gdb_assert (annex[i] == '\0');
   11418 
   11419   i = putpkt (rs->buf);
   11420   if (i < 0)
   11421     return TARGET_XFER_E_IO;
   11422 
   11423   getpkt (&rs->buf, 0);
   11424   strcpy ((char *) readbuf, rs->buf.data ());
   11425 
   11426   *xfered_len = strlen ((char *) readbuf);
   11427   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
   11428 }
   11429 
   11430 /* Implementation of to_get_memory_xfer_limit.  */
   11431 
   11432 ULONGEST
   11433 remote_target::get_memory_xfer_limit ()
   11434 {
   11435   return get_memory_write_packet_size ();
   11436 }
   11437 
   11438 int
   11439 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
   11440 			      const gdb_byte *pattern, ULONGEST pattern_len,
   11441 			      CORE_ADDR *found_addrp)
   11442 {
   11443   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
   11444   struct remote_state *rs = get_remote_state ();
   11445   int max_size = get_memory_write_packet_size ();
   11446   struct packet_config *packet =
   11447     &remote_protocol_packets[PACKET_qSearch_memory];
   11448   /* Number of packet bytes used to encode the pattern;
   11449      this could be more than PATTERN_LEN due to escape characters.  */
   11450   int escaped_pattern_len;
   11451   /* Amount of pattern that was encodable in the packet.  */
   11452   int used_pattern_len;
   11453   int i;
   11454   int found;
   11455   ULONGEST found_addr;
   11456 
   11457   auto read_memory = [=] (CORE_ADDR addr, gdb_byte *result, size_t len)
   11458     {
   11459       return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
   11460 	      == len);
   11461     };
   11462 
   11463   /* Don't go to the target if we don't have to.  This is done before
   11464      checking packet_config_support to avoid the possibility that a
   11465      success for this edge case means the facility works in
   11466      general.  */
   11467   if (pattern_len > search_space_len)
   11468     return 0;
   11469   if (pattern_len == 0)
   11470     {
   11471       *found_addrp = start_addr;
   11472       return 1;
   11473     }
   11474 
   11475   /* If we already know the packet isn't supported, fall back to the simple
   11476      way of searching memory.  */
   11477 
   11478   if (packet_config_support (packet) == PACKET_DISABLE)
   11479     {
   11480       /* Target doesn't provided special support, fall back and use the
   11481 	 standard support (copy memory and do the search here).  */
   11482       return simple_search_memory (read_memory, start_addr, search_space_len,
   11483 				   pattern, pattern_len, found_addrp);
   11484     }
   11485 
   11486   /* Make sure the remote is pointing at the right process.  */
   11487   set_general_process ();
   11488 
   11489   /* Insert header.  */
   11490   i = snprintf (rs->buf.data (), max_size,
   11491 		"qSearch:memory:%s;%s;",
   11492 		phex_nz (start_addr, addr_size),
   11493 		phex_nz (search_space_len, sizeof (search_space_len)));
   11494   max_size -= (i + 1);
   11495 
   11496   /* Escape as much data as fits into rs->buf.  */
   11497   escaped_pattern_len =
   11498     remote_escape_output (pattern, pattern_len, 1,
   11499 			  (gdb_byte *) rs->buf.data () + i,
   11500 			  &used_pattern_len, max_size);
   11501 
   11502   /* Bail if the pattern is too large.  */
   11503   if (used_pattern_len != pattern_len)
   11504     error (_("Pattern is too large to transmit to remote target."));
   11505 
   11506   if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
   11507       || getpkt_sane (&rs->buf, 0) < 0
   11508       || packet_ok (rs->buf, packet) != PACKET_OK)
   11509     {
   11510       /* The request may not have worked because the command is not
   11511 	 supported.  If so, fall back to the simple way.  */
   11512       if (packet_config_support (packet) == PACKET_DISABLE)
   11513 	{
   11514 	  return simple_search_memory (read_memory, start_addr, search_space_len,
   11515 				       pattern, pattern_len, found_addrp);
   11516 	}
   11517       return -1;
   11518     }
   11519 
   11520   if (rs->buf[0] == '0')
   11521     found = 0;
   11522   else if (rs->buf[0] == '1')
   11523     {
   11524       found = 1;
   11525       if (rs->buf[1] != ',')
   11526 	error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
   11527       unpack_varlen_hex (&rs->buf[2], &found_addr);
   11528       *found_addrp = found_addr;
   11529     }
   11530   else
   11531     error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
   11532 
   11533   return found;
   11534 }
   11535 
   11536 void
   11537 remote_target::rcmd (const char *command, struct ui_file *outbuf)
   11538 {
   11539   struct remote_state *rs = get_remote_state ();
   11540   char *p = rs->buf.data ();
   11541 
   11542   if (!rs->remote_desc)
   11543     error (_("remote rcmd is only available after target open"));
   11544 
   11545   /* Send a NULL command across as an empty command.  */
   11546   if (command == NULL)
   11547     command = "";
   11548 
   11549   /* The query prefix.  */
   11550   strcpy (rs->buf.data (), "qRcmd,");
   11551   p = strchr (rs->buf.data (), '\0');
   11552 
   11553   if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
   11554       > get_remote_packet_size ())
   11555     error (_("\"monitor\" command ``%s'' is too long."), command);
   11556 
   11557   /* Encode the actual command.  */
   11558   bin2hex ((const gdb_byte *) command, p, strlen (command));
   11559 
   11560   if (putpkt (rs->buf) < 0)
   11561     error (_("Communication problem with target."));
   11562 
   11563   /* get/display the response */
   11564   while (1)
   11565     {
   11566       char *buf;
   11567 
   11568       /* XXX - see also remote_get_noisy_reply().  */
   11569       QUIT;			/* Allow user to bail out with ^C.  */
   11570       rs->buf[0] = '\0';
   11571       if (getpkt_sane (&rs->buf, 0) == -1)
   11572 	{
   11573 	  /* Timeout.  Continue to (try to) read responses.
   11574 	     This is better than stopping with an error, assuming the stub
   11575 	     is still executing the (long) monitor command.
   11576 	     If needed, the user can interrupt gdb using C-c, obtaining
   11577 	     an effect similar to stop on timeout.  */
   11578 	  continue;
   11579 	}
   11580       buf = rs->buf.data ();
   11581       if (buf[0] == '\0')
   11582 	error (_("Target does not support this command."));
   11583       if (buf[0] == 'O' && buf[1] != 'K')
   11584 	{
   11585 	  remote_console_output (buf + 1); /* 'O' message from stub.  */
   11586 	  continue;
   11587 	}
   11588       if (strcmp (buf, "OK") == 0)
   11589 	break;
   11590       if (strlen (buf) == 3 && buf[0] == 'E'
   11591 	  && isxdigit (buf[1]) && isxdigit (buf[2]))
   11592 	{
   11593 	  error (_("Protocol error with Rcmd"));
   11594 	}
   11595       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
   11596 	{
   11597 	  char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
   11598 
   11599 	  gdb_putc (c, outbuf);
   11600 	}
   11601       break;
   11602     }
   11603 }
   11604 
   11605 std::vector<mem_region>
   11606 remote_target::memory_map ()
   11607 {
   11608   std::vector<mem_region> result;
   11609   gdb::optional<gdb::char_vector> text
   11610     = target_read_stralloc (current_inferior ()->top_target (),
   11611 			    TARGET_OBJECT_MEMORY_MAP, NULL);
   11612 
   11613   if (text)
   11614     result = parse_memory_map (text->data ());
   11615 
   11616   return result;
   11617 }
   11618 
   11619 /* Set of callbacks used to implement the 'maint packet' command.  */
   11620 
   11621 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
   11622 {
   11623   /* Called before the packet is sent.  BUF is the packet content before
   11624      the protocol specific prefix, suffix, and escaping is added.  */
   11625 
   11626   void sending (gdb::array_view<const char> &buf) override
   11627   {
   11628     gdb_puts ("sending: ");
   11629     print_packet (buf);
   11630     gdb_puts ("\n");
   11631   }
   11632 
   11633   /* Called with BUF, the reply from the remote target.  */
   11634 
   11635   void received (gdb::array_view<const char> &buf) override
   11636   {
   11637     gdb_puts ("received: \"");
   11638     print_packet (buf);
   11639     gdb_puts ("\"\n");
   11640   }
   11641 
   11642 private:
   11643 
   11644   /* Print BUF o gdb_stdout.  Any non-printable bytes in BUF are printed as
   11645      '\x??' with '??' replaced by the hexadecimal value of the byte.  */
   11646 
   11647   static void
   11648   print_packet (gdb::array_view<const char> &buf)
   11649   {
   11650     string_file stb;
   11651 
   11652     for (int i = 0; i < buf.size (); ++i)
   11653       {
   11654 	gdb_byte c = buf[i];
   11655 	if (isprint (c))
   11656 	  gdb_putc (c, &stb);
   11657 	else
   11658 	  gdb_printf (&stb, "\\x%02x", (unsigned char) c);
   11659       }
   11660 
   11661     gdb_puts (stb.string ().c_str ());
   11662   }
   11663 };
   11664 
   11665 /* See remote.h.  */
   11666 
   11667 void
   11668 send_remote_packet (gdb::array_view<const char> &buf,
   11669 		    send_remote_packet_callbacks *callbacks)
   11670 {
   11671   if (buf.size () == 0 || buf.data ()[0] == '\0')
   11672     error (_("a remote packet must not be empty"));
   11673 
   11674   remote_target *remote = get_current_remote_target ();
   11675   if (remote == nullptr)
   11676     error (_("packets can only be sent to a remote target"));
   11677 
   11678   callbacks->sending (buf);
   11679 
   11680   remote->putpkt_binary (buf.data (), buf.size ());
   11681   remote_state *rs = remote->get_remote_state ();
   11682   int bytes = remote->getpkt_sane (&rs->buf, 0);
   11683 
   11684   if (bytes < 0)
   11685     error (_("error while fetching packet from remote target"));
   11686 
   11687   gdb::array_view<const char> view (&rs->buf[0], bytes);
   11688   callbacks->received (view);
   11689 }
   11690 
   11691 /* Entry point for the 'maint packet' command.  */
   11692 
   11693 static void
   11694 cli_packet_command (const char *args, int from_tty)
   11695 {
   11696   cli_packet_command_callbacks cb;
   11697   gdb::array_view<const char> view
   11698     = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
   11699   send_remote_packet (view, &cb);
   11700 }
   11701 
   11702 #if 0
   11703 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
   11704 
   11705 static void display_thread_info (struct gdb_ext_thread_info *info);
   11706 
   11707 static void threadset_test_cmd (char *cmd, int tty);
   11708 
   11709 static void threadalive_test (char *cmd, int tty);
   11710 
   11711 static void threadlist_test_cmd (char *cmd, int tty);
   11712 
   11713 int get_and_display_threadinfo (threadref *ref);
   11714 
   11715 static void threadinfo_test_cmd (char *cmd, int tty);
   11716 
   11717 static int thread_display_step (threadref *ref, void *context);
   11718 
   11719 static void threadlist_update_test_cmd (char *cmd, int tty);
   11720 
   11721 static void init_remote_threadtests (void);
   11722 
   11723 #define SAMPLE_THREAD  0x05060708	/* Truncated 64 bit threadid.  */
   11724 
   11725 static void
   11726 threadset_test_cmd (const char *cmd, int tty)
   11727 {
   11728   int sample_thread = SAMPLE_THREAD;
   11729 
   11730   gdb_printf (_("Remote threadset test\n"));
   11731   set_general_thread (sample_thread);
   11732 }
   11733 
   11734 
   11735 static void
   11736 threadalive_test (const char *cmd, int tty)
   11737 {
   11738   int sample_thread = SAMPLE_THREAD;
   11739   int pid = inferior_ptid.pid ();
   11740   ptid_t ptid = ptid_t (pid, sample_thread, 0);
   11741 
   11742   if (remote_thread_alive (ptid))
   11743     gdb_printf ("PASS: Thread alive test\n");
   11744   else
   11745     gdb_printf ("FAIL: Thread alive test\n");
   11746 }
   11747 
   11748 void output_threadid (char *title, threadref *ref);
   11749 
   11750 void
   11751 output_threadid (char *title, threadref *ref)
   11752 {
   11753   char hexid[20];
   11754 
   11755   pack_threadid (&hexid[0], ref);	/* Convert thread id into hex.  */
   11756   hexid[16] = 0;
   11757   gdb_printf ("%s  %s\n", title, (&hexid[0]));
   11758 }
   11759 
   11760 static void
   11761 threadlist_test_cmd (const char *cmd, int tty)
   11762 {
   11763   int startflag = 1;
   11764   threadref nextthread;
   11765   int done, result_count;
   11766   threadref threadlist[3];
   11767 
   11768   gdb_printf ("Remote Threadlist test\n");
   11769   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
   11770 			      &result_count, &threadlist[0]))
   11771     gdb_printf ("FAIL: threadlist test\n");
   11772   else
   11773     {
   11774       threadref *scan = threadlist;
   11775       threadref *limit = scan + result_count;
   11776 
   11777       while (scan < limit)
   11778 	output_threadid (" thread ", scan++);
   11779     }
   11780 }
   11781 
   11782 void
   11783 display_thread_info (struct gdb_ext_thread_info *info)
   11784 {
   11785   output_threadid ("Threadid: ", &info->threadid);
   11786   gdb_printf ("Name: %s\n ", info->shortname);
   11787   gdb_printf ("State: %s\n", info->display);
   11788   gdb_printf ("other: %s\n\n", info->more_display);
   11789 }
   11790 
   11791 int
   11792 get_and_display_threadinfo (threadref *ref)
   11793 {
   11794   int result;
   11795   int set;
   11796   struct gdb_ext_thread_info threadinfo;
   11797 
   11798   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
   11799     | TAG_MOREDISPLAY | TAG_DISPLAY;
   11800   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
   11801     display_thread_info (&threadinfo);
   11802   return result;
   11803 }
   11804 
   11805 static void
   11806 threadinfo_test_cmd (const char *cmd, int tty)
   11807 {
   11808   int athread = SAMPLE_THREAD;
   11809   threadref thread;
   11810   int set;
   11811 
   11812   int_to_threadref (&thread, athread);
   11813   gdb_printf ("Remote Threadinfo test\n");
   11814   if (!get_and_display_threadinfo (&thread))
   11815     gdb_printf ("FAIL cannot get thread info\n");
   11816 }
   11817 
   11818 static int
   11819 thread_display_step (threadref *ref, void *context)
   11820 {
   11821   /* output_threadid(" threadstep ",ref); *//* simple test */
   11822   return get_and_display_threadinfo (ref);
   11823 }
   11824 
   11825 static void
   11826 threadlist_update_test_cmd (const char *cmd, int tty)
   11827 {
   11828   gdb_printf ("Remote Threadlist update test\n");
   11829   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
   11830 }
   11831 
   11832 static void
   11833 init_remote_threadtests (void)
   11834 {
   11835   add_com ("tlist", class_obscure, threadlist_test_cmd,
   11836 	   _("Fetch and print the remote list of "
   11837 	     "thread identifiers, one pkt only."));
   11838   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
   11839 	   _("Fetch and display info about one thread."));
   11840   add_com ("tset", class_obscure, threadset_test_cmd,
   11841 	   _("Test setting to a different thread."));
   11842   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
   11843 	   _("Iterate through updating all remote thread info."));
   11844   add_com ("talive", class_obscure, threadalive_test,
   11845 	   _("Remote thread alive test."));
   11846 }
   11847 
   11848 #endif /* 0 */
   11849 
   11850 /* Convert a thread ID to a string.  */
   11851 
   11852 std::string
   11853 remote_target::pid_to_str (ptid_t ptid)
   11854 {
   11855   struct remote_state *rs = get_remote_state ();
   11856 
   11857   if (ptid == null_ptid)
   11858     return normal_pid_to_str (ptid);
   11859   else if (ptid.is_pid ())
   11860     {
   11861       /* Printing an inferior target id.  */
   11862 
   11863       /* When multi-process extensions are off, there's no way in the
   11864 	 remote protocol to know the remote process id, if there's any
   11865 	 at all.  There's one exception --- when we're connected with
   11866 	 target extended-remote, and we manually attached to a process
   11867 	 with "attach PID".  We don't record anywhere a flag that
   11868 	 allows us to distinguish that case from the case of
   11869 	 connecting with extended-remote and the stub already being
   11870 	 attached to a process, and reporting yes to qAttached, hence
   11871 	 no smart special casing here.  */
   11872       if (!remote_multi_process_p (rs))
   11873 	return "Remote target";
   11874 
   11875       return normal_pid_to_str (ptid);
   11876     }
   11877   else
   11878     {
   11879       if (magic_null_ptid == ptid)
   11880 	return "Thread <main>";
   11881       else if (remote_multi_process_p (rs))
   11882 	if (ptid.lwp () == 0)
   11883 	  return normal_pid_to_str (ptid);
   11884 	else
   11885 	  return string_printf ("Thread %d.%ld",
   11886 				ptid.pid (), ptid.lwp ());
   11887       else
   11888 	return string_printf ("Thread %ld", ptid.lwp ());
   11889     }
   11890 }
   11891 
   11892 /* Get the address of the thread local variable in OBJFILE which is
   11893    stored at OFFSET within the thread local storage for thread PTID.  */
   11894 
   11895 CORE_ADDR
   11896 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
   11897 					 CORE_ADDR offset)
   11898 {
   11899   if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
   11900     {
   11901       struct remote_state *rs = get_remote_state ();
   11902       char *p = rs->buf.data ();
   11903       char *endp = p + get_remote_packet_size ();
   11904       enum packet_result result;
   11905 
   11906       strcpy (p, "qGetTLSAddr:");
   11907       p += strlen (p);
   11908       p = write_ptid (p, endp, ptid);
   11909       *p++ = ',';
   11910       p += hexnumstr (p, offset);
   11911       *p++ = ',';
   11912       p += hexnumstr (p, lm);
   11913       *p++ = '\0';
   11914 
   11915       putpkt (rs->buf);
   11916       getpkt (&rs->buf, 0);
   11917       result = packet_ok (rs->buf,
   11918 			  &remote_protocol_packets[PACKET_qGetTLSAddr]);
   11919       if (result == PACKET_OK)
   11920 	{
   11921 	  ULONGEST addr;
   11922 
   11923 	  unpack_varlen_hex (rs->buf.data (), &addr);
   11924 	  return addr;
   11925 	}
   11926       else if (result == PACKET_UNKNOWN)
   11927 	throw_error (TLS_GENERIC_ERROR,
   11928 		     _("Remote target doesn't support qGetTLSAddr packet"));
   11929       else
   11930 	throw_error (TLS_GENERIC_ERROR,
   11931 		     _("Remote target failed to process qGetTLSAddr request"));
   11932     }
   11933   else
   11934     throw_error (TLS_GENERIC_ERROR,
   11935 		 _("TLS not supported or disabled on this target"));
   11936   /* Not reached.  */
   11937   return 0;
   11938 }
   11939 
   11940 /* Provide thread local base, i.e. Thread Information Block address.
   11941    Returns 1 if ptid is found and thread_local_base is non zero.  */
   11942 
   11943 bool
   11944 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
   11945 {
   11946   if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
   11947     {
   11948       struct remote_state *rs = get_remote_state ();
   11949       char *p = rs->buf.data ();
   11950       char *endp = p + get_remote_packet_size ();
   11951       enum packet_result result;
   11952 
   11953       strcpy (p, "qGetTIBAddr:");
   11954       p += strlen (p);
   11955       p = write_ptid (p, endp, ptid);
   11956       *p++ = '\0';
   11957 
   11958       putpkt (rs->buf);
   11959       getpkt (&rs->buf, 0);
   11960       result = packet_ok (rs->buf,
   11961 			  &remote_protocol_packets[PACKET_qGetTIBAddr]);
   11962       if (result == PACKET_OK)
   11963 	{
   11964 	  ULONGEST val;
   11965 	  unpack_varlen_hex (rs->buf.data (), &val);
   11966 	  if (addr)
   11967 	    *addr = (CORE_ADDR) val;
   11968 	  return true;
   11969 	}
   11970       else if (result == PACKET_UNKNOWN)
   11971 	error (_("Remote target doesn't support qGetTIBAddr packet"));
   11972       else
   11973 	error (_("Remote target failed to process qGetTIBAddr request"));
   11974     }
   11975   else
   11976     error (_("qGetTIBAddr not supported or disabled on this target"));
   11977   /* Not reached.  */
   11978   return false;
   11979 }
   11980 
   11981 /* Support for inferring a target description based on the current
   11982    architecture and the size of a 'g' packet.  While the 'g' packet
   11983    can have any size (since optional registers can be left off the
   11984    end), some sizes are easily recognizable given knowledge of the
   11985    approximate architecture.  */
   11986 
   11987 struct remote_g_packet_guess
   11988 {
   11989   remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
   11990     : bytes (bytes_),
   11991       tdesc (tdesc_)
   11992   {
   11993   }
   11994 
   11995   int bytes;
   11996   const struct target_desc *tdesc;
   11997 };
   11998 
   11999 struct remote_g_packet_data
   12000 {
   12001   std::vector<remote_g_packet_guess> guesses;
   12002 };
   12003 
   12004 static const registry<gdbarch>::key<struct remote_g_packet_data>
   12005      remote_g_packet_data_handle;
   12006 
   12007 static struct remote_g_packet_data *
   12008 get_g_packet_data (struct gdbarch *gdbarch)
   12009 {
   12010   struct remote_g_packet_data *data
   12011     = remote_g_packet_data_handle.get (gdbarch);
   12012   if (data == nullptr)
   12013     data = remote_g_packet_data_handle.emplace (gdbarch);
   12014   return data;
   12015 }
   12016 
   12017 void
   12018 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
   12019 				const struct target_desc *tdesc)
   12020 {
   12021   struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
   12022 
   12023   gdb_assert (tdesc != NULL);
   12024 
   12025   for (const remote_g_packet_guess &guess : data->guesses)
   12026     if (guess.bytes == bytes)
   12027       internal_error (_("Duplicate g packet description added for size %d"),
   12028 		      bytes);
   12029 
   12030   data->guesses.emplace_back (bytes, tdesc);
   12031 }
   12032 
   12033 /* Return true if remote_read_description would do anything on this target
   12034    and architecture, false otherwise.  */
   12035 
   12036 static bool
   12037 remote_read_description_p (struct target_ops *target)
   12038 {
   12039   struct remote_g_packet_data *data = get_g_packet_data (target_gdbarch ());
   12040 
   12041   return !data->guesses.empty ();
   12042 }
   12043 
   12044 const struct target_desc *
   12045 remote_target::read_description ()
   12046 {
   12047   struct remote_g_packet_data *data = get_g_packet_data (target_gdbarch ());
   12048 
   12049   /* Do not try this during initial connection, when we do not know
   12050      whether there is a running but stopped thread.  */
   12051   if (!target_has_execution () || inferior_ptid == null_ptid)
   12052     return beneath ()->read_description ();
   12053 
   12054   if (!data->guesses.empty ())
   12055     {
   12056       int bytes = send_g_packet ();
   12057 
   12058       for (const remote_g_packet_guess &guess : data->guesses)
   12059 	if (guess.bytes == bytes)
   12060 	  return guess.tdesc;
   12061 
   12062       /* We discard the g packet.  A minor optimization would be to
   12063 	 hold on to it, and fill the register cache once we have selected
   12064 	 an architecture, but it's too tricky to do safely.  */
   12065     }
   12066 
   12067   return beneath ()->read_description ();
   12068 }
   12069 
   12070 /* Remote file transfer support.  This is host-initiated I/O, not
   12071    target-initiated; for target-initiated, see remote-fileio.c.  */
   12072 
   12073 /* If *LEFT is at least the length of STRING, copy STRING to
   12074    *BUFFER, update *BUFFER to point to the new end of the buffer, and
   12075    decrease *LEFT.  Otherwise raise an error.  */
   12076 
   12077 static void
   12078 remote_buffer_add_string (char **buffer, int *left, const char *string)
   12079 {
   12080   int len = strlen (string);
   12081 
   12082   if (len > *left)
   12083     error (_("Packet too long for target."));
   12084 
   12085   memcpy (*buffer, string, len);
   12086   *buffer += len;
   12087   *left -= len;
   12088 
   12089   /* NUL-terminate the buffer as a convenience, if there is
   12090      room.  */
   12091   if (*left)
   12092     **buffer = '\0';
   12093 }
   12094 
   12095 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
   12096    *BUFFER, update *BUFFER to point to the new end of the buffer, and
   12097    decrease *LEFT.  Otherwise raise an error.  */
   12098 
   12099 static void
   12100 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
   12101 			 int len)
   12102 {
   12103   if (2 * len > *left)
   12104     error (_("Packet too long for target."));
   12105 
   12106   bin2hex (bytes, *buffer, len);
   12107   *buffer += 2 * len;
   12108   *left -= 2 * len;
   12109 
   12110   /* NUL-terminate the buffer as a convenience, if there is
   12111      room.  */
   12112   if (*left)
   12113     **buffer = '\0';
   12114 }
   12115 
   12116 /* If *LEFT is large enough, convert VALUE to hex and add it to
   12117    *BUFFER, update *BUFFER to point to the new end of the buffer, and
   12118    decrease *LEFT.  Otherwise raise an error.  */
   12119 
   12120 static void
   12121 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
   12122 {
   12123   int len = hexnumlen (value);
   12124 
   12125   if (len > *left)
   12126     error (_("Packet too long for target."));
   12127 
   12128   hexnumstr (*buffer, value);
   12129   *buffer += len;
   12130   *left -= len;
   12131 
   12132   /* NUL-terminate the buffer as a convenience, if there is
   12133      room.  */
   12134   if (*left)
   12135     **buffer = '\0';
   12136 }
   12137 
   12138 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
   12139    value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
   12140    was included, and *ATTACHMENT to point to the start of the annex
   12141    if any.  The length of the packet isn't needed here; there may
   12142    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
   12143 
   12144    Return 0 if the packet could be parsed, -1 if it could not.  If
   12145    -1 is returned, the other variables may not be initialized.  */
   12146 
   12147 static int
   12148 remote_hostio_parse_result (const char *buffer, int *retcode,
   12149 			    fileio_error *remote_errno, const char **attachment)
   12150 {
   12151   char *p, *p2;
   12152 
   12153   *remote_errno = FILEIO_SUCCESS;
   12154   *attachment = NULL;
   12155 
   12156   if (buffer[0] != 'F')
   12157     return -1;
   12158 
   12159   errno = 0;
   12160   *retcode = strtol (&buffer[1], &p, 16);
   12161   if (errno != 0 || p == &buffer[1])
   12162     return -1;
   12163 
   12164   /* Check for ",errno".  */
   12165   if (*p == ',')
   12166     {
   12167       errno = 0;
   12168       *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
   12169       if (errno != 0 || p + 1 == p2)
   12170 	return -1;
   12171       p = p2;
   12172     }
   12173 
   12174   /* Check for ";attachment".  If there is no attachment, the
   12175      packet should end here.  */
   12176   if (*p == ';')
   12177     {
   12178       *attachment = p + 1;
   12179       return 0;
   12180     }
   12181   else if (*p == '\0')
   12182     return 0;
   12183   else
   12184     return -1;
   12185 }
   12186 
   12187 /* Send a prepared I/O packet to the target and read its response.
   12188    The prepared packet is in the global RS->BUF before this function
   12189    is called, and the answer is there when we return.
   12190 
   12191    COMMAND_BYTES is the length of the request to send, which may include
   12192    binary data.  WHICH_PACKET is the packet configuration to check
   12193    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
   12194    is set to the error number and -1 is returned.  Otherwise the value
   12195    returned by the function is returned.
   12196 
   12197    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
   12198    attachment is expected; an error will be reported if there's a
   12199    mismatch.  If one is found, *ATTACHMENT will be set to point into
   12200    the packet buffer and *ATTACHMENT_LEN will be set to the
   12201    attachment's length.  */
   12202 
   12203 int
   12204 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
   12205 					   fileio_error *remote_errno, const char **attachment,
   12206 					   int *attachment_len)
   12207 {
   12208   struct remote_state *rs = get_remote_state ();
   12209   int ret, bytes_read;
   12210   const char *attachment_tmp;
   12211 
   12212   if (packet_support (which_packet) == PACKET_DISABLE)
   12213     {
   12214       *remote_errno = FILEIO_ENOSYS;
   12215       return -1;
   12216     }
   12217 
   12218   putpkt_binary (rs->buf.data (), command_bytes);
   12219   bytes_read = getpkt_sane (&rs->buf, 0);
   12220 
   12221   /* If it timed out, something is wrong.  Don't try to parse the
   12222      buffer.  */
   12223   if (bytes_read < 0)
   12224     {
   12225       *remote_errno = FILEIO_EINVAL;
   12226       return -1;
   12227     }
   12228 
   12229   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
   12230     {
   12231     case PACKET_ERROR:
   12232       *remote_errno = FILEIO_EINVAL;
   12233       return -1;
   12234     case PACKET_UNKNOWN:
   12235       *remote_errno = FILEIO_ENOSYS;
   12236       return -1;
   12237     case PACKET_OK:
   12238       break;
   12239     }
   12240 
   12241   if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
   12242 				  &attachment_tmp))
   12243     {
   12244       *remote_errno = FILEIO_EINVAL;
   12245       return -1;
   12246     }
   12247 
   12248   /* Make sure we saw an attachment if and only if we expected one.  */
   12249   if ((attachment_tmp == NULL && attachment != NULL)
   12250       || (attachment_tmp != NULL && attachment == NULL))
   12251     {
   12252       *remote_errno = FILEIO_EINVAL;
   12253       return -1;
   12254     }
   12255 
   12256   /* If an attachment was found, it must point into the packet buffer;
   12257      work out how many bytes there were.  */
   12258   if (attachment_tmp != NULL)
   12259     {
   12260       *attachment = attachment_tmp;
   12261       *attachment_len = bytes_read - (*attachment - rs->buf.data ());
   12262     }
   12263 
   12264   return ret;
   12265 }
   12266 
   12267 /* See declaration.h.  */
   12268 
   12269 void
   12270 readahead_cache::invalidate ()
   12271 {
   12272   this->fd = -1;
   12273 }
   12274 
   12275 /* See declaration.h.  */
   12276 
   12277 void
   12278 readahead_cache::invalidate_fd (int fd)
   12279 {
   12280   if (this->fd == fd)
   12281     this->fd = -1;
   12282 }
   12283 
   12284 /* Set the filesystem remote_hostio functions that take FILENAME
   12285    arguments will use.  Return 0 on success, or -1 if an error
   12286    occurs (and set *REMOTE_ERRNO).  */
   12287 
   12288 int
   12289 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
   12290 					     fileio_error *remote_errno)
   12291 {
   12292   struct remote_state *rs = get_remote_state ();
   12293   int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
   12294   char *p = rs->buf.data ();
   12295   int left = get_remote_packet_size () - 1;
   12296   char arg[9];
   12297   int ret;
   12298 
   12299   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
   12300     return 0;
   12301 
   12302   if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
   12303     return 0;
   12304 
   12305   remote_buffer_add_string (&p, &left, "vFile:setfs:");
   12306 
   12307   xsnprintf (arg, sizeof (arg), "%x", required_pid);
   12308   remote_buffer_add_string (&p, &left, arg);
   12309 
   12310   ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
   12311 				    remote_errno, NULL, NULL);
   12312 
   12313   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
   12314     return 0;
   12315 
   12316   if (ret == 0)
   12317     rs->fs_pid = required_pid;
   12318 
   12319   return ret;
   12320 }
   12321 
   12322 /* Implementation of to_fileio_open.  */
   12323 
   12324 int
   12325 remote_target::remote_hostio_open (inferior *inf, const char *filename,
   12326 				   int flags, int mode, int warn_if_slow,
   12327 				   fileio_error *remote_errno)
   12328 {
   12329   struct remote_state *rs = get_remote_state ();
   12330   char *p = rs->buf.data ();
   12331   int left = get_remote_packet_size () - 1;
   12332 
   12333   if (warn_if_slow)
   12334     {
   12335       static int warning_issued = 0;
   12336 
   12337       gdb_printf (_("Reading %s from remote target...\n"),
   12338 		  filename);
   12339 
   12340       if (!warning_issued)
   12341 	{
   12342 	  warning (_("File transfers from remote targets can be slow."
   12343 		     " Use \"set sysroot\" to access files locally"
   12344 		     " instead."));
   12345 	  warning_issued = 1;
   12346 	}
   12347     }
   12348 
   12349   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
   12350     return -1;
   12351 
   12352   remote_buffer_add_string (&p, &left, "vFile:open:");
   12353 
   12354   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
   12355 			   strlen (filename));
   12356   remote_buffer_add_string (&p, &left, ",");
   12357 
   12358   remote_buffer_add_int (&p, &left, flags);
   12359   remote_buffer_add_string (&p, &left, ",");
   12360 
   12361   remote_buffer_add_int (&p, &left, mode);
   12362 
   12363   return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
   12364 				     remote_errno, NULL, NULL);
   12365 }
   12366 
   12367 int
   12368 remote_target::fileio_open (struct inferior *inf, const char *filename,
   12369 			    int flags, int mode, int warn_if_slow,
   12370 			    fileio_error *remote_errno)
   12371 {
   12372   return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
   12373 			     remote_errno);
   12374 }
   12375 
   12376 /* Implementation of to_fileio_pwrite.  */
   12377 
   12378 int
   12379 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
   12380 				     ULONGEST offset, fileio_error *remote_errno)
   12381 {
   12382   struct remote_state *rs = get_remote_state ();
   12383   char *p = rs->buf.data ();
   12384   int left = get_remote_packet_size ();
   12385   int out_len;
   12386 
   12387   rs->readahead_cache.invalidate_fd (fd);
   12388 
   12389   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
   12390 
   12391   remote_buffer_add_int (&p, &left, fd);
   12392   remote_buffer_add_string (&p, &left, ",");
   12393 
   12394   remote_buffer_add_int (&p, &left, offset);
   12395   remote_buffer_add_string (&p, &left, ",");
   12396 
   12397   p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
   12398 			     (get_remote_packet_size ()
   12399 			      - (p - rs->buf.data ())));
   12400 
   12401   return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
   12402 				     remote_errno, NULL, NULL);
   12403 }
   12404 
   12405 int
   12406 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
   12407 			      ULONGEST offset, fileio_error *remote_errno)
   12408 {
   12409   return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
   12410 }
   12411 
   12412 /* Helper for the implementation of to_fileio_pread.  Read the file
   12413    from the remote side with vFile:pread.  */
   12414 
   12415 int
   12416 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
   12417 					  ULONGEST offset, fileio_error *remote_errno)
   12418 {
   12419   struct remote_state *rs = get_remote_state ();
   12420   char *p = rs->buf.data ();
   12421   const char *attachment;
   12422   int left = get_remote_packet_size ();
   12423   int ret, attachment_len;
   12424   int read_len;
   12425 
   12426   remote_buffer_add_string (&p, &left, "vFile:pread:");
   12427 
   12428   remote_buffer_add_int (&p, &left, fd);
   12429   remote_buffer_add_string (&p, &left, ",");
   12430 
   12431   remote_buffer_add_int (&p, &left, len);
   12432   remote_buffer_add_string (&p, &left, ",");
   12433 
   12434   remote_buffer_add_int (&p, &left, offset);
   12435 
   12436   ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
   12437 				    remote_errno, &attachment,
   12438 				    &attachment_len);
   12439 
   12440   if (ret < 0)
   12441     return ret;
   12442 
   12443   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
   12444 				    read_buf, len);
   12445   if (read_len != ret)
   12446     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
   12447 
   12448   return ret;
   12449 }
   12450 
   12451 /* See declaration.h.  */
   12452 
   12453 int
   12454 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
   12455 			ULONGEST offset)
   12456 {
   12457   if (this->fd == fd
   12458       && this->offset <= offset
   12459       && offset < this->offset + this->bufsize)
   12460     {
   12461       ULONGEST max = this->offset + this->bufsize;
   12462 
   12463       if (offset + len > max)
   12464 	len = max - offset;
   12465 
   12466       memcpy (read_buf, this->buf + offset - this->offset, len);
   12467       return len;
   12468     }
   12469 
   12470   return 0;
   12471 }
   12472 
   12473 /* Implementation of to_fileio_pread.  */
   12474 
   12475 int
   12476 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
   12477 				    ULONGEST offset, fileio_error *remote_errno)
   12478 {
   12479   int ret;
   12480   struct remote_state *rs = get_remote_state ();
   12481   readahead_cache *cache = &rs->readahead_cache;
   12482 
   12483   ret = cache->pread (fd, read_buf, len, offset);
   12484   if (ret > 0)
   12485     {
   12486       cache->hit_count++;
   12487 
   12488       remote_debug_printf ("readahead cache hit %s",
   12489 			   pulongest (cache->hit_count));
   12490       return ret;
   12491     }
   12492 
   12493   cache->miss_count++;
   12494 
   12495   remote_debug_printf ("readahead cache miss %s",
   12496 		       pulongest (cache->miss_count));
   12497 
   12498   cache->fd = fd;
   12499   cache->offset = offset;
   12500   cache->bufsize = get_remote_packet_size ();
   12501   cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
   12502 
   12503   ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
   12504 				   cache->offset, remote_errno);
   12505   if (ret <= 0)
   12506     {
   12507       cache->invalidate_fd (fd);
   12508       return ret;
   12509     }
   12510 
   12511   cache->bufsize = ret;
   12512   return cache->pread (fd, read_buf, len, offset);
   12513 }
   12514 
   12515 int
   12516 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
   12517 			     ULONGEST offset, fileio_error *remote_errno)
   12518 {
   12519   return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
   12520 }
   12521 
   12522 /* Implementation of to_fileio_close.  */
   12523 
   12524 int
   12525 remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
   12526 {
   12527   struct remote_state *rs = get_remote_state ();
   12528   char *p = rs->buf.data ();
   12529   int left = get_remote_packet_size () - 1;
   12530 
   12531   rs->readahead_cache.invalidate_fd (fd);
   12532 
   12533   remote_buffer_add_string (&p, &left, "vFile:close:");
   12534 
   12535   remote_buffer_add_int (&p, &left, fd);
   12536 
   12537   return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
   12538 				     remote_errno, NULL, NULL);
   12539 }
   12540 
   12541 int
   12542 remote_target::fileio_close (int fd, fileio_error *remote_errno)
   12543 {
   12544   return remote_hostio_close (fd, remote_errno);
   12545 }
   12546 
   12547 /* Implementation of to_fileio_unlink.  */
   12548 
   12549 int
   12550 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
   12551 				     fileio_error *remote_errno)
   12552 {
   12553   struct remote_state *rs = get_remote_state ();
   12554   char *p = rs->buf.data ();
   12555   int left = get_remote_packet_size () - 1;
   12556 
   12557   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
   12558     return -1;
   12559 
   12560   remote_buffer_add_string (&p, &left, "vFile:unlink:");
   12561 
   12562   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
   12563 			   strlen (filename));
   12564 
   12565   return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
   12566 				     remote_errno, NULL, NULL);
   12567 }
   12568 
   12569 int
   12570 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
   12571 			      fileio_error *remote_errno)
   12572 {
   12573   return remote_hostio_unlink (inf, filename, remote_errno);
   12574 }
   12575 
   12576 /* Implementation of to_fileio_readlink.  */
   12577 
   12578 gdb::optional<std::string>
   12579 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
   12580 				fileio_error *remote_errno)
   12581 {
   12582   struct remote_state *rs = get_remote_state ();
   12583   char *p = rs->buf.data ();
   12584   const char *attachment;
   12585   int left = get_remote_packet_size ();
   12586   int len, attachment_len;
   12587   int read_len;
   12588 
   12589   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
   12590     return {};
   12591 
   12592   remote_buffer_add_string (&p, &left, "vFile:readlink:");
   12593 
   12594   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
   12595 			   strlen (filename));
   12596 
   12597   len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
   12598 				    remote_errno, &attachment,
   12599 				    &attachment_len);
   12600 
   12601   if (len < 0)
   12602     return {};
   12603 
   12604   std::string ret (len, '\0');
   12605 
   12606   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
   12607 				    (gdb_byte *) &ret[0], len);
   12608   if (read_len != len)
   12609     error (_("Readlink returned %d, but %d bytes."), len, read_len);
   12610 
   12611   return ret;
   12612 }
   12613 
   12614 /* Implementation of to_fileio_fstat.  */
   12615 
   12616 int
   12617 remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
   12618 {
   12619   struct remote_state *rs = get_remote_state ();
   12620   char *p = rs->buf.data ();
   12621   int left = get_remote_packet_size ();
   12622   int attachment_len, ret;
   12623   const char *attachment;
   12624   struct fio_stat fst;
   12625   int read_len;
   12626 
   12627   remote_buffer_add_string (&p, &left, "vFile:fstat:");
   12628 
   12629   remote_buffer_add_int (&p, &left, fd);
   12630 
   12631   ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
   12632 				    remote_errno, &attachment,
   12633 				    &attachment_len);
   12634   if (ret < 0)
   12635     {
   12636       if (*remote_errno != FILEIO_ENOSYS)
   12637 	return ret;
   12638 
   12639       /* Strictly we should return -1, ENOSYS here, but when
   12640 	 "set sysroot remote:" was implemented in August 2008
   12641 	 BFD's need for a stat function was sidestepped with
   12642 	 this hack.  This was not remedied until March 2015
   12643 	 so we retain the previous behavior to avoid breaking
   12644 	 compatibility.
   12645 
   12646 	 Note that the memset is a March 2015 addition; older
   12647 	 GDBs set st_size *and nothing else* so the structure
   12648 	 would have garbage in all other fields.  This might
   12649 	 break something but retaining the previous behavior
   12650 	 here would be just too wrong.  */
   12651 
   12652       memset (st, 0, sizeof (struct stat));
   12653       st->st_size = INT_MAX;
   12654       return 0;
   12655     }
   12656 
   12657   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
   12658 				    (gdb_byte *) &fst, sizeof (fst));
   12659 
   12660   if (read_len != ret)
   12661     error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
   12662 
   12663   if (read_len != sizeof (fst))
   12664     error (_("vFile:fstat returned %d bytes, but expecting %d."),
   12665 	   read_len, (int) sizeof (fst));
   12666 
   12667   remote_fileio_to_host_stat (&fst, st);
   12668 
   12669   return 0;
   12670 }
   12671 
   12672 /* Implementation of to_filesystem_is_local.  */
   12673 
   12674 bool
   12675 remote_target::filesystem_is_local ()
   12676 {
   12677   /* Valgrind GDB presents itself as a remote target but works
   12678      on the local filesystem: it does not implement remote get
   12679      and users are not expected to set a sysroot.  To handle
   12680      this case we treat the remote filesystem as local if the
   12681      sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
   12682      does not support vFile:open.  */
   12683   if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
   12684     {
   12685       enum packet_support ps = packet_support (PACKET_vFile_open);
   12686 
   12687       if (ps == PACKET_SUPPORT_UNKNOWN)
   12688 	{
   12689 	  int fd;
   12690 	  fileio_error remote_errno;
   12691 
   12692 	  /* Try opening a file to probe support.  The supplied
   12693 	     filename is irrelevant, we only care about whether
   12694 	     the stub recognizes the packet or not.  */
   12695 	  fd = remote_hostio_open (NULL, "just probing",
   12696 				   FILEIO_O_RDONLY, 0700, 0,
   12697 				   &remote_errno);
   12698 
   12699 	  if (fd >= 0)
   12700 	    remote_hostio_close (fd, &remote_errno);
   12701 
   12702 	  ps = packet_support (PACKET_vFile_open);
   12703 	}
   12704 
   12705       if (ps == PACKET_DISABLE)
   12706 	{
   12707 	  static int warning_issued = 0;
   12708 
   12709 	  if (!warning_issued)
   12710 	    {
   12711 	      warning (_("remote target does not support file"
   12712 			 " transfer, attempting to access files"
   12713 			 " from local filesystem."));
   12714 	      warning_issued = 1;
   12715 	    }
   12716 
   12717 	  return true;
   12718 	}
   12719     }
   12720 
   12721   return false;
   12722 }
   12723 
   12724 static char *
   12725 remote_hostio_error (fileio_error errnum)
   12726 {
   12727   int host_error = fileio_error_to_host (errnum);
   12728 
   12729   if (host_error == -1)
   12730     error (_("Unknown remote I/O error %d"), errnum);
   12731   else
   12732     error (_("Remote I/O error: %s"), safe_strerror (host_error));
   12733 }
   12734 
   12735 /* A RAII wrapper around a remote file descriptor.  */
   12736 
   12737 class scoped_remote_fd
   12738 {
   12739 public:
   12740   scoped_remote_fd (remote_target *remote, int fd)
   12741     : m_remote (remote), m_fd (fd)
   12742   {
   12743   }
   12744 
   12745   ~scoped_remote_fd ()
   12746   {
   12747     if (m_fd != -1)
   12748       {
   12749 	try
   12750 	  {
   12751 	    fileio_error remote_errno;
   12752 	    m_remote->remote_hostio_close (m_fd, &remote_errno);
   12753 	  }
   12754 	catch (...)
   12755 	  {
   12756 	    /* Swallow exception before it escapes the dtor.  If
   12757 	       something goes wrong, likely the connection is gone,
   12758 	       and there's nothing else that can be done.  */
   12759 	  }
   12760       }
   12761   }
   12762 
   12763   DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
   12764 
   12765   /* Release ownership of the file descriptor, and return it.  */
   12766   ATTRIBUTE_UNUSED_RESULT int release () noexcept
   12767   {
   12768     int fd = m_fd;
   12769     m_fd = -1;
   12770     return fd;
   12771   }
   12772 
   12773   /* Return the owned file descriptor.  */
   12774   int get () const noexcept
   12775   {
   12776     return m_fd;
   12777   }
   12778 
   12779 private:
   12780   /* The remote target.  */
   12781   remote_target *m_remote;
   12782 
   12783   /* The owned remote I/O file descriptor.  */
   12784   int m_fd;
   12785 };
   12786 
   12787 void
   12788 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
   12789 {
   12790   remote_target *remote = get_current_remote_target ();
   12791 
   12792   if (remote == nullptr)
   12793     error (_("command can only be used with remote target"));
   12794 
   12795   remote->remote_file_put (local_file, remote_file, from_tty);
   12796 }
   12797 
   12798 void
   12799 remote_target::remote_file_put (const char *local_file, const char *remote_file,
   12800 				int from_tty)
   12801 {
   12802   int retcode, bytes, io_size;
   12803   fileio_error remote_errno;
   12804   int bytes_in_buffer;
   12805   int saw_eof;
   12806   ULONGEST offset;
   12807 
   12808   gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
   12809   if (file == NULL)
   12810     perror_with_name (local_file);
   12811 
   12812   scoped_remote_fd fd
   12813     (this, remote_hostio_open (NULL,
   12814 			       remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
   12815 					     | FILEIO_O_TRUNC),
   12816 			       0700, 0, &remote_errno));
   12817   if (fd.get () == -1)
   12818     remote_hostio_error (remote_errno);
   12819 
   12820   /* Send up to this many bytes at once.  They won't all fit in the
   12821      remote packet limit, so we'll transfer slightly fewer.  */
   12822   io_size = get_remote_packet_size ();
   12823   gdb::byte_vector buffer (io_size);
   12824 
   12825   bytes_in_buffer = 0;
   12826   saw_eof = 0;
   12827   offset = 0;
   12828   while (bytes_in_buffer || !saw_eof)
   12829     {
   12830       if (!saw_eof)
   12831 	{
   12832 	  bytes = fread (buffer.data () + bytes_in_buffer, 1,
   12833 			 io_size - bytes_in_buffer,
   12834 			 file.get ());
   12835 	  if (bytes == 0)
   12836 	    {
   12837 	      if (ferror (file.get ()))
   12838 		error (_("Error reading %s."), local_file);
   12839 	      else
   12840 		{
   12841 		  /* EOF.  Unless there is something still in the
   12842 		     buffer from the last iteration, we are done.  */
   12843 		  saw_eof = 1;
   12844 		  if (bytes_in_buffer == 0)
   12845 		    break;
   12846 		}
   12847 	    }
   12848 	}
   12849       else
   12850 	bytes = 0;
   12851 
   12852       bytes += bytes_in_buffer;
   12853       bytes_in_buffer = 0;
   12854 
   12855       retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
   12856 				      offset, &remote_errno);
   12857 
   12858       if (retcode < 0)
   12859 	remote_hostio_error (remote_errno);
   12860       else if (retcode == 0)
   12861 	error (_("Remote write of %d bytes returned 0!"), bytes);
   12862       else if (retcode < bytes)
   12863 	{
   12864 	  /* Short write.  Save the rest of the read data for the next
   12865 	     write.  */
   12866 	  bytes_in_buffer = bytes - retcode;
   12867 	  memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
   12868 	}
   12869 
   12870       offset += retcode;
   12871     }
   12872 
   12873   if (remote_hostio_close (fd.release (), &remote_errno))
   12874     remote_hostio_error (remote_errno);
   12875 
   12876   if (from_tty)
   12877     gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
   12878 }
   12879 
   12880 void
   12881 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
   12882 {
   12883   remote_target *remote = get_current_remote_target ();
   12884 
   12885   if (remote == nullptr)
   12886     error (_("command can only be used with remote target"));
   12887 
   12888   remote->remote_file_get (remote_file, local_file, from_tty);
   12889 }
   12890 
   12891 void
   12892 remote_target::remote_file_get (const char *remote_file, const char *local_file,
   12893 				int from_tty)
   12894 {
   12895   fileio_error remote_errno;
   12896   int bytes, io_size;
   12897   ULONGEST offset;
   12898 
   12899   scoped_remote_fd fd
   12900     (this, remote_hostio_open (NULL,
   12901 			       remote_file, FILEIO_O_RDONLY, 0, 0,
   12902 			       &remote_errno));
   12903   if (fd.get () == -1)
   12904     remote_hostio_error (remote_errno);
   12905 
   12906   gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
   12907   if (file == NULL)
   12908     perror_with_name (local_file);
   12909 
   12910   /* Send up to this many bytes at once.  They won't all fit in the
   12911      remote packet limit, so we'll transfer slightly fewer.  */
   12912   io_size = get_remote_packet_size ();
   12913   gdb::byte_vector buffer (io_size);
   12914 
   12915   offset = 0;
   12916   while (1)
   12917     {
   12918       bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
   12919 				   &remote_errno);
   12920       if (bytes == 0)
   12921 	/* Success, but no bytes, means end-of-file.  */
   12922 	break;
   12923       if (bytes == -1)
   12924 	remote_hostio_error (remote_errno);
   12925 
   12926       offset += bytes;
   12927 
   12928       bytes = fwrite (buffer.data (), 1, bytes, file.get ());
   12929       if (bytes == 0)
   12930 	perror_with_name (local_file);
   12931     }
   12932 
   12933   if (remote_hostio_close (fd.release (), &remote_errno))
   12934     remote_hostio_error (remote_errno);
   12935 
   12936   if (from_tty)
   12937     gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
   12938 }
   12939 
   12940 void
   12941 remote_file_delete (const char *remote_file, int from_tty)
   12942 {
   12943   remote_target *remote = get_current_remote_target ();
   12944 
   12945   if (remote == nullptr)
   12946     error (_("command can only be used with remote target"));
   12947 
   12948   remote->remote_file_delete (remote_file, from_tty);
   12949 }
   12950 
   12951 void
   12952 remote_target::remote_file_delete (const char *remote_file, int from_tty)
   12953 {
   12954   int retcode;
   12955   fileio_error remote_errno;
   12956 
   12957   retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
   12958   if (retcode == -1)
   12959     remote_hostio_error (remote_errno);
   12960 
   12961   if (from_tty)
   12962     gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
   12963 }
   12964 
   12965 static void
   12966 remote_put_command (const char *args, int from_tty)
   12967 {
   12968   if (args == NULL)
   12969     error_no_arg (_("file to put"));
   12970 
   12971   gdb_argv argv (args);
   12972   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
   12973     error (_("Invalid parameters to remote put"));
   12974 
   12975   remote_file_put (argv[0], argv[1], from_tty);
   12976 }
   12977 
   12978 static void
   12979 remote_get_command (const char *args, int from_tty)
   12980 {
   12981   if (args == NULL)
   12982     error_no_arg (_("file to get"));
   12983 
   12984   gdb_argv argv (args);
   12985   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
   12986     error (_("Invalid parameters to remote get"));
   12987 
   12988   remote_file_get (argv[0], argv[1], from_tty);
   12989 }
   12990 
   12991 static void
   12992 remote_delete_command (const char *args, int from_tty)
   12993 {
   12994   if (args == NULL)
   12995     error_no_arg (_("file to delete"));
   12996 
   12997   gdb_argv argv (args);
   12998   if (argv[0] == NULL || argv[1] != NULL)
   12999     error (_("Invalid parameters to remote delete"));
   13000 
   13001   remote_file_delete (argv[0], from_tty);
   13002 }
   13003 
   13004 bool
   13005 remote_target::can_execute_reverse ()
   13006 {
   13007   if (packet_support (PACKET_bs) == PACKET_ENABLE
   13008       || packet_support (PACKET_bc) == PACKET_ENABLE)
   13009     return true;
   13010   else
   13011     return false;
   13012 }
   13013 
   13014 bool
   13015 remote_target::supports_non_stop ()
   13016 {
   13017   return true;
   13018 }
   13019 
   13020 bool
   13021 remote_target::supports_disable_randomization ()
   13022 {
   13023   /* Only supported in extended mode.  */
   13024   return false;
   13025 }
   13026 
   13027 bool
   13028 remote_target::supports_multi_process ()
   13029 {
   13030   struct remote_state *rs = get_remote_state ();
   13031 
   13032   return remote_multi_process_p (rs);
   13033 }
   13034 
   13035 static int
   13036 remote_supports_cond_tracepoints ()
   13037 {
   13038   return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
   13039 }
   13040 
   13041 bool
   13042 remote_target::supports_evaluation_of_breakpoint_conditions ()
   13043 {
   13044   return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
   13045 }
   13046 
   13047 static int
   13048 remote_supports_fast_tracepoints ()
   13049 {
   13050   return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
   13051 }
   13052 
   13053 static int
   13054 remote_supports_static_tracepoints ()
   13055 {
   13056   return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
   13057 }
   13058 
   13059 static int
   13060 remote_supports_install_in_trace ()
   13061 {
   13062   return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
   13063 }
   13064 
   13065 bool
   13066 remote_target::supports_enable_disable_tracepoint ()
   13067 {
   13068   return (packet_support (PACKET_EnableDisableTracepoints_feature)
   13069 	  == PACKET_ENABLE);
   13070 }
   13071 
   13072 bool
   13073 remote_target::supports_string_tracing ()
   13074 {
   13075   return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
   13076 }
   13077 
   13078 bool
   13079 remote_target::can_run_breakpoint_commands ()
   13080 {
   13081   return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
   13082 }
   13083 
   13084 void
   13085 remote_target::trace_init ()
   13086 {
   13087   struct remote_state *rs = get_remote_state ();
   13088 
   13089   putpkt ("QTinit");
   13090   remote_get_noisy_reply ();
   13091   if (strcmp (rs->buf.data (), "OK") != 0)
   13092     error (_("Target does not support this command."));
   13093 }
   13094 
   13095 /* Recursive routine to walk through command list including loops, and
   13096    download packets for each command.  */
   13097 
   13098 void
   13099 remote_target::remote_download_command_source (int num, ULONGEST addr,
   13100 					       struct command_line *cmds)
   13101 {
   13102   struct remote_state *rs = get_remote_state ();
   13103   struct command_line *cmd;
   13104 
   13105   for (cmd = cmds; cmd; cmd = cmd->next)
   13106     {
   13107       QUIT;	/* Allow user to bail out with ^C.  */
   13108       strcpy (rs->buf.data (), "QTDPsrc:");
   13109       encode_source_string (num, addr, "cmd", cmd->line,
   13110 			    rs->buf.data () + strlen (rs->buf.data ()),
   13111 			    rs->buf.size () - strlen (rs->buf.data ()));
   13112       putpkt (rs->buf);
   13113       remote_get_noisy_reply ();
   13114       if (strcmp (rs->buf.data (), "OK"))
   13115 	warning (_("Target does not support source download."));
   13116 
   13117       if (cmd->control_type == while_control
   13118 	  || cmd->control_type == while_stepping_control)
   13119 	{
   13120 	  remote_download_command_source (num, addr, cmd->body_list_0.get ());
   13121 
   13122 	  QUIT;	/* Allow user to bail out with ^C.  */
   13123 	  strcpy (rs->buf.data (), "QTDPsrc:");
   13124 	  encode_source_string (num, addr, "cmd", "end",
   13125 				rs->buf.data () + strlen (rs->buf.data ()),
   13126 				rs->buf.size () - strlen (rs->buf.data ()));
   13127 	  putpkt (rs->buf);
   13128 	  remote_get_noisy_reply ();
   13129 	  if (strcmp (rs->buf.data (), "OK"))
   13130 	    warning (_("Target does not support source download."));
   13131 	}
   13132     }
   13133 }
   13134 
   13135 void
   13136 remote_target::download_tracepoint (struct bp_location *loc)
   13137 {
   13138   CORE_ADDR tpaddr;
   13139   char addrbuf[40];
   13140   std::vector<std::string> tdp_actions;
   13141   std::vector<std::string> stepping_actions;
   13142   char *pkt;
   13143   struct breakpoint *b = loc->owner;
   13144   struct tracepoint *t = (struct tracepoint *) b;
   13145   struct remote_state *rs = get_remote_state ();
   13146   int ret;
   13147   const char *err_msg = _("Tracepoint packet too large for target.");
   13148   size_t size_left;
   13149 
   13150   /* We use a buffer other than rs->buf because we'll build strings
   13151      across multiple statements, and other statements in between could
   13152      modify rs->buf.  */
   13153   gdb::char_vector buf (get_remote_packet_size ());
   13154 
   13155   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
   13156 
   13157   tpaddr = loc->address;
   13158   strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
   13159   ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
   13160 		  b->number, addrbuf, /* address */
   13161 		  (b->enable_state == bp_enabled ? 'E' : 'D'),
   13162 		  t->step_count, t->pass_count);
   13163 
   13164   if (ret < 0 || ret >= buf.size ())
   13165     error ("%s", err_msg);
   13166 
   13167   /* Fast tracepoints are mostly handled by the target, but we can
   13168      tell the target how big of an instruction block should be moved
   13169      around.  */
   13170   if (b->type == bp_fast_tracepoint)
   13171     {
   13172       /* Only test for support at download time; we may not know
   13173 	 target capabilities at definition time.  */
   13174       if (remote_supports_fast_tracepoints ())
   13175 	{
   13176 	  if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
   13177 						NULL))
   13178 	    {
   13179 	      size_left = buf.size () - strlen (buf.data ());
   13180 	      ret = snprintf (buf.data () + strlen (buf.data ()),
   13181 			      size_left, ":F%x",
   13182 			      gdb_insn_length (loc->gdbarch, tpaddr));
   13183 
   13184 	      if (ret < 0 || ret >= size_left)
   13185 		error ("%s", err_msg);
   13186 	    }
   13187 	  else
   13188 	    /* If it passed validation at definition but fails now,
   13189 	       something is very wrong.  */
   13190 	    internal_error (_("Fast tracepoint not valid during download"));
   13191 	}
   13192       else
   13193 	/* Fast tracepoints are functionally identical to regular
   13194 	   tracepoints, so don't take lack of support as a reason to
   13195 	   give up on the trace run.  */
   13196 	warning (_("Target does not support fast tracepoints, "
   13197 		   "downloading %d as regular tracepoint"), b->number);
   13198     }
   13199   else if (b->type == bp_static_tracepoint
   13200 	   || b->type == bp_static_marker_tracepoint)
   13201     {
   13202       /* Only test for support at download time; we may not know
   13203 	 target capabilities at definition time.  */
   13204       if (remote_supports_static_tracepoints ())
   13205 	{
   13206 	  struct static_tracepoint_marker marker;
   13207 
   13208 	  if (target_static_tracepoint_marker_at (tpaddr, &marker))
   13209 	    {
   13210 	      size_left = buf.size () - strlen (buf.data ());
   13211 	      ret = snprintf (buf.data () + strlen (buf.data ()),
   13212 			      size_left, ":S");
   13213 
   13214 	      if (ret < 0 || ret >= size_left)
   13215 		error ("%s", err_msg);
   13216 	    }
   13217 	  else
   13218 	    error (_("Static tracepoint not valid during download"));
   13219 	}
   13220       else
   13221 	/* Fast tracepoints are functionally identical to regular
   13222 	   tracepoints, so don't take lack of support as a reason
   13223 	   to give up on the trace run.  */
   13224 	error (_("Target does not support static tracepoints"));
   13225     }
   13226   /* If the tracepoint has a conditional, make it into an agent
   13227      expression and append to the definition.  */
   13228   if (loc->cond)
   13229     {
   13230       /* Only test support at download time, we may not know target
   13231 	 capabilities at definition time.  */
   13232       if (remote_supports_cond_tracepoints ())
   13233 	{
   13234 	  agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
   13235 						   loc->cond.get ());
   13236 
   13237 	  size_left = buf.size () - strlen (buf.data ());
   13238 
   13239 	  ret = snprintf (buf.data () + strlen (buf.data ()),
   13240 			  size_left, ":X%x,", aexpr->len);
   13241 
   13242 	  if (ret < 0 || ret >= size_left)
   13243 	    error ("%s", err_msg);
   13244 
   13245 	  size_left = buf.size () - strlen (buf.data ());
   13246 
   13247 	  /* Two bytes to encode each aexpr byte, plus the terminating
   13248 	     null byte.  */
   13249 	  if (aexpr->len * 2 + 1 > size_left)
   13250 	    error ("%s", err_msg);
   13251 
   13252 	  pkt = buf.data () + strlen (buf.data ());
   13253 
   13254 	  for (int ndx = 0; ndx < aexpr->len; ++ndx)
   13255 	    pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
   13256 	  *pkt = '\0';
   13257 	}
   13258       else
   13259 	warning (_("Target does not support conditional tracepoints, "
   13260 		   "ignoring tp %d cond"), b->number);
   13261     }
   13262 
   13263   if (b->commands || !default_collect.empty ())
   13264     {
   13265       size_left = buf.size () - strlen (buf.data ());
   13266 
   13267       ret = snprintf (buf.data () + strlen (buf.data ()),
   13268 		      size_left, "-");
   13269 
   13270       if (ret < 0 || ret >= size_left)
   13271 	error ("%s", err_msg);
   13272     }
   13273 
   13274   putpkt (buf.data ());
   13275   remote_get_noisy_reply ();
   13276   if (strcmp (rs->buf.data (), "OK"))
   13277     error (_("Target does not support tracepoints."));
   13278 
   13279   /* do_single_steps (t); */
   13280   for (auto action_it = tdp_actions.begin ();
   13281        action_it != tdp_actions.end (); action_it++)
   13282     {
   13283       QUIT;	/* Allow user to bail out with ^C.  */
   13284 
   13285       bool has_more = ((action_it + 1) != tdp_actions.end ()
   13286 		       || !stepping_actions.empty ());
   13287 
   13288       ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
   13289 		      b->number, addrbuf, /* address */
   13290 		      action_it->c_str (),
   13291 		      has_more ? '-' : 0);
   13292 
   13293       if (ret < 0 || ret >= buf.size ())
   13294 	error ("%s", err_msg);
   13295 
   13296       putpkt (buf.data ());
   13297       remote_get_noisy_reply ();
   13298       if (strcmp (rs->buf.data (), "OK"))
   13299 	error (_("Error on target while setting tracepoints."));
   13300     }
   13301 
   13302   for (auto action_it = stepping_actions.begin ();
   13303        action_it != stepping_actions.end (); action_it++)
   13304     {
   13305       QUIT;	/* Allow user to bail out with ^C.  */
   13306 
   13307       bool is_first = action_it == stepping_actions.begin ();
   13308       bool has_more = (action_it + 1) != stepping_actions.end ();
   13309 
   13310       ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
   13311 		      b->number, addrbuf, /* address */
   13312 		      is_first ? "S" : "",
   13313 		      action_it->c_str (),
   13314 		      has_more ? "-" : "");
   13315 
   13316       if (ret < 0 || ret >= buf.size ())
   13317 	error ("%s", err_msg);
   13318 
   13319       putpkt (buf.data ());
   13320       remote_get_noisy_reply ();
   13321       if (strcmp (rs->buf.data (), "OK"))
   13322 	error (_("Error on target while setting tracepoints."));
   13323     }
   13324 
   13325   if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
   13326     {
   13327       if (b->locspec != nullptr)
   13328 	{
   13329 	  ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
   13330 
   13331 	  if (ret < 0 || ret >= buf.size ())
   13332 	    error ("%s", err_msg);
   13333 
   13334 	  const char *str = b->locspec->to_string ();
   13335 	  encode_source_string (b->number, loc->address, "at", str,
   13336 				buf.data () + strlen (buf.data ()),
   13337 				buf.size () - strlen (buf.data ()));
   13338 	  putpkt (buf.data ());
   13339 	  remote_get_noisy_reply ();
   13340 	  if (strcmp (rs->buf.data (), "OK"))
   13341 	    warning (_("Target does not support source download."));
   13342 	}
   13343       if (b->cond_string)
   13344 	{
   13345 	  ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
   13346 
   13347 	  if (ret < 0 || ret >= buf.size ())
   13348 	    error ("%s", err_msg);
   13349 
   13350 	  encode_source_string (b->number, loc->address,
   13351 				"cond", b->cond_string.get (),
   13352 				buf.data () + strlen (buf.data ()),
   13353 				buf.size () - strlen (buf.data ()));
   13354 	  putpkt (buf.data ());
   13355 	  remote_get_noisy_reply ();
   13356 	  if (strcmp (rs->buf.data (), "OK"))
   13357 	    warning (_("Target does not support source download."));
   13358 	}
   13359       remote_download_command_source (b->number, loc->address,
   13360 				      breakpoint_commands (b));
   13361     }
   13362 }
   13363 
   13364 bool
   13365 remote_target::can_download_tracepoint ()
   13366 {
   13367   struct remote_state *rs = get_remote_state ();
   13368   struct trace_status *ts;
   13369   int status;
   13370 
   13371   /* Don't try to install tracepoints until we've relocated our
   13372      symbols, and fetched and merged the target's tracepoint list with
   13373      ours.  */
   13374   if (rs->starting_up)
   13375     return false;
   13376 
   13377   ts = current_trace_status ();
   13378   status = get_trace_status (ts);
   13379 
   13380   if (status == -1 || !ts->running_known || !ts->running)
   13381     return false;
   13382 
   13383   /* If we are in a tracing experiment, but remote stub doesn't support
   13384      installing tracepoint in trace, we have to return.  */
   13385   if (!remote_supports_install_in_trace ())
   13386     return false;
   13387 
   13388   return true;
   13389 }
   13390 
   13391 
   13392 void
   13393 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
   13394 {
   13395   struct remote_state *rs = get_remote_state ();
   13396   char *p;
   13397 
   13398   xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
   13399 	     tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
   13400 	     tsv.builtin);
   13401   p = rs->buf.data () + strlen (rs->buf.data ());
   13402   if ((p - rs->buf.data ()) + tsv.name.length () * 2
   13403       >= get_remote_packet_size ())
   13404     error (_("Trace state variable name too long for tsv definition packet"));
   13405   p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
   13406   *p++ = '\0';
   13407   putpkt (rs->buf);
   13408   remote_get_noisy_reply ();
   13409   if (rs->buf[0] == '\0')
   13410     error (_("Target does not support this command."));
   13411   if (strcmp (rs->buf.data (), "OK") != 0)
   13412     error (_("Error on target while downloading trace state variable."));
   13413 }
   13414 
   13415 void
   13416 remote_target::enable_tracepoint (struct bp_location *location)
   13417 {
   13418   struct remote_state *rs = get_remote_state ();
   13419 
   13420   xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
   13421 	     location->owner->number,
   13422 	     phex (location->address, sizeof (CORE_ADDR)));
   13423   putpkt (rs->buf);
   13424   remote_get_noisy_reply ();
   13425   if (rs->buf[0] == '\0')
   13426     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
   13427   if (strcmp (rs->buf.data (), "OK") != 0)
   13428     error (_("Error on target while enabling tracepoint."));
   13429 }
   13430 
   13431 void
   13432 remote_target::disable_tracepoint (struct bp_location *location)
   13433 {
   13434   struct remote_state *rs = get_remote_state ();
   13435 
   13436   xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
   13437 	     location->owner->number,
   13438 	     phex (location->address, sizeof (CORE_ADDR)));
   13439   putpkt (rs->buf);
   13440   remote_get_noisy_reply ();
   13441   if (rs->buf[0] == '\0')
   13442     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
   13443   if (strcmp (rs->buf.data (), "OK") != 0)
   13444     error (_("Error on target while disabling tracepoint."));
   13445 }
   13446 
   13447 void
   13448 remote_target::trace_set_readonly_regions ()
   13449 {
   13450   asection *s;
   13451   bfd_size_type size;
   13452   bfd_vma vma;
   13453   int anysecs = 0;
   13454   int offset = 0;
   13455   bfd *abfd = current_program_space->exec_bfd ();
   13456 
   13457   if (!abfd)
   13458     return;			/* No information to give.  */
   13459 
   13460   struct remote_state *rs = get_remote_state ();
   13461 
   13462   strcpy (rs->buf.data (), "QTro");
   13463   offset = strlen (rs->buf.data ());
   13464   for (s = abfd->sections; s; s = s->next)
   13465     {
   13466       char tmp1[40], tmp2[40];
   13467       int sec_length;
   13468 
   13469       if ((s->flags & SEC_LOAD) == 0
   13470 	  /* || (s->flags & SEC_CODE) == 0 */
   13471 	  || (s->flags & SEC_READONLY) == 0)
   13472 	continue;
   13473 
   13474       anysecs = 1;
   13475       vma = bfd_section_vma (s);
   13476       size = bfd_section_size (s);
   13477       bfd_sprintf_vma (abfd, tmp1, vma);
   13478       bfd_sprintf_vma (abfd, tmp2, vma + size);
   13479       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
   13480       if (offset + sec_length + 1 > rs->buf.size ())
   13481 	{
   13482 	  if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
   13483 	    warning (_("\
   13484 Too many sections for read-only sections definition packet."));
   13485 	  break;
   13486 	}
   13487       xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
   13488 		 tmp1, tmp2);
   13489       offset += sec_length;
   13490     }
   13491   if (anysecs)
   13492     {
   13493       putpkt (rs->buf);
   13494       getpkt (&rs->buf, 0);
   13495     }
   13496 }
   13497 
   13498 void
   13499 remote_target::trace_start ()
   13500 {
   13501   struct remote_state *rs = get_remote_state ();
   13502 
   13503   putpkt ("QTStart");
   13504   remote_get_noisy_reply ();
   13505   if (rs->buf[0] == '\0')
   13506     error (_("Target does not support this command."));
   13507   if (strcmp (rs->buf.data (), "OK") != 0)
   13508     error (_("Bogus reply from target: %s"), rs->buf.data ());
   13509 }
   13510 
   13511 int
   13512 remote_target::get_trace_status (struct trace_status *ts)
   13513 {
   13514   /* Initialize it just to avoid a GCC false warning.  */
   13515   char *p = NULL;
   13516   enum packet_result result;
   13517   struct remote_state *rs = get_remote_state ();
   13518 
   13519   if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
   13520     return -1;
   13521 
   13522   /* FIXME we need to get register block size some other way.  */
   13523   trace_regblock_size
   13524     = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
   13525 
   13526   putpkt ("qTStatus");
   13527 
   13528   try
   13529     {
   13530       p = remote_get_noisy_reply ();
   13531     }
   13532   catch (const gdb_exception_error &ex)
   13533     {
   13534       if (ex.error != TARGET_CLOSE_ERROR)
   13535 	{
   13536 	  exception_fprintf (gdb_stderr, ex, "qTStatus: ");
   13537 	  return -1;
   13538 	}
   13539       throw;
   13540     }
   13541 
   13542   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
   13543 
   13544   /* If the remote target doesn't do tracing, flag it.  */
   13545   if (result == PACKET_UNKNOWN)
   13546     return -1;
   13547 
   13548   /* We're working with a live target.  */
   13549   ts->filename = NULL;
   13550 
   13551   if (*p++ != 'T')
   13552     error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
   13553 
   13554   /* Function 'parse_trace_status' sets default value of each field of
   13555      'ts' at first, so we don't have to do it here.  */
   13556   parse_trace_status (p, ts);
   13557 
   13558   return ts->running;
   13559 }
   13560 
   13561 void
   13562 remote_target::get_tracepoint_status (struct breakpoint *bp,
   13563 				      struct uploaded_tp *utp)
   13564 {
   13565   struct remote_state *rs = get_remote_state ();
   13566   char *reply;
   13567   struct tracepoint *tp = (struct tracepoint *) bp;
   13568   size_t size = get_remote_packet_size ();
   13569 
   13570   if (tp)
   13571     {
   13572       tp->hit_count = 0;
   13573       tp->traceframe_usage = 0;
   13574       for (bp_location *loc : tp->locations ())
   13575 	{
   13576 	  /* If the tracepoint was never downloaded, don't go asking for
   13577 	     any status.  */
   13578 	  if (tp->number_on_target == 0)
   13579 	    continue;
   13580 	  xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
   13581 		     phex_nz (loc->address, 0));
   13582 	  putpkt (rs->buf);
   13583 	  reply = remote_get_noisy_reply ();
   13584 	  if (reply && *reply)
   13585 	    {
   13586 	      if (*reply == 'V')
   13587 		parse_tracepoint_status (reply + 1, bp, utp);
   13588 	    }
   13589 	}
   13590     }
   13591   else if (utp)
   13592     {
   13593       utp->hit_count = 0;
   13594       utp->traceframe_usage = 0;
   13595       xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
   13596 		 phex_nz (utp->addr, 0));
   13597       putpkt (rs->buf);
   13598       reply = remote_get_noisy_reply ();
   13599       if (reply && *reply)
   13600 	{
   13601 	  if (*reply == 'V')
   13602 	    parse_tracepoint_status (reply + 1, bp, utp);
   13603 	}
   13604     }
   13605 }
   13606 
   13607 void
   13608 remote_target::trace_stop ()
   13609 {
   13610   struct remote_state *rs = get_remote_state ();
   13611 
   13612   putpkt ("QTStop");
   13613   remote_get_noisy_reply ();
   13614   if (rs->buf[0] == '\0')
   13615     error (_("Target does not support this command."));
   13616   if (strcmp (rs->buf.data (), "OK") != 0)
   13617     error (_("Bogus reply from target: %s"), rs->buf.data ());
   13618 }
   13619 
   13620 int
   13621 remote_target::trace_find (enum trace_find_type type, int num,
   13622 			   CORE_ADDR addr1, CORE_ADDR addr2,
   13623 			   int *tpp)
   13624 {
   13625   struct remote_state *rs = get_remote_state ();
   13626   char *endbuf = rs->buf.data () + get_remote_packet_size ();
   13627   char *p, *reply;
   13628   int target_frameno = -1, target_tracept = -1;
   13629 
   13630   /* Lookups other than by absolute frame number depend on the current
   13631      trace selected, so make sure it is correct on the remote end
   13632      first.  */
   13633   if (type != tfind_number)
   13634     set_remote_traceframe ();
   13635 
   13636   p = rs->buf.data ();
   13637   strcpy (p, "QTFrame:");
   13638   p = strchr (p, '\0');
   13639   switch (type)
   13640     {
   13641     case tfind_number:
   13642       xsnprintf (p, endbuf - p, "%x", num);
   13643       break;
   13644     case tfind_pc:
   13645       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
   13646       break;
   13647     case tfind_tp:
   13648       xsnprintf (p, endbuf - p, "tdp:%x", num);
   13649       break;
   13650     case tfind_range:
   13651       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
   13652 		 phex_nz (addr2, 0));
   13653       break;
   13654     case tfind_outside:
   13655       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
   13656 		 phex_nz (addr2, 0));
   13657       break;
   13658     default:
   13659       error (_("Unknown trace find type %d"), type);
   13660     }
   13661 
   13662   putpkt (rs->buf);
   13663   reply = remote_get_noisy_reply ();
   13664   if (*reply == '\0')
   13665     error (_("Target does not support this command."));
   13666 
   13667   while (reply && *reply)
   13668     switch (*reply)
   13669       {
   13670       case 'F':
   13671 	p = ++reply;
   13672 	target_frameno = (int) strtol (p, &reply, 16);
   13673 	if (reply == p)
   13674 	  error (_("Unable to parse trace frame number"));
   13675 	/* Don't update our remote traceframe number cache on failure
   13676 	   to select a remote traceframe.  */
   13677 	if (target_frameno == -1)
   13678 	  return -1;
   13679 	break;
   13680       case 'T':
   13681 	p = ++reply;
   13682 	target_tracept = (int) strtol (p, &reply, 16);
   13683 	if (reply == p)
   13684 	  error (_("Unable to parse tracepoint number"));
   13685 	break;
   13686       case 'O':		/* "OK"? */
   13687 	if (reply[1] == 'K' && reply[2] == '\0')
   13688 	  reply += 2;
   13689 	else
   13690 	  error (_("Bogus reply from target: %s"), reply);
   13691 	break;
   13692       default:
   13693 	error (_("Bogus reply from target: %s"), reply);
   13694       }
   13695   if (tpp)
   13696     *tpp = target_tracept;
   13697 
   13698   rs->remote_traceframe_number = target_frameno;
   13699   return target_frameno;
   13700 }
   13701 
   13702 bool
   13703 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
   13704 {
   13705   struct remote_state *rs = get_remote_state ();
   13706   char *reply;
   13707   ULONGEST uval;
   13708 
   13709   set_remote_traceframe ();
   13710 
   13711   xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
   13712   putpkt (rs->buf);
   13713   reply = remote_get_noisy_reply ();
   13714   if (reply && *reply)
   13715     {
   13716       if (*reply == 'V')
   13717 	{
   13718 	  unpack_varlen_hex (reply + 1, &uval);
   13719 	  *val = (LONGEST) uval;
   13720 	  return true;
   13721 	}
   13722     }
   13723   return false;
   13724 }
   13725 
   13726 int
   13727 remote_target::save_trace_data (const char *filename)
   13728 {
   13729   struct remote_state *rs = get_remote_state ();
   13730   char *p, *reply;
   13731 
   13732   p = rs->buf.data ();
   13733   strcpy (p, "QTSave:");
   13734   p += strlen (p);
   13735   if ((p - rs->buf.data ()) + strlen (filename) * 2
   13736       >= get_remote_packet_size ())
   13737     error (_("Remote file name too long for trace save packet"));
   13738   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
   13739   *p++ = '\0';
   13740   putpkt (rs->buf);
   13741   reply = remote_get_noisy_reply ();
   13742   if (*reply == '\0')
   13743     error (_("Target does not support this command."));
   13744   if (strcmp (reply, "OK") != 0)
   13745     error (_("Bogus reply from target: %s"), reply);
   13746   return 0;
   13747 }
   13748 
   13749 /* This is basically a memory transfer, but needs to be its own packet
   13750    because we don't know how the target actually organizes its trace
   13751    memory, plus we want to be able to ask for as much as possible, but
   13752    not be unhappy if we don't get as much as we ask for.  */
   13753 
   13754 LONGEST
   13755 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
   13756 {
   13757   struct remote_state *rs = get_remote_state ();
   13758   char *reply;
   13759   char *p;
   13760   int rslt;
   13761 
   13762   p = rs->buf.data ();
   13763   strcpy (p, "qTBuffer:");
   13764   p += strlen (p);
   13765   p += hexnumstr (p, offset);
   13766   *p++ = ',';
   13767   p += hexnumstr (p, len);
   13768   *p++ = '\0';
   13769 
   13770   putpkt (rs->buf);
   13771   reply = remote_get_noisy_reply ();
   13772   if (reply && *reply)
   13773     {
   13774       /* 'l' by itself means we're at the end of the buffer and
   13775 	 there is nothing more to get.  */
   13776       if (*reply == 'l')
   13777 	return 0;
   13778 
   13779       /* Convert the reply into binary.  Limit the number of bytes to
   13780 	 convert according to our passed-in buffer size, rather than
   13781 	 what was returned in the packet; if the target is
   13782 	 unexpectedly generous and gives us a bigger reply than we
   13783 	 asked for, we don't want to crash.  */
   13784       rslt = hex2bin (reply, buf, len);
   13785       return rslt;
   13786     }
   13787 
   13788   /* Something went wrong, flag as an error.  */
   13789   return -1;
   13790 }
   13791 
   13792 void
   13793 remote_target::set_disconnected_tracing (int val)
   13794 {
   13795   struct remote_state *rs = get_remote_state ();
   13796 
   13797   if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
   13798     {
   13799       char *reply;
   13800 
   13801       xsnprintf (rs->buf.data (), get_remote_packet_size (),
   13802 		 "QTDisconnected:%x", val);
   13803       putpkt (rs->buf);
   13804       reply = remote_get_noisy_reply ();
   13805       if (*reply == '\0')
   13806 	error (_("Target does not support this command."));
   13807       if (strcmp (reply, "OK") != 0)
   13808 	error (_("Bogus reply from target: %s"), reply);
   13809     }
   13810   else if (val)
   13811     warning (_("Target does not support disconnected tracing."));
   13812 }
   13813 
   13814 int
   13815 remote_target::core_of_thread (ptid_t ptid)
   13816 {
   13817   thread_info *info = find_thread_ptid (this, ptid);
   13818 
   13819   if (info != NULL && info->priv != NULL)
   13820     return get_remote_thread_info (info)->core;
   13821 
   13822   return -1;
   13823 }
   13824 
   13825 void
   13826 remote_target::set_circular_trace_buffer (int val)
   13827 {
   13828   struct remote_state *rs = get_remote_state ();
   13829   char *reply;
   13830 
   13831   xsnprintf (rs->buf.data (), get_remote_packet_size (),
   13832 	     "QTBuffer:circular:%x", val);
   13833   putpkt (rs->buf);
   13834   reply = remote_get_noisy_reply ();
   13835   if (*reply == '\0')
   13836     error (_("Target does not support this command."));
   13837   if (strcmp (reply, "OK") != 0)
   13838     error (_("Bogus reply from target: %s"), reply);
   13839 }
   13840 
   13841 traceframe_info_up
   13842 remote_target::traceframe_info ()
   13843 {
   13844   gdb::optional<gdb::char_vector> text
   13845     = target_read_stralloc (current_inferior ()->top_target (),
   13846 			    TARGET_OBJECT_TRACEFRAME_INFO,
   13847 			    NULL);
   13848   if (text)
   13849     return parse_traceframe_info (text->data ());
   13850 
   13851   return NULL;
   13852 }
   13853 
   13854 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
   13855    instruction on which a fast tracepoint may be placed.  Returns -1
   13856    if the packet is not supported, and 0 if the minimum instruction
   13857    length is unknown.  */
   13858 
   13859 int
   13860 remote_target::get_min_fast_tracepoint_insn_len ()
   13861 {
   13862   struct remote_state *rs = get_remote_state ();
   13863   char *reply;
   13864 
   13865   /* If we're not debugging a process yet, the IPA can't be
   13866      loaded.  */
   13867   if (!target_has_execution ())
   13868     return 0;
   13869 
   13870   /* Make sure the remote is pointing at the right process.  */
   13871   set_general_process ();
   13872 
   13873   xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
   13874   putpkt (rs->buf);
   13875   reply = remote_get_noisy_reply ();
   13876   if (*reply == '\0')
   13877     return -1;
   13878   else
   13879     {
   13880       ULONGEST min_insn_len;
   13881 
   13882       unpack_varlen_hex (reply, &min_insn_len);
   13883 
   13884       return (int) min_insn_len;
   13885     }
   13886 }
   13887 
   13888 void
   13889 remote_target::set_trace_buffer_size (LONGEST val)
   13890 {
   13891   if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
   13892     {
   13893       struct remote_state *rs = get_remote_state ();
   13894       char *buf = rs->buf.data ();
   13895       char *endbuf = buf + get_remote_packet_size ();
   13896       enum packet_result result;
   13897 
   13898       gdb_assert (val >= 0 || val == -1);
   13899       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
   13900       /* Send -1 as literal "-1" to avoid host size dependency.  */
   13901       if (val < 0)
   13902 	{
   13903 	  *buf++ = '-';
   13904 	  buf += hexnumstr (buf, (ULONGEST) -val);
   13905 	}
   13906       else
   13907 	buf += hexnumstr (buf, (ULONGEST) val);
   13908 
   13909       putpkt (rs->buf);
   13910       remote_get_noisy_reply ();
   13911       result = packet_ok (rs->buf,
   13912 		  &remote_protocol_packets[PACKET_QTBuffer_size]);
   13913 
   13914       if (result != PACKET_OK)
   13915 	warning (_("Bogus reply from target: %s"), rs->buf.data ());
   13916     }
   13917 }
   13918 
   13919 bool
   13920 remote_target::set_trace_notes (const char *user, const char *notes,
   13921 				const char *stop_notes)
   13922 {
   13923   struct remote_state *rs = get_remote_state ();
   13924   char *reply;
   13925   char *buf = rs->buf.data ();
   13926   char *endbuf = buf + get_remote_packet_size ();
   13927   int nbytes;
   13928 
   13929   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
   13930   if (user)
   13931     {
   13932       buf += xsnprintf (buf, endbuf - buf, "user:");
   13933       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
   13934       buf += 2 * nbytes;
   13935       *buf++ = ';';
   13936     }
   13937   if (notes)
   13938     {
   13939       buf += xsnprintf (buf, endbuf - buf, "notes:");
   13940       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
   13941       buf += 2 * nbytes;
   13942       *buf++ = ';';
   13943     }
   13944   if (stop_notes)
   13945     {
   13946       buf += xsnprintf (buf, endbuf - buf, "tstop:");
   13947       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
   13948       buf += 2 * nbytes;
   13949       *buf++ = ';';
   13950     }
   13951   /* Ensure the buffer is terminated.  */
   13952   *buf = '\0';
   13953 
   13954   putpkt (rs->buf);
   13955   reply = remote_get_noisy_reply ();
   13956   if (*reply == '\0')
   13957     return false;
   13958 
   13959   if (strcmp (reply, "OK") != 0)
   13960     error (_("Bogus reply from target: %s"), reply);
   13961 
   13962   return true;
   13963 }
   13964 
   13965 bool
   13966 remote_target::use_agent (bool use)
   13967 {
   13968   if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
   13969     {
   13970       struct remote_state *rs = get_remote_state ();
   13971 
   13972       /* If the stub supports QAgent.  */
   13973       xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
   13974       putpkt (rs->buf);
   13975       getpkt (&rs->buf, 0);
   13976 
   13977       if (strcmp (rs->buf.data (), "OK") == 0)
   13978 	{
   13979 	  ::use_agent = use;
   13980 	  return true;
   13981 	}
   13982     }
   13983 
   13984   return false;
   13985 }
   13986 
   13987 bool
   13988 remote_target::can_use_agent ()
   13989 {
   13990   return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
   13991 }
   13992 
   13993 struct btrace_target_info
   13994 {
   13995   /* The ptid of the traced thread.  */
   13996   ptid_t ptid;
   13997 
   13998   /* The obtained branch trace configuration.  */
   13999   struct btrace_config conf;
   14000 };
   14001 
   14002 /* Reset our idea of our target's btrace configuration.  */
   14003 
   14004 static void
   14005 remote_btrace_reset (remote_state *rs)
   14006 {
   14007   memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
   14008 }
   14009 
   14010 /* Synchronize the configuration with the target.  */
   14011 
   14012 void
   14013 remote_target::btrace_sync_conf (const btrace_config *conf)
   14014 {
   14015   struct packet_config *packet;
   14016   struct remote_state *rs;
   14017   char *buf, *pos, *endbuf;
   14018 
   14019   rs = get_remote_state ();
   14020   buf = rs->buf.data ();
   14021   endbuf = buf + get_remote_packet_size ();
   14022 
   14023   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
   14024   if (packet_config_support (packet) == PACKET_ENABLE
   14025       && conf->bts.size != rs->btrace_config.bts.size)
   14026     {
   14027       pos = buf;
   14028       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
   14029 			conf->bts.size);
   14030 
   14031       putpkt (buf);
   14032       getpkt (&rs->buf, 0);
   14033 
   14034       if (packet_ok (buf, packet) == PACKET_ERROR)
   14035 	{
   14036 	  if (buf[0] == 'E' && buf[1] == '.')
   14037 	    error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
   14038 	  else
   14039 	    error (_("Failed to configure the BTS buffer size."));
   14040 	}
   14041 
   14042       rs->btrace_config.bts.size = conf->bts.size;
   14043     }
   14044 
   14045   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
   14046   if (packet_config_support (packet) == PACKET_ENABLE
   14047       && conf->pt.size != rs->btrace_config.pt.size)
   14048     {
   14049       pos = buf;
   14050       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
   14051 			conf->pt.size);
   14052 
   14053       putpkt (buf);
   14054       getpkt (&rs->buf, 0);
   14055 
   14056       if (packet_ok (buf, packet) == PACKET_ERROR)
   14057 	{
   14058 	  if (buf[0] == 'E' && buf[1] == '.')
   14059 	    error (_("Failed to configure the trace buffer size: %s"), buf + 2);
   14060 	  else
   14061 	    error (_("Failed to configure the trace buffer size."));
   14062 	}
   14063 
   14064       rs->btrace_config.pt.size = conf->pt.size;
   14065     }
   14066 }
   14067 
   14068 /* Read TP's btrace configuration from the target and store it into CONF.  */
   14069 
   14070 static void
   14071 btrace_read_config (thread_info *tp, struct btrace_config *conf)
   14072 {
   14073   /* target_read_stralloc relies on INFERIOR_PTID.  */
   14074   scoped_restore_current_thread restore_thread;
   14075   switch_to_thread (tp);
   14076 
   14077   gdb::optional<gdb::char_vector> xml
   14078     = target_read_stralloc (current_inferior ()->top_target (),
   14079 			    TARGET_OBJECT_BTRACE_CONF, "");
   14080   if (xml)
   14081     parse_xml_btrace_conf (conf, xml->data ());
   14082 }
   14083 
   14084 /* Maybe reopen target btrace.  */
   14085 
   14086 void
   14087 remote_target::remote_btrace_maybe_reopen ()
   14088 {
   14089   struct remote_state *rs = get_remote_state ();
   14090   int btrace_target_pushed = 0;
   14091 #if !defined (HAVE_LIBIPT)
   14092   int warned = 0;
   14093 #endif
   14094 
   14095   /* Don't bother walking the entirety of the remote thread list when
   14096      we know the feature isn't supported by the remote.  */
   14097   if (packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
   14098     return;
   14099 
   14100   for (thread_info *tp : all_non_exited_threads (this))
   14101     {
   14102       memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
   14103       btrace_read_config (tp, &rs->btrace_config);
   14104 
   14105       if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
   14106 	continue;
   14107 
   14108 #if !defined (HAVE_LIBIPT)
   14109       if (rs->btrace_config.format == BTRACE_FORMAT_PT)
   14110 	{
   14111 	  if (!warned)
   14112 	    {
   14113 	      warned = 1;
   14114 	      warning (_("Target is recording using Intel Processor Trace "
   14115 			 "but support was disabled at compile time."));
   14116 	    }
   14117 
   14118 	  continue;
   14119 	}
   14120 #endif /* !defined (HAVE_LIBIPT) */
   14121 
   14122       /* Push target, once, but before anything else happens.  This way our
   14123 	 changes to the threads will be cleaned up by unpushing the target
   14124 	 in case btrace_read_config () throws.  */
   14125       if (!btrace_target_pushed)
   14126 	{
   14127 	  btrace_target_pushed = 1;
   14128 	  record_btrace_push_target ();
   14129 	  gdb_printf (_("Target is recording using %s.\n"),
   14130 		      btrace_format_string (rs->btrace_config.format));
   14131 	}
   14132 
   14133       tp->btrace.target = XCNEW (struct btrace_target_info);
   14134       tp->btrace.target->ptid = tp->ptid;
   14135       tp->btrace.target->conf = rs->btrace_config;
   14136     }
   14137 }
   14138 
   14139 /* Enable branch tracing.  */
   14140 
   14141 struct btrace_target_info *
   14142 remote_target::enable_btrace (thread_info *tp,
   14143 			      const struct btrace_config *conf)
   14144 {
   14145   struct btrace_target_info *tinfo = NULL;
   14146   struct packet_config *packet = NULL;
   14147   struct remote_state *rs = get_remote_state ();
   14148   char *buf = rs->buf.data ();
   14149   char *endbuf = buf + get_remote_packet_size ();
   14150 
   14151   switch (conf->format)
   14152     {
   14153       case BTRACE_FORMAT_BTS:
   14154 	packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
   14155 	break;
   14156 
   14157       case BTRACE_FORMAT_PT:
   14158 	packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
   14159 	break;
   14160     }
   14161 
   14162   if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
   14163     error (_("Target does not support branch tracing."));
   14164 
   14165   btrace_sync_conf (conf);
   14166 
   14167   ptid_t ptid = tp->ptid;
   14168   set_general_thread (ptid);
   14169 
   14170   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
   14171   putpkt (rs->buf);
   14172   getpkt (&rs->buf, 0);
   14173 
   14174   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
   14175     {
   14176       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
   14177 	error (_("Could not enable branch tracing for %s: %s"),
   14178 	       target_pid_to_str (ptid).c_str (), &rs->buf[2]);
   14179       else
   14180 	error (_("Could not enable branch tracing for %s."),
   14181 	       target_pid_to_str (ptid).c_str ());
   14182     }
   14183 
   14184   tinfo = XCNEW (struct btrace_target_info);
   14185   tinfo->ptid = ptid;
   14186 
   14187   /* If we fail to read the configuration, we lose some information, but the
   14188      tracing itself is not impacted.  */
   14189   try
   14190     {
   14191       btrace_read_config (tp, &tinfo->conf);
   14192     }
   14193   catch (const gdb_exception_error &err)
   14194     {
   14195       if (err.message != NULL)
   14196 	warning ("%s", err.what ());
   14197     }
   14198 
   14199   return tinfo;
   14200 }
   14201 
   14202 /* Disable branch tracing.  */
   14203 
   14204 void
   14205 remote_target::disable_btrace (struct btrace_target_info *tinfo)
   14206 {
   14207   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
   14208   struct remote_state *rs = get_remote_state ();
   14209   char *buf = rs->buf.data ();
   14210   char *endbuf = buf + get_remote_packet_size ();
   14211 
   14212   if (packet_config_support (packet) != PACKET_ENABLE)
   14213     error (_("Target does not support branch tracing."));
   14214 
   14215   set_general_thread (tinfo->ptid);
   14216 
   14217   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
   14218   putpkt (rs->buf);
   14219   getpkt (&rs->buf, 0);
   14220 
   14221   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
   14222     {
   14223       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
   14224 	error (_("Could not disable branch tracing for %s: %s"),
   14225 	       target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
   14226       else
   14227 	error (_("Could not disable branch tracing for %s."),
   14228 	       target_pid_to_str (tinfo->ptid).c_str ());
   14229     }
   14230 
   14231   xfree (tinfo);
   14232 }
   14233 
   14234 /* Teardown branch tracing.  */
   14235 
   14236 void
   14237 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
   14238 {
   14239   /* We must not talk to the target during teardown.  */
   14240   xfree (tinfo);
   14241 }
   14242 
   14243 /* Read the branch trace.  */
   14244 
   14245 enum btrace_error
   14246 remote_target::read_btrace (struct btrace_data *btrace,
   14247 			    struct btrace_target_info *tinfo,
   14248 			    enum btrace_read_type type)
   14249 {
   14250   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
   14251   const char *annex;
   14252 
   14253   if (packet_config_support (packet) != PACKET_ENABLE)
   14254     error (_("Target does not support branch tracing."));
   14255 
   14256 #if !defined(HAVE_LIBEXPAT)
   14257   error (_("Cannot process branch tracing result. XML parsing not supported."));
   14258 #endif
   14259 
   14260   switch (type)
   14261     {
   14262     case BTRACE_READ_ALL:
   14263       annex = "all";
   14264       break;
   14265     case BTRACE_READ_NEW:
   14266       annex = "new";
   14267       break;
   14268     case BTRACE_READ_DELTA:
   14269       annex = "delta";
   14270       break;
   14271     default:
   14272       internal_error (_("Bad branch tracing read type: %u."),
   14273 		      (unsigned int) type);
   14274     }
   14275 
   14276   gdb::optional<gdb::char_vector> xml
   14277     = target_read_stralloc (current_inferior ()->top_target (),
   14278 			    TARGET_OBJECT_BTRACE, annex);
   14279   if (!xml)
   14280     return BTRACE_ERR_UNKNOWN;
   14281 
   14282   parse_xml_btrace (btrace, xml->data ());
   14283 
   14284   return BTRACE_ERR_NONE;
   14285 }
   14286 
   14287 const struct btrace_config *
   14288 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
   14289 {
   14290   return &tinfo->conf;
   14291 }
   14292 
   14293 bool
   14294 remote_target::augmented_libraries_svr4_read ()
   14295 {
   14296   return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
   14297 	  == PACKET_ENABLE);
   14298 }
   14299 
   14300 /* Implementation of to_load.  */
   14301 
   14302 void
   14303 remote_target::load (const char *name, int from_tty)
   14304 {
   14305   generic_load (name, from_tty);
   14306 }
   14307 
   14308 /* Accepts an integer PID; returns a string representing a file that
   14309    can be opened on the remote side to get the symbols for the child
   14310    process.  Returns NULL if the operation is not supported.  */
   14311 
   14312 const char *
   14313 remote_target::pid_to_exec_file (int pid)
   14314 {
   14315   static gdb::optional<gdb::char_vector> filename;
   14316   char *annex = NULL;
   14317 
   14318   if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
   14319     return NULL;
   14320 
   14321   inferior *inf = find_inferior_pid (this, pid);
   14322   if (inf == NULL)
   14323     internal_error (_("not currently attached to process %d"), pid);
   14324 
   14325   if (!inf->fake_pid_p)
   14326     {
   14327       const int annex_size = 9;
   14328 
   14329       annex = (char *) alloca (annex_size);
   14330       xsnprintf (annex, annex_size, "%x", pid);
   14331     }
   14332 
   14333   filename = target_read_stralloc (current_inferior ()->top_target (),
   14334 				   TARGET_OBJECT_EXEC_FILE, annex);
   14335 
   14336   return filename ? filename->data () : nullptr;
   14337 }
   14338 
   14339 /* Implement the to_can_do_single_step target_ops method.  */
   14340 
   14341 int
   14342 remote_target::can_do_single_step ()
   14343 {
   14344   /* We can only tell whether target supports single step or not by
   14345      supported s and S vCont actions if the stub supports vContSupported
   14346      feature.  If the stub doesn't support vContSupported feature,
   14347      we have conservatively to think target doesn't supports single
   14348      step.  */
   14349   if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
   14350     {
   14351       struct remote_state *rs = get_remote_state ();
   14352 
   14353       if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
   14354 	remote_vcont_probe ();
   14355 
   14356       return rs->supports_vCont.s && rs->supports_vCont.S;
   14357     }
   14358   else
   14359     return 0;
   14360 }
   14361 
   14362 /* Implementation of the to_execution_direction method for the remote
   14363    target.  */
   14364 
   14365 enum exec_direction_kind
   14366 remote_target::execution_direction ()
   14367 {
   14368   struct remote_state *rs = get_remote_state ();
   14369 
   14370   return rs->last_resume_exec_dir;
   14371 }
   14372 
   14373 /* Return pointer to the thread_info struct which corresponds to
   14374    THREAD_HANDLE (having length HANDLE_LEN).  */
   14375 
   14376 thread_info *
   14377 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
   14378 					     int handle_len,
   14379 					     inferior *inf)
   14380 {
   14381   for (thread_info *tp : all_non_exited_threads (this))
   14382     {
   14383       remote_thread_info *priv = get_remote_thread_info (tp);
   14384 
   14385       if (tp->inf == inf && priv != NULL)
   14386 	{
   14387 	  if (handle_len != priv->thread_handle.size ())
   14388 	    error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
   14389 		   handle_len, priv->thread_handle.size ());
   14390 	  if (memcmp (thread_handle, priv->thread_handle.data (),
   14391 		      handle_len) == 0)
   14392 	    return tp;
   14393 	}
   14394     }
   14395 
   14396   return NULL;
   14397 }
   14398 
   14399 gdb::byte_vector
   14400 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
   14401 {
   14402   remote_thread_info *priv = get_remote_thread_info (tp);
   14403   return priv->thread_handle;
   14404 }
   14405 
   14406 bool
   14407 remote_target::can_async_p ()
   14408 {
   14409   /* This flag should be checked in the common target.c code.  */
   14410   gdb_assert (target_async_permitted);
   14411 
   14412   /* We're async whenever the serial device can.  */
   14413   struct remote_state *rs = get_remote_state ();
   14414   return serial_can_async_p (rs->remote_desc);
   14415 }
   14416 
   14417 bool
   14418 remote_target::is_async_p ()
   14419 {
   14420   /* We're async whenever the serial device is.  */
   14421   struct remote_state *rs = get_remote_state ();
   14422   return serial_is_async_p (rs->remote_desc);
   14423 }
   14424 
   14425 /* Pass the SERIAL event on and up to the client.  One day this code
   14426    will be able to delay notifying the client of an event until the
   14427    point where an entire packet has been received.  */
   14428 
   14429 static serial_event_ftype remote_async_serial_handler;
   14430 
   14431 static void
   14432 remote_async_serial_handler (struct serial *scb, void *context)
   14433 {
   14434   /* Don't propogate error information up to the client.  Instead let
   14435      the client find out about the error by querying the target.  */
   14436   inferior_event_handler (INF_REG_EVENT);
   14437 }
   14438 
   14439 static void
   14440 remote_async_inferior_event_handler (gdb_client_data data)
   14441 {
   14442   inferior_event_handler (INF_REG_EVENT);
   14443 }
   14444 
   14445 int
   14446 remote_target::async_wait_fd ()
   14447 {
   14448   struct remote_state *rs = get_remote_state ();
   14449   return rs->remote_desc->fd;
   14450 }
   14451 
   14452 void
   14453 remote_target::async (bool enable)
   14454 {
   14455   struct remote_state *rs = get_remote_state ();
   14456 
   14457   if (enable)
   14458     {
   14459       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
   14460 
   14461       /* If there are pending events in the stop reply queue tell the
   14462 	 event loop to process them.  */
   14463       if (!rs->stop_reply_queue.empty ())
   14464 	mark_async_event_handler (rs->remote_async_inferior_event_token);
   14465       /* For simplicity, below we clear the pending events token
   14466 	 without remembering whether it is marked, so here we always
   14467 	 mark it.  If there's actually no pending notification to
   14468 	 process, this ends up being a no-op (other than a spurious
   14469 	 event-loop wakeup).  */
   14470       if (target_is_non_stop_p ())
   14471 	mark_async_event_handler (rs->notif_state->get_pending_events_token);
   14472     }
   14473   else
   14474     {
   14475       serial_async (rs->remote_desc, NULL, NULL);
   14476       /* If the core is disabling async, it doesn't want to be
   14477 	 disturbed with target events.  Clear all async event sources
   14478 	 too.  */
   14479       clear_async_event_handler (rs->remote_async_inferior_event_token);
   14480       if (target_is_non_stop_p ())
   14481 	clear_async_event_handler (rs->notif_state->get_pending_events_token);
   14482     }
   14483 }
   14484 
   14485 /* Implementation of the to_thread_events method.  */
   14486 
   14487 void
   14488 remote_target::thread_events (int enable)
   14489 {
   14490   struct remote_state *rs = get_remote_state ();
   14491   size_t size = get_remote_packet_size ();
   14492 
   14493   if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
   14494     return;
   14495 
   14496   xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
   14497   putpkt (rs->buf);
   14498   getpkt (&rs->buf, 0);
   14499 
   14500   switch (packet_ok (rs->buf,
   14501 		     &remote_protocol_packets[PACKET_QThreadEvents]))
   14502     {
   14503     case PACKET_OK:
   14504       if (strcmp (rs->buf.data (), "OK") != 0)
   14505 	error (_("Remote refused setting thread events: %s"), rs->buf.data ());
   14506       break;
   14507     case PACKET_ERROR:
   14508       warning (_("Remote failure reply: %s"), rs->buf.data ());
   14509       break;
   14510     case PACKET_UNKNOWN:
   14511       break;
   14512     }
   14513 }
   14514 
   14515 static void
   14516 show_remote_cmd (const char *args, int from_tty)
   14517 {
   14518   /* We can't just use cmd_show_list here, because we want to skip
   14519      the redundant "show remote Z-packet" and the legacy aliases.  */
   14520   struct cmd_list_element *list = remote_show_cmdlist;
   14521   struct ui_out *uiout = current_uiout;
   14522 
   14523   ui_out_emit_tuple tuple_emitter (uiout, "showlist");
   14524   for (; list != NULL; list = list->next)
   14525     if (strcmp (list->name, "Z-packet") == 0)
   14526       continue;
   14527     else if (list->type == not_set_cmd)
   14528       /* Alias commands are exactly like the original, except they
   14529 	 don't have the normal type.  */
   14530       continue;
   14531     else
   14532       {
   14533 	ui_out_emit_tuple option_emitter (uiout, "option");
   14534 
   14535 	uiout->field_string ("name", list->name);
   14536 	uiout->text (":  ");
   14537 	if (list->type == show_cmd)
   14538 	  do_show_command (NULL, from_tty, list);
   14539 	else
   14540 	  cmd_func (list, NULL, from_tty);
   14541       }
   14542 }
   14543 
   14544 
   14545 /* Function to be called whenever a new objfile (shlib) is detected.  */
   14546 static void
   14547 remote_new_objfile (struct objfile *objfile)
   14548 {
   14549   /* The objfile change happened in that program space.  */
   14550   program_space *pspace = current_program_space;
   14551 
   14552   /* The affected program space is possibly shared by multiple inferiors.
   14553      Consider sending a qSymbol packet for each of the inferiors using that
   14554      program space.  */
   14555   for (inferior *inf : all_inferiors ())
   14556     {
   14557       if (inf->pspace != pspace)
   14558 	continue;
   14559 
   14560       /* Check whether the inferior's process target is a remote target.  */
   14561       remote_target *remote = as_remote_target (inf->process_target ());
   14562       if (remote == nullptr)
   14563 	continue;
   14564 
   14565       /* When we are attaching or handling a fork child and the shared library
   14566 	 subsystem reads the list of loaded libraries, we receive new objfile
   14567 	 events in between each found library.  The libraries are read in an
   14568 	 undefined order, so if we gave the remote side a chance to look up
   14569 	 symbols between each objfile, we might give it an inconsistent picture
   14570 	 of the inferior.  It could appear that a library A appears loaded but
   14571 	 a library B does not, even though library A requires library B.  That
   14572 	 would present a state that couldn't normally exist in the inferior.
   14573 
   14574 	 So, skip these events, we'll give the remote a chance to look up
   14575 	 symbols once all the loaded libraries and their symbols are known to
   14576 	 GDB.  */
   14577       if (inf->in_initial_library_scan)
   14578 	continue;
   14579 
   14580       if (!remote->has_execution (inf))
   14581 	continue;
   14582 
   14583       /* Need to switch to a specific thread, because remote_check_symbols will
   14584          set the general thread using INFERIOR_PTID.
   14585 
   14586 	 It's possible to have inferiors with no thread here, because we are
   14587 	 called very early in the connection process, while the inferior is
   14588 	 being set up, before threads are added.  Just skip it, start_remote_1
   14589 	 also calls remote_check_symbols when it's done setting things up.  */
   14590       thread_info *thread = any_thread_of_inferior (inf);
   14591       if (thread != nullptr)
   14592 	{
   14593 	  scoped_restore_current_thread restore_thread;
   14594 	  switch_to_thread (thread);
   14595 	  remote->remote_check_symbols ();
   14596 	}
   14597   }
   14598 }
   14599 
   14600 /* Pull all the tracepoints defined on the target and create local
   14601    data structures representing them.  We don't want to create real
   14602    tracepoints yet, we don't want to mess up the user's existing
   14603    collection.  */
   14604 
   14605 int
   14606 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
   14607 {
   14608   struct remote_state *rs = get_remote_state ();
   14609   char *p;
   14610 
   14611   /* Ask for a first packet of tracepoint definition.  */
   14612   putpkt ("qTfP");
   14613   getpkt (&rs->buf, 0);
   14614   p = rs->buf.data ();
   14615   while (*p && *p != 'l')
   14616     {
   14617       parse_tracepoint_definition (p, utpp);
   14618       /* Ask for another packet of tracepoint definition.  */
   14619       putpkt ("qTsP");
   14620       getpkt (&rs->buf, 0);
   14621       p = rs->buf.data ();
   14622     }
   14623   return 0;
   14624 }
   14625 
   14626 int
   14627 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
   14628 {
   14629   struct remote_state *rs = get_remote_state ();
   14630   char *p;
   14631 
   14632   /* Ask for a first packet of variable definition.  */
   14633   putpkt ("qTfV");
   14634   getpkt (&rs->buf, 0);
   14635   p = rs->buf.data ();
   14636   while (*p && *p != 'l')
   14637     {
   14638       parse_tsv_definition (p, utsvp);
   14639       /* Ask for another packet of variable definition.  */
   14640       putpkt ("qTsV");
   14641       getpkt (&rs->buf, 0);
   14642       p = rs->buf.data ();
   14643     }
   14644   return 0;
   14645 }
   14646 
   14647 /* The "set/show range-stepping" show hook.  */
   14648 
   14649 static void
   14650 show_range_stepping (struct ui_file *file, int from_tty,
   14651 		     struct cmd_list_element *c,
   14652 		     const char *value)
   14653 {
   14654   gdb_printf (file,
   14655 	      _("Debugger's willingness to use range stepping "
   14656 		"is %s.\n"), value);
   14657 }
   14658 
   14659 /* Return true if the vCont;r action is supported by the remote
   14660    stub.  */
   14661 
   14662 bool
   14663 remote_target::vcont_r_supported ()
   14664 {
   14665   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
   14666     remote_vcont_probe ();
   14667 
   14668   return (packet_support (PACKET_vCont) == PACKET_ENABLE
   14669 	  && get_remote_state ()->supports_vCont.r);
   14670 }
   14671 
   14672 /* The "set/show range-stepping" set hook.  */
   14673 
   14674 static void
   14675 set_range_stepping (const char *ignore_args, int from_tty,
   14676 		    struct cmd_list_element *c)
   14677 {
   14678   /* When enabling, check whether range stepping is actually supported
   14679      by the target, and warn if not.  */
   14680   if (use_range_stepping)
   14681     {
   14682       remote_target *remote = get_current_remote_target ();
   14683       if (remote == NULL
   14684 	  || !remote->vcont_r_supported ())
   14685 	warning (_("Range stepping is not supported by the current target"));
   14686     }
   14687 }
   14688 
   14689 static void
   14690 show_remote_debug (struct ui_file *file, int from_tty,
   14691 		   struct cmd_list_element *c, const char *value)
   14692 {
   14693   gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
   14694 	      value);
   14695 }
   14696 
   14697 static void
   14698 show_remote_timeout (struct ui_file *file, int from_tty,
   14699 		     struct cmd_list_element *c, const char *value)
   14700 {
   14701   gdb_printf (file,
   14702 	      _("Timeout limit to wait for target to respond is %s.\n"),
   14703 	      value);
   14704 }
   14705 
   14706 /* Implement the "supports_memory_tagging" target_ops method.  */
   14707 
   14708 bool
   14709 remote_target::supports_memory_tagging ()
   14710 {
   14711   return remote_memory_tagging_p ();
   14712 }
   14713 
   14714 /* Create the qMemTags packet given ADDRESS, LEN and TYPE.  */
   14715 
   14716 static void
   14717 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
   14718 			      size_t len, int type)
   14719 {
   14720   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
   14721 
   14722   std::string request = string_printf ("qMemTags:%s,%s:%s",
   14723 				       phex_nz (address, addr_size),
   14724 				       phex_nz (len, sizeof (len)),
   14725 				       phex_nz (type, sizeof (type)));
   14726 
   14727   strcpy (packet.data (), request.c_str ());
   14728 }
   14729 
   14730 /* Parse the qMemTags packet reply into TAGS.
   14731 
   14732    Return true if successful, false otherwise.  */
   14733 
   14734 static bool
   14735 parse_fetch_memtags_reply (const gdb::char_vector &reply,
   14736 			   gdb::byte_vector &tags)
   14737 {
   14738   if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
   14739     return false;
   14740 
   14741   /* Copy the tag data.  */
   14742   tags = hex2bin (reply.data () + 1);
   14743 
   14744   return true;
   14745 }
   14746 
   14747 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS.  */
   14748 
   14749 static void
   14750 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
   14751 			      size_t len, int type,
   14752 			      const gdb::byte_vector &tags)
   14753 {
   14754   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
   14755 
   14756   /* Put together the main packet, address and length.  */
   14757   std::string request = string_printf ("QMemTags:%s,%s:%s:",
   14758 				       phex_nz (address, addr_size),
   14759 				       phex_nz (len, sizeof (len)),
   14760 				       phex_nz (type, sizeof (type)));
   14761   request += bin2hex (tags.data (), tags.size ());
   14762 
   14763   /* Check if we have exceeded the maximum packet size.  */
   14764   if (packet.size () < request.length ())
   14765     error (_("Contents too big for packet QMemTags."));
   14766 
   14767   strcpy (packet.data (), request.c_str ());
   14768 }
   14769 
   14770 /* Implement the "fetch_memtags" target_ops method.  */
   14771 
   14772 bool
   14773 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
   14774 			      gdb::byte_vector &tags, int type)
   14775 {
   14776   /* Make sure the qMemTags packet is supported.  */
   14777   if (!remote_memory_tagging_p ())
   14778     gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
   14779 
   14780   struct remote_state *rs = get_remote_state ();
   14781 
   14782   create_fetch_memtags_request (rs->buf, address, len, type);
   14783 
   14784   putpkt (rs->buf);
   14785   getpkt (&rs->buf, 0);
   14786 
   14787   return parse_fetch_memtags_reply (rs->buf, tags);
   14788 }
   14789 
   14790 /* Implement the "store_memtags" target_ops method.  */
   14791 
   14792 bool
   14793 remote_target::store_memtags (CORE_ADDR address, size_t len,
   14794 			      const gdb::byte_vector &tags, int type)
   14795 {
   14796   /* Make sure the QMemTags packet is supported.  */
   14797   if (!remote_memory_tagging_p ())
   14798     gdb_assert_not_reached ("remote store_memtags called with packet disabled");
   14799 
   14800   struct remote_state *rs = get_remote_state ();
   14801 
   14802   create_store_memtags_request (rs->buf, address, len, type, tags);
   14803 
   14804   putpkt (rs->buf);
   14805   getpkt (&rs->buf, 0);
   14806 
   14807   /* Verify if the request was successful.  */
   14808   return packet_check_result (rs->buf.data ()) == PACKET_OK;
   14809 }
   14810 
   14811 /* Return true if remote target T is non-stop.  */
   14812 
   14813 bool
   14814 remote_target_is_non_stop_p (remote_target *t)
   14815 {
   14816   scoped_restore_current_thread restore_thread;
   14817   switch_to_target_no_thread (t);
   14818 
   14819   return target_is_non_stop_p ();
   14820 }
   14821 
   14822 #if GDB_SELF_TEST
   14823 
   14824 namespace selftests {
   14825 
   14826 static void
   14827 test_memory_tagging_functions ()
   14828 {
   14829   remote_target remote;
   14830 
   14831   struct packet_config *config
   14832     = &remote_protocol_packets[PACKET_memory_tagging_feature];
   14833 
   14834   scoped_restore restore_memtag_support_
   14835     = make_scoped_restore (&config->support);
   14836 
   14837   /* Test memory tagging packet support.  */
   14838   config->support = PACKET_SUPPORT_UNKNOWN;
   14839   SELF_CHECK (remote.supports_memory_tagging () == false);
   14840   config->support = PACKET_DISABLE;
   14841   SELF_CHECK (remote.supports_memory_tagging () == false);
   14842   config->support = PACKET_ENABLE;
   14843   SELF_CHECK (remote.supports_memory_tagging () == true);
   14844 
   14845   /* Setup testing.  */
   14846   gdb::char_vector packet;
   14847   gdb::byte_vector tags, bv;
   14848   std::string expected, reply;
   14849   packet.resize (32000);
   14850 
   14851   /* Test creating a qMemTags request.  */
   14852 
   14853   expected = "qMemTags:0,0:0";
   14854   create_fetch_memtags_request (packet, 0x0, 0x0, 0);
   14855   SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
   14856 
   14857   expected = "qMemTags:deadbeef,10:1";
   14858   create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
   14859   SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
   14860 
   14861   /* Test parsing a qMemTags reply.  */
   14862 
   14863   /* Error reply, tags vector unmodified.  */
   14864   reply = "E00";
   14865   strcpy (packet.data (), reply.c_str ());
   14866   tags.resize (0);
   14867   SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
   14868   SELF_CHECK (tags.size () == 0);
   14869 
   14870   /* Valid reply, tags vector updated.  */
   14871   tags.resize (0);
   14872   bv.resize (0);
   14873 
   14874   for (int i = 0; i < 5; i++)
   14875     bv.push_back (i);
   14876 
   14877   reply = "m" + bin2hex (bv.data (), bv.size ());
   14878   strcpy (packet.data (), reply.c_str ());
   14879 
   14880   SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
   14881   SELF_CHECK (tags.size () == 5);
   14882 
   14883   for (int i = 0; i < 5; i++)
   14884     SELF_CHECK (tags[i] == i);
   14885 
   14886   /* Test creating a QMemTags request.  */
   14887 
   14888   /* Empty tag data.  */
   14889   tags.resize (0);
   14890   expected = "QMemTags:0,0:0:";
   14891   create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
   14892   SELF_CHECK (memcmp (packet.data (), expected.c_str (),
   14893 		      expected.length ()) == 0);
   14894 
   14895   /* Non-empty tag data.  */
   14896   tags.resize (0);
   14897   for (int i = 0; i < 5; i++)
   14898     tags.push_back (i);
   14899   expected = "QMemTags:deadbeef,ff:1:0001020304";
   14900   create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
   14901   SELF_CHECK (memcmp (packet.data (), expected.c_str (),
   14902 		      expected.length ()) == 0);
   14903 }
   14904 
   14905 } // namespace selftests
   14906 #endif /* GDB_SELF_TEST */
   14907 
   14908 void _initialize_remote ();
   14909 void
   14910 _initialize_remote ()
   14911 {
   14912   add_target (remote_target_info, remote_target::open);
   14913   add_target (extended_remote_target_info, extended_remote_target::open);
   14914 
   14915   /* Hook into new objfile notification.  */
   14916   gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
   14917 
   14918 #if 0
   14919   init_remote_threadtests ();
   14920 #endif
   14921 
   14922   /* set/show remote ...  */
   14923 
   14924   add_basic_prefix_cmd ("remote", class_maintenance, _("\
   14925 Remote protocol specific variables.\n\
   14926 Configure various remote-protocol specific variables such as\n\
   14927 the packets being used."),
   14928 			&remote_set_cmdlist,
   14929 			0 /* allow-unknown */, &setlist);
   14930   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
   14931 Remote protocol specific variables.\n\
   14932 Configure various remote-protocol specific variables such as\n\
   14933 the packets being used."),
   14934 		  &remote_show_cmdlist,
   14935 		  0 /* allow-unknown */, &showlist);
   14936 
   14937   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
   14938 Compare section data on target to the exec file.\n\
   14939 Argument is a single section name (default: all loaded sections).\n\
   14940 To compare only read-only loaded sections, specify the -r option."),
   14941 	   &cmdlist);
   14942 
   14943   add_cmd ("packet", class_maintenance, cli_packet_command, _("\
   14944 Send an arbitrary packet to a remote target.\n\
   14945    maintenance packet TEXT\n\
   14946 If GDB is talking to an inferior via the GDB serial protocol, then\n\
   14947 this command sends the string TEXT to the inferior, and displays the\n\
   14948 response packet.  GDB supplies the initial `$' character, and the\n\
   14949 terminating `#' character and checksum."),
   14950 	   &maintenancelist);
   14951 
   14952   set_show_commands remotebreak_cmds
   14953     = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
   14954 Set whether to send break if interrupted."), _("\
   14955 Show whether to send break if interrupted."), _("\
   14956 If set, a break, instead of a cntrl-c, is sent to the remote target."),
   14957 			       set_remotebreak, show_remotebreak,
   14958 			       &setlist, &showlist);
   14959   deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
   14960   deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
   14961 
   14962   add_setshow_enum_cmd ("interrupt-sequence", class_support,
   14963 			interrupt_sequence_modes, &interrupt_sequence_mode,
   14964 			_("\
   14965 Set interrupt sequence to remote target."), _("\
   14966 Show interrupt sequence to remote target."), _("\
   14967 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
   14968 			NULL, show_interrupt_sequence,
   14969 			&remote_set_cmdlist,
   14970 			&remote_show_cmdlist);
   14971 
   14972   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
   14973 			   &interrupt_on_connect, _("\
   14974 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
   14975 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
   14976 If set, interrupt sequence is sent to remote target."),
   14977 			   NULL, NULL,
   14978 			   &remote_set_cmdlist, &remote_show_cmdlist);
   14979 
   14980   /* Install commands for configuring memory read/write packets.  */
   14981 
   14982   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
   14983 Set the maximum number of bytes per memory write packet (deprecated)."),
   14984 	   &setlist);
   14985   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
   14986 Show the maximum number of bytes per memory write packet (deprecated)."),
   14987 	   &showlist);
   14988   add_cmd ("memory-write-packet-size", no_class,
   14989 	   set_memory_write_packet_size, _("\
   14990 Set the maximum number of bytes per memory-write packet.\n\
   14991 Specify the number of bytes in a packet or 0 (zero) for the\n\
   14992 default packet size.  The actual limit is further reduced\n\
   14993 dependent on the target.  Specify ``fixed'' to disable the\n\
   14994 further restriction and ``limit'' to enable that restriction."),
   14995 	   &remote_set_cmdlist);
   14996   add_cmd ("memory-read-packet-size", no_class,
   14997 	   set_memory_read_packet_size, _("\
   14998 Set the maximum number of bytes per memory-read packet.\n\
   14999 Specify the number of bytes in a packet or 0 (zero) for the\n\
   15000 default packet size.  The actual limit is further reduced\n\
   15001 dependent on the target.  Specify ``fixed'' to disable the\n\
   15002 further restriction and ``limit'' to enable that restriction."),
   15003 	   &remote_set_cmdlist);
   15004   add_cmd ("memory-write-packet-size", no_class,
   15005 	   show_memory_write_packet_size,
   15006 	   _("Show the maximum number of bytes per memory-write packet."),
   15007 	   &remote_show_cmdlist);
   15008   add_cmd ("memory-read-packet-size", no_class,
   15009 	   show_memory_read_packet_size,
   15010 	   _("Show the maximum number of bytes per memory-read packet."),
   15011 	   &remote_show_cmdlist);
   15012 
   15013   add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
   15014 			    &remote_hw_watchpoint_limit, _("\
   15015 Set the maximum number of target hardware watchpoints."), _("\
   15016 Show the maximum number of target hardware watchpoints."), _("\
   15017 Specify \"unlimited\" for unlimited hardware watchpoints."),
   15018 			    NULL, show_hardware_watchpoint_limit,
   15019 			    &remote_set_cmdlist,
   15020 			    &remote_show_cmdlist);
   15021   add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
   15022 			    no_class,
   15023 			    &remote_hw_watchpoint_length_limit, _("\
   15024 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
   15025 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
   15026 Specify \"unlimited\" to allow watchpoints of unlimited size."),
   15027 			    NULL, show_hardware_watchpoint_length_limit,
   15028 			    &remote_set_cmdlist, &remote_show_cmdlist);
   15029   add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
   15030 			    &remote_hw_breakpoint_limit, _("\
   15031 Set the maximum number of target hardware breakpoints."), _("\
   15032 Show the maximum number of target hardware breakpoints."), _("\
   15033 Specify \"unlimited\" for unlimited hardware breakpoints."),
   15034 			    NULL, show_hardware_breakpoint_limit,
   15035 			    &remote_set_cmdlist, &remote_show_cmdlist);
   15036 
   15037   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
   15038 			     &remote_address_size, _("\
   15039 Set the maximum size of the address (in bits) in a memory packet."), _("\
   15040 Show the maximum size of the address (in bits) in a memory packet."), NULL,
   15041 			     NULL,
   15042 			     NULL, /* FIXME: i18n: */
   15043 			     &setlist, &showlist);
   15044 
   15045   init_all_packet_configs ();
   15046 
   15047   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
   15048 			 "X", "binary-download", 1);
   15049 
   15050   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
   15051 			 "vCont", "verbose-resume", 0);
   15052 
   15053   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
   15054 			 "QPassSignals", "pass-signals", 0);
   15055 
   15056   add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
   15057 			 "QCatchSyscalls", "catch-syscalls", 0);
   15058 
   15059   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
   15060 			 "QProgramSignals", "program-signals", 0);
   15061 
   15062   add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
   15063 			 "QSetWorkingDir", "set-working-dir", 0);
   15064 
   15065   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
   15066 			 "QStartupWithShell", "startup-with-shell", 0);
   15067 
   15068   add_packet_config_cmd (&remote_protocol_packets
   15069 			 [PACKET_QEnvironmentHexEncoded],
   15070 			 "QEnvironmentHexEncoded", "environment-hex-encoded",
   15071 			 0);
   15072 
   15073   add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
   15074 			 "QEnvironmentReset", "environment-reset",
   15075 			 0);
   15076 
   15077   add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
   15078 			 "QEnvironmentUnset", "environment-unset",
   15079 			 0);
   15080 
   15081   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
   15082 			 "qSymbol", "symbol-lookup", 0);
   15083 
   15084   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
   15085 			 "P", "set-register", 1);
   15086 
   15087   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
   15088 			 "p", "fetch-register", 1);
   15089 
   15090   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
   15091 			 "Z0", "software-breakpoint", 0);
   15092 
   15093   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
   15094 			 "Z1", "hardware-breakpoint", 0);
   15095 
   15096   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
   15097 			 "Z2", "write-watchpoint", 0);
   15098 
   15099   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
   15100 			 "Z3", "read-watchpoint", 0);
   15101 
   15102   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
   15103 			 "Z4", "access-watchpoint", 0);
   15104 
   15105   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
   15106 			 "qXfer:auxv:read", "read-aux-vector", 0);
   15107 
   15108   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
   15109 			 "qXfer:exec-file:read", "pid-to-exec-file", 0);
   15110 
   15111   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
   15112 			 "qXfer:features:read", "target-features", 0);
   15113 
   15114   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
   15115 			 "qXfer:libraries:read", "library-info", 0);
   15116 
   15117   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
   15118 			 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
   15119 
   15120   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
   15121 			 "qXfer:memory-map:read", "memory-map", 0);
   15122 
   15123   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
   15124 			"qXfer:osdata:read", "osdata", 0);
   15125 
   15126   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
   15127 			 "qXfer:threads:read", "threads", 0);
   15128 
   15129   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
   15130 			 "qXfer:siginfo:read", "read-siginfo-object", 0);
   15131 
   15132   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
   15133 			 "qXfer:siginfo:write", "write-siginfo-object", 0);
   15134 
   15135   add_packet_config_cmd
   15136     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
   15137      "qXfer:traceframe-info:read", "traceframe-info", 0);
   15138 
   15139   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
   15140 			 "qXfer:uib:read", "unwind-info-block", 0);
   15141 
   15142   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
   15143 			 "qGetTLSAddr", "get-thread-local-storage-address",
   15144 			 0);
   15145 
   15146   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
   15147 			 "qGetTIBAddr", "get-thread-information-block-address",
   15148 			 0);
   15149 
   15150   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
   15151 			 "bc", "reverse-continue", 0);
   15152 
   15153   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
   15154 			 "bs", "reverse-step", 0);
   15155 
   15156   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
   15157 			 "qSupported", "supported-packets", 0);
   15158 
   15159   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
   15160 			 "qSearch:memory", "search-memory", 0);
   15161 
   15162   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
   15163 			 "qTStatus", "trace-status", 0);
   15164 
   15165   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
   15166 			 "vFile:setfs", "hostio-setfs", 0);
   15167 
   15168   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
   15169 			 "vFile:open", "hostio-open", 0);
   15170 
   15171   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
   15172 			 "vFile:pread", "hostio-pread", 0);
   15173 
   15174   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
   15175 			 "vFile:pwrite", "hostio-pwrite", 0);
   15176 
   15177   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
   15178 			 "vFile:close", "hostio-close", 0);
   15179 
   15180   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
   15181 			 "vFile:unlink", "hostio-unlink", 0);
   15182 
   15183   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
   15184 			 "vFile:readlink", "hostio-readlink", 0);
   15185 
   15186   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
   15187 			 "vFile:fstat", "hostio-fstat", 0);
   15188 
   15189   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
   15190 			 "vAttach", "attach", 0);
   15191 
   15192   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
   15193 			 "vRun", "run", 0);
   15194 
   15195   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
   15196 			 "QStartNoAckMode", "noack", 0);
   15197 
   15198   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
   15199 			 "vKill", "kill", 0);
   15200 
   15201   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
   15202 			 "qAttached", "query-attached", 0);
   15203 
   15204   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
   15205 			 "ConditionalTracepoints",
   15206 			 "conditional-tracepoints", 0);
   15207 
   15208   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
   15209 			 "ConditionalBreakpoints",
   15210 			 "conditional-breakpoints", 0);
   15211 
   15212   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
   15213 			 "BreakpointCommands",
   15214 			 "breakpoint-commands", 0);
   15215 
   15216   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
   15217 			 "FastTracepoints", "fast-tracepoints", 0);
   15218 
   15219   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
   15220 			 "TracepointSource", "TracepointSource", 0);
   15221 
   15222   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
   15223 			 "QAllow", "allow", 0);
   15224 
   15225   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
   15226 			 "StaticTracepoints", "static-tracepoints", 0);
   15227 
   15228   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
   15229 			 "InstallInTrace", "install-in-trace", 0);
   15230 
   15231   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
   15232 			 "qXfer:statictrace:read", "read-sdata-object", 0);
   15233 
   15234   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
   15235 			 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
   15236 
   15237   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
   15238 			 "QDisableRandomization", "disable-randomization", 0);
   15239 
   15240   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
   15241 			 "QAgent", "agent", 0);
   15242 
   15243   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
   15244 			 "QTBuffer:size", "trace-buffer-size", 0);
   15245 
   15246   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
   15247        "Qbtrace:off", "disable-btrace", 0);
   15248 
   15249   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
   15250        "Qbtrace:bts", "enable-btrace-bts", 0);
   15251 
   15252   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
   15253        "Qbtrace:pt", "enable-btrace-pt", 0);
   15254 
   15255   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
   15256        "qXfer:btrace", "read-btrace", 0);
   15257 
   15258   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
   15259        "qXfer:btrace-conf", "read-btrace-conf", 0);
   15260 
   15261   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
   15262        "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
   15263 
   15264   add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
   15265        "multiprocess-feature", "multiprocess-feature", 0);
   15266 
   15267   add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
   15268 			 "swbreak-feature", "swbreak-feature", 0);
   15269 
   15270   add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
   15271 			 "hwbreak-feature", "hwbreak-feature", 0);
   15272 
   15273   add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
   15274 			 "fork-event-feature", "fork-event-feature", 0);
   15275 
   15276   add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
   15277 			 "vfork-event-feature", "vfork-event-feature", 0);
   15278 
   15279   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
   15280        "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
   15281 
   15282   add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
   15283 			 "vContSupported", "verbose-resume-supported", 0);
   15284 
   15285   add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
   15286 			 "exec-event-feature", "exec-event-feature", 0);
   15287 
   15288   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
   15289 			 "vCtrlC", "ctrl-c", 0);
   15290 
   15291   add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
   15292 			 "QThreadEvents", "thread-events", 0);
   15293 
   15294   add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
   15295 			 "N stop reply", "no-resumed-stop-reply", 0);
   15296 
   15297   add_packet_config_cmd (&remote_protocol_packets[PACKET_memory_tagging_feature],
   15298 			 "memory-tagging-feature", "memory-tagging-feature", 0);
   15299 
   15300   /* Assert that we've registered "set remote foo-packet" commands
   15301      for all packet configs.  */
   15302   {
   15303     int i;
   15304 
   15305     for (i = 0; i < PACKET_MAX; i++)
   15306       {
   15307 	/* Ideally all configs would have a command associated.  Some
   15308 	   still don't though.  */
   15309 	int excepted;
   15310 
   15311 	switch (i)
   15312 	  {
   15313 	  case PACKET_QNonStop:
   15314 	  case PACKET_EnableDisableTracepoints_feature:
   15315 	  case PACKET_tracenz_feature:
   15316 	  case PACKET_DisconnectedTracing_feature:
   15317 	  case PACKET_augmented_libraries_svr4_read_feature:
   15318 	  case PACKET_qCRC:
   15319 	    /* Additions to this list need to be well justified:
   15320 	       pre-existing packets are OK; new packets are not.  */
   15321 	    excepted = 1;
   15322 	    break;
   15323 	  default:
   15324 	    excepted = 0;
   15325 	    break;
   15326 	  }
   15327 
   15328 	/* This catches both forgetting to add a config command, and
   15329 	   forgetting to remove a packet from the exception list.  */
   15330 	gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
   15331       }
   15332   }
   15333 
   15334   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
   15335      Z sub-packet has its own set and show commands, but users may
   15336      have sets to this variable in their .gdbinit files (or in their
   15337      documentation).  */
   15338   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
   15339 				&remote_Z_packet_detect, _("\
   15340 Set use of remote protocol `Z' packets."), _("\
   15341 Show use of remote protocol `Z' packets."), _("\
   15342 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
   15343 packets."),
   15344 				set_remote_protocol_Z_packet_cmd,
   15345 				show_remote_protocol_Z_packet_cmd,
   15346 				/* FIXME: i18n: Use of remote protocol
   15347 				   `Z' packets is %s.  */
   15348 				&remote_set_cmdlist, &remote_show_cmdlist);
   15349 
   15350   add_basic_prefix_cmd ("remote", class_files, _("\
   15351 Manipulate files on the remote system.\n\
   15352 Transfer files to and from the remote target system."),
   15353 			&remote_cmdlist,
   15354 			0 /* allow-unknown */, &cmdlist);
   15355 
   15356   add_cmd ("put", class_files, remote_put_command,
   15357 	   _("Copy a local file to the remote system."),
   15358 	   &remote_cmdlist);
   15359 
   15360   add_cmd ("get", class_files, remote_get_command,
   15361 	   _("Copy a remote file to the local system."),
   15362 	   &remote_cmdlist);
   15363 
   15364   add_cmd ("delete", class_files, remote_delete_command,
   15365 	   _("Delete a remote file."),
   15366 	   &remote_cmdlist);
   15367 
   15368   add_setshow_string_noescape_cmd ("exec-file", class_files,
   15369 				   &remote_exec_file_var, _("\
   15370 Set the remote pathname for \"run\"."), _("\
   15371 Show the remote pathname for \"run\"."), NULL,
   15372 				   set_remote_exec_file,
   15373 				   show_remote_exec_file,
   15374 				   &remote_set_cmdlist,
   15375 				   &remote_show_cmdlist);
   15376 
   15377   add_setshow_boolean_cmd ("range-stepping", class_run,
   15378 			   &use_range_stepping, _("\
   15379 Enable or disable range stepping."), _("\
   15380 Show whether target-assisted range stepping is enabled."), _("\
   15381 If on, and the target supports it, when stepping a source line, GDB\n\
   15382 tells the target to step the corresponding range of addresses itself instead\n\
   15383 of issuing multiple single-steps.  This speeds up source level\n\
   15384 stepping.  If off, GDB always issues single-steps, even if range\n\
   15385 stepping is supported by the target.  The default is on."),
   15386 			   set_range_stepping,
   15387 			   show_range_stepping,
   15388 			   &setlist,
   15389 			   &showlist);
   15390 
   15391   add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
   15392 Set watchdog timer."), _("\
   15393 Show watchdog timer."), _("\
   15394 When non-zero, this timeout is used instead of waiting forever for a target\n\
   15395 to finish a low-level step or continue operation.  If the specified amount\n\
   15396 of time passes without a response from the target, an error occurs."),
   15397 			    NULL,
   15398 			    show_watchdog,
   15399 			    &setlist, &showlist);
   15400 
   15401   add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
   15402 				       &remote_packet_max_chars, _("\
   15403 Set the maximum number of characters to display for each remote packet."), _("\
   15404 Show the maximum number of characters to display for each remote packet."), _("\
   15405 Specify \"unlimited\" to display all the characters."),
   15406 				       NULL, show_remote_packet_max_chars,
   15407 				       &setdebuglist, &showdebuglist);
   15408 
   15409   add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
   15410 			   _("Set debugging of remote protocol."),
   15411 			   _("Show debugging of remote protocol."),
   15412 			   _("\
   15413 When enabled, each packet sent or received with the remote target\n\
   15414 is displayed."),
   15415 			   NULL,
   15416 			   show_remote_debug,
   15417 			   &setdebuglist, &showdebuglist);
   15418 
   15419   add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
   15420 				       &remote_timeout, _("\
   15421 Set timeout limit to wait for target to respond."), _("\
   15422 Show timeout limit to wait for target to respond."), _("\
   15423 This value is used to set the time limit for gdb to wait for a response\n\
   15424 from the target."),
   15425 				       NULL,
   15426 				       show_remote_timeout,
   15427 				       &setlist, &showlist);
   15428 
   15429   /* Eventually initialize fileio.  See fileio.c */
   15430   initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
   15431 
   15432 #if GDB_SELF_TEST
   15433   selftests::register_test ("remote_memory_tagging",
   15434 			    selftests::test_memory_tagging_functions);
   15435 #endif
   15436 }
   15437