Home | History | Annotate | Line # | Download | only in gdb
remote.c revision 1.1.1.6
      1 /* Remote target communications for serial-line targets in custom GDB protocol
      2 
      3    Copyright (C) 1988-2019 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 "common/filestuff.h"
     46 #include "common/rsp-low.h"
     47 #include "disasm.h"
     48 #include "location.h"
     49 
     50 #include "common/gdb_sys_time.h"
     51 
     52 #include "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" /* for exec_bfd */
     60 
     61 #include "remote-fileio.h"
     62 #include "gdb/fileio.h"
     63 #include <sys/stat.h>
     64 #include "xml-support.h"
     65 
     66 #include "memory-map.h"
     67 
     68 #include "tracepoint.h"
     69 #include "ax.h"
     70 #include "ax-gdb.h"
     71 #include "common/agent.h"
     72 #include "btrace.h"
     73 #include "record-btrace.h"
     74 #include <algorithm>
     75 #include "common/scoped_restore.h"
     76 #include "common/environ.h"
     77 #include "common/byte-vector.h"
     78 #include <unordered_map>
     79 
     80 /* The remote target.  */
     81 
     82 static const char remote_doc[] = N_("\
     83 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
     84 Specify the serial device it is connected to\n\
     85 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
     86 
     87 #define OPAQUETHREADBYTES 8
     88 
     89 /* a 64 bit opaque identifier */
     90 typedef unsigned char threadref[OPAQUETHREADBYTES];
     91 
     92 struct gdb_ext_thread_info;
     93 struct threads_listing_context;
     94 typedef int (*rmt_thread_action) (threadref *ref, void *context);
     95 struct protocol_feature;
     96 struct packet_reg;
     97 
     98 struct stop_reply;
     99 static void stop_reply_xfree (struct stop_reply *);
    100 
    101 struct stop_reply_deleter
    102 {
    103   void operator() (stop_reply *r) const
    104   {
    105     stop_reply_xfree (r);
    106   }
    107 };
    108 
    109 typedef std::unique_ptr<stop_reply, stop_reply_deleter> stop_reply_up;
    110 
    111 /* Generic configuration support for packets the stub optionally
    112    supports.  Allows the user to specify the use of the packet as well
    113    as allowing GDB to auto-detect support in the remote stub.  */
    114 
    115 enum packet_support
    116   {
    117     PACKET_SUPPORT_UNKNOWN = 0,
    118     PACKET_ENABLE,
    119     PACKET_DISABLE
    120   };
    121 
    122 /* Analyze a packet's return value and update the packet config
    123    accordingly.  */
    124 
    125 enum packet_result
    126 {
    127   PACKET_ERROR,
    128   PACKET_OK,
    129   PACKET_UNKNOWN
    130 };
    131 
    132 struct threads_listing_context;
    133 
    134 /* Stub vCont actions support.
    135 
    136    Each field is a boolean flag indicating whether the stub reports
    137    support for the corresponding action.  */
    138 
    139 struct vCont_action_support
    140 {
    141   /* vCont;t */
    142   bool t = false;
    143 
    144   /* vCont;r */
    145   bool r = false;
    146 
    147   /* vCont;s */
    148   bool s = false;
    149 
    150   /* vCont;S */
    151   bool S = false;
    152 };
    153 
    154 /* About this many threadisds fit in a packet.  */
    155 
    156 #define MAXTHREADLISTRESULTS 32
    157 
    158 /* Data for the vFile:pread readahead cache.  */
    159 
    160 struct readahead_cache
    161 {
    162   /* Invalidate the readahead cache.  */
    163   void invalidate ();
    164 
    165   /* Invalidate the readahead cache if it is holding data for FD.  */
    166   void invalidate_fd (int fd);
    167 
    168   /* Serve pread from the readahead cache.  Returns number of bytes
    169      read, or 0 if the request can't be served from the cache.  */
    170   int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
    171 
    172   /* The file descriptor for the file that is being cached.  -1 if the
    173      cache is invalid.  */
    174   int fd = -1;
    175 
    176   /* The offset into the file that the cache buffer corresponds
    177      to.  */
    178   ULONGEST offset = 0;
    179 
    180   /* The buffer holding the cache contents.  */
    181   gdb_byte *buf = nullptr;
    182   /* The buffer's size.  We try to read as much as fits into a packet
    183      at a time.  */
    184   size_t bufsize = 0;
    185 
    186   /* Cache hit and miss counters.  */
    187   ULONGEST hit_count = 0;
    188   ULONGEST miss_count = 0;
    189 };
    190 
    191 /* Description of the remote protocol for a given architecture.  */
    192 
    193 struct packet_reg
    194 {
    195   long offset; /* Offset into G packet.  */
    196   long regnum; /* GDB's internal register number.  */
    197   LONGEST pnum; /* Remote protocol register number.  */
    198   int in_g_packet; /* Always part of G packet.  */
    199   /* long size in bytes;  == register_size (target_gdbarch (), regnum);
    200      at present.  */
    201   /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
    202      at present.  */
    203 };
    204 
    205 struct remote_arch_state
    206 {
    207   explicit remote_arch_state (struct gdbarch *gdbarch);
    208 
    209   /* Description of the remote protocol registers.  */
    210   long sizeof_g_packet;
    211 
    212   /* Description of the remote protocol registers indexed by REGNUM
    213      (making an array gdbarch_num_regs in size).  */
    214   std::unique_ptr<packet_reg[]> regs;
    215 
    216   /* This is the size (in chars) of the first response to the ``g''
    217      packet.  It is used as a heuristic when determining the maximum
    218      size of memory-read and memory-write packets.  A target will
    219      typically only reserve a buffer large enough to hold the ``g''
    220      packet.  The size does not include packet overhead (headers and
    221      trailers).  */
    222   long actual_register_packet_size;
    223 
    224   /* This is the maximum size (in chars) of a non read/write packet.
    225      It is also used as a cap on the size of read/write packets.  */
    226   long remote_packet_size;
    227 };
    228 
    229 /* Description of the remote protocol state for the currently
    230    connected target.  This is per-target state, and independent of the
    231    selected architecture.  */
    232 
    233 class remote_state
    234 {
    235 public:
    236 
    237   remote_state ();
    238   ~remote_state ();
    239 
    240   /* Get the remote arch state for GDBARCH.  */
    241   struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
    242 
    243 public: /* data */
    244 
    245   /* A buffer to use for incoming packets, and its current size.  The
    246      buffer is grown dynamically for larger incoming packets.
    247      Outgoing packets may also be constructed in this buffer.
    248      The size of the buffer is always at least REMOTE_PACKET_SIZE;
    249      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
    250      packets.  */
    251   gdb::char_vector buf;
    252 
    253   /* True if we're going through initial connection setup (finding out
    254      about the remote side's threads, relocating symbols, etc.).  */
    255   bool starting_up = false;
    256 
    257   /* If we negotiated packet size explicitly (and thus can bypass
    258      heuristics for the largest packet size that will not overflow
    259      a buffer in the stub), this will be set to that packet size.
    260      Otherwise zero, meaning to use the guessed size.  */
    261   long explicit_packet_size = 0;
    262 
    263   /* remote_wait is normally called when the target is running and
    264      waits for a stop reply packet.  But sometimes we need to call it
    265      when the target is already stopped.  We can send a "?" packet
    266      and have remote_wait read the response.  Or, if we already have
    267      the response, we can stash it in BUF and tell remote_wait to
    268      skip calling getpkt.  This flag is set when BUF contains a
    269      stop reply packet and the target is not waiting.  */
    270   int cached_wait_status = 0;
    271 
    272   /* True, if in no ack mode.  That is, neither GDB nor the stub will
    273      expect acks from each other.  The connection is assumed to be
    274      reliable.  */
    275   bool noack_mode = false;
    276 
    277   /* True if we're connected in extended remote mode.  */
    278   bool extended = false;
    279 
    280   /* True if we resumed the target and we're waiting for the target to
    281      stop.  In the mean time, we can't start another command/query.
    282      The remote server wouldn't be ready to process it, so we'd
    283      timeout waiting for a reply that would never come and eventually
    284      we'd close the connection.  This can happen in asynchronous mode
    285      because we allow GDB commands while the target is running.  */
    286   bool waiting_for_stop_reply = false;
    287 
    288   /* The status of the stub support for the various vCont actions.  */
    289   vCont_action_support supports_vCont;
    290 
    291   /* True if the user has pressed Ctrl-C, but the target hasn't
    292      responded to that.  */
    293   bool ctrlc_pending_p = false;
    294 
    295   /* True if we saw a Ctrl-C while reading or writing from/to the
    296      remote descriptor.  At that point it is not safe to send a remote
    297      interrupt packet, so we instead remember we saw the Ctrl-C and
    298      process it once we're done with sending/receiving the current
    299      packet, which should be shortly.  If however that takes too long,
    300      and the user presses Ctrl-C again, we offer to disconnect.  */
    301   bool got_ctrlc_during_io = false;
    302 
    303   /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
    304      remote_open knows that we don't have a file open when the program
    305      starts.  */
    306   struct serial *remote_desc = nullptr;
    307 
    308   /* These are the threads which we last sent to the remote system.  The
    309      TID member will be -1 for all or -2 for not sent yet.  */
    310   ptid_t general_thread = null_ptid;
    311   ptid_t continue_thread = null_ptid;
    312 
    313   /* This is the traceframe which we last selected on the remote system.
    314      It will be -1 if no traceframe is selected.  */
    315   int remote_traceframe_number = -1;
    316 
    317   char *last_pass_packet = nullptr;
    318 
    319   /* The last QProgramSignals packet sent to the target.  We bypass
    320      sending a new program signals list down to the target if the new
    321      packet is exactly the same as the last we sent.  IOW, we only let
    322      the target know about program signals list changes.  */
    323   char *last_program_signals_packet = nullptr;
    324 
    325   gdb_signal last_sent_signal = GDB_SIGNAL_0;
    326 
    327   bool last_sent_step = false;
    328 
    329   /* The execution direction of the last resume we got.  */
    330   exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
    331 
    332   char *finished_object = nullptr;
    333   char *finished_annex = nullptr;
    334   ULONGEST finished_offset = 0;
    335 
    336   /* Should we try the 'ThreadInfo' query packet?
    337 
    338      This variable (NOT available to the user: auto-detect only!)
    339      determines whether GDB will use the new, simpler "ThreadInfo"
    340      query or the older, more complex syntax for thread queries.
    341      This is an auto-detect variable (set to true at each connect,
    342      and set to false when the target fails to recognize it).  */
    343   bool use_threadinfo_query = false;
    344   bool use_threadextra_query = false;
    345 
    346   threadref echo_nextthread {};
    347   threadref nextthread {};
    348   threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
    349 
    350   /* The state of remote notification.  */
    351   struct remote_notif_state *notif_state = nullptr;
    352 
    353   /* The branch trace configuration.  */
    354   struct btrace_config btrace_config {};
    355 
    356   /* The argument to the last "vFile:setfs:" packet we sent, used
    357      to avoid sending repeated unnecessary "vFile:setfs:" packets.
    358      Initialized to -1 to indicate that no "vFile:setfs:" packet
    359      has yet been sent.  */
    360   int fs_pid = -1;
    361 
    362   /* A readahead cache for vFile:pread.  Often, reading a binary
    363      involves a sequence of small reads.  E.g., when parsing an ELF
    364      file.  A readahead cache helps mostly the case of remote
    365      debugging on a connection with higher latency, due to the
    366      request/reply nature of the RSP.  We only cache data for a single
    367      file descriptor at a time.  */
    368   struct readahead_cache readahead_cache;
    369 
    370   /* The list of already fetched and acknowledged stop events.  This
    371      queue is used for notification Stop, and other notifications
    372      don't need queue for their events, because the notification
    373      events of Stop can't be consumed immediately, so that events
    374      should be queued first, and be consumed by remote_wait_{ns,as}
    375      one per time.  Other notifications can consume their events
    376      immediately, so queue is not needed for them.  */
    377   std::vector<stop_reply_up> stop_reply_queue;
    378 
    379   /* Asynchronous signal handle registered as event loop source for
    380      when we have pending events ready to be passed to the core.  */
    381   struct async_event_handler *remote_async_inferior_event_token = nullptr;
    382 
    383   /* FIXME: cagney/1999-09-23: Even though getpkt was called with
    384      ``forever'' still use the normal timeout mechanism.  This is
    385      currently used by the ASYNC code to guarentee that target reads
    386      during the initial connect always time-out.  Once getpkt has been
    387      modified to return a timeout indication and, in turn
    388      remote_wait()/wait_for_inferior() have gained a timeout parameter
    389      this can go away.  */
    390   int wait_forever_enabled_p = 1;
    391 
    392 private:
    393   /* Mapping of remote protocol data for each gdbarch.  Usually there
    394      is only one entry here, though we may see more with stubs that
    395      support multi-process.  */
    396   std::unordered_map<struct gdbarch *, remote_arch_state>
    397     m_arch_states;
    398 };
    399 
    400 static const target_info remote_target_info = {
    401   "remote",
    402   N_("Remote serial target in gdb-specific protocol"),
    403   remote_doc
    404 };
    405 
    406 class remote_target : public process_stratum_target
    407 {
    408 public:
    409   remote_target () = default;
    410   ~remote_target () override;
    411 
    412   const target_info &info () const override
    413   { return remote_target_info; }
    414 
    415   thread_control_capabilities get_thread_control_capabilities () override
    416   { return tc_schedlock; }
    417 
    418   /* Open a remote connection.  */
    419   static void open (const char *, int);
    420 
    421   void close () override;
    422 
    423   void detach (inferior *, int) override;
    424   void disconnect (const char *, int) override;
    425 
    426   void commit_resume () override;
    427   void resume (ptid_t, int, enum gdb_signal) override;
    428   ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
    429 
    430   void fetch_registers (struct regcache *, int) override;
    431   void store_registers (struct regcache *, int) override;
    432   void prepare_to_store (struct regcache *) override;
    433 
    434   void files_info () override;
    435 
    436   int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
    437 
    438   int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
    439 			 enum remove_bp_reason) override;
    440 
    441 
    442   bool stopped_by_sw_breakpoint () override;
    443   bool supports_stopped_by_sw_breakpoint () override;
    444 
    445   bool stopped_by_hw_breakpoint () override;
    446 
    447   bool supports_stopped_by_hw_breakpoint () override;
    448 
    449   bool stopped_by_watchpoint () override;
    450 
    451   bool stopped_data_address (CORE_ADDR *) override;
    452 
    453   bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
    454 
    455   int can_use_hw_breakpoint (enum bptype, int, int) override;
    456 
    457   int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
    458 
    459   int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
    460 
    461   int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
    462 
    463   int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
    464 			 struct expression *) override;
    465 
    466   int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
    467 			 struct expression *) override;
    468 
    469   void kill () override;
    470 
    471   void load (const char *, int) override;
    472 
    473   void mourn_inferior () override;
    474 
    475   void pass_signals (gdb::array_view<const unsigned char>) override;
    476 
    477   int set_syscall_catchpoint (int, bool, int,
    478 			      gdb::array_view<const int>) override;
    479 
    480   void program_signals (gdb::array_view<const unsigned char>) override;
    481 
    482   bool thread_alive (ptid_t ptid) override;
    483 
    484   const char *thread_name (struct thread_info *) override;
    485 
    486   void update_thread_list () override;
    487 
    488   const char *pid_to_str (ptid_t) override;
    489 
    490   const char *extra_thread_info (struct thread_info *) override;
    491 
    492   ptid_t get_ada_task_ptid (long lwp, long thread) override;
    493 
    494   thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
    495 					     int handle_len,
    496 					     inferior *inf) override;
    497 
    498   void stop (ptid_t) override;
    499 
    500   void interrupt () override;
    501 
    502   void pass_ctrlc () override;
    503 
    504   enum target_xfer_status xfer_partial (enum target_object object,
    505 					const char *annex,
    506 					gdb_byte *readbuf,
    507 					const gdb_byte *writebuf,
    508 					ULONGEST offset, ULONGEST len,
    509 					ULONGEST *xfered_len) override;
    510 
    511   ULONGEST get_memory_xfer_limit () override;
    512 
    513   void rcmd (const char *command, struct ui_file *output) override;
    514 
    515   char *pid_to_exec_file (int pid) override;
    516 
    517   void log_command (const char *cmd) override
    518   {
    519     serial_log_command (this, cmd);
    520   }
    521 
    522   CORE_ADDR get_thread_local_address (ptid_t ptid,
    523 				      CORE_ADDR load_module_addr,
    524 				      CORE_ADDR offset) override;
    525 
    526   bool can_execute_reverse () override;
    527 
    528   std::vector<mem_region> memory_map () override;
    529 
    530   void flash_erase (ULONGEST address, LONGEST length) override;
    531 
    532   void flash_done () override;
    533 
    534   const struct target_desc *read_description () override;
    535 
    536   int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
    537 		     const gdb_byte *pattern, ULONGEST pattern_len,
    538 		     CORE_ADDR *found_addrp) override;
    539 
    540   bool can_async_p () override;
    541 
    542   bool is_async_p () override;
    543 
    544   void async (int) override;
    545 
    546   void thread_events (int) override;
    547 
    548   int can_do_single_step () override;
    549 
    550   void terminal_inferior () override;
    551 
    552   void terminal_ours () override;
    553 
    554   bool supports_non_stop () override;
    555 
    556   bool supports_multi_process () override;
    557 
    558   bool supports_disable_randomization () override;
    559 
    560   bool filesystem_is_local () override;
    561 
    562 
    563   int fileio_open (struct inferior *inf, const char *filename,
    564 		   int flags, int mode, int warn_if_slow,
    565 		   int *target_errno) override;
    566 
    567   int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
    568 		     ULONGEST offset, int *target_errno) override;
    569 
    570   int fileio_pread (int fd, gdb_byte *read_buf, int len,
    571 		    ULONGEST offset, int *target_errno) override;
    572 
    573   int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
    574 
    575   int fileio_close (int fd, int *target_errno) override;
    576 
    577   int fileio_unlink (struct inferior *inf,
    578 		     const char *filename,
    579 		     int *target_errno) override;
    580 
    581   gdb::optional<std::string>
    582     fileio_readlink (struct inferior *inf,
    583 		     const char *filename,
    584 		     int *target_errno) override;
    585 
    586   bool supports_enable_disable_tracepoint () override;
    587 
    588   bool supports_string_tracing () override;
    589 
    590   bool supports_evaluation_of_breakpoint_conditions () override;
    591 
    592   bool can_run_breakpoint_commands () override;
    593 
    594   void trace_init () override;
    595 
    596   void download_tracepoint (struct bp_location *location) override;
    597 
    598   bool can_download_tracepoint () override;
    599 
    600   void download_trace_state_variable (const trace_state_variable &tsv) override;
    601 
    602   void enable_tracepoint (struct bp_location *location) override;
    603 
    604   void disable_tracepoint (struct bp_location *location) override;
    605 
    606   void trace_set_readonly_regions () override;
    607 
    608   void trace_start () override;
    609 
    610   int get_trace_status (struct trace_status *ts) override;
    611 
    612   void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
    613     override;
    614 
    615   void trace_stop () override;
    616 
    617   int trace_find (enum trace_find_type type, int num,
    618 		  CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
    619 
    620   bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
    621 
    622   int save_trace_data (const char *filename) override;
    623 
    624   int upload_tracepoints (struct uploaded_tp **utpp) override;
    625 
    626   int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
    627 
    628   LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
    629 
    630   int get_min_fast_tracepoint_insn_len () override;
    631 
    632   void set_disconnected_tracing (int val) override;
    633 
    634   void set_circular_trace_buffer (int val) override;
    635 
    636   void set_trace_buffer_size (LONGEST val) override;
    637 
    638   bool set_trace_notes (const char *user, const char *notes,
    639 			const char *stopnotes) override;
    640 
    641   int core_of_thread (ptid_t ptid) override;
    642 
    643   int verify_memory (const gdb_byte *data,
    644 		     CORE_ADDR memaddr, ULONGEST size) override;
    645 
    646 
    647   bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
    648 
    649   void set_permissions () override;
    650 
    651   bool static_tracepoint_marker_at (CORE_ADDR,
    652 				    struct static_tracepoint_marker *marker)
    653     override;
    654 
    655   std::vector<static_tracepoint_marker>
    656     static_tracepoint_markers_by_strid (const char *id) override;
    657 
    658   traceframe_info_up traceframe_info () override;
    659 
    660   bool use_agent (bool use) override;
    661   bool can_use_agent () override;
    662 
    663   struct btrace_target_info *enable_btrace (ptid_t ptid,
    664 					    const struct btrace_config *conf) override;
    665 
    666   void disable_btrace (struct btrace_target_info *tinfo) override;
    667 
    668   void teardown_btrace (struct btrace_target_info *tinfo) override;
    669 
    670   enum btrace_error read_btrace (struct btrace_data *data,
    671 				 struct btrace_target_info *btinfo,
    672 				 enum btrace_read_type type) override;
    673 
    674   const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
    675   bool augmented_libraries_svr4_read () override;
    676   int follow_fork (int, int) override;
    677   void follow_exec (struct inferior *, char *) override;
    678   int insert_fork_catchpoint (int) override;
    679   int remove_fork_catchpoint (int) override;
    680   int insert_vfork_catchpoint (int) override;
    681   int remove_vfork_catchpoint (int) override;
    682   int insert_exec_catchpoint (int) override;
    683   int remove_exec_catchpoint (int) override;
    684   enum exec_direction_kind execution_direction () override;
    685 
    686 public: /* Remote specific methods.  */
    687 
    688   void remote_download_command_source (int num, ULONGEST addr,
    689 				       struct command_line *cmds);
    690 
    691   void remote_file_put (const char *local_file, const char *remote_file,
    692 			int from_tty);
    693   void remote_file_get (const char *remote_file, const char *local_file,
    694 			int from_tty);
    695   void remote_file_delete (const char *remote_file, int from_tty);
    696 
    697   int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
    698 			   ULONGEST offset, int *remote_errno);
    699   int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
    700 			    ULONGEST offset, int *remote_errno);
    701   int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
    702 				 ULONGEST offset, int *remote_errno);
    703 
    704   int remote_hostio_send_command (int command_bytes, int which_packet,
    705 				  int *remote_errno, char **attachment,
    706 				  int *attachment_len);
    707   int remote_hostio_set_filesystem (struct inferior *inf,
    708 				    int *remote_errno);
    709   /* We should get rid of this and use fileio_open directly.  */
    710   int remote_hostio_open (struct inferior *inf, const char *filename,
    711 			  int flags, int mode, int warn_if_slow,
    712 			  int *remote_errno);
    713   int remote_hostio_close (int fd, int *remote_errno);
    714 
    715   int remote_hostio_unlink (inferior *inf, const char *filename,
    716 			    int *remote_errno);
    717 
    718   struct remote_state *get_remote_state ();
    719 
    720   long get_remote_packet_size (void);
    721   long get_memory_packet_size (struct memory_packet_config *config);
    722 
    723   long get_memory_write_packet_size ();
    724   long get_memory_read_packet_size ();
    725 
    726   char *append_pending_thread_resumptions (char *p, char *endp,
    727 					   ptid_t ptid);
    728   static void open_1 (const char *name, int from_tty, int extended_p);
    729   void start_remote (int from_tty, int extended_p);
    730   void remote_detach_1 (struct inferior *inf, int from_tty);
    731 
    732   char *append_resumption (char *p, char *endp,
    733 			   ptid_t ptid, int step, gdb_signal siggnal);
    734   int remote_resume_with_vcont (ptid_t ptid, int step,
    735 				gdb_signal siggnal);
    736 
    737   void add_current_inferior_and_thread (char *wait_status);
    738 
    739   ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
    740 		  int options);
    741   ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
    742 		  int options);
    743 
    744   ptid_t process_stop_reply (struct stop_reply *stop_reply,
    745 			     target_waitstatus *status);
    746 
    747   void remote_notice_new_inferior (ptid_t currthread, int executing);
    748 
    749   void process_initial_stop_replies (int from_tty);
    750 
    751   thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing);
    752 
    753   void btrace_sync_conf (const btrace_config *conf);
    754 
    755   void remote_btrace_maybe_reopen ();
    756 
    757   void remove_new_fork_children (threads_listing_context *context);
    758   void kill_new_fork_children (int pid);
    759   void discard_pending_stop_replies (struct inferior *inf);
    760   int stop_reply_queue_length ();
    761 
    762   void check_pending_events_prevent_wildcard_vcont
    763     (int *may_global_wildcard_vcont);
    764 
    765   void discard_pending_stop_replies_in_queue ();
    766   struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
    767   struct stop_reply *queued_stop_reply (ptid_t ptid);
    768   int peek_stop_reply (ptid_t ptid);
    769   void remote_parse_stop_reply (const char *buf, stop_reply *event);
    770 
    771   void remote_stop_ns (ptid_t ptid);
    772   void remote_interrupt_as ();
    773   void remote_interrupt_ns ();
    774 
    775   char *remote_get_noisy_reply ();
    776   int remote_query_attached (int pid);
    777   inferior *remote_add_inferior (int fake_pid_p, int pid, int attached,
    778 				 int try_open_exec);
    779 
    780   ptid_t remote_current_thread (ptid_t oldpid);
    781   ptid_t get_current_thread (char *wait_status);
    782 
    783   void set_thread (ptid_t ptid, int gen);
    784   void set_general_thread (ptid_t ptid);
    785   void set_continue_thread (ptid_t ptid);
    786   void set_general_process ();
    787 
    788   char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
    789 
    790   int remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
    791 					  gdb_ext_thread_info *info);
    792   int remote_get_threadinfo (threadref *threadid, int fieldset,
    793 			     gdb_ext_thread_info *info);
    794 
    795   int parse_threadlist_response (char *pkt, int result_limit,
    796 				 threadref *original_echo,
    797 				 threadref *resultlist,
    798 				 int *doneflag);
    799   int remote_get_threadlist (int startflag, threadref *nextthread,
    800 			     int result_limit, int *done, int *result_count,
    801 			     threadref *threadlist);
    802 
    803   int remote_threadlist_iterator (rmt_thread_action stepfunction,
    804 				  void *context, int looplimit);
    805 
    806   int remote_get_threads_with_ql (threads_listing_context *context);
    807   int remote_get_threads_with_qxfer (threads_listing_context *context);
    808   int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
    809 
    810   void extended_remote_restart ();
    811 
    812   void get_offsets ();
    813 
    814   void remote_check_symbols ();
    815 
    816   void remote_supported_packet (const struct protocol_feature *feature,
    817 				enum packet_support support,
    818 				const char *argument);
    819 
    820   void remote_query_supported ();
    821 
    822   void remote_packet_size (const protocol_feature *feature,
    823 			   packet_support support, const char *value);
    824 
    825   void remote_serial_quit_handler ();
    826 
    827   void remote_detach_pid (int pid);
    828 
    829   void remote_vcont_probe ();
    830 
    831   void remote_resume_with_hc (ptid_t ptid, int step,
    832 			      gdb_signal siggnal);
    833 
    834   void send_interrupt_sequence ();
    835   void interrupt_query ();
    836 
    837   void remote_notif_get_pending_events (notif_client *nc);
    838 
    839   int fetch_register_using_p (struct regcache *regcache,
    840 			      packet_reg *reg);
    841   int send_g_packet ();
    842   void process_g_packet (struct regcache *regcache);
    843   void fetch_registers_using_g (struct regcache *regcache);
    844   int store_register_using_P (const struct regcache *regcache,
    845 			      packet_reg *reg);
    846   void store_registers_using_G (const struct regcache *regcache);
    847 
    848   void set_remote_traceframe ();
    849 
    850   void check_binary_download (CORE_ADDR addr);
    851 
    852   target_xfer_status remote_write_bytes_aux (const char *header,
    853 					     CORE_ADDR memaddr,
    854 					     const gdb_byte *myaddr,
    855 					     ULONGEST len_units,
    856 					     int unit_size,
    857 					     ULONGEST *xfered_len_units,
    858 					     char packet_format,
    859 					     int use_length);
    860 
    861   target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
    862 					 const gdb_byte *myaddr, ULONGEST len,
    863 					 int unit_size, ULONGEST *xfered_len);
    864 
    865   target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
    866 					  ULONGEST len_units,
    867 					  int unit_size, ULONGEST *xfered_len_units);
    868 
    869   target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
    870 							ULONGEST memaddr,
    871 							ULONGEST len,
    872 							int unit_size,
    873 							ULONGEST *xfered_len);
    874 
    875   target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
    876 					gdb_byte *myaddr, ULONGEST len,
    877 					int unit_size,
    878 					ULONGEST *xfered_len);
    879 
    880   packet_result remote_send_printf (const char *format, ...)
    881     ATTRIBUTE_PRINTF (2, 3);
    882 
    883   target_xfer_status remote_flash_write (ULONGEST address,
    884 					 ULONGEST length, ULONGEST *xfered_len,
    885 					 const gdb_byte *data);
    886 
    887   int readchar (int timeout);
    888 
    889   void remote_serial_write (const char *str, int len);
    890 
    891   int putpkt (const char *buf);
    892   int putpkt_binary (const char *buf, int cnt);
    893 
    894   int putpkt (const gdb::char_vector &buf)
    895   {
    896     return putpkt (buf.data ());
    897   }
    898 
    899   void skip_frame ();
    900   long read_frame (gdb::char_vector *buf_p);
    901   void getpkt (gdb::char_vector *buf, int forever);
    902   int getpkt_or_notif_sane_1 (gdb::char_vector *buf, int forever,
    903 			      int expecting_notif, int *is_notif);
    904   int getpkt_sane (gdb::char_vector *buf, int forever);
    905   int getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
    906 			    int *is_notif);
    907   int remote_vkill (int pid);
    908   void remote_kill_k ();
    909 
    910   void extended_remote_disable_randomization (int val);
    911   int extended_remote_run (const std::string &args);
    912 
    913   void send_environment_packet (const char *action,
    914 				const char *packet,
    915 				const char *value);
    916 
    917   void extended_remote_environment_support ();
    918   void extended_remote_set_inferior_cwd ();
    919 
    920   target_xfer_status remote_write_qxfer (const char *object_name,
    921 					 const char *annex,
    922 					 const gdb_byte *writebuf,
    923 					 ULONGEST offset, LONGEST len,
    924 					 ULONGEST *xfered_len,
    925 					 struct packet_config *packet);
    926 
    927   target_xfer_status remote_read_qxfer (const char *object_name,
    928 					const char *annex,
    929 					gdb_byte *readbuf, ULONGEST offset,
    930 					LONGEST len,
    931 					ULONGEST *xfered_len,
    932 					struct packet_config *packet);
    933 
    934   void push_stop_reply (struct stop_reply *new_event);
    935 
    936   bool vcont_r_supported ();
    937 
    938   void packet_command (const char *args, int from_tty);
    939 
    940 private: /* data fields */
    941 
    942   /* The remote state.  Don't reference this directly.  Use the
    943      get_remote_state method instead.  */
    944   remote_state m_remote_state;
    945 };
    946 
    947 static const target_info extended_remote_target_info = {
    948   "extended-remote",
    949   N_("Extended remote serial target in gdb-specific protocol"),
    950   remote_doc
    951 };
    952 
    953 /* Set up the extended remote target by extending the standard remote
    954    target and adding to it.  */
    955 
    956 class extended_remote_target final : public remote_target
    957 {
    958 public:
    959   const target_info &info () const override
    960   { return extended_remote_target_info; }
    961 
    962   /* Open an extended-remote connection.  */
    963   static void open (const char *, int);
    964 
    965   bool can_create_inferior () override { return true; }
    966   void create_inferior (const char *, const std::string &,
    967 			char **, int) override;
    968 
    969   void detach (inferior *, int) override;
    970 
    971   bool can_attach () override { return true; }
    972   void attach (const char *, int) override;
    973 
    974   void post_attach (int) override;
    975   bool supports_disable_randomization () override;
    976 };
    977 
    978 /* Per-program-space data key.  */
    979 static const struct program_space_data *remote_pspace_data;
    980 
    981 /* The variable registered as the control variable used by the
    982    remote exec-file commands.  While the remote exec-file setting is
    983    per-program-space, the set/show machinery uses this as the
    984    location of the remote exec-file value.  */
    985 static char *remote_exec_file_var;
    986 
    987 /* The size to align memory write packets, when practical.  The protocol
    988    does not guarantee any alignment, and gdb will generate short
    989    writes and unaligned writes, but even as a best-effort attempt this
    990    can improve bulk transfers.  For instance, if a write is misaligned
    991    relative to the target's data bus, the stub may need to make an extra
    992    round trip fetching data from the target.  This doesn't make a
    993    huge difference, but it's easy to do, so we try to be helpful.
    994 
    995    The alignment chosen is arbitrary; usually data bus width is
    996    important here, not the possibly larger cache line size.  */
    997 enum { REMOTE_ALIGN_WRITES = 16 };
    998 
    999 /* Prototypes for local functions.  */
   1000 
   1001 static int hexnumlen (ULONGEST num);
   1002 
   1003 static int stubhex (int ch);
   1004 
   1005 static int hexnumstr (char *, ULONGEST);
   1006 
   1007 static int hexnumnstr (char *, ULONGEST, int);
   1008 
   1009 static CORE_ADDR remote_address_masked (CORE_ADDR);
   1010 
   1011 static void print_packet (const char *);
   1012 
   1013 static int stub_unpack_int (char *buff, int fieldlength);
   1014 
   1015 struct packet_config;
   1016 
   1017 static void show_packet_config_cmd (struct packet_config *config);
   1018 
   1019 static void show_remote_protocol_packet_cmd (struct ui_file *file,
   1020 					     int from_tty,
   1021 					     struct cmd_list_element *c,
   1022 					     const char *value);
   1023 
   1024 static ptid_t read_ptid (const char *buf, const char **obuf);
   1025 
   1026 static void remote_async_inferior_event_handler (gdb_client_data);
   1027 
   1028 static bool remote_read_description_p (struct target_ops *target);
   1029 
   1030 static void remote_console_output (const char *msg);
   1031 
   1032 static void remote_btrace_reset (remote_state *rs);
   1033 
   1034 static void remote_unpush_and_throw (void);
   1035 
   1036 /* For "remote".  */
   1037 
   1038 static struct cmd_list_element *remote_cmdlist;
   1039 
   1040 /* For "set remote" and "show remote".  */
   1041 
   1042 static struct cmd_list_element *remote_set_cmdlist;
   1043 static struct cmd_list_element *remote_show_cmdlist;
   1044 
   1045 /* Controls whether GDB is willing to use range stepping.  */
   1046 
   1047 static int use_range_stepping = 1;
   1048 
   1049 /* The max number of chars in debug output.  The rest of chars are
   1050    omitted.  */
   1051 
   1052 #define REMOTE_DEBUG_MAX_CHAR 512
   1053 
   1054 /* Private data that we'll store in (struct thread_info)->priv.  */
   1055 struct remote_thread_info : public private_thread_info
   1056 {
   1057   std::string extra;
   1058   std::string name;
   1059   int core = -1;
   1060 
   1061   /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
   1062      sequence of bytes.  */
   1063   gdb::byte_vector thread_handle;
   1064 
   1065   /* Whether the target stopped for a breakpoint/watchpoint.  */
   1066   enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
   1067 
   1068   /* This is set to the data address of the access causing the target
   1069      to stop for a watchpoint.  */
   1070   CORE_ADDR watch_data_address = 0;
   1071 
   1072   /* Fields used by the vCont action coalescing implemented in
   1073      remote_resume / remote_commit_resume.  remote_resume stores each
   1074      thread's last resume request in these fields, so that a later
   1075      remote_commit_resume knows which is the proper action for this
   1076      thread to include in the vCont packet.  */
   1077 
   1078   /* True if the last target_resume call for this thread was a step
   1079      request, false if a continue request.  */
   1080   int last_resume_step = 0;
   1081 
   1082   /* The signal specified in the last target_resume call for this
   1083      thread.  */
   1084   gdb_signal last_resume_sig = GDB_SIGNAL_0;
   1085 
   1086   /* Whether this thread was already vCont-resumed on the remote
   1087      side.  */
   1088   int vcont_resumed = 0;
   1089 };
   1090 
   1091 remote_state::remote_state ()
   1092   : buf (400)
   1093 {
   1094 }
   1095 
   1096 remote_state::~remote_state ()
   1097 {
   1098   xfree (this->last_pass_packet);
   1099   xfree (this->last_program_signals_packet);
   1100   xfree (this->finished_object);
   1101   xfree (this->finished_annex);
   1102 }
   1103 
   1104 /* Utility: generate error from an incoming stub packet.  */
   1105 static void
   1106 trace_error (char *buf)
   1107 {
   1108   if (*buf++ != 'E')
   1109     return;			/* not an error msg */
   1110   switch (*buf)
   1111     {
   1112     case '1':			/* malformed packet error */
   1113       if (*++buf == '0')	/*   general case: */
   1114 	error (_("remote.c: error in outgoing packet."));
   1115       else
   1116 	error (_("remote.c: error in outgoing packet at field #%ld."),
   1117 	       strtol (buf, NULL, 16));
   1118     default:
   1119       error (_("Target returns error code '%s'."), buf);
   1120     }
   1121 }
   1122 
   1123 /* Utility: wait for reply from stub, while accepting "O" packets.  */
   1124 
   1125 char *
   1126 remote_target::remote_get_noisy_reply ()
   1127 {
   1128   struct remote_state *rs = get_remote_state ();
   1129 
   1130   do				/* Loop on reply from remote stub.  */
   1131     {
   1132       char *buf;
   1133 
   1134       QUIT;			/* Allow user to bail out with ^C.  */
   1135       getpkt (&rs->buf, 0);
   1136       buf = rs->buf.data ();
   1137       if (buf[0] == 'E')
   1138 	trace_error (buf);
   1139       else if (startswith (buf, "qRelocInsn:"))
   1140 	{
   1141 	  ULONGEST ul;
   1142 	  CORE_ADDR from, to, org_to;
   1143 	  const char *p, *pp;
   1144 	  int adjusted_size = 0;
   1145 	  int relocated = 0;
   1146 
   1147 	  p = buf + strlen ("qRelocInsn:");
   1148 	  pp = unpack_varlen_hex (p, &ul);
   1149 	  if (*pp != ';')
   1150 	    error (_("invalid qRelocInsn packet: %s"), buf);
   1151 	  from = ul;
   1152 
   1153 	  p = pp + 1;
   1154 	  unpack_varlen_hex (p, &ul);
   1155 	  to = ul;
   1156 
   1157 	  org_to = to;
   1158 
   1159 	  TRY
   1160 	    {
   1161 	      gdbarch_relocate_instruction (target_gdbarch (), &to, from);
   1162 	      relocated = 1;
   1163 	    }
   1164 	  CATCH (ex, RETURN_MASK_ALL)
   1165 	    {
   1166 	      if (ex.error == MEMORY_ERROR)
   1167 		{
   1168 		  /* Propagate memory errors silently back to the
   1169 		     target.  The stub may have limited the range of
   1170 		     addresses we can write to, for example.  */
   1171 		}
   1172 	      else
   1173 		{
   1174 		  /* Something unexpectedly bad happened.  Be verbose
   1175 		     so we can tell what, and propagate the error back
   1176 		     to the stub, so it doesn't get stuck waiting for
   1177 		     a response.  */
   1178 		  exception_fprintf (gdb_stderr, ex,
   1179 				     _("warning: relocating instruction: "));
   1180 		}
   1181 	      putpkt ("E01");
   1182 	    }
   1183 	  END_CATCH
   1184 
   1185 	  if (relocated)
   1186 	    {
   1187 	      adjusted_size = to - org_to;
   1188 
   1189 	      xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
   1190 	      putpkt (buf);
   1191 	    }
   1192 	}
   1193       else if (buf[0] == 'O' && buf[1] != 'K')
   1194 	remote_console_output (buf + 1);	/* 'O' message from stub */
   1195       else
   1196 	return buf;		/* Here's the actual reply.  */
   1197     }
   1198   while (1);
   1199 }
   1200 
   1201 struct remote_arch_state *
   1202 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
   1203 {
   1204   remote_arch_state *rsa;
   1205 
   1206   auto it = this->m_arch_states.find (gdbarch);
   1207   if (it == this->m_arch_states.end ())
   1208     {
   1209       auto p = this->m_arch_states.emplace (std::piecewise_construct,
   1210 					    std::forward_as_tuple (gdbarch),
   1211 					    std::forward_as_tuple (gdbarch));
   1212       rsa = &p.first->second;
   1213 
   1214       /* Make sure that the packet buffer is plenty big enough for
   1215 	 this architecture.  */
   1216       if (this->buf.size () < rsa->remote_packet_size)
   1217 	this->buf.resize (2 * rsa->remote_packet_size);
   1218     }
   1219   else
   1220     rsa = &it->second;
   1221 
   1222   return rsa;
   1223 }
   1224 
   1225 /* Fetch the global remote target state.  */
   1226 
   1227 remote_state *
   1228 remote_target::get_remote_state ()
   1229 {
   1230   /* Make sure that the remote architecture state has been
   1231      initialized, because doing so might reallocate rs->buf.  Any
   1232      function which calls getpkt also needs to be mindful of changes
   1233      to rs->buf, but this call limits the number of places which run
   1234      into trouble.  */
   1235   m_remote_state.get_remote_arch_state (target_gdbarch ());
   1236 
   1237   return &m_remote_state;
   1238 }
   1239 
   1240 /* Cleanup routine for the remote module's pspace data.  */
   1241 
   1242 static void
   1243 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
   1244 {
   1245   char *remote_exec_file = (char *) arg;
   1246 
   1247   xfree (remote_exec_file);
   1248 }
   1249 
   1250 /* Fetch the remote exec-file from the current program space.  */
   1251 
   1252 static const char *
   1253 get_remote_exec_file (void)
   1254 {
   1255   char *remote_exec_file;
   1256 
   1257   remote_exec_file
   1258     = (char *) program_space_data (current_program_space,
   1259 				   remote_pspace_data);
   1260   if (remote_exec_file == NULL)
   1261     return "";
   1262 
   1263   return remote_exec_file;
   1264 }
   1265 
   1266 /* Set the remote exec file for PSPACE.  */
   1267 
   1268 static void
   1269 set_pspace_remote_exec_file (struct program_space *pspace,
   1270 			char *remote_exec_file)
   1271 {
   1272   char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
   1273 
   1274   xfree (old_file);
   1275   set_program_space_data (pspace, remote_pspace_data,
   1276 			  xstrdup (remote_exec_file));
   1277 }
   1278 
   1279 /* The "set/show remote exec-file" set command hook.  */
   1280 
   1281 static void
   1282 set_remote_exec_file (const char *ignored, int from_tty,
   1283 		      struct cmd_list_element *c)
   1284 {
   1285   gdb_assert (remote_exec_file_var != NULL);
   1286   set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
   1287 }
   1288 
   1289 /* The "set/show remote exec-file" show command hook.  */
   1290 
   1291 static void
   1292 show_remote_exec_file (struct ui_file *file, int from_tty,
   1293 		       struct cmd_list_element *cmd, const char *value)
   1294 {
   1295   fprintf_filtered (file, "%s\n", remote_exec_file_var);
   1296 }
   1297 
   1298 static int
   1299 compare_pnums (const void *lhs_, const void *rhs_)
   1300 {
   1301   const struct packet_reg * const *lhs
   1302     = (const struct packet_reg * const *) lhs_;
   1303   const struct packet_reg * const *rhs
   1304     = (const struct packet_reg * const *) rhs_;
   1305 
   1306   if ((*lhs)->pnum < (*rhs)->pnum)
   1307     return -1;
   1308   else if ((*lhs)->pnum == (*rhs)->pnum)
   1309     return 0;
   1310   else
   1311     return 1;
   1312 }
   1313 
   1314 static int
   1315 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
   1316 {
   1317   int regnum, num_remote_regs, offset;
   1318   struct packet_reg **remote_regs;
   1319 
   1320   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
   1321     {
   1322       struct packet_reg *r = &regs[regnum];
   1323 
   1324       if (register_size (gdbarch, regnum) == 0)
   1325 	/* Do not try to fetch zero-sized (placeholder) registers.  */
   1326 	r->pnum = -1;
   1327       else
   1328 	r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
   1329 
   1330       r->regnum = regnum;
   1331     }
   1332 
   1333   /* Define the g/G packet format as the contents of each register
   1334      with a remote protocol number, in order of ascending protocol
   1335      number.  */
   1336 
   1337   remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
   1338   for (num_remote_regs = 0, regnum = 0;
   1339        regnum < gdbarch_num_regs (gdbarch);
   1340        regnum++)
   1341     if (regs[regnum].pnum != -1)
   1342       remote_regs[num_remote_regs++] = &regs[regnum];
   1343 
   1344   qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
   1345 	 compare_pnums);
   1346 
   1347   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
   1348     {
   1349       remote_regs[regnum]->in_g_packet = 1;
   1350       remote_regs[regnum]->offset = offset;
   1351       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
   1352     }
   1353 
   1354   return offset;
   1355 }
   1356 
   1357 /* Given the architecture described by GDBARCH, return the remote
   1358    protocol register's number and the register's offset in the g/G
   1359    packets of GDB register REGNUM, in PNUM and POFFSET respectively.
   1360    If the target does not have a mapping for REGNUM, return false,
   1361    otherwise, return true.  */
   1362 
   1363 int
   1364 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
   1365 				   int *pnum, int *poffset)
   1366 {
   1367   gdb_assert (regnum < gdbarch_num_regs (gdbarch));
   1368 
   1369   std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
   1370 
   1371   map_regcache_remote_table (gdbarch, regs.data ());
   1372 
   1373   *pnum = regs[regnum].pnum;
   1374   *poffset = regs[regnum].offset;
   1375 
   1376   return *pnum != -1;
   1377 }
   1378 
   1379 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
   1380 {
   1381   /* Use the architecture to build a regnum<->pnum table, which will be
   1382      1:1 unless a feature set specifies otherwise.  */
   1383   this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
   1384 
   1385   /* Record the maximum possible size of the g packet - it may turn out
   1386      to be smaller.  */
   1387   this->sizeof_g_packet
   1388     = map_regcache_remote_table (gdbarch, this->regs.get ());
   1389 
   1390   /* Default maximum number of characters in a packet body.  Many
   1391      remote stubs have a hardwired buffer size of 400 bytes
   1392      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
   1393      as the maximum packet-size to ensure that the packet and an extra
   1394      NUL character can always fit in the buffer.  This stops GDB
   1395      trashing stubs that try to squeeze an extra NUL into what is
   1396      already a full buffer (As of 1999-12-04 that was most stubs).  */
   1397   this->remote_packet_size = 400 - 1;
   1398 
   1399   /* This one is filled in when a ``g'' packet is received.  */
   1400   this->actual_register_packet_size = 0;
   1401 
   1402   /* Should rsa->sizeof_g_packet needs more space than the
   1403      default, adjust the size accordingly.  Remember that each byte is
   1404      encoded as two characters.  32 is the overhead for the packet
   1405      header / footer.  NOTE: cagney/1999-10-26: I suspect that 8
   1406      (``$NN:G...#NN'') is a better guess, the below has been padded a
   1407      little.  */
   1408   if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
   1409     this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
   1410 }
   1411 
   1412 /* Get a pointer to the current remote target.  If not connected to a
   1413    remote target, return NULL.  */
   1414 
   1415 static remote_target *
   1416 get_current_remote_target ()
   1417 {
   1418   target_ops *proc_target = find_target_at (process_stratum);
   1419   return dynamic_cast<remote_target *> (proc_target);
   1420 }
   1421 
   1422 /* Return the current allowed size of a remote packet.  This is
   1423    inferred from the current architecture, and should be used to
   1424    limit the length of outgoing packets.  */
   1425 long
   1426 remote_target::get_remote_packet_size ()
   1427 {
   1428   struct remote_state *rs = get_remote_state ();
   1429   remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
   1430 
   1431   if (rs->explicit_packet_size)
   1432     return rs->explicit_packet_size;
   1433 
   1434   return rsa->remote_packet_size;
   1435 }
   1436 
   1437 static struct packet_reg *
   1438 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
   1439 			long regnum)
   1440 {
   1441   if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
   1442     return NULL;
   1443   else
   1444     {
   1445       struct packet_reg *r = &rsa->regs[regnum];
   1446 
   1447       gdb_assert (r->regnum == regnum);
   1448       return r;
   1449     }
   1450 }
   1451 
   1452 static struct packet_reg *
   1453 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
   1454 		      LONGEST pnum)
   1455 {
   1456   int i;
   1457 
   1458   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
   1459     {
   1460       struct packet_reg *r = &rsa->regs[i];
   1461 
   1462       if (r->pnum == pnum)
   1463 	return r;
   1464     }
   1465   return NULL;
   1466 }
   1467 
   1468 /* Allow the user to specify what sequence to send to the remote
   1469    when he requests a program interruption: Although ^C is usually
   1470    what remote systems expect (this is the default, here), it is
   1471    sometimes preferable to send a break.  On other systems such
   1472    as the Linux kernel, a break followed by g, which is Magic SysRq g
   1473    is required in order to interrupt the execution.  */
   1474 const char interrupt_sequence_control_c[] = "Ctrl-C";
   1475 const char interrupt_sequence_break[] = "BREAK";
   1476 const char interrupt_sequence_break_g[] = "BREAK-g";
   1477 static const char *const interrupt_sequence_modes[] =
   1478   {
   1479     interrupt_sequence_control_c,
   1480     interrupt_sequence_break,
   1481     interrupt_sequence_break_g,
   1482     NULL
   1483   };
   1484 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
   1485 
   1486 static void
   1487 show_interrupt_sequence (struct ui_file *file, int from_tty,
   1488 			 struct cmd_list_element *c,
   1489 			 const char *value)
   1490 {
   1491   if (interrupt_sequence_mode == interrupt_sequence_control_c)
   1492     fprintf_filtered (file,
   1493 		      _("Send the ASCII ETX character (Ctrl-c) "
   1494 			"to the remote target to interrupt the "
   1495 			"execution of the program.\n"));
   1496   else if (interrupt_sequence_mode == interrupt_sequence_break)
   1497     fprintf_filtered (file,
   1498 		      _("send a break signal to the remote target "
   1499 			"to interrupt the execution of the program.\n"));
   1500   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
   1501     fprintf_filtered (file,
   1502 		      _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
   1503 			"the remote target to interrupt the execution "
   1504 			"of Linux kernel.\n"));
   1505   else
   1506     internal_error (__FILE__, __LINE__,
   1507 		    _("Invalid value for interrupt_sequence_mode: %s."),
   1508 		    interrupt_sequence_mode);
   1509 }
   1510 
   1511 /* This boolean variable specifies whether interrupt_sequence is sent
   1512    to the remote target when gdb connects to it.
   1513    This is mostly needed when you debug the Linux kernel: The Linux kernel
   1514    expects BREAK g which is Magic SysRq g for connecting gdb.  */
   1515 static int interrupt_on_connect = 0;
   1516 
   1517 /* This variable is used to implement the "set/show remotebreak" commands.
   1518    Since these commands are now deprecated in favor of "set/show remote
   1519    interrupt-sequence", it no longer has any effect on the code.  */
   1520 static int remote_break;
   1521 
   1522 static void
   1523 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
   1524 {
   1525   if (remote_break)
   1526     interrupt_sequence_mode = interrupt_sequence_break;
   1527   else
   1528     interrupt_sequence_mode = interrupt_sequence_control_c;
   1529 }
   1530 
   1531 static void
   1532 show_remotebreak (struct ui_file *file, int from_tty,
   1533 		  struct cmd_list_element *c,
   1534 		  const char *value)
   1535 {
   1536 }
   1537 
   1538 /* This variable sets the number of bits in an address that are to be
   1539    sent in a memory ("M" or "m") packet.  Normally, after stripping
   1540    leading zeros, the entire address would be sent.  This variable
   1541    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
   1542    initial implementation of remote.c restricted the address sent in
   1543    memory packets to ``host::sizeof long'' bytes - (typically 32
   1544    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
   1545    address was never sent.  Since fixing this bug may cause a break in
   1546    some remote targets this variable is principly provided to
   1547    facilitate backward compatibility.  */
   1548 
   1549 static unsigned int remote_address_size;
   1550 
   1551 
   1552 /* User configurable variables for the number of characters in a
   1554    memory read/write packet.  MIN (rsa->remote_packet_size,
   1555    rsa->sizeof_g_packet) is the default.  Some targets need smaller
   1556    values (fifo overruns, et.al.) and some users need larger values
   1557    (speed up transfers).  The variables ``preferred_*'' (the user
   1558    request), ``current_*'' (what was actually set) and ``forced_*''
   1559    (Positive - a soft limit, negative - a hard limit).  */
   1560 
   1561 struct memory_packet_config
   1562 {
   1563   const char *name;
   1564   long size;
   1565   int fixed_p;
   1566 };
   1567 
   1568 /* The default max memory-write-packet-size, when the setting is
   1569    "fixed".  The 16k is historical.  (It came from older GDB's using
   1570    alloca for buffers and the knowledge (folklore?) that some hosts
   1571    don't cope very well with large alloca calls.)  */
   1572 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
   1573 
   1574 /* The minimum remote packet size for memory transfers.  Ensures we
   1575    can write at least one byte.  */
   1576 #define MIN_MEMORY_PACKET_SIZE 20
   1577 
   1578 /* Get the memory packet size, assuming it is fixed.  */
   1579 
   1580 static long
   1581 get_fixed_memory_packet_size (struct memory_packet_config *config)
   1582 {
   1583   gdb_assert (config->fixed_p);
   1584 
   1585   if (config->size <= 0)
   1586     return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
   1587   else
   1588     return config->size;
   1589 }
   1590 
   1591 /* Compute the current size of a read/write packet.  Since this makes
   1592    use of ``actual_register_packet_size'' the computation is dynamic.  */
   1593 
   1594 long
   1595 remote_target::get_memory_packet_size (struct memory_packet_config *config)
   1596 {
   1597   struct remote_state *rs = get_remote_state ();
   1598   remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
   1599 
   1600   long what_they_get;
   1601   if (config->fixed_p)
   1602     what_they_get = get_fixed_memory_packet_size (config);
   1603   else
   1604     {
   1605       what_they_get = get_remote_packet_size ();
   1606       /* Limit the packet to the size specified by the user.  */
   1607       if (config->size > 0
   1608 	  && what_they_get > config->size)
   1609 	what_they_get = config->size;
   1610 
   1611       /* Limit it to the size of the targets ``g'' response unless we have
   1612 	 permission from the stub to use a larger packet size.  */
   1613       if (rs->explicit_packet_size == 0
   1614 	  && rsa->actual_register_packet_size > 0
   1615 	  && what_they_get > rsa->actual_register_packet_size)
   1616 	what_they_get = rsa->actual_register_packet_size;
   1617     }
   1618   if (what_they_get < MIN_MEMORY_PACKET_SIZE)
   1619     what_they_get = MIN_MEMORY_PACKET_SIZE;
   1620 
   1621   /* Make sure there is room in the global buffer for this packet
   1622      (including its trailing NUL byte).  */
   1623   if (rs->buf.size () < what_they_get + 1)
   1624     rs->buf.resize (2 * what_they_get);
   1625 
   1626   return what_they_get;
   1627 }
   1628 
   1629 /* Update the size of a read/write packet.  If they user wants
   1630    something really big then do a sanity check.  */
   1631 
   1632 static void
   1633 set_memory_packet_size (const char *args, struct memory_packet_config *config)
   1634 {
   1635   int fixed_p = config->fixed_p;
   1636   long size = config->size;
   1637 
   1638   if (args == NULL)
   1639     error (_("Argument required (integer, `fixed' or `limited')."));
   1640   else if (strcmp (args, "hard") == 0
   1641       || strcmp (args, "fixed") == 0)
   1642     fixed_p = 1;
   1643   else if (strcmp (args, "soft") == 0
   1644 	   || strcmp (args, "limit") == 0)
   1645     fixed_p = 0;
   1646   else
   1647     {
   1648       char *end;
   1649 
   1650       size = strtoul (args, &end, 0);
   1651       if (args == end)
   1652 	error (_("Invalid %s (bad syntax)."), config->name);
   1653 
   1654       /* Instead of explicitly capping the size of a packet to or
   1655 	 disallowing it, the user is allowed to set the size to
   1656 	 something arbitrarily large.  */
   1657     }
   1658 
   1659   /* Extra checks?  */
   1660   if (fixed_p && !config->fixed_p)
   1661     {
   1662       /* So that the query shows the correct value.  */
   1663       long query_size = (size <= 0
   1664 			 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
   1665 			 : size);
   1666 
   1667       if (! query (_("The target may not be able to correctly handle a %s\n"
   1668 		   "of %ld bytes. Change the packet size? "),
   1669 		   config->name, query_size))
   1670 	error (_("Packet size not changed."));
   1671     }
   1672   /* Update the config.  */
   1673   config->fixed_p = fixed_p;
   1674   config->size = size;
   1675 }
   1676 
   1677 static void
   1678 show_memory_packet_size (struct memory_packet_config *config)
   1679 {
   1680   if (config->size == 0)
   1681     printf_filtered (_("The %s is 0 (default). "), config->name);
   1682   else
   1683     printf_filtered (_("The %s is %ld. "), config->name, config->size);
   1684   if (config->fixed_p)
   1685     printf_filtered (_("Packets are fixed at %ld bytes.\n"),
   1686 		     get_fixed_memory_packet_size (config));
   1687   else
   1688     {
   1689       remote_target *remote = get_current_remote_target ();
   1690 
   1691       if (remote != NULL)
   1692 	printf_filtered (_("Packets are limited to %ld bytes.\n"),
   1693 			 remote->get_memory_packet_size (config));
   1694       else
   1695 	puts_filtered ("The actual limit will be further reduced "
   1696 		       "dependent on the target.\n");
   1697     }
   1698 }
   1699 
   1700 static struct memory_packet_config memory_write_packet_config =
   1701 {
   1702   "memory-write-packet-size",
   1703 };
   1704 
   1705 static void
   1706 set_memory_write_packet_size (const char *args, int from_tty)
   1707 {
   1708   set_memory_packet_size (args, &memory_write_packet_config);
   1709 }
   1710 
   1711 static void
   1712 show_memory_write_packet_size (const char *args, int from_tty)
   1713 {
   1714   show_memory_packet_size (&memory_write_packet_config);
   1715 }
   1716 
   1717 /* Show the number of hardware watchpoints that can be used.  */
   1718 
   1719 static void
   1720 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
   1721 				struct cmd_list_element *c,
   1722 				const char *value)
   1723 {
   1724   fprintf_filtered (file, _("The maximum number of target hardware "
   1725 			    "watchpoints is %s.\n"), value);
   1726 }
   1727 
   1728 /* Show the length limit (in bytes) for hardware watchpoints.  */
   1729 
   1730 static void
   1731 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
   1732 				       struct cmd_list_element *c,
   1733 				       const char *value)
   1734 {
   1735   fprintf_filtered (file, _("The maximum length (in bytes) of a target "
   1736 			    "hardware watchpoint is %s.\n"), value);
   1737 }
   1738 
   1739 /* Show the number of hardware breakpoints that can be used.  */
   1740 
   1741 static void
   1742 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
   1743 				struct cmd_list_element *c,
   1744 				const char *value)
   1745 {
   1746   fprintf_filtered (file, _("The maximum number of target hardware "
   1747 			    "breakpoints is %s.\n"), value);
   1748 }
   1749 
   1750 long
   1751 remote_target::get_memory_write_packet_size ()
   1752 {
   1753   return get_memory_packet_size (&memory_write_packet_config);
   1754 }
   1755 
   1756 static struct memory_packet_config memory_read_packet_config =
   1757 {
   1758   "memory-read-packet-size",
   1759 };
   1760 
   1761 static void
   1762 set_memory_read_packet_size (const char *args, int from_tty)
   1763 {
   1764   set_memory_packet_size (args, &memory_read_packet_config);
   1765 }
   1766 
   1767 static void
   1768 show_memory_read_packet_size (const char *args, int from_tty)
   1769 {
   1770   show_memory_packet_size (&memory_read_packet_config);
   1771 }
   1772 
   1773 long
   1774 remote_target::get_memory_read_packet_size ()
   1775 {
   1776   long size = get_memory_packet_size (&memory_read_packet_config);
   1777 
   1778   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
   1779      extra buffer size argument before the memory read size can be
   1780      increased beyond this.  */
   1781   if (size > get_remote_packet_size ())
   1782     size = get_remote_packet_size ();
   1783   return size;
   1784 }
   1785 
   1786 
   1787 
   1789 struct packet_config
   1790   {
   1791     const char *name;
   1792     const char *title;
   1793 
   1794     /* If auto, GDB auto-detects support for this packet or feature,
   1795        either through qSupported, or by trying the packet and looking
   1796        at the response.  If true, GDB assumes the target supports this
   1797        packet.  If false, the packet is disabled.  Configs that don't
   1798        have an associated command always have this set to auto.  */
   1799     enum auto_boolean detect;
   1800 
   1801     /* Does the target support this packet?  */
   1802     enum packet_support support;
   1803   };
   1804 
   1805 static enum packet_support packet_config_support (struct packet_config *config);
   1806 static enum packet_support packet_support (int packet);
   1807 
   1808 static void
   1809 show_packet_config_cmd (struct packet_config *config)
   1810 {
   1811   const char *support = "internal-error";
   1812 
   1813   switch (packet_config_support (config))
   1814     {
   1815     case PACKET_ENABLE:
   1816       support = "enabled";
   1817       break;
   1818     case PACKET_DISABLE:
   1819       support = "disabled";
   1820       break;
   1821     case PACKET_SUPPORT_UNKNOWN:
   1822       support = "unknown";
   1823       break;
   1824     }
   1825   switch (config->detect)
   1826     {
   1827     case AUTO_BOOLEAN_AUTO:
   1828       printf_filtered (_("Support for the `%s' packet "
   1829 			 "is auto-detected, currently %s.\n"),
   1830 		       config->name, support);
   1831       break;
   1832     case AUTO_BOOLEAN_TRUE:
   1833     case AUTO_BOOLEAN_FALSE:
   1834       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
   1835 		       config->name, support);
   1836       break;
   1837     }
   1838 }
   1839 
   1840 static void
   1841 add_packet_config_cmd (struct packet_config *config, const char *name,
   1842 		       const char *title, int legacy)
   1843 {
   1844   char *set_doc;
   1845   char *show_doc;
   1846   char *cmd_name;
   1847 
   1848   config->name = name;
   1849   config->title = title;
   1850   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
   1851 			name, title);
   1852   show_doc = xstrprintf ("Show current use of remote "
   1853 			 "protocol `%s' (%s) packet",
   1854 			 name, title);
   1855   /* set/show TITLE-packet {auto,on,off} */
   1856   cmd_name = xstrprintf ("%s-packet", title);
   1857   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
   1858 				&config->detect, set_doc,
   1859 				show_doc, NULL, /* help_doc */
   1860 				NULL,
   1861 				show_remote_protocol_packet_cmd,
   1862 				&remote_set_cmdlist, &remote_show_cmdlist);
   1863   /* The command code copies the documentation strings.  */
   1864   xfree (set_doc);
   1865   xfree (show_doc);
   1866   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
   1867   if (legacy)
   1868     {
   1869       char *legacy_name;
   1870 
   1871       legacy_name = xstrprintf ("%s-packet", name);
   1872       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
   1873 		     &remote_set_cmdlist);
   1874       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
   1875 		     &remote_show_cmdlist);
   1876     }
   1877 }
   1878 
   1879 static enum packet_result
   1880 packet_check_result (const char *buf)
   1881 {
   1882   if (buf[0] != '\0')
   1883     {
   1884       /* The stub recognized the packet request.  Check that the
   1885 	 operation succeeded.  */
   1886       if (buf[0] == 'E'
   1887 	  && isxdigit (buf[1]) && isxdigit (buf[2])
   1888 	  && buf[3] == '\0')
   1889 	/* "Enn"  - definitly an error.  */
   1890 	return PACKET_ERROR;
   1891 
   1892       /* Always treat "E." as an error.  This will be used for
   1893 	 more verbose error messages, such as E.memtypes.  */
   1894       if (buf[0] == 'E' && buf[1] == '.')
   1895 	return PACKET_ERROR;
   1896 
   1897       /* The packet may or may not be OK.  Just assume it is.  */
   1898       return PACKET_OK;
   1899     }
   1900   else
   1901     /* The stub does not support the packet.  */
   1902     return PACKET_UNKNOWN;
   1903 }
   1904 
   1905 static enum packet_result
   1906 packet_check_result (const gdb::char_vector &buf)
   1907 {
   1908   return packet_check_result (buf.data ());
   1909 }
   1910 
   1911 static enum packet_result
   1912 packet_ok (const char *buf, struct packet_config *config)
   1913 {
   1914   enum packet_result result;
   1915 
   1916   if (config->detect != AUTO_BOOLEAN_TRUE
   1917       && config->support == PACKET_DISABLE)
   1918     internal_error (__FILE__, __LINE__,
   1919 		    _("packet_ok: attempt to use a disabled packet"));
   1920 
   1921   result = packet_check_result (buf);
   1922   switch (result)
   1923     {
   1924     case PACKET_OK:
   1925     case PACKET_ERROR:
   1926       /* The stub recognized the packet request.  */
   1927       if (config->support == PACKET_SUPPORT_UNKNOWN)
   1928 	{
   1929 	  if (remote_debug)
   1930 	    fprintf_unfiltered (gdb_stdlog,
   1931 				"Packet %s (%s) is supported\n",
   1932 				config->name, config->title);
   1933 	  config->support = PACKET_ENABLE;
   1934 	}
   1935       break;
   1936     case PACKET_UNKNOWN:
   1937       /* The stub does not support the packet.  */
   1938       if (config->detect == AUTO_BOOLEAN_AUTO
   1939 	  && config->support == PACKET_ENABLE)
   1940 	{
   1941 	  /* If the stub previously indicated that the packet was
   1942 	     supported then there is a protocol error.  */
   1943 	  error (_("Protocol error: %s (%s) conflicting enabled responses."),
   1944 		 config->name, config->title);
   1945 	}
   1946       else if (config->detect == AUTO_BOOLEAN_TRUE)
   1947 	{
   1948 	  /* The user set it wrong.  */
   1949 	  error (_("Enabled packet %s (%s) not recognized by stub"),
   1950 		 config->name, config->title);
   1951 	}
   1952 
   1953       if (remote_debug)
   1954 	fprintf_unfiltered (gdb_stdlog,
   1955 			    "Packet %s (%s) is NOT supported\n",
   1956 			    config->name, config->title);
   1957       config->support = PACKET_DISABLE;
   1958       break;
   1959     }
   1960 
   1961   return result;
   1962 }
   1963 
   1964 static enum packet_result
   1965 packet_ok (const gdb::char_vector &buf, struct packet_config *config)
   1966 {
   1967   return packet_ok (buf.data (), config);
   1968 }
   1969 
   1970 enum {
   1971   PACKET_vCont = 0,
   1972   PACKET_X,
   1973   PACKET_qSymbol,
   1974   PACKET_P,
   1975   PACKET_p,
   1976   PACKET_Z0,
   1977   PACKET_Z1,
   1978   PACKET_Z2,
   1979   PACKET_Z3,
   1980   PACKET_Z4,
   1981   PACKET_vFile_setfs,
   1982   PACKET_vFile_open,
   1983   PACKET_vFile_pread,
   1984   PACKET_vFile_pwrite,
   1985   PACKET_vFile_close,
   1986   PACKET_vFile_unlink,
   1987   PACKET_vFile_readlink,
   1988   PACKET_vFile_fstat,
   1989   PACKET_qXfer_auxv,
   1990   PACKET_qXfer_features,
   1991   PACKET_qXfer_exec_file,
   1992   PACKET_qXfer_libraries,
   1993   PACKET_qXfer_libraries_svr4,
   1994   PACKET_qXfer_memory_map,
   1995   PACKET_qXfer_spu_read,
   1996   PACKET_qXfer_spu_write,
   1997   PACKET_qXfer_osdata,
   1998   PACKET_qXfer_threads,
   1999   PACKET_qXfer_statictrace_read,
   2000   PACKET_qXfer_traceframe_info,
   2001   PACKET_qXfer_uib,
   2002   PACKET_qGetTIBAddr,
   2003   PACKET_qGetTLSAddr,
   2004   PACKET_qSupported,
   2005   PACKET_qTStatus,
   2006   PACKET_QPassSignals,
   2007   PACKET_QCatchSyscalls,
   2008   PACKET_QProgramSignals,
   2009   PACKET_QSetWorkingDir,
   2010   PACKET_QStartupWithShell,
   2011   PACKET_QEnvironmentHexEncoded,
   2012   PACKET_QEnvironmentReset,
   2013   PACKET_QEnvironmentUnset,
   2014   PACKET_qCRC,
   2015   PACKET_qSearch_memory,
   2016   PACKET_vAttach,
   2017   PACKET_vRun,
   2018   PACKET_QStartNoAckMode,
   2019   PACKET_vKill,
   2020   PACKET_qXfer_siginfo_read,
   2021   PACKET_qXfer_siginfo_write,
   2022   PACKET_qAttached,
   2023 
   2024   /* Support for conditional tracepoints.  */
   2025   PACKET_ConditionalTracepoints,
   2026 
   2027   /* Support for target-side breakpoint conditions.  */
   2028   PACKET_ConditionalBreakpoints,
   2029 
   2030   /* Support for target-side breakpoint commands.  */
   2031   PACKET_BreakpointCommands,
   2032 
   2033   /* Support for fast tracepoints.  */
   2034   PACKET_FastTracepoints,
   2035 
   2036   /* Support for static tracepoints.  */
   2037   PACKET_StaticTracepoints,
   2038 
   2039   /* Support for installing tracepoints while a trace experiment is
   2040      running.  */
   2041   PACKET_InstallInTrace,
   2042 
   2043   PACKET_bc,
   2044   PACKET_bs,
   2045   PACKET_TracepointSource,
   2046   PACKET_QAllow,
   2047   PACKET_qXfer_fdpic,
   2048   PACKET_QDisableRandomization,
   2049   PACKET_QAgent,
   2050   PACKET_QTBuffer_size,
   2051   PACKET_Qbtrace_off,
   2052   PACKET_Qbtrace_bts,
   2053   PACKET_Qbtrace_pt,
   2054   PACKET_qXfer_btrace,
   2055 
   2056   /* Support for the QNonStop packet.  */
   2057   PACKET_QNonStop,
   2058 
   2059   /* Support for the QThreadEvents packet.  */
   2060   PACKET_QThreadEvents,
   2061 
   2062   /* Support for multi-process extensions.  */
   2063   PACKET_multiprocess_feature,
   2064 
   2065   /* Support for enabling and disabling tracepoints while a trace
   2066      experiment is running.  */
   2067   PACKET_EnableDisableTracepoints_feature,
   2068 
   2069   /* Support for collecting strings using the tracenz bytecode.  */
   2070   PACKET_tracenz_feature,
   2071 
   2072   /* Support for continuing to run a trace experiment while GDB is
   2073      disconnected.  */
   2074   PACKET_DisconnectedTracing_feature,
   2075 
   2076   /* Support for qXfer:libraries-svr4:read with a non-empty annex.  */
   2077   PACKET_augmented_libraries_svr4_read_feature,
   2078 
   2079   /* Support for the qXfer:btrace-conf:read packet.  */
   2080   PACKET_qXfer_btrace_conf,
   2081 
   2082   /* Support for the Qbtrace-conf:bts:size packet.  */
   2083   PACKET_Qbtrace_conf_bts_size,
   2084 
   2085   /* Support for swbreak+ feature.  */
   2086   PACKET_swbreak_feature,
   2087 
   2088   /* Support for hwbreak+ feature.  */
   2089   PACKET_hwbreak_feature,
   2090 
   2091   /* Support for fork events.  */
   2092   PACKET_fork_event_feature,
   2093 
   2094   /* Support for vfork events.  */
   2095   PACKET_vfork_event_feature,
   2096 
   2097   /* Support for the Qbtrace-conf:pt:size packet.  */
   2098   PACKET_Qbtrace_conf_pt_size,
   2099 
   2100   /* Support for exec events.  */
   2101   PACKET_exec_event_feature,
   2102 
   2103   /* Support for query supported vCont actions.  */
   2104   PACKET_vContSupported,
   2105 
   2106   /* Support remote CTRL-C.  */
   2107   PACKET_vCtrlC,
   2108 
   2109   /* Support TARGET_WAITKIND_NO_RESUMED.  */
   2110   PACKET_no_resumed,
   2111 
   2112   PACKET_MAX
   2113 };
   2114 
   2115 static struct packet_config remote_protocol_packets[PACKET_MAX];
   2116 
   2117 /* Returns the packet's corresponding "set remote foo-packet" command
   2118    state.  See struct packet_config for more details.  */
   2119 
   2120 static enum auto_boolean
   2121 packet_set_cmd_state (int packet)
   2122 {
   2123   return remote_protocol_packets[packet].detect;
   2124 }
   2125 
   2126 /* Returns whether a given packet or feature is supported.  This takes
   2127    into account the state of the corresponding "set remote foo-packet"
   2128    command, which may be used to bypass auto-detection.  */
   2129 
   2130 static enum packet_support
   2131 packet_config_support (struct packet_config *config)
   2132 {
   2133   switch (config->detect)
   2134     {
   2135     case AUTO_BOOLEAN_TRUE:
   2136       return PACKET_ENABLE;
   2137     case AUTO_BOOLEAN_FALSE:
   2138       return PACKET_DISABLE;
   2139     case AUTO_BOOLEAN_AUTO:
   2140       return config->support;
   2141     default:
   2142       gdb_assert_not_reached (_("bad switch"));
   2143     }
   2144 }
   2145 
   2146 /* Same as packet_config_support, but takes the packet's enum value as
   2147    argument.  */
   2148 
   2149 static enum packet_support
   2150 packet_support (int packet)
   2151 {
   2152   struct packet_config *config = &remote_protocol_packets[packet];
   2153 
   2154   return packet_config_support (config);
   2155 }
   2156 
   2157 static void
   2158 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
   2159 				 struct cmd_list_element *c,
   2160 				 const char *value)
   2161 {
   2162   struct packet_config *packet;
   2163 
   2164   for (packet = remote_protocol_packets;
   2165        packet < &remote_protocol_packets[PACKET_MAX];
   2166        packet++)
   2167     {
   2168       if (&packet->detect == c->var)
   2169 	{
   2170 	  show_packet_config_cmd (packet);
   2171 	  return;
   2172 	}
   2173     }
   2174   internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
   2175 		  c->name);
   2176 }
   2177 
   2178 /* Should we try one of the 'Z' requests?  */
   2179 
   2180 enum Z_packet_type
   2181 {
   2182   Z_PACKET_SOFTWARE_BP,
   2183   Z_PACKET_HARDWARE_BP,
   2184   Z_PACKET_WRITE_WP,
   2185   Z_PACKET_READ_WP,
   2186   Z_PACKET_ACCESS_WP,
   2187   NR_Z_PACKET_TYPES
   2188 };
   2189 
   2190 /* For compatibility with older distributions.  Provide a ``set remote
   2191    Z-packet ...'' command that updates all the Z packet types.  */
   2192 
   2193 static enum auto_boolean remote_Z_packet_detect;
   2194 
   2195 static void
   2196 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
   2197 				  struct cmd_list_element *c)
   2198 {
   2199   int i;
   2200 
   2201   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
   2202     remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
   2203 }
   2204 
   2205 static void
   2206 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
   2207 				   struct cmd_list_element *c,
   2208 				   const char *value)
   2209 {
   2210   int i;
   2211 
   2212   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
   2213     {
   2214       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
   2215     }
   2216 }
   2217 
   2218 /* Returns true if the multi-process extensions are in effect.  */
   2219 
   2220 static int
   2221 remote_multi_process_p (struct remote_state *rs)
   2222 {
   2223   return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
   2224 }
   2225 
   2226 /* Returns true if fork events are supported.  */
   2227 
   2228 static int
   2229 remote_fork_event_p (struct remote_state *rs)
   2230 {
   2231   return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
   2232 }
   2233 
   2234 /* Returns true if vfork events are supported.  */
   2235 
   2236 static int
   2237 remote_vfork_event_p (struct remote_state *rs)
   2238 {
   2239   return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
   2240 }
   2241 
   2242 /* Returns true if exec events are supported.  */
   2243 
   2244 static int
   2245 remote_exec_event_p (struct remote_state *rs)
   2246 {
   2247   return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
   2248 }
   2249 
   2250 /* Insert fork catchpoint target routine.  If fork events are enabled
   2251    then return success, nothing more to do.  */
   2252 
   2253 int
   2254 remote_target::insert_fork_catchpoint (int pid)
   2255 {
   2256   struct remote_state *rs = get_remote_state ();
   2257 
   2258   return !remote_fork_event_p (rs);
   2259 }
   2260 
   2261 /* Remove fork catchpoint target routine.  Nothing to do, just
   2262    return success.  */
   2263 
   2264 int
   2265 remote_target::remove_fork_catchpoint (int pid)
   2266 {
   2267   return 0;
   2268 }
   2269 
   2270 /* Insert vfork catchpoint target routine.  If vfork events are enabled
   2271    then return success, nothing more to do.  */
   2272 
   2273 int
   2274 remote_target::insert_vfork_catchpoint (int pid)
   2275 {
   2276   struct remote_state *rs = get_remote_state ();
   2277 
   2278   return !remote_vfork_event_p (rs);
   2279 }
   2280 
   2281 /* Remove vfork catchpoint target routine.  Nothing to do, just
   2282    return success.  */
   2283 
   2284 int
   2285 remote_target::remove_vfork_catchpoint (int pid)
   2286 {
   2287   return 0;
   2288 }
   2289 
   2290 /* Insert exec catchpoint target routine.  If exec events are
   2291    enabled, just return success.  */
   2292 
   2293 int
   2294 remote_target::insert_exec_catchpoint (int pid)
   2295 {
   2296   struct remote_state *rs = get_remote_state ();
   2297 
   2298   return !remote_exec_event_p (rs);
   2299 }
   2300 
   2301 /* Remove exec catchpoint target routine.  Nothing to do, just
   2302    return success.  */
   2303 
   2304 int
   2305 remote_target::remove_exec_catchpoint (int pid)
   2306 {
   2307   return 0;
   2308 }
   2309 
   2310 
   2311 
   2313 static ptid_t magic_null_ptid;
   2314 static ptid_t not_sent_ptid;
   2315 static ptid_t any_thread_ptid;
   2316 
   2317 /* Find out if the stub attached to PID (and hence GDB should offer to
   2318    detach instead of killing it when bailing out).  */
   2319 
   2320 int
   2321 remote_target::remote_query_attached (int pid)
   2322 {
   2323   struct remote_state *rs = get_remote_state ();
   2324   size_t size = get_remote_packet_size ();
   2325 
   2326   if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
   2327     return 0;
   2328 
   2329   if (remote_multi_process_p (rs))
   2330     xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
   2331   else
   2332     xsnprintf (rs->buf.data (), size, "qAttached");
   2333 
   2334   putpkt (rs->buf);
   2335   getpkt (&rs->buf, 0);
   2336 
   2337   switch (packet_ok (rs->buf,
   2338 		     &remote_protocol_packets[PACKET_qAttached]))
   2339     {
   2340     case PACKET_OK:
   2341       if (strcmp (rs->buf.data (), "1") == 0)
   2342 	return 1;
   2343       break;
   2344     case PACKET_ERROR:
   2345       warning (_("Remote failure reply: %s"), rs->buf.data ());
   2346       break;
   2347     case PACKET_UNKNOWN:
   2348       break;
   2349     }
   2350 
   2351   return 0;
   2352 }
   2353 
   2354 /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
   2355    has been invented by GDB, instead of reported by the target.  Since
   2356    we can be connected to a remote system before before knowing about
   2357    any inferior, mark the target with execution when we find the first
   2358    inferior.  If ATTACHED is 1, then we had just attached to this
   2359    inferior.  If it is 0, then we just created this inferior.  If it
   2360    is -1, then try querying the remote stub to find out if it had
   2361    attached to the inferior or not.  If TRY_OPEN_EXEC is true then
   2362    attempt to open this inferior's executable as the main executable
   2363    if no main executable is open already.  */
   2364 
   2365 inferior *
   2366 remote_target::remote_add_inferior (int fake_pid_p, int pid, int attached,
   2367 				    int try_open_exec)
   2368 {
   2369   struct inferior *inf;
   2370 
   2371   /* Check whether this process we're learning about is to be
   2372      considered attached, or if is to be considered to have been
   2373      spawned by the stub.  */
   2374   if (attached == -1)
   2375     attached = remote_query_attached (pid);
   2376 
   2377   if (gdbarch_has_global_solist (target_gdbarch ()))
   2378     {
   2379       /* If the target shares code across all inferiors, then every
   2380 	 attach adds a new inferior.  */
   2381       inf = add_inferior (pid);
   2382 
   2383       /* ... and every inferior is bound to the same program space.
   2384 	 However, each inferior may still have its own address
   2385 	 space.  */
   2386       inf->aspace = maybe_new_address_space ();
   2387       inf->pspace = current_program_space;
   2388     }
   2389   else
   2390     {
   2391       /* In the traditional debugging scenario, there's a 1-1 match
   2392 	 between program/address spaces.  We simply bind the inferior
   2393 	 to the program space's address space.  */
   2394       inf = current_inferior ();
   2395       inferior_appeared (inf, pid);
   2396     }
   2397 
   2398   inf->attach_flag = attached;
   2399   inf->fake_pid_p = fake_pid_p;
   2400 
   2401   /* If no main executable is currently open then attempt to
   2402      open the file that was executed to create this inferior.  */
   2403   if (try_open_exec && get_exec_file (0) == NULL)
   2404     exec_file_locate_attach (pid, 0, 1);
   2405 
   2406   return inf;
   2407 }
   2408 
   2409 static remote_thread_info *get_remote_thread_info (thread_info *thread);
   2410 static remote_thread_info *get_remote_thread_info (ptid_t ptid);
   2411 
   2412 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
   2413    according to RUNNING.  */
   2414 
   2415 thread_info *
   2416 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing)
   2417 {
   2418   struct remote_state *rs = get_remote_state ();
   2419   struct thread_info *thread;
   2420 
   2421   /* GDB historically didn't pull threads in the initial connection
   2422      setup.  If the remote target doesn't even have a concept of
   2423      threads (e.g., a bare-metal target), even if internally we
   2424      consider that a single-threaded target, mentioning a new thread
   2425      might be confusing to the user.  Be silent then, preserving the
   2426      age old behavior.  */
   2427   if (rs->starting_up)
   2428     thread = add_thread_silent (ptid);
   2429   else
   2430     thread = add_thread (ptid);
   2431 
   2432   get_remote_thread_info (thread)->vcont_resumed = executing;
   2433   set_executing (ptid, executing);
   2434   set_running (ptid, running);
   2435 
   2436   return thread;
   2437 }
   2438 
   2439 /* Come here when we learn about a thread id from the remote target.
   2440    It may be the first time we hear about such thread, so take the
   2441    opportunity to add it to GDB's thread list.  In case this is the
   2442    first time we're noticing its corresponding inferior, add it to
   2443    GDB's inferior list as well.  EXECUTING indicates whether the
   2444    thread is (internally) executing or stopped.  */
   2445 
   2446 void
   2447 remote_target::remote_notice_new_inferior (ptid_t currthread, int executing)
   2448 {
   2449   /* In non-stop mode, we assume new found threads are (externally)
   2450      running until proven otherwise with a stop reply.  In all-stop,
   2451      we can only get here if all threads are stopped.  */
   2452   int running = target_is_non_stop_p () ? 1 : 0;
   2453 
   2454   /* If this is a new thread, add it to GDB's thread list.
   2455      If we leave it up to WFI to do this, bad things will happen.  */
   2456 
   2457   thread_info *tp = find_thread_ptid (currthread);
   2458   if (tp != NULL && tp->state == THREAD_EXITED)
   2459     {
   2460       /* We're seeing an event on a thread id we knew had exited.
   2461 	 This has to be a new thread reusing the old id.  Add it.  */
   2462       remote_add_thread (currthread, running, executing);
   2463       return;
   2464     }
   2465 
   2466   if (!in_thread_list (currthread))
   2467     {
   2468       struct inferior *inf = NULL;
   2469       int pid = currthread.pid ();
   2470 
   2471       if (inferior_ptid.is_pid ()
   2472 	  && pid == inferior_ptid.pid ())
   2473 	{
   2474 	  /* inferior_ptid has no thread member yet.  This can happen
   2475 	     with the vAttach -> remote_wait,"TAAthread:" path if the
   2476 	     stub doesn't support qC.  This is the first stop reported
   2477 	     after an attach, so this is the main thread.  Update the
   2478 	     ptid in the thread list.  */
   2479 	  if (in_thread_list (ptid_t (pid)))
   2480 	    thread_change_ptid (inferior_ptid, currthread);
   2481 	  else
   2482 	    {
   2483 	      remote_add_thread (currthread, running, executing);
   2484 	      inferior_ptid = currthread;
   2485 	    }
   2486 	  return;
   2487 	}
   2488 
   2489       if (magic_null_ptid == inferior_ptid)
   2490 	{
   2491 	  /* inferior_ptid is not set yet.  This can happen with the
   2492 	     vRun -> remote_wait,"TAAthread:" path if the stub
   2493 	     doesn't support qC.  This is the first stop reported
   2494 	     after an attach, so this is the main thread.  Update the
   2495 	     ptid in the thread list.  */
   2496 	  thread_change_ptid (inferior_ptid, currthread);
   2497 	  return;
   2498 	}
   2499 
   2500       /* When connecting to a target remote, or to a target
   2501 	 extended-remote which already was debugging an inferior, we
   2502 	 may not know about it yet.  Add it before adding its child
   2503 	 thread, so notifications are emitted in a sensible order.  */
   2504       if (find_inferior_pid (currthread.pid ()) == NULL)
   2505 	{
   2506 	  struct remote_state *rs = get_remote_state ();
   2507 	  int fake_pid_p = !remote_multi_process_p (rs);
   2508 
   2509 	  inf = remote_add_inferior (fake_pid_p,
   2510 				     currthread.pid (), -1, 1);
   2511 	}
   2512 
   2513       /* This is really a new thread.  Add it.  */
   2514       thread_info *new_thr
   2515 	= remote_add_thread (currthread, running, executing);
   2516 
   2517       /* If we found a new inferior, let the common code do whatever
   2518 	 it needs to with it (e.g., read shared libraries, insert
   2519 	 breakpoints), unless we're just setting up an all-stop
   2520 	 connection.  */
   2521       if (inf != NULL)
   2522 	{
   2523 	  struct remote_state *rs = get_remote_state ();
   2524 
   2525 	  if (!rs->starting_up)
   2526 	    notice_new_inferior (new_thr, executing, 0);
   2527 	}
   2528     }
   2529 }
   2530 
   2531 /* Return THREAD's private thread data, creating it if necessary.  */
   2532 
   2533 static remote_thread_info *
   2534 get_remote_thread_info (thread_info *thread)
   2535 {
   2536   gdb_assert (thread != NULL);
   2537 
   2538   if (thread->priv == NULL)
   2539     thread->priv.reset (new remote_thread_info);
   2540 
   2541   return static_cast<remote_thread_info *> (thread->priv.get ());
   2542 }
   2543 
   2544 static remote_thread_info *
   2545 get_remote_thread_info (ptid_t ptid)
   2546 {
   2547   thread_info *thr = find_thread_ptid (ptid);
   2548   return get_remote_thread_info (thr);
   2549 }
   2550 
   2551 /* Call this function as a result of
   2552    1) A halt indication (T packet) containing a thread id
   2553    2) A direct query of currthread
   2554    3) Successful execution of set thread */
   2555 
   2556 static void
   2557 record_currthread (struct remote_state *rs, ptid_t currthread)
   2558 {
   2559   rs->general_thread = currthread;
   2560 }
   2561 
   2562 /* If 'QPassSignals' is supported, tell the remote stub what signals
   2563    it can simply pass through to the inferior without reporting.  */
   2564 
   2565 void
   2566 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
   2567 {
   2568   if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
   2569     {
   2570       char *pass_packet, *p;
   2571       int count = 0;
   2572       struct remote_state *rs = get_remote_state ();
   2573 
   2574       gdb_assert (pass_signals.size () < 256);
   2575       for (size_t i = 0; i < pass_signals.size (); i++)
   2576 	{
   2577 	  if (pass_signals[i])
   2578 	    count++;
   2579 	}
   2580       pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
   2581       strcpy (pass_packet, "QPassSignals:");
   2582       p = pass_packet + strlen (pass_packet);
   2583       for (size_t i = 0; i < pass_signals.size (); i++)
   2584 	{
   2585 	  if (pass_signals[i])
   2586 	    {
   2587 	      if (i >= 16)
   2588 		*p++ = tohex (i >> 4);
   2589 	      *p++ = tohex (i & 15);
   2590 	      if (count)
   2591 		*p++ = ';';
   2592 	      else
   2593 		break;
   2594 	      count--;
   2595 	    }
   2596 	}
   2597       *p = 0;
   2598       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
   2599 	{
   2600 	  putpkt (pass_packet);
   2601 	  getpkt (&rs->buf, 0);
   2602 	  packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
   2603 	  if (rs->last_pass_packet)
   2604 	    xfree (rs->last_pass_packet);
   2605 	  rs->last_pass_packet = pass_packet;
   2606 	}
   2607       else
   2608 	xfree (pass_packet);
   2609     }
   2610 }
   2611 
   2612 /* If 'QCatchSyscalls' is supported, tell the remote stub
   2613    to report syscalls to GDB.  */
   2614 
   2615 int
   2616 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
   2617 				       gdb::array_view<const int> syscall_counts)
   2618 {
   2619   const char *catch_packet;
   2620   enum packet_result result;
   2621   int n_sysno = 0;
   2622 
   2623   if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
   2624     {
   2625       /* Not supported.  */
   2626       return 1;
   2627     }
   2628 
   2629   if (needed && any_count == 0)
   2630     {
   2631       /* Count how many syscalls are to be caught.  */
   2632       for (size_t i = 0; i < syscall_counts.size (); i++)
   2633 	{
   2634 	  if (syscall_counts[i] != 0)
   2635 	    n_sysno++;
   2636 	}
   2637     }
   2638 
   2639   if (remote_debug)
   2640     {
   2641       fprintf_unfiltered (gdb_stdlog,
   2642 			  "remote_set_syscall_catchpoint "
   2643 			  "pid %d needed %d any_count %d n_sysno %d\n",
   2644 			  pid, needed, any_count, n_sysno);
   2645     }
   2646 
   2647   std::string built_packet;
   2648   if (needed)
   2649     {
   2650       /* Prepare a packet with the sysno list, assuming max 8+1
   2651 	 characters for a sysno.  If the resulting packet size is too
   2652 	 big, fallback on the non-selective packet.  */
   2653       const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
   2654       built_packet.reserve (maxpktsz);
   2655       built_packet = "QCatchSyscalls:1";
   2656       if (any_count == 0)
   2657 	{
   2658 	  /* Add in each syscall to be caught.  */
   2659 	  for (size_t i = 0; i < syscall_counts.size (); i++)
   2660 	    {
   2661 	      if (syscall_counts[i] != 0)
   2662 		string_appendf (built_packet, ";%zx", i);
   2663 	    }
   2664 	}
   2665       if (built_packet.size () > get_remote_packet_size ())
   2666 	{
   2667 	  /* catch_packet too big.  Fallback to less efficient
   2668 	     non selective mode, with GDB doing the filtering.  */
   2669 	  catch_packet = "QCatchSyscalls:1";
   2670 	}
   2671       else
   2672 	catch_packet = built_packet.c_str ();
   2673     }
   2674   else
   2675     catch_packet = "QCatchSyscalls:0";
   2676 
   2677   struct remote_state *rs = get_remote_state ();
   2678 
   2679   putpkt (catch_packet);
   2680   getpkt (&rs->buf, 0);
   2681   result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
   2682   if (result == PACKET_OK)
   2683     return 0;
   2684   else
   2685     return -1;
   2686 }
   2687 
   2688 /* If 'QProgramSignals' is supported, tell the remote stub what
   2689    signals it should pass through to the inferior when detaching.  */
   2690 
   2691 void
   2692 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
   2693 {
   2694   if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
   2695     {
   2696       char *packet, *p;
   2697       int count = 0;
   2698       struct remote_state *rs = get_remote_state ();
   2699 
   2700       gdb_assert (signals.size () < 256);
   2701       for (size_t i = 0; i < signals.size (); i++)
   2702 	{
   2703 	  if (signals[i])
   2704 	    count++;
   2705 	}
   2706       packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
   2707       strcpy (packet, "QProgramSignals:");
   2708       p = packet + strlen (packet);
   2709       for (size_t i = 0; i < signals.size (); i++)
   2710 	{
   2711 	  if (signal_pass_state (i))
   2712 	    {
   2713 	      if (i >= 16)
   2714 		*p++ = tohex (i >> 4);
   2715 	      *p++ = tohex (i & 15);
   2716 	      if (count)
   2717 		*p++ = ';';
   2718 	      else
   2719 		break;
   2720 	      count--;
   2721 	    }
   2722 	}
   2723       *p = 0;
   2724       if (!rs->last_program_signals_packet
   2725 	  || strcmp (rs->last_program_signals_packet, packet) != 0)
   2726 	{
   2727 	  putpkt (packet);
   2728 	  getpkt (&rs->buf, 0);
   2729 	  packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
   2730 	  xfree (rs->last_program_signals_packet);
   2731 	  rs->last_program_signals_packet = packet;
   2732 	}
   2733       else
   2734 	xfree (packet);
   2735     }
   2736 }
   2737 
   2738 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
   2739    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
   2740    thread.  If GEN is set, set the general thread, if not, then set
   2741    the step/continue thread.  */
   2742 void
   2743 remote_target::set_thread (ptid_t ptid, int gen)
   2744 {
   2745   struct remote_state *rs = get_remote_state ();
   2746   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
   2747   char *buf = rs->buf.data ();
   2748   char *endbuf = buf + get_remote_packet_size ();
   2749 
   2750   if (state == ptid)
   2751     return;
   2752 
   2753   *buf++ = 'H';
   2754   *buf++ = gen ? 'g' : 'c';
   2755   if (ptid == magic_null_ptid)
   2756     xsnprintf (buf, endbuf - buf, "0");
   2757   else if (ptid == any_thread_ptid)
   2758     xsnprintf (buf, endbuf - buf, "0");
   2759   else if (ptid == minus_one_ptid)
   2760     xsnprintf (buf, endbuf - buf, "-1");
   2761   else
   2762     write_ptid (buf, endbuf, ptid);
   2763   putpkt (rs->buf);
   2764   getpkt (&rs->buf, 0);
   2765   if (gen)
   2766     rs->general_thread = ptid;
   2767   else
   2768     rs->continue_thread = ptid;
   2769 }
   2770 
   2771 void
   2772 remote_target::set_general_thread (ptid_t ptid)
   2773 {
   2774   set_thread (ptid, 1);
   2775 }
   2776 
   2777 void
   2778 remote_target::set_continue_thread (ptid_t ptid)
   2779 {
   2780   set_thread (ptid, 0);
   2781 }
   2782 
   2783 /* Change the remote current process.  Which thread within the process
   2784    ends up selected isn't important, as long as it is the same process
   2785    as what INFERIOR_PTID points to.
   2786 
   2787    This comes from that fact that there is no explicit notion of
   2788    "selected process" in the protocol.  The selected process for
   2789    general operations is the process the selected general thread
   2790    belongs to.  */
   2791 
   2792 void
   2793 remote_target::set_general_process ()
   2794 {
   2795   struct remote_state *rs = get_remote_state ();
   2796 
   2797   /* If the remote can't handle multiple processes, don't bother.  */
   2798   if (!remote_multi_process_p (rs))
   2799     return;
   2800 
   2801   /* We only need to change the remote current thread if it's pointing
   2802      at some other process.  */
   2803   if (rs->general_thread.pid () != inferior_ptid.pid ())
   2804     set_general_thread (inferior_ptid);
   2805 }
   2806 
   2807 
   2808 /* Return nonzero if this is the main thread that we made up ourselves
   2810    to model non-threaded targets as single-threaded.  */
   2811 
   2812 static int
   2813 remote_thread_always_alive (ptid_t ptid)
   2814 {
   2815   if (ptid == magic_null_ptid)
   2816     /* The main thread is always alive.  */
   2817     return 1;
   2818 
   2819   if (ptid.pid () != 0 && ptid.lwp () == 0)
   2820     /* The main thread is always alive.  This can happen after a
   2821        vAttach, if the remote side doesn't support
   2822        multi-threading.  */
   2823     return 1;
   2824 
   2825   return 0;
   2826 }
   2827 
   2828 /* Return nonzero if the thread PTID is still alive on the remote
   2829    system.  */
   2830 
   2831 bool
   2832 remote_target::thread_alive (ptid_t ptid)
   2833 {
   2834   struct remote_state *rs = get_remote_state ();
   2835   char *p, *endp;
   2836 
   2837   /* Check if this is a thread that we made up ourselves to model
   2838      non-threaded targets as single-threaded.  */
   2839   if (remote_thread_always_alive (ptid))
   2840     return 1;
   2841 
   2842   p = rs->buf.data ();
   2843   endp = p + get_remote_packet_size ();
   2844 
   2845   *p++ = 'T';
   2846   write_ptid (p, endp, ptid);
   2847 
   2848   putpkt (rs->buf);
   2849   getpkt (&rs->buf, 0);
   2850   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
   2851 }
   2852 
   2853 /* Return a pointer to a thread name if we know it and NULL otherwise.
   2854    The thread_info object owns the memory for the name.  */
   2855 
   2856 const char *
   2857 remote_target::thread_name (struct thread_info *info)
   2858 {
   2859   if (info->priv != NULL)
   2860     {
   2861       const std::string &name = get_remote_thread_info (info)->name;
   2862       return !name.empty () ? name.c_str () : NULL;
   2863     }
   2864 
   2865   return NULL;
   2866 }
   2867 
   2868 /* About these extended threadlist and threadinfo packets.  They are
   2869    variable length packets but, the fields within them are often fixed
   2870    length.  They are redundent enough to send over UDP as is the
   2871    remote protocol in general.  There is a matching unit test module
   2872    in libstub.  */
   2873 
   2874 /* WARNING: This threadref data structure comes from the remote O.S.,
   2875    libstub protocol encoding, and remote.c.  It is not particularly
   2876    changable.  */
   2877 
   2878 /* Right now, the internal structure is int. We want it to be bigger.
   2879    Plan to fix this.  */
   2880 
   2881 typedef int gdb_threadref;	/* Internal GDB thread reference.  */
   2882 
   2883 /* gdb_ext_thread_info is an internal GDB data structure which is
   2884    equivalent to the reply of the remote threadinfo packet.  */
   2885 
   2886 struct gdb_ext_thread_info
   2887   {
   2888     threadref threadid;		/* External form of thread reference.  */
   2889     int active;			/* Has state interesting to GDB?
   2890 				   regs, stack.  */
   2891     char display[256];		/* Brief state display, name,
   2892 				   blocked/suspended.  */
   2893     char shortname[32];		/* To be used to name threads.  */
   2894     char more_display[256];	/* Long info, statistics, queue depth,
   2895 				   whatever.  */
   2896   };
   2897 
   2898 /* The volume of remote transfers can be limited by submitting
   2899    a mask containing bits specifying the desired information.
   2900    Use a union of these values as the 'selection' parameter to
   2901    get_thread_info.  FIXME: Make these TAG names more thread specific.  */
   2902 
   2903 #define TAG_THREADID 1
   2904 #define TAG_EXISTS 2
   2905 #define TAG_DISPLAY 4
   2906 #define TAG_THREADNAME 8
   2907 #define TAG_MOREDISPLAY 16
   2908 
   2909 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
   2910 
   2911 static char *unpack_nibble (char *buf, int *val);
   2912 
   2913 static char *unpack_byte (char *buf, int *value);
   2914 
   2915 static char *pack_int (char *buf, int value);
   2916 
   2917 static char *unpack_int (char *buf, int *value);
   2918 
   2919 static char *unpack_string (char *src, char *dest, int length);
   2920 
   2921 static char *pack_threadid (char *pkt, threadref *id);
   2922 
   2923 static char *unpack_threadid (char *inbuf, threadref *id);
   2924 
   2925 void int_to_threadref (threadref *id, int value);
   2926 
   2927 static int threadref_to_int (threadref *ref);
   2928 
   2929 static void copy_threadref (threadref *dest, threadref *src);
   2930 
   2931 static int threadmatch (threadref *dest, threadref *src);
   2932 
   2933 static char *pack_threadinfo_request (char *pkt, int mode,
   2934 				      threadref *id);
   2935 
   2936 static char *pack_threadlist_request (char *pkt, int startflag,
   2937 				      int threadcount,
   2938 				      threadref *nextthread);
   2939 
   2940 static int remote_newthread_step (threadref *ref, void *context);
   2941 
   2942 
   2943 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
   2944    buffer we're allowed to write to.  Returns
   2945    BUF+CHARACTERS_WRITTEN.  */
   2946 
   2947 char *
   2948 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
   2949 {
   2950   int pid, tid;
   2951   struct remote_state *rs = get_remote_state ();
   2952 
   2953   if (remote_multi_process_p (rs))
   2954     {
   2955       pid = ptid.pid ();
   2956       if (pid < 0)
   2957 	buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
   2958       else
   2959 	buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
   2960     }
   2961   tid = ptid.lwp ();
   2962   if (tid < 0)
   2963     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
   2964   else
   2965     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
   2966 
   2967   return buf;
   2968 }
   2969 
   2970 /* Extract a PTID from BUF.  If non-null, OBUF is set to one past the
   2971    last parsed char.  Returns null_ptid if no thread id is found, and
   2972    throws an error if the thread id has an invalid format.  */
   2973 
   2974 static ptid_t
   2975 read_ptid (const char *buf, const char **obuf)
   2976 {
   2977   const char *p = buf;
   2978   const char *pp;
   2979   ULONGEST pid = 0, tid = 0;
   2980 
   2981   if (*p == 'p')
   2982     {
   2983       /* Multi-process ptid.  */
   2984       pp = unpack_varlen_hex (p + 1, &pid);
   2985       if (*pp != '.')
   2986 	error (_("invalid remote ptid: %s"), p);
   2987 
   2988       p = pp;
   2989       pp = unpack_varlen_hex (p + 1, &tid);
   2990       if (obuf)
   2991 	*obuf = pp;
   2992       return ptid_t (pid, tid, 0);
   2993     }
   2994 
   2995   /* No multi-process.  Just a tid.  */
   2996   pp = unpack_varlen_hex (p, &tid);
   2997 
   2998   /* Return null_ptid when no thread id is found.  */
   2999   if (p == pp)
   3000     {
   3001       if (obuf)
   3002 	*obuf = pp;
   3003       return null_ptid;
   3004     }
   3005 
   3006   /* Since the stub is not sending a process id, then default to
   3007      what's in inferior_ptid, unless it's null at this point.  If so,
   3008      then since there's no way to know the pid of the reported
   3009      threads, use the magic number.  */
   3010   if (inferior_ptid == null_ptid)
   3011     pid = magic_null_ptid.pid ();
   3012   else
   3013     pid = inferior_ptid.pid ();
   3014 
   3015   if (obuf)
   3016     *obuf = pp;
   3017   return ptid_t (pid, tid, 0);
   3018 }
   3019 
   3020 static int
   3021 stubhex (int ch)
   3022 {
   3023   if (ch >= 'a' && ch <= 'f')
   3024     return ch - 'a' + 10;
   3025   if (ch >= '0' && ch <= '9')
   3026     return ch - '0';
   3027   if (ch >= 'A' && ch <= 'F')
   3028     return ch - 'A' + 10;
   3029   return -1;
   3030 }
   3031 
   3032 static int
   3033 stub_unpack_int (char *buff, int fieldlength)
   3034 {
   3035   int nibble;
   3036   int retval = 0;
   3037 
   3038   while (fieldlength)
   3039     {
   3040       nibble = stubhex (*buff++);
   3041       retval |= nibble;
   3042       fieldlength--;
   3043       if (fieldlength)
   3044 	retval = retval << 4;
   3045     }
   3046   return retval;
   3047 }
   3048 
   3049 static char *
   3050 unpack_nibble (char *buf, int *val)
   3051 {
   3052   *val = fromhex (*buf++);
   3053   return buf;
   3054 }
   3055 
   3056 static char *
   3057 unpack_byte (char *buf, int *value)
   3058 {
   3059   *value = stub_unpack_int (buf, 2);
   3060   return buf + 2;
   3061 }
   3062 
   3063 static char *
   3064 pack_int (char *buf, int value)
   3065 {
   3066   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
   3067   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
   3068   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
   3069   buf = pack_hex_byte (buf, (value & 0xff));
   3070   return buf;
   3071 }
   3072 
   3073 static char *
   3074 unpack_int (char *buf, int *value)
   3075 {
   3076   *value = stub_unpack_int (buf, 8);
   3077   return buf + 8;
   3078 }
   3079 
   3080 #if 0			/* Currently unused, uncomment when needed.  */
   3081 static char *pack_string (char *pkt, char *string);
   3082 
   3083 static char *
   3084 pack_string (char *pkt, char *string)
   3085 {
   3086   char ch;
   3087   int len;
   3088 
   3089   len = strlen (string);
   3090   if (len > 200)
   3091     len = 200;		/* Bigger than most GDB packets, junk???  */
   3092   pkt = pack_hex_byte (pkt, len);
   3093   while (len-- > 0)
   3094     {
   3095       ch = *string++;
   3096       if ((ch == '\0') || (ch == '#'))
   3097 	ch = '*';		/* Protect encapsulation.  */
   3098       *pkt++ = ch;
   3099     }
   3100   return pkt;
   3101 }
   3102 #endif /* 0 (unused) */
   3103 
   3104 static char *
   3105 unpack_string (char *src, char *dest, int length)
   3106 {
   3107   while (length--)
   3108     *dest++ = *src++;
   3109   *dest = '\0';
   3110   return src;
   3111 }
   3112 
   3113 static char *
   3114 pack_threadid (char *pkt, threadref *id)
   3115 {
   3116   char *limit;
   3117   unsigned char *altid;
   3118 
   3119   altid = (unsigned char *) id;
   3120   limit = pkt + BUF_THREAD_ID_SIZE;
   3121   while (pkt < limit)
   3122     pkt = pack_hex_byte (pkt, *altid++);
   3123   return pkt;
   3124 }
   3125 
   3126 
   3127 static char *
   3128 unpack_threadid (char *inbuf, threadref *id)
   3129 {
   3130   char *altref;
   3131   char *limit = inbuf + BUF_THREAD_ID_SIZE;
   3132   int x, y;
   3133 
   3134   altref = (char *) id;
   3135 
   3136   while (inbuf < limit)
   3137     {
   3138       x = stubhex (*inbuf++);
   3139       y = stubhex (*inbuf++);
   3140       *altref++ = (x << 4) | y;
   3141     }
   3142   return inbuf;
   3143 }
   3144 
   3145 /* Externally, threadrefs are 64 bits but internally, they are still
   3146    ints.  This is due to a mismatch of specifications.  We would like
   3147    to use 64bit thread references internally.  This is an adapter
   3148    function.  */
   3149 
   3150 void
   3151 int_to_threadref (threadref *id, int value)
   3152 {
   3153   unsigned char *scan;
   3154 
   3155   scan = (unsigned char *) id;
   3156   {
   3157     int i = 4;
   3158     while (i--)
   3159       *scan++ = 0;
   3160   }
   3161   *scan++ = (value >> 24) & 0xff;
   3162   *scan++ = (value >> 16) & 0xff;
   3163   *scan++ = (value >> 8) & 0xff;
   3164   *scan++ = (value & 0xff);
   3165 }
   3166 
   3167 static int
   3168 threadref_to_int (threadref *ref)
   3169 {
   3170   int i, value = 0;
   3171   unsigned char *scan;
   3172 
   3173   scan = *ref;
   3174   scan += 4;
   3175   i = 4;
   3176   while (i-- > 0)
   3177     value = (value << 8) | ((*scan++) & 0xff);
   3178   return value;
   3179 }
   3180 
   3181 static void
   3182 copy_threadref (threadref *dest, threadref *src)
   3183 {
   3184   int i;
   3185   unsigned char *csrc, *cdest;
   3186 
   3187   csrc = (unsigned char *) src;
   3188   cdest = (unsigned char *) dest;
   3189   i = 8;
   3190   while (i--)
   3191     *cdest++ = *csrc++;
   3192 }
   3193 
   3194 static int
   3195 threadmatch (threadref *dest, threadref *src)
   3196 {
   3197   /* Things are broken right now, so just assume we got a match.  */
   3198 #if 0
   3199   unsigned char *srcp, *destp;
   3200   int i, result;
   3201   srcp = (char *) src;
   3202   destp = (char *) dest;
   3203 
   3204   result = 1;
   3205   while (i-- > 0)
   3206     result &= (*srcp++ == *destp++) ? 1 : 0;
   3207   return result;
   3208 #endif
   3209   return 1;
   3210 }
   3211 
   3212 /*
   3213    threadid:1,        # always request threadid
   3214    context_exists:2,
   3215    display:4,
   3216    unique_name:8,
   3217    more_display:16
   3218  */
   3219 
   3220 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
   3221 
   3222 static char *
   3223 pack_threadinfo_request (char *pkt, int mode, threadref *id)
   3224 {
   3225   *pkt++ = 'q';				/* Info Query */
   3226   *pkt++ = 'P';				/* process or thread info */
   3227   pkt = pack_int (pkt, mode);		/* mode */
   3228   pkt = pack_threadid (pkt, id);	/* threadid */
   3229   *pkt = '\0';				/* terminate */
   3230   return pkt;
   3231 }
   3232 
   3233 /* These values tag the fields in a thread info response packet.  */
   3234 /* Tagging the fields allows us to request specific fields and to
   3235    add more fields as time goes by.  */
   3236 
   3237 #define TAG_THREADID 1		/* Echo the thread identifier.  */
   3238 #define TAG_EXISTS 2		/* Is this process defined enough to
   3239 				   fetch registers and its stack?  */
   3240 #define TAG_DISPLAY 4		/* A short thing maybe to put on a window */
   3241 #define TAG_THREADNAME 8	/* string, maps 1-to-1 with a thread is.  */
   3242 #define TAG_MOREDISPLAY 16	/* Whatever the kernel wants to say about
   3243 				   the process.  */
   3244 
   3245 int
   3246 remote_target::remote_unpack_thread_info_response (char *pkt,
   3247 						   threadref *expectedref,
   3248 						   gdb_ext_thread_info *info)
   3249 {
   3250   struct remote_state *rs = get_remote_state ();
   3251   int mask, length;
   3252   int tag;
   3253   threadref ref;
   3254   char *limit = pkt + rs->buf.size (); /* Plausible parsing limit.  */
   3255   int retval = 1;
   3256 
   3257   /* info->threadid = 0; FIXME: implement zero_threadref.  */
   3258   info->active = 0;
   3259   info->display[0] = '\0';
   3260   info->shortname[0] = '\0';
   3261   info->more_display[0] = '\0';
   3262 
   3263   /* Assume the characters indicating the packet type have been
   3264      stripped.  */
   3265   pkt = unpack_int (pkt, &mask);	/* arg mask */
   3266   pkt = unpack_threadid (pkt, &ref);
   3267 
   3268   if (mask == 0)
   3269     warning (_("Incomplete response to threadinfo request."));
   3270   if (!threadmatch (&ref, expectedref))
   3271     {			/* This is an answer to a different request.  */
   3272       warning (_("ERROR RMT Thread info mismatch."));
   3273       return 0;
   3274     }
   3275   copy_threadref (&info->threadid, &ref);
   3276 
   3277   /* Loop on tagged fields , try to bail if somthing goes wrong.  */
   3278 
   3279   /* Packets are terminated with nulls.  */
   3280   while ((pkt < limit) && mask && *pkt)
   3281     {
   3282       pkt = unpack_int (pkt, &tag);	/* tag */
   3283       pkt = unpack_byte (pkt, &length);	/* length */
   3284       if (!(tag & mask))		/* Tags out of synch with mask.  */
   3285 	{
   3286 	  warning (_("ERROR RMT: threadinfo tag mismatch."));
   3287 	  retval = 0;
   3288 	  break;
   3289 	}
   3290       if (tag == TAG_THREADID)
   3291 	{
   3292 	  if (length != 16)
   3293 	    {
   3294 	      warning (_("ERROR RMT: length of threadid is not 16."));
   3295 	      retval = 0;
   3296 	      break;
   3297 	    }
   3298 	  pkt = unpack_threadid (pkt, &ref);
   3299 	  mask = mask & ~TAG_THREADID;
   3300 	  continue;
   3301 	}
   3302       if (tag == TAG_EXISTS)
   3303 	{
   3304 	  info->active = stub_unpack_int (pkt, length);
   3305 	  pkt += length;
   3306 	  mask = mask & ~(TAG_EXISTS);
   3307 	  if (length > 8)
   3308 	    {
   3309 	      warning (_("ERROR RMT: 'exists' length too long."));
   3310 	      retval = 0;
   3311 	      break;
   3312 	    }
   3313 	  continue;
   3314 	}
   3315       if (tag == TAG_THREADNAME)
   3316 	{
   3317 	  pkt = unpack_string (pkt, &info->shortname[0], length);
   3318 	  mask = mask & ~TAG_THREADNAME;
   3319 	  continue;
   3320 	}
   3321       if (tag == TAG_DISPLAY)
   3322 	{
   3323 	  pkt = unpack_string (pkt, &info->display[0], length);
   3324 	  mask = mask & ~TAG_DISPLAY;
   3325 	  continue;
   3326 	}
   3327       if (tag == TAG_MOREDISPLAY)
   3328 	{
   3329 	  pkt = unpack_string (pkt, &info->more_display[0], length);
   3330 	  mask = mask & ~TAG_MOREDISPLAY;
   3331 	  continue;
   3332 	}
   3333       warning (_("ERROR RMT: unknown thread info tag."));
   3334       break;			/* Not a tag we know about.  */
   3335     }
   3336   return retval;
   3337 }
   3338 
   3339 int
   3340 remote_target::remote_get_threadinfo (threadref *threadid,
   3341 				      int fieldset,
   3342 				      gdb_ext_thread_info *info)
   3343 {
   3344   struct remote_state *rs = get_remote_state ();
   3345   int result;
   3346 
   3347   pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
   3348   putpkt (rs->buf);
   3349   getpkt (&rs->buf, 0);
   3350 
   3351   if (rs->buf[0] == '\0')
   3352     return 0;
   3353 
   3354   result = remote_unpack_thread_info_response (&rs->buf[2],
   3355 					       threadid, info);
   3356   return result;
   3357 }
   3358 
   3359 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
   3360 
   3361 static char *
   3362 pack_threadlist_request (char *pkt, int startflag, int threadcount,
   3363 			 threadref *nextthread)
   3364 {
   3365   *pkt++ = 'q';			/* info query packet */
   3366   *pkt++ = 'L';			/* Process LIST or threadLIST request */
   3367   pkt = pack_nibble (pkt, startflag);		/* initflag 1 bytes */
   3368   pkt = pack_hex_byte (pkt, threadcount);	/* threadcount 2 bytes */
   3369   pkt = pack_threadid (pkt, nextthread);	/* 64 bit thread identifier */
   3370   *pkt = '\0';
   3371   return pkt;
   3372 }
   3373 
   3374 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
   3375 
   3376 int
   3377 remote_target::parse_threadlist_response (char *pkt, int result_limit,
   3378 					  threadref *original_echo,
   3379 					  threadref *resultlist,
   3380 					  int *doneflag)
   3381 {
   3382   struct remote_state *rs = get_remote_state ();
   3383   char *limit;
   3384   int count, resultcount, done;
   3385 
   3386   resultcount = 0;
   3387   /* Assume the 'q' and 'M chars have been stripped.  */
   3388   limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
   3389   /* done parse past here */
   3390   pkt = unpack_byte (pkt, &count);	/* count field */
   3391   pkt = unpack_nibble (pkt, &done);
   3392   /* The first threadid is the argument threadid.  */
   3393   pkt = unpack_threadid (pkt, original_echo);	/* should match query packet */
   3394   while ((count-- > 0) && (pkt < limit))
   3395     {
   3396       pkt = unpack_threadid (pkt, resultlist++);
   3397       if (resultcount++ >= result_limit)
   3398 	break;
   3399     }
   3400   if (doneflag)
   3401     *doneflag = done;
   3402   return resultcount;
   3403 }
   3404 
   3405 /* Fetch the next batch of threads from the remote.  Returns -1 if the
   3406    qL packet is not supported, 0 on error and 1 on success.  */
   3407 
   3408 int
   3409 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
   3410 				      int result_limit, int *done, int *result_count,
   3411 				      threadref *threadlist)
   3412 {
   3413   struct remote_state *rs = get_remote_state ();
   3414   int result = 1;
   3415 
   3416   /* Trancate result limit to be smaller than the packet size.  */
   3417   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
   3418       >= get_remote_packet_size ())
   3419     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
   3420 
   3421   pack_threadlist_request (rs->buf.data (), startflag, result_limit,
   3422 			   nextthread);
   3423   putpkt (rs->buf);
   3424   getpkt (&rs->buf, 0);
   3425   if (rs->buf[0] == '\0')
   3426     {
   3427       /* Packet not supported.  */
   3428       return -1;
   3429     }
   3430 
   3431   *result_count =
   3432     parse_threadlist_response (&rs->buf[2], result_limit,
   3433 			       &rs->echo_nextthread, threadlist, done);
   3434 
   3435   if (!threadmatch (&rs->echo_nextthread, nextthread))
   3436     {
   3437       /* FIXME: This is a good reason to drop the packet.  */
   3438       /* Possably, there is a duplicate response.  */
   3439       /* Possabilities :
   3440          retransmit immediatly - race conditions
   3441          retransmit after timeout - yes
   3442          exit
   3443          wait for packet, then exit
   3444        */
   3445       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
   3446       return 0;			/* I choose simply exiting.  */
   3447     }
   3448   if (*result_count <= 0)
   3449     {
   3450       if (*done != 1)
   3451 	{
   3452 	  warning (_("RMT ERROR : failed to get remote thread list."));
   3453 	  result = 0;
   3454 	}
   3455       return result;		/* break; */
   3456     }
   3457   if (*result_count > result_limit)
   3458     {
   3459       *result_count = 0;
   3460       warning (_("RMT ERROR: threadlist response longer than requested."));
   3461       return 0;
   3462     }
   3463   return result;
   3464 }
   3465 
   3466 /* Fetch the list of remote threads, with the qL packet, and call
   3467    STEPFUNCTION for each thread found.  Stops iterating and returns 1
   3468    if STEPFUNCTION returns true.  Stops iterating and returns 0 if the
   3469    STEPFUNCTION returns false.  If the packet is not supported,
   3470    returns -1.  */
   3471 
   3472 int
   3473 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
   3474 					   void *context, int looplimit)
   3475 {
   3476   struct remote_state *rs = get_remote_state ();
   3477   int done, i, result_count;
   3478   int startflag = 1;
   3479   int result = 1;
   3480   int loopcount = 0;
   3481 
   3482   done = 0;
   3483   while (!done)
   3484     {
   3485       if (loopcount++ > looplimit)
   3486 	{
   3487 	  result = 0;
   3488 	  warning (_("Remote fetch threadlist -infinite loop-."));
   3489 	  break;
   3490 	}
   3491       result = remote_get_threadlist (startflag, &rs->nextthread,
   3492 				      MAXTHREADLISTRESULTS,
   3493 				      &done, &result_count,
   3494 				      rs->resultthreadlist);
   3495       if (result <= 0)
   3496 	break;
   3497       /* Clear for later iterations.  */
   3498       startflag = 0;
   3499       /* Setup to resume next batch of thread references, set nextthread.  */
   3500       if (result_count >= 1)
   3501 	copy_threadref (&rs->nextthread,
   3502 			&rs->resultthreadlist[result_count - 1]);
   3503       i = 0;
   3504       while (result_count--)
   3505 	{
   3506 	  if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
   3507 	    {
   3508 	      result = 0;
   3509 	      break;
   3510 	    }
   3511 	}
   3512     }
   3513   return result;
   3514 }
   3515 
   3516 /* A thread found on the remote target.  */
   3517 
   3518 struct thread_item
   3519 {
   3520   explicit thread_item (ptid_t ptid_)
   3521   : ptid (ptid_)
   3522   {}
   3523 
   3524   thread_item (thread_item &&other) = default;
   3525   thread_item &operator= (thread_item &&other) = default;
   3526 
   3527   DISABLE_COPY_AND_ASSIGN (thread_item);
   3528 
   3529   /* The thread's PTID.  */
   3530   ptid_t ptid;
   3531 
   3532   /* The thread's extra info.  */
   3533   std::string extra;
   3534 
   3535   /* The thread's name.  */
   3536   std::string name;
   3537 
   3538   /* The core the thread was running on.  -1 if not known.  */
   3539   int core = -1;
   3540 
   3541   /* The thread handle associated with the thread.  */
   3542   gdb::byte_vector thread_handle;
   3543 };
   3544 
   3545 /* Context passed around to the various methods listing remote
   3546    threads.  As new threads are found, they're added to the ITEMS
   3547    vector.  */
   3548 
   3549 struct threads_listing_context
   3550 {
   3551   /* Return true if this object contains an entry for a thread with ptid
   3552      PTID.  */
   3553 
   3554   bool contains_thread (ptid_t ptid) const
   3555   {
   3556     auto match_ptid = [&] (const thread_item &item)
   3557       {
   3558 	return item.ptid == ptid;
   3559       };
   3560 
   3561     auto it = std::find_if (this->items.begin (),
   3562 			    this->items.end (),
   3563 			    match_ptid);
   3564 
   3565     return it != this->items.end ();
   3566   }
   3567 
   3568   /* Remove the thread with ptid PTID.  */
   3569 
   3570   void remove_thread (ptid_t ptid)
   3571   {
   3572     auto match_ptid = [&] (const thread_item &item)
   3573       {
   3574         return item.ptid == ptid;
   3575       };
   3576 
   3577     auto it = std::remove_if (this->items.begin (),
   3578 			      this->items.end (),
   3579 			      match_ptid);
   3580 
   3581     if (it != this->items.end ())
   3582       this->items.erase (it);
   3583   }
   3584 
   3585   /* The threads found on the remote target.  */
   3586   std::vector<thread_item> items;
   3587 };
   3588 
   3589 static int
   3590 remote_newthread_step (threadref *ref, void *data)
   3591 {
   3592   struct threads_listing_context *context
   3593     = (struct threads_listing_context *) data;
   3594   int pid = inferior_ptid.pid ();
   3595   int lwp = threadref_to_int (ref);
   3596   ptid_t ptid (pid, lwp);
   3597 
   3598   context->items.emplace_back (ptid);
   3599 
   3600   return 1;			/* continue iterator */
   3601 }
   3602 
   3603 #define CRAZY_MAX_THREADS 1000
   3604 
   3605 ptid_t
   3606 remote_target::remote_current_thread (ptid_t oldpid)
   3607 {
   3608   struct remote_state *rs = get_remote_state ();
   3609 
   3610   putpkt ("qC");
   3611   getpkt (&rs->buf, 0);
   3612   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
   3613     {
   3614       const char *obuf;
   3615       ptid_t result;
   3616 
   3617       result = read_ptid (&rs->buf[2], &obuf);
   3618       if (*obuf != '\0' && remote_debug)
   3619         fprintf_unfiltered (gdb_stdlog,
   3620 	                    "warning: garbage in qC reply\n");
   3621 
   3622       return result;
   3623     }
   3624   else
   3625     return oldpid;
   3626 }
   3627 
   3628 /* List remote threads using the deprecated qL packet.  */
   3629 
   3630 int
   3631 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
   3632 {
   3633   if (remote_threadlist_iterator (remote_newthread_step, context,
   3634 				  CRAZY_MAX_THREADS) >= 0)
   3635     return 1;
   3636 
   3637   return 0;
   3638 }
   3639 
   3640 #if defined(HAVE_LIBEXPAT)
   3641 
   3642 static void
   3643 start_thread (struct gdb_xml_parser *parser,
   3644 	      const struct gdb_xml_element *element,
   3645 	      void *user_data,
   3646 	      std::vector<gdb_xml_value> &attributes)
   3647 {
   3648   struct threads_listing_context *data
   3649     = (struct threads_listing_context *) user_data;
   3650   struct gdb_xml_value *attr;
   3651 
   3652   char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
   3653   ptid_t ptid = read_ptid (id, NULL);
   3654 
   3655   data->items.emplace_back (ptid);
   3656   thread_item &item = data->items.back ();
   3657 
   3658   attr = xml_find_attribute (attributes, "core");
   3659   if (attr != NULL)
   3660     item.core = *(ULONGEST *) attr->value.get ();
   3661 
   3662   attr = xml_find_attribute (attributes, "name");
   3663   if (attr != NULL)
   3664     item.name = (const char *) attr->value.get ();
   3665 
   3666   attr = xml_find_attribute (attributes, "handle");
   3667   if (attr != NULL)
   3668     item.thread_handle = hex2bin ((const char *) attr->value.get ());
   3669 }
   3670 
   3671 static void
   3672 end_thread (struct gdb_xml_parser *parser,
   3673 	    const struct gdb_xml_element *element,
   3674 	    void *user_data, const char *body_text)
   3675 {
   3676   struct threads_listing_context *data
   3677     = (struct threads_listing_context *) user_data;
   3678 
   3679   if (body_text != NULL && *body_text != '\0')
   3680     data->items.back ().extra = body_text;
   3681 }
   3682 
   3683 const struct gdb_xml_attribute thread_attributes[] = {
   3684   { "id", GDB_XML_AF_NONE, NULL, NULL },
   3685   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
   3686   { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
   3687   { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
   3688   { NULL, GDB_XML_AF_NONE, NULL, NULL }
   3689 };
   3690 
   3691 const struct gdb_xml_element thread_children[] = {
   3692   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
   3693 };
   3694 
   3695 const struct gdb_xml_element threads_children[] = {
   3696   { "thread", thread_attributes, thread_children,
   3697     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
   3698     start_thread, end_thread },
   3699   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
   3700 };
   3701 
   3702 const struct gdb_xml_element threads_elements[] = {
   3703   { "threads", NULL, threads_children,
   3704     GDB_XML_EF_NONE, NULL, NULL },
   3705   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
   3706 };
   3707 
   3708 #endif
   3709 
   3710 /* List remote threads using qXfer:threads:read.  */
   3711 
   3712 int
   3713 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
   3714 {
   3715 #if defined(HAVE_LIBEXPAT)
   3716   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
   3717     {
   3718       gdb::optional<gdb::char_vector> xml
   3719 	= target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
   3720 
   3721       if (xml && (*xml)[0] != '\0')
   3722 	{
   3723 	  gdb_xml_parse_quick (_("threads"), "threads.dtd",
   3724 			       threads_elements, xml->data (), context);
   3725 	}
   3726 
   3727       return 1;
   3728     }
   3729 #endif
   3730 
   3731   return 0;
   3732 }
   3733 
   3734 /* List remote threads using qfThreadInfo/qsThreadInfo.  */
   3735 
   3736 int
   3737 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
   3738 {
   3739   struct remote_state *rs = get_remote_state ();
   3740 
   3741   if (rs->use_threadinfo_query)
   3742     {
   3743       const char *bufp;
   3744 
   3745       putpkt ("qfThreadInfo");
   3746       getpkt (&rs->buf, 0);
   3747       bufp = rs->buf.data ();
   3748       if (bufp[0] != '\0')		/* q packet recognized */
   3749 	{
   3750 	  while (*bufp++ == 'm')	/* reply contains one or more TID */
   3751 	    {
   3752 	      do
   3753 		{
   3754 		  ptid_t ptid = read_ptid (bufp, &bufp);
   3755 		  context->items.emplace_back (ptid);
   3756 		}
   3757 	      while (*bufp++ == ',');	/* comma-separated list */
   3758 	      putpkt ("qsThreadInfo");
   3759 	      getpkt (&rs->buf, 0);
   3760 	      bufp = rs->buf.data ();
   3761 	    }
   3762 	  return 1;
   3763 	}
   3764       else
   3765 	{
   3766 	  /* Packet not recognized.  */
   3767 	  rs->use_threadinfo_query = 0;
   3768 	}
   3769     }
   3770 
   3771   return 0;
   3772 }
   3773 
   3774 /* Implement the to_update_thread_list function for the remote
   3775    targets.  */
   3776 
   3777 void
   3778 remote_target::update_thread_list ()
   3779 {
   3780   struct threads_listing_context context;
   3781   int got_list = 0;
   3782 
   3783   /* We have a few different mechanisms to fetch the thread list.  Try
   3784      them all, starting with the most preferred one first, falling
   3785      back to older methods.  */
   3786   if (remote_get_threads_with_qxfer (&context)
   3787       || remote_get_threads_with_qthreadinfo (&context)
   3788       || remote_get_threads_with_ql (&context))
   3789     {
   3790       got_list = 1;
   3791 
   3792       if (context.items.empty ()
   3793 	  && remote_thread_always_alive (inferior_ptid))
   3794 	{
   3795 	  /* Some targets don't really support threads, but still
   3796 	     reply an (empty) thread list in response to the thread
   3797 	     listing packets, instead of replying "packet not
   3798 	     supported".  Exit early so we don't delete the main
   3799 	     thread.  */
   3800 	  return;
   3801 	}
   3802 
   3803       /* CONTEXT now holds the current thread list on the remote
   3804 	 target end.  Delete GDB-side threads no longer found on the
   3805 	 target.  */
   3806       for (thread_info *tp : all_threads_safe ())
   3807 	{
   3808 	  if (!context.contains_thread (tp->ptid))
   3809 	    {
   3810 	      /* Not found.  */
   3811 	      delete_thread (tp);
   3812 	    }
   3813 	}
   3814 
   3815       /* Remove any unreported fork child threads from CONTEXT so
   3816 	 that we don't interfere with follow fork, which is where
   3817 	 creation of such threads is handled.  */
   3818       remove_new_fork_children (&context);
   3819 
   3820       /* And now add threads we don't know about yet to our list.  */
   3821       for (thread_item &item : context.items)
   3822 	{
   3823 	  if (item.ptid != null_ptid)
   3824 	    {
   3825 	      /* In non-stop mode, we assume new found threads are
   3826 		 executing until proven otherwise with a stop reply.
   3827 		 In all-stop, we can only get here if all threads are
   3828 		 stopped.  */
   3829 	      int executing = target_is_non_stop_p () ? 1 : 0;
   3830 
   3831 	      remote_notice_new_inferior (item.ptid, executing);
   3832 
   3833 	      thread_info *tp = find_thread_ptid (item.ptid);
   3834 	      remote_thread_info *info = get_remote_thread_info (tp);
   3835 	      info->core = item.core;
   3836 	      info->extra = std::move (item.extra);
   3837 	      info->name = std::move (item.name);
   3838 	      info->thread_handle = std::move (item.thread_handle);
   3839 	    }
   3840 	}
   3841     }
   3842 
   3843   if (!got_list)
   3844     {
   3845       /* If no thread listing method is supported, then query whether
   3846 	 each known thread is alive, one by one, with the T packet.
   3847 	 If the target doesn't support threads at all, then this is a
   3848 	 no-op.  See remote_thread_alive.  */
   3849       prune_threads ();
   3850     }
   3851 }
   3852 
   3853 /*
   3854  * Collect a descriptive string about the given thread.
   3855  * The target may say anything it wants to about the thread
   3856  * (typically info about its blocked / runnable state, name, etc.).
   3857  * This string will appear in the info threads display.
   3858  *
   3859  * Optional: targets are not required to implement this function.
   3860  */
   3861 
   3862 const char *
   3863 remote_target::extra_thread_info (thread_info *tp)
   3864 {
   3865   struct remote_state *rs = get_remote_state ();
   3866   int set;
   3867   threadref id;
   3868   struct gdb_ext_thread_info threadinfo;
   3869 
   3870   if (rs->remote_desc == 0)		/* paranoia */
   3871     internal_error (__FILE__, __LINE__,
   3872 		    _("remote_threads_extra_info"));
   3873 
   3874   if (tp->ptid == magic_null_ptid
   3875       || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
   3876     /* This is the main thread which was added by GDB.  The remote
   3877        server doesn't know about it.  */
   3878     return NULL;
   3879 
   3880   std::string &extra = get_remote_thread_info (tp)->extra;
   3881 
   3882   /* If already have cached info, use it.  */
   3883   if (!extra.empty ())
   3884     return extra.c_str ();
   3885 
   3886   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
   3887     {
   3888       /* If we're using qXfer:threads:read, then the extra info is
   3889 	 included in the XML.  So if we didn't have anything cached,
   3890 	 it's because there's really no extra info.  */
   3891       return NULL;
   3892     }
   3893 
   3894   if (rs->use_threadextra_query)
   3895     {
   3896       char *b = rs->buf.data ();
   3897       char *endb = b + get_remote_packet_size ();
   3898 
   3899       xsnprintf (b, endb - b, "qThreadExtraInfo,");
   3900       b += strlen (b);
   3901       write_ptid (b, endb, tp->ptid);
   3902 
   3903       putpkt (rs->buf);
   3904       getpkt (&rs->buf, 0);
   3905       if (rs->buf[0] != 0)
   3906 	{
   3907 	  extra.resize (strlen (rs->buf.data ()) / 2);
   3908 	  hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
   3909 	  return extra.c_str ();
   3910 	}
   3911     }
   3912 
   3913   /* If the above query fails, fall back to the old method.  */
   3914   rs->use_threadextra_query = 0;
   3915   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
   3916     | TAG_MOREDISPLAY | TAG_DISPLAY;
   3917   int_to_threadref (&id, tp->ptid.lwp ());
   3918   if (remote_get_threadinfo (&id, set, &threadinfo))
   3919     if (threadinfo.active)
   3920       {
   3921 	if (*threadinfo.shortname)
   3922 	  string_appendf (extra, " Name: %s", threadinfo.shortname);
   3923 	if (*threadinfo.display)
   3924 	  {
   3925 	    if (!extra.empty ())
   3926 	      extra += ',';
   3927 	    string_appendf (extra, " State: %s", threadinfo.display);
   3928 	  }
   3929 	if (*threadinfo.more_display)
   3930 	  {
   3931 	    if (!extra.empty ())
   3932 	      extra += ',';
   3933 	    string_appendf (extra, " Priority: %s", threadinfo.more_display);
   3934 	  }
   3935 	return extra.c_str ();
   3936       }
   3937   return NULL;
   3938 }
   3939 
   3940 
   3942 bool
   3943 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
   3944 					    struct static_tracepoint_marker *marker)
   3945 {
   3946   struct remote_state *rs = get_remote_state ();
   3947   char *p = rs->buf.data ();
   3948 
   3949   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
   3950   p += strlen (p);
   3951   p += hexnumstr (p, addr);
   3952   putpkt (rs->buf);
   3953   getpkt (&rs->buf, 0);
   3954   p = rs->buf.data ();
   3955 
   3956   if (*p == 'E')
   3957     error (_("Remote failure reply: %s"), p);
   3958 
   3959   if (*p++ == 'm')
   3960     {
   3961       parse_static_tracepoint_marker_definition (p, NULL, marker);
   3962       return true;
   3963     }
   3964 
   3965   return false;
   3966 }
   3967 
   3968 std::vector<static_tracepoint_marker>
   3969 remote_target::static_tracepoint_markers_by_strid (const char *strid)
   3970 {
   3971   struct remote_state *rs = get_remote_state ();
   3972   std::vector<static_tracepoint_marker> markers;
   3973   const char *p;
   3974   static_tracepoint_marker marker;
   3975 
   3976   /* Ask for a first packet of static tracepoint marker
   3977      definition.  */
   3978   putpkt ("qTfSTM");
   3979   getpkt (&rs->buf, 0);
   3980   p = rs->buf.data ();
   3981   if (*p == 'E')
   3982     error (_("Remote failure reply: %s"), p);
   3983 
   3984   while (*p++ == 'm')
   3985     {
   3986       do
   3987 	{
   3988 	  parse_static_tracepoint_marker_definition (p, &p, &marker);
   3989 
   3990 	  if (strid == NULL || marker.str_id == strid)
   3991 	    markers.push_back (std::move (marker));
   3992 	}
   3993       while (*p++ == ',');	/* comma-separated list */
   3994       /* Ask for another packet of static tracepoint definition.  */
   3995       putpkt ("qTsSTM");
   3996       getpkt (&rs->buf, 0);
   3997       p = rs->buf.data ();
   3998     }
   3999 
   4000   return markers;
   4001 }
   4002 
   4003 
   4004 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
   4006 
   4007 ptid_t
   4008 remote_target::get_ada_task_ptid (long lwp, long thread)
   4009 {
   4010   return ptid_t (inferior_ptid.pid (), lwp, 0);
   4011 }
   4012 
   4013 
   4015 /* Restart the remote side; this is an extended protocol operation.  */
   4016 
   4017 void
   4018 remote_target::extended_remote_restart ()
   4019 {
   4020   struct remote_state *rs = get_remote_state ();
   4021 
   4022   /* Send the restart command; for reasons I don't understand the
   4023      remote side really expects a number after the "R".  */
   4024   xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
   4025   putpkt (rs->buf);
   4026 
   4027   remote_fileio_reset ();
   4028 }
   4029 
   4030 /* Clean up connection to a remote debugger.  */
   4032 
   4033 void
   4034 remote_target::close ()
   4035 {
   4036   /* Make sure we leave stdin registered in the event loop.  */
   4037   terminal_ours ();
   4038 
   4039   /* We don't have a connection to the remote stub anymore.  Get rid
   4040      of all the inferiors and their threads we were controlling.
   4041      Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
   4042      will be unable to find the thread corresponding to (pid, 0, 0).  */
   4043   inferior_ptid = null_ptid;
   4044   discard_all_inferiors ();
   4045 
   4046   trace_reset_local_state ();
   4047 
   4048   delete this;
   4049 }
   4050 
   4051 remote_target::~remote_target ()
   4052 {
   4053   struct remote_state *rs = get_remote_state ();
   4054 
   4055   /* Check for NULL because we may get here with a partially
   4056      constructed target/connection.  */
   4057   if (rs->remote_desc == nullptr)
   4058     return;
   4059 
   4060   serial_close (rs->remote_desc);
   4061 
   4062   /* We are destroying the remote target, so we should discard
   4063      everything of this target.  */
   4064   discard_pending_stop_replies_in_queue ();
   4065 
   4066   if (rs->remote_async_inferior_event_token)
   4067     delete_async_event_handler (&rs->remote_async_inferior_event_token);
   4068 
   4069   remote_notif_state_xfree (rs->notif_state);
   4070 }
   4071 
   4072 /* Query the remote side for the text, data and bss offsets.  */
   4073 
   4074 void
   4075 remote_target::get_offsets ()
   4076 {
   4077   struct remote_state *rs = get_remote_state ();
   4078   char *buf;
   4079   char *ptr;
   4080   int lose, num_segments = 0, do_sections, do_segments;
   4081   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
   4082   struct section_offsets *offs;
   4083   struct symfile_segment_data *data;
   4084 
   4085   if (symfile_objfile == NULL)
   4086     return;
   4087 
   4088   putpkt ("qOffsets");
   4089   getpkt (&rs->buf, 0);
   4090   buf = rs->buf.data ();
   4091 
   4092   if (buf[0] == '\000')
   4093     return;			/* Return silently.  Stub doesn't support
   4094 				   this command.  */
   4095   if (buf[0] == 'E')
   4096     {
   4097       warning (_("Remote failure reply: %s"), buf);
   4098       return;
   4099     }
   4100 
   4101   /* Pick up each field in turn.  This used to be done with scanf, but
   4102      scanf will make trouble if CORE_ADDR size doesn't match
   4103      conversion directives correctly.  The following code will work
   4104      with any size of CORE_ADDR.  */
   4105   text_addr = data_addr = bss_addr = 0;
   4106   ptr = buf;
   4107   lose = 0;
   4108 
   4109   if (startswith (ptr, "Text="))
   4110     {
   4111       ptr += 5;
   4112       /* Don't use strtol, could lose on big values.  */
   4113       while (*ptr && *ptr != ';')
   4114 	text_addr = (text_addr << 4) + fromhex (*ptr++);
   4115 
   4116       if (startswith (ptr, ";Data="))
   4117 	{
   4118 	  ptr += 6;
   4119 	  while (*ptr && *ptr != ';')
   4120 	    data_addr = (data_addr << 4) + fromhex (*ptr++);
   4121 	}
   4122       else
   4123 	lose = 1;
   4124 
   4125       if (!lose && startswith (ptr, ";Bss="))
   4126 	{
   4127 	  ptr += 5;
   4128 	  while (*ptr && *ptr != ';')
   4129 	    bss_addr = (bss_addr << 4) + fromhex (*ptr++);
   4130 
   4131 	  if (bss_addr != data_addr)
   4132 	    warning (_("Target reported unsupported offsets: %s"), buf);
   4133 	}
   4134       else
   4135 	lose = 1;
   4136     }
   4137   else if (startswith (ptr, "TextSeg="))
   4138     {
   4139       ptr += 8;
   4140       /* Don't use strtol, could lose on big values.  */
   4141       while (*ptr && *ptr != ';')
   4142 	text_addr = (text_addr << 4) + fromhex (*ptr++);
   4143       num_segments = 1;
   4144 
   4145       if (startswith (ptr, ";DataSeg="))
   4146 	{
   4147 	  ptr += 9;
   4148 	  while (*ptr && *ptr != ';')
   4149 	    data_addr = (data_addr << 4) + fromhex (*ptr++);
   4150 	  num_segments++;
   4151 	}
   4152     }
   4153   else
   4154     lose = 1;
   4155 
   4156   if (lose)
   4157     error (_("Malformed response to offset query, %s"), buf);
   4158   else if (*ptr != '\0')
   4159     warning (_("Target reported unsupported offsets: %s"), buf);
   4160 
   4161   offs = ((struct section_offsets *)
   4162 	  alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
   4163   memcpy (offs, symfile_objfile->section_offsets,
   4164 	  SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
   4165 
   4166   data = get_symfile_segment_data (symfile_objfile->obfd);
   4167   do_segments = (data != NULL);
   4168   do_sections = num_segments == 0;
   4169 
   4170   if (num_segments > 0)
   4171     {
   4172       segments[0] = text_addr;
   4173       segments[1] = data_addr;
   4174     }
   4175   /* If we have two segments, we can still try to relocate everything
   4176      by assuming that the .text and .data offsets apply to the whole
   4177      text and data segments.  Convert the offsets given in the packet
   4178      to base addresses for symfile_map_offsets_to_segments.  */
   4179   else if (data && data->num_segments == 2)
   4180     {
   4181       segments[0] = data->segment_bases[0] + text_addr;
   4182       segments[1] = data->segment_bases[1] + data_addr;
   4183       num_segments = 2;
   4184     }
   4185   /* If the object file has only one segment, assume that it is text
   4186      rather than data; main programs with no writable data are rare,
   4187      but programs with no code are useless.  Of course the code might
   4188      have ended up in the data segment... to detect that we would need
   4189      the permissions here.  */
   4190   else if (data && data->num_segments == 1)
   4191     {
   4192       segments[0] = data->segment_bases[0] + text_addr;
   4193       num_segments = 1;
   4194     }
   4195   /* There's no way to relocate by segment.  */
   4196   else
   4197     do_segments = 0;
   4198 
   4199   if (do_segments)
   4200     {
   4201       int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
   4202 						 offs, num_segments, segments);
   4203 
   4204       if (ret == 0 && !do_sections)
   4205 	error (_("Can not handle qOffsets TextSeg "
   4206 		 "response with this symbol file"));
   4207 
   4208       if (ret > 0)
   4209 	do_sections = 0;
   4210     }
   4211 
   4212   if (data)
   4213     free_symfile_segment_data (data);
   4214 
   4215   if (do_sections)
   4216     {
   4217       offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
   4218 
   4219       /* This is a temporary kludge to force data and bss to use the
   4220 	 same offsets because that's what nlmconv does now.  The real
   4221 	 solution requires changes to the stub and remote.c that I
   4222 	 don't have time to do right now.  */
   4223 
   4224       offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
   4225       offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
   4226     }
   4227 
   4228   objfile_relocate (symfile_objfile, offs);
   4229 }
   4230 
   4231 /* Send interrupt_sequence to remote target.  */
   4232 
   4233 void
   4234 remote_target::send_interrupt_sequence ()
   4235 {
   4236   struct remote_state *rs = get_remote_state ();
   4237 
   4238   if (interrupt_sequence_mode == interrupt_sequence_control_c)
   4239     remote_serial_write ("\x03", 1);
   4240   else if (interrupt_sequence_mode == interrupt_sequence_break)
   4241     serial_send_break (rs->remote_desc);
   4242   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
   4243     {
   4244       serial_send_break (rs->remote_desc);
   4245       remote_serial_write ("g", 1);
   4246     }
   4247   else
   4248     internal_error (__FILE__, __LINE__,
   4249 		    _("Invalid value for interrupt_sequence_mode: %s."),
   4250 		    interrupt_sequence_mode);
   4251 }
   4252 
   4253 
   4254 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
   4255    and extract the PTID.  Returns NULL_PTID if not found.  */
   4256 
   4257 static ptid_t
   4258 stop_reply_extract_thread (char *stop_reply)
   4259 {
   4260   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
   4261     {
   4262       const char *p;
   4263 
   4264       /* Txx r:val ; r:val (...)  */
   4265       p = &stop_reply[3];
   4266 
   4267       /* Look for "register" named "thread".  */
   4268       while (*p != '\0')
   4269 	{
   4270 	  const char *p1;
   4271 
   4272 	  p1 = strchr (p, ':');
   4273 	  if (p1 == NULL)
   4274 	    return null_ptid;
   4275 
   4276 	  if (strncmp (p, "thread", p1 - p) == 0)
   4277 	    return read_ptid (++p1, &p);
   4278 
   4279 	  p1 = strchr (p, ';');
   4280 	  if (p1 == NULL)
   4281 	    return null_ptid;
   4282 	  p1++;
   4283 
   4284 	  p = p1;
   4285 	}
   4286     }
   4287 
   4288   return null_ptid;
   4289 }
   4290 
   4291 /* Determine the remote side's current thread.  If we have a stop
   4292    reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
   4293    "thread" register we can extract the current thread from.  If not,
   4294    ask the remote which is the current thread with qC.  The former
   4295    method avoids a roundtrip.  */
   4296 
   4297 ptid_t
   4298 remote_target::get_current_thread (char *wait_status)
   4299 {
   4300   ptid_t ptid = null_ptid;
   4301 
   4302   /* Note we don't use remote_parse_stop_reply as that makes use of
   4303      the target architecture, which we haven't yet fully determined at
   4304      this point.  */
   4305   if (wait_status != NULL)
   4306     ptid = stop_reply_extract_thread (wait_status);
   4307   if (ptid == null_ptid)
   4308     ptid = remote_current_thread (inferior_ptid);
   4309 
   4310   return ptid;
   4311 }
   4312 
   4313 /* Query the remote target for which is the current thread/process,
   4314    add it to our tables, and update INFERIOR_PTID.  The caller is
   4315    responsible for setting the state such that the remote end is ready
   4316    to return the current thread.
   4317 
   4318    This function is called after handling the '?' or 'vRun' packets,
   4319    whose response is a stop reply from which we can also try
   4320    extracting the thread.  If the target doesn't support the explicit
   4321    qC query, we infer the current thread from that stop reply, passed
   4322    in in WAIT_STATUS, which may be NULL.  */
   4323 
   4324 void
   4325 remote_target::add_current_inferior_and_thread (char *wait_status)
   4326 {
   4327   struct remote_state *rs = get_remote_state ();
   4328   int fake_pid_p = 0;
   4329 
   4330   inferior_ptid = null_ptid;
   4331 
   4332   /* Now, if we have thread information, update inferior_ptid.  */
   4333   ptid_t curr_ptid = get_current_thread (wait_status);
   4334 
   4335   if (curr_ptid != null_ptid)
   4336     {
   4337       if (!remote_multi_process_p (rs))
   4338 	fake_pid_p = 1;
   4339     }
   4340   else
   4341     {
   4342       /* Without this, some commands which require an active target
   4343 	 (such as kill) won't work.  This variable serves (at least)
   4344 	 double duty as both the pid of the target process (if it has
   4345 	 such), and as a flag indicating that a target is active.  */
   4346       curr_ptid = magic_null_ptid;
   4347       fake_pid_p = 1;
   4348     }
   4349 
   4350   remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
   4351 
   4352   /* Add the main thread and switch to it.  Don't try reading
   4353      registers yet, since we haven't fetched the target description
   4354      yet.  */
   4355   thread_info *tp = add_thread_silent (curr_ptid);
   4356   switch_to_thread_no_regs (tp);
   4357 }
   4358 
   4359 /* Print info about a thread that was found already stopped on
   4360    connection.  */
   4361 
   4362 static void
   4363 print_one_stopped_thread (struct thread_info *thread)
   4364 {
   4365   struct target_waitstatus *ws = &thread->suspend.waitstatus;
   4366 
   4367   switch_to_thread (thread);
   4368   thread->suspend.stop_pc = get_frame_pc (get_current_frame ());
   4369   set_current_sal_from_frame (get_current_frame ());
   4370 
   4371   thread->suspend.waitstatus_pending_p = 0;
   4372 
   4373   if (ws->kind == TARGET_WAITKIND_STOPPED)
   4374     {
   4375       enum gdb_signal sig = ws->value.sig;
   4376 
   4377       if (signal_print_state (sig))
   4378 	gdb::observers::signal_received.notify (sig);
   4379     }
   4380   gdb::observers::normal_stop.notify (NULL, 1);
   4381 }
   4382 
   4383 /* Process all initial stop replies the remote side sent in response
   4384    to the ? packet.  These indicate threads that were already stopped
   4385    on initial connection.  We mark these threads as stopped and print
   4386    their current frame before giving the user the prompt.  */
   4387 
   4388 void
   4389 remote_target::process_initial_stop_replies (int from_tty)
   4390 {
   4391   int pending_stop_replies = stop_reply_queue_length ();
   4392   struct thread_info *selected = NULL;
   4393   struct thread_info *lowest_stopped = NULL;
   4394   struct thread_info *first = NULL;
   4395 
   4396   /* Consume the initial pending events.  */
   4397   while (pending_stop_replies-- > 0)
   4398     {
   4399       ptid_t waiton_ptid = minus_one_ptid;
   4400       ptid_t event_ptid;
   4401       struct target_waitstatus ws;
   4402       int ignore_event = 0;
   4403 
   4404       memset (&ws, 0, sizeof (ws));
   4405       event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
   4406       if (remote_debug)
   4407 	print_target_wait_results (waiton_ptid, event_ptid, &ws);
   4408 
   4409       switch (ws.kind)
   4410 	{
   4411 	case TARGET_WAITKIND_IGNORE:
   4412 	case TARGET_WAITKIND_NO_RESUMED:
   4413 	case TARGET_WAITKIND_SIGNALLED:
   4414 	case TARGET_WAITKIND_EXITED:
   4415 	  /* We shouldn't see these, but if we do, just ignore.  */
   4416 	  if (remote_debug)
   4417 	    fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
   4418 	  ignore_event = 1;
   4419 	  break;
   4420 
   4421 	case TARGET_WAITKIND_EXECD:
   4422 	  xfree (ws.value.execd_pathname);
   4423 	  break;
   4424 	default:
   4425 	  break;
   4426 	}
   4427 
   4428       if (ignore_event)
   4429 	continue;
   4430 
   4431       struct thread_info *evthread = find_thread_ptid (event_ptid);
   4432 
   4433       if (ws.kind == TARGET_WAITKIND_STOPPED)
   4434 	{
   4435 	  enum gdb_signal sig = ws.value.sig;
   4436 
   4437 	  /* Stubs traditionally report SIGTRAP as initial signal,
   4438 	     instead of signal 0.  Suppress it.  */
   4439 	  if (sig == GDB_SIGNAL_TRAP)
   4440 	    sig = GDB_SIGNAL_0;
   4441 	  evthread->suspend.stop_signal = sig;
   4442 	  ws.value.sig = sig;
   4443 	}
   4444 
   4445       evthread->suspend.waitstatus = ws;
   4446 
   4447       if (ws.kind != TARGET_WAITKIND_STOPPED
   4448 	  || ws.value.sig != GDB_SIGNAL_0)
   4449 	evthread->suspend.waitstatus_pending_p = 1;
   4450 
   4451       set_executing (event_ptid, 0);
   4452       set_running (event_ptid, 0);
   4453       get_remote_thread_info (evthread)->vcont_resumed = 0;
   4454     }
   4455 
   4456   /* "Notice" the new inferiors before anything related to
   4457      registers/memory.  */
   4458   for (inferior *inf : all_non_exited_inferiors ())
   4459     {
   4460       inf->needs_setup = 1;
   4461 
   4462       if (non_stop)
   4463 	{
   4464 	  thread_info *thread = any_live_thread_of_inferior (inf);
   4465 	  notice_new_inferior (thread, thread->state == THREAD_RUNNING,
   4466 			       from_tty);
   4467 	}
   4468     }
   4469 
   4470   /* If all-stop on top of non-stop, pause all threads.  Note this
   4471      records the threads' stop pc, so must be done after "noticing"
   4472      the inferiors.  */
   4473   if (!non_stop)
   4474     {
   4475       stop_all_threads ();
   4476 
   4477       /* If all threads of an inferior were already stopped, we
   4478 	 haven't setup the inferior yet.  */
   4479       for (inferior *inf : all_non_exited_inferiors ())
   4480 	{
   4481 	  if (inf->needs_setup)
   4482 	    {
   4483 	      thread_info *thread = any_live_thread_of_inferior (inf);
   4484 	      switch_to_thread_no_regs (thread);
   4485 	      setup_inferior (0);
   4486 	    }
   4487 	}
   4488     }
   4489 
   4490   /* Now go over all threads that are stopped, and print their current
   4491      frame.  If all-stop, then if there's a signalled thread, pick
   4492      that as current.  */
   4493   for (thread_info *thread : all_non_exited_threads ())
   4494     {
   4495       if (first == NULL)
   4496 	first = thread;
   4497 
   4498       if (!non_stop)
   4499 	thread->set_running (false);
   4500       else if (thread->state != THREAD_STOPPED)
   4501 	continue;
   4502 
   4503       if (selected == NULL
   4504 	  && thread->suspend.waitstatus_pending_p)
   4505 	selected = thread;
   4506 
   4507       if (lowest_stopped == NULL
   4508 	  || thread->inf->num < lowest_stopped->inf->num
   4509 	  || thread->per_inf_num < lowest_stopped->per_inf_num)
   4510 	lowest_stopped = thread;
   4511 
   4512       if (non_stop)
   4513 	print_one_stopped_thread (thread);
   4514     }
   4515 
   4516   /* In all-stop, we only print the status of one thread, and leave
   4517      others with their status pending.  */
   4518   if (!non_stop)
   4519     {
   4520       thread_info *thread = selected;
   4521       if (thread == NULL)
   4522 	thread = lowest_stopped;
   4523       if (thread == NULL)
   4524 	thread = first;
   4525 
   4526       print_one_stopped_thread (thread);
   4527     }
   4528 
   4529   /* For "info program".  */
   4530   thread_info *thread = inferior_thread ();
   4531   if (thread->state == THREAD_STOPPED)
   4532     set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
   4533 }
   4534 
   4535 /* Start the remote connection and sync state.  */
   4536 
   4537 void
   4538 remote_target::start_remote (int from_tty, int extended_p)
   4539 {
   4540   struct remote_state *rs = get_remote_state ();
   4541   struct packet_config *noack_config;
   4542   char *wait_status = NULL;
   4543 
   4544   /* Signal other parts that we're going through the initial setup,
   4545      and so things may not be stable yet.  E.g., we don't try to
   4546      install tracepoints until we've relocated symbols.  Also, a
   4547      Ctrl-C before we're connected and synced up can't interrupt the
   4548      target.  Instead, it offers to drop the (potentially wedged)
   4549      connection.  */
   4550   rs->starting_up = 1;
   4551 
   4552   QUIT;
   4553 
   4554   if (interrupt_on_connect)
   4555     send_interrupt_sequence ();
   4556 
   4557   /* Ack any packet which the remote side has already sent.  */
   4558   remote_serial_write ("+", 1);
   4559 
   4560   /* The first packet we send to the target is the optional "supported
   4561      packets" request.  If the target can answer this, it will tell us
   4562      which later probes to skip.  */
   4563   remote_query_supported ();
   4564 
   4565   /* If the stub wants to get a QAllow, compose one and send it.  */
   4566   if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
   4567     set_permissions ();
   4568 
   4569   /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
   4570      unknown 'v' packet with string "OK".  "OK" gets interpreted by GDB
   4571      as a reply to known packet.  For packet "vFile:setfs:" it is an
   4572      invalid reply and GDB would return error in
   4573      remote_hostio_set_filesystem, making remote files access impossible.
   4574      Disable "vFile:setfs:" in such case.  Do not disable other 'v' packets as
   4575      other "vFile" packets get correctly detected even on gdbserver < 7.7.  */
   4576   {
   4577     const char v_mustreplyempty[] = "vMustReplyEmpty";
   4578 
   4579     putpkt (v_mustreplyempty);
   4580     getpkt (&rs->buf, 0);
   4581     if (strcmp (rs->buf.data (), "OK") == 0)
   4582       remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
   4583     else if (strcmp (rs->buf.data (), "") != 0)
   4584       error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
   4585 	     rs->buf.data ());
   4586   }
   4587 
   4588   /* Next, we possibly activate noack mode.
   4589 
   4590      If the QStartNoAckMode packet configuration is set to AUTO,
   4591      enable noack mode if the stub reported a wish for it with
   4592      qSupported.
   4593 
   4594      If set to TRUE, then enable noack mode even if the stub didn't
   4595      report it in qSupported.  If the stub doesn't reply OK, the
   4596      session ends with an error.
   4597 
   4598      If FALSE, then don't activate noack mode, regardless of what the
   4599      stub claimed should be the default with qSupported.  */
   4600 
   4601   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
   4602   if (packet_config_support (noack_config) != PACKET_DISABLE)
   4603     {
   4604       putpkt ("QStartNoAckMode");
   4605       getpkt (&rs->buf, 0);
   4606       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
   4607 	rs->noack_mode = 1;
   4608     }
   4609 
   4610   if (extended_p)
   4611     {
   4612       /* Tell the remote that we are using the extended protocol.  */
   4613       putpkt ("!");
   4614       getpkt (&rs->buf, 0);
   4615     }
   4616 
   4617   /* Let the target know which signals it is allowed to pass down to
   4618      the program.  */
   4619   update_signals_program_target ();
   4620 
   4621   /* Next, if the target can specify a description, read it.  We do
   4622      this before anything involving memory or registers.  */
   4623   target_find_description ();
   4624 
   4625   /* Next, now that we know something about the target, update the
   4626      address spaces in the program spaces.  */
   4627   update_address_spaces ();
   4628 
   4629   /* On OSs where the list of libraries is global to all
   4630      processes, we fetch them early.  */
   4631   if (gdbarch_has_global_solist (target_gdbarch ()))
   4632     solib_add (NULL, from_tty, auto_solib_add);
   4633 
   4634   if (target_is_non_stop_p ())
   4635     {
   4636       if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
   4637 	error (_("Non-stop mode requested, but remote "
   4638 		 "does not support non-stop"));
   4639 
   4640       putpkt ("QNonStop:1");
   4641       getpkt (&rs->buf, 0);
   4642 
   4643       if (strcmp (rs->buf.data (), "OK") != 0)
   4644 	error (_("Remote refused setting non-stop mode with: %s"),
   4645 	       rs->buf.data ());
   4646 
   4647       /* Find about threads and processes the stub is already
   4648 	 controlling.  We default to adding them in the running state.
   4649 	 The '?' query below will then tell us about which threads are
   4650 	 stopped.  */
   4651       this->update_thread_list ();
   4652     }
   4653   else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
   4654     {
   4655       /* Don't assume that the stub can operate in all-stop mode.
   4656 	 Request it explicitly.  */
   4657       putpkt ("QNonStop:0");
   4658       getpkt (&rs->buf, 0);
   4659 
   4660       if (strcmp (rs->buf.data (), "OK") != 0)
   4661 	error (_("Remote refused setting all-stop mode with: %s"),
   4662 	       rs->buf.data ());
   4663     }
   4664 
   4665   /* Upload TSVs regardless of whether the target is running or not.  The
   4666      remote stub, such as GDBserver, may have some predefined or builtin
   4667      TSVs, even if the target is not running.  */
   4668   if (get_trace_status (current_trace_status ()) != -1)
   4669     {
   4670       struct uploaded_tsv *uploaded_tsvs = NULL;
   4671 
   4672       upload_trace_state_variables (&uploaded_tsvs);
   4673       merge_uploaded_trace_state_variables (&uploaded_tsvs);
   4674     }
   4675 
   4676   /* Check whether the target is running now.  */
   4677   putpkt ("?");
   4678   getpkt (&rs->buf, 0);
   4679 
   4680   if (!target_is_non_stop_p ())
   4681     {
   4682       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
   4683 	{
   4684 	  if (!extended_p)
   4685 	    error (_("The target is not running (try extended-remote?)"));
   4686 
   4687 	  /* We're connected, but not running.  Drop out before we
   4688 	     call start_remote.  */
   4689 	  rs->starting_up = 0;
   4690 	  return;
   4691 	}
   4692       else
   4693 	{
   4694 	  /* Save the reply for later.  */
   4695 	  wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
   4696 	  strcpy (wait_status, rs->buf.data ());
   4697 	}
   4698 
   4699       /* Fetch thread list.  */
   4700       target_update_thread_list ();
   4701 
   4702       /* Let the stub know that we want it to return the thread.  */
   4703       set_continue_thread (minus_one_ptid);
   4704 
   4705       if (thread_count () == 0)
   4706 	{
   4707 	  /* Target has no concept of threads at all.  GDB treats
   4708 	     non-threaded target as single-threaded; add a main
   4709 	     thread.  */
   4710 	  add_current_inferior_and_thread (wait_status);
   4711 	}
   4712       else
   4713 	{
   4714 	  /* We have thread information; select the thread the target
   4715 	     says should be current.  If we're reconnecting to a
   4716 	     multi-threaded program, this will ideally be the thread
   4717 	     that last reported an event before GDB disconnected.  */
   4718 	  inferior_ptid = get_current_thread (wait_status);
   4719 	  if (inferior_ptid == null_ptid)
   4720 	    {
   4721 	      /* Odd... The target was able to list threads, but not
   4722 		 tell us which thread was current (no "thread"
   4723 		 register in T stop reply?).  Just pick the first
   4724 		 thread in the thread list then.  */
   4725 
   4726 	      if (remote_debug)
   4727 		fprintf_unfiltered (gdb_stdlog,
   4728 		                    "warning: couldn't determine remote "
   4729 				    "current thread; picking first in list.\n");
   4730 
   4731 	      inferior_ptid = inferior_list->thread_list->ptid;
   4732 	    }
   4733 	}
   4734 
   4735       /* init_wait_for_inferior should be called before get_offsets in order
   4736 	 to manage `inserted' flag in bp loc in a correct state.
   4737 	 breakpoint_init_inferior, called from init_wait_for_inferior, set
   4738 	 `inserted' flag to 0, while before breakpoint_re_set, called from
   4739 	 start_remote, set `inserted' flag to 1.  In the initialization of
   4740 	 inferior, breakpoint_init_inferior should be called first, and then
   4741 	 breakpoint_re_set can be called.  If this order is broken, state of
   4742 	 `inserted' flag is wrong, and cause some problems on breakpoint
   4743 	 manipulation.  */
   4744       init_wait_for_inferior ();
   4745 
   4746       get_offsets ();		/* Get text, data & bss offsets.  */
   4747 
   4748       /* If we could not find a description using qXfer, and we know
   4749 	 how to do it some other way, try again.  This is not
   4750 	 supported for non-stop; it could be, but it is tricky if
   4751 	 there are no stopped threads when we connect.  */
   4752       if (remote_read_description_p (this)
   4753 	  && gdbarch_target_desc (target_gdbarch ()) == NULL)
   4754 	{
   4755 	  target_clear_description ();
   4756 	  target_find_description ();
   4757 	}
   4758 
   4759       /* Use the previously fetched status.  */
   4760       gdb_assert (wait_status != NULL);
   4761       strcpy (rs->buf.data (), wait_status);
   4762       rs->cached_wait_status = 1;
   4763 
   4764       ::start_remote (from_tty); /* Initialize gdb process mechanisms.  */
   4765     }
   4766   else
   4767     {
   4768       /* Clear WFI global state.  Do this before finding about new
   4769 	 threads and inferiors, and setting the current inferior.
   4770 	 Otherwise we would clear the proceed status of the current
   4771 	 inferior when we want its stop_soon state to be preserved
   4772 	 (see notice_new_inferior).  */
   4773       init_wait_for_inferior ();
   4774 
   4775       /* In non-stop, we will either get an "OK", meaning that there
   4776 	 are no stopped threads at this time; or, a regular stop
   4777 	 reply.  In the latter case, there may be more than one thread
   4778 	 stopped --- we pull them all out using the vStopped
   4779 	 mechanism.  */
   4780       if (strcmp (rs->buf.data (), "OK") != 0)
   4781 	{
   4782 	  struct notif_client *notif = &notif_client_stop;
   4783 
   4784 	  /* remote_notif_get_pending_replies acks this one, and gets
   4785 	     the rest out.  */
   4786 	  rs->notif_state->pending_event[notif_client_stop.id]
   4787 	    = remote_notif_parse (this, notif, rs->buf.data ());
   4788 	  remote_notif_get_pending_events (notif);
   4789 	}
   4790 
   4791       if (thread_count () == 0)
   4792 	{
   4793 	  if (!extended_p)
   4794 	    error (_("The target is not running (try extended-remote?)"));
   4795 
   4796 	  /* We're connected, but not running.  Drop out before we
   4797 	     call start_remote.  */
   4798 	  rs->starting_up = 0;
   4799 	  return;
   4800 	}
   4801 
   4802       /* In non-stop mode, any cached wait status will be stored in
   4803 	 the stop reply queue.  */
   4804       gdb_assert (wait_status == NULL);
   4805 
   4806       /* Report all signals during attach/startup.  */
   4807       pass_signals ({});
   4808 
   4809       /* If there are already stopped threads, mark them stopped and
   4810 	 report their stops before giving the prompt to the user.  */
   4811       process_initial_stop_replies (from_tty);
   4812 
   4813       if (target_can_async_p ())
   4814 	target_async (1);
   4815     }
   4816 
   4817   /* If we connected to a live target, do some additional setup.  */
   4818   if (target_has_execution)
   4819     {
   4820       if (symfile_objfile) 	/* No use without a symbol-file.  */
   4821 	remote_check_symbols ();
   4822     }
   4823 
   4824   /* Possibly the target has been engaged in a trace run started
   4825      previously; find out where things are at.  */
   4826   if (get_trace_status (current_trace_status ()) != -1)
   4827     {
   4828       struct uploaded_tp *uploaded_tps = NULL;
   4829 
   4830       if (current_trace_status ()->running)
   4831 	printf_filtered (_("Trace is already running on the target.\n"));
   4832 
   4833       upload_tracepoints (&uploaded_tps);
   4834 
   4835       merge_uploaded_tracepoints (&uploaded_tps);
   4836     }
   4837 
   4838   /* Possibly the target has been engaged in a btrace record started
   4839      previously; find out where things are at.  */
   4840   remote_btrace_maybe_reopen ();
   4841 
   4842   /* The thread and inferior lists are now synchronized with the
   4843      target, our symbols have been relocated, and we're merged the
   4844      target's tracepoints with ours.  We're done with basic start
   4845      up.  */
   4846   rs->starting_up = 0;
   4847 
   4848   /* Maybe breakpoints are global and need to be inserted now.  */
   4849   if (breakpoints_should_be_inserted_now ())
   4850     insert_breakpoints ();
   4851 }
   4852 
   4853 /* Open a connection to a remote debugger.
   4854    NAME is the filename used for communication.  */
   4855 
   4856 void
   4857 remote_target::open (const char *name, int from_tty)
   4858 {
   4859   open_1 (name, from_tty, 0);
   4860 }
   4861 
   4862 /* Open a connection to a remote debugger using the extended
   4863    remote gdb protocol.  NAME is the filename used for communication.  */
   4864 
   4865 void
   4866 extended_remote_target::open (const char *name, int from_tty)
   4867 {
   4868   open_1 (name, from_tty, 1 /*extended_p */);
   4869 }
   4870 
   4871 /* Reset all packets back to "unknown support".  Called when opening a
   4872    new connection to a remote target.  */
   4873 
   4874 static void
   4875 reset_all_packet_configs_support (void)
   4876 {
   4877   int i;
   4878 
   4879   for (i = 0; i < PACKET_MAX; i++)
   4880     remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
   4881 }
   4882 
   4883 /* Initialize all packet configs.  */
   4884 
   4885 static void
   4886 init_all_packet_configs (void)
   4887 {
   4888   int i;
   4889 
   4890   for (i = 0; i < PACKET_MAX; i++)
   4891     {
   4892       remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
   4893       remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
   4894     }
   4895 }
   4896 
   4897 /* Symbol look-up.  */
   4898 
   4899 void
   4900 remote_target::remote_check_symbols ()
   4901 {
   4902   char *tmp;
   4903   int end;
   4904 
   4905   /* The remote side has no concept of inferiors that aren't running
   4906      yet, it only knows about running processes.  If we're connected
   4907      but our current inferior is not running, we should not invite the
   4908      remote target to request symbol lookups related to its
   4909      (unrelated) current process.  */
   4910   if (!target_has_execution)
   4911     return;
   4912 
   4913   if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
   4914     return;
   4915 
   4916   /* Make sure the remote is pointing at the right process.  Note
   4917      there's no way to select "no process".  */
   4918   set_general_process ();
   4919 
   4920   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
   4921      because we need both at the same time.  */
   4922   gdb::char_vector msg (get_remote_packet_size ());
   4923   gdb::char_vector reply (get_remote_packet_size ());
   4924 
   4925   /* Invite target to request symbol lookups.  */
   4926 
   4927   putpkt ("qSymbol::");
   4928   getpkt (&reply, 0);
   4929   packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
   4930 
   4931   while (startswith (reply.data (), "qSymbol:"))
   4932     {
   4933       struct bound_minimal_symbol sym;
   4934 
   4935       tmp = &reply[8];
   4936       end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
   4937 		     strlen (tmp) / 2);
   4938       msg[end] = '\0';
   4939       sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
   4940       if (sym.minsym == NULL)
   4941 	xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
   4942 		   &reply[8]);
   4943       else
   4944 	{
   4945 	  int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
   4946 	  CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
   4947 
   4948 	  /* If this is a function address, return the start of code
   4949 	     instead of any data function descriptor.  */
   4950 	  sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
   4951 							 sym_addr,
   4952 							 current_top_target ());
   4953 
   4954 	  xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
   4955 		     phex_nz (sym_addr, addr_size), &reply[8]);
   4956 	}
   4957 
   4958       putpkt (msg.data ());
   4959       getpkt (&reply, 0);
   4960     }
   4961 }
   4962 
   4963 static struct serial *
   4964 remote_serial_open (const char *name)
   4965 {
   4966   static int udp_warning = 0;
   4967 
   4968   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
   4969      of in ser-tcp.c, because it is the remote protocol assuming that the
   4970      serial connection is reliable and not the serial connection promising
   4971      to be.  */
   4972   if (!udp_warning && startswith (name, "udp:"))
   4973     {
   4974       warning (_("The remote protocol may be unreliable over UDP.\n"
   4975 		 "Some events may be lost, rendering further debugging "
   4976 		 "impossible."));
   4977       udp_warning = 1;
   4978     }
   4979 
   4980   return serial_open (name);
   4981 }
   4982 
   4983 /* Inform the target of our permission settings.  The permission flags
   4984    work without this, but if the target knows the settings, it can do
   4985    a couple things.  First, it can add its own check, to catch cases
   4986    that somehow manage to get by the permissions checks in target
   4987    methods.  Second, if the target is wired to disallow particular
   4988    settings (for instance, a system in the field that is not set up to
   4989    be able to stop at a breakpoint), it can object to any unavailable
   4990    permissions.  */
   4991 
   4992 void
   4993 remote_target::set_permissions ()
   4994 {
   4995   struct remote_state *rs = get_remote_state ();
   4996 
   4997   xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
   4998 	     "WriteReg:%x;WriteMem:%x;"
   4999 	     "InsertBreak:%x;InsertTrace:%x;"
   5000 	     "InsertFastTrace:%x;Stop:%x",
   5001 	     may_write_registers, may_write_memory,
   5002 	     may_insert_breakpoints, may_insert_tracepoints,
   5003 	     may_insert_fast_tracepoints, may_stop);
   5004   putpkt (rs->buf);
   5005   getpkt (&rs->buf, 0);
   5006 
   5007   /* If the target didn't like the packet, warn the user.  Do not try
   5008      to undo the user's settings, that would just be maddening.  */
   5009   if (strcmp (rs->buf.data (), "OK") != 0)
   5010     warning (_("Remote refused setting permissions with: %s"),
   5011 	     rs->buf.data ());
   5012 }
   5013 
   5014 /* This type describes each known response to the qSupported
   5015    packet.  */
   5016 struct protocol_feature
   5017 {
   5018   /* The name of this protocol feature.  */
   5019   const char *name;
   5020 
   5021   /* The default for this protocol feature.  */
   5022   enum packet_support default_support;
   5023 
   5024   /* The function to call when this feature is reported, or after
   5025      qSupported processing if the feature is not supported.
   5026      The first argument points to this structure.  The second
   5027      argument indicates whether the packet requested support be
   5028      enabled, disabled, or probed (or the default, if this function
   5029      is being called at the end of processing and this feature was
   5030      not reported).  The third argument may be NULL; if not NULL, it
   5031      is a NUL-terminated string taken from the packet following
   5032      this feature's name and an equals sign.  */
   5033   void (*func) (remote_target *remote, const struct protocol_feature *,
   5034 		enum packet_support, const char *);
   5035 
   5036   /* The corresponding packet for this feature.  Only used if
   5037      FUNC is remote_supported_packet.  */
   5038   int packet;
   5039 };
   5040 
   5041 static void
   5042 remote_supported_packet (remote_target *remote,
   5043 			 const struct protocol_feature *feature,
   5044 			 enum packet_support support,
   5045 			 const char *argument)
   5046 {
   5047   if (argument)
   5048     {
   5049       warning (_("Remote qSupported response supplied an unexpected value for"
   5050 		 " \"%s\"."), feature->name);
   5051       return;
   5052     }
   5053 
   5054   remote_protocol_packets[feature->packet].support = support;
   5055 }
   5056 
   5057 void
   5058 remote_target::remote_packet_size (const protocol_feature *feature,
   5059 				   enum packet_support support, const char *value)
   5060 {
   5061   struct remote_state *rs = get_remote_state ();
   5062 
   5063   int packet_size;
   5064   char *value_end;
   5065 
   5066   if (support != PACKET_ENABLE)
   5067     return;
   5068 
   5069   if (value == NULL || *value == '\0')
   5070     {
   5071       warning (_("Remote target reported \"%s\" without a size."),
   5072 	       feature->name);
   5073       return;
   5074     }
   5075 
   5076   errno = 0;
   5077   packet_size = strtol (value, &value_end, 16);
   5078   if (errno != 0 || *value_end != '\0' || packet_size < 0)
   5079     {
   5080       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
   5081 	       feature->name, value);
   5082       return;
   5083     }
   5084 
   5085   /* Record the new maximum packet size.  */
   5086   rs->explicit_packet_size = packet_size;
   5087 }
   5088 
   5089 void
   5090 remote_packet_size (remote_target *remote, const protocol_feature *feature,
   5091 		    enum packet_support support, const char *value)
   5092 {
   5093   remote->remote_packet_size (feature, support, value);
   5094 }
   5095 
   5096 static const struct protocol_feature remote_protocol_features[] = {
   5097   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
   5098   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
   5099     PACKET_qXfer_auxv },
   5100   { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
   5101     PACKET_qXfer_exec_file },
   5102   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
   5103     PACKET_qXfer_features },
   5104   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
   5105     PACKET_qXfer_libraries },
   5106   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
   5107     PACKET_qXfer_libraries_svr4 },
   5108   { "augmented-libraries-svr4-read", PACKET_DISABLE,
   5109     remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
   5110   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
   5111     PACKET_qXfer_memory_map },
   5112   { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
   5113     PACKET_qXfer_spu_read },
   5114   { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
   5115     PACKET_qXfer_spu_write },
   5116   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
   5117     PACKET_qXfer_osdata },
   5118   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
   5119     PACKET_qXfer_threads },
   5120   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
   5121     PACKET_qXfer_traceframe_info },
   5122   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
   5123     PACKET_QPassSignals },
   5124   { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
   5125     PACKET_QCatchSyscalls },
   5126   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
   5127     PACKET_QProgramSignals },
   5128   { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
   5129     PACKET_QSetWorkingDir },
   5130   { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
   5131     PACKET_QStartupWithShell },
   5132   { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
   5133     PACKET_QEnvironmentHexEncoded },
   5134   { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
   5135     PACKET_QEnvironmentReset },
   5136   { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
   5137     PACKET_QEnvironmentUnset },
   5138   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
   5139     PACKET_QStartNoAckMode },
   5140   { "multiprocess", PACKET_DISABLE, remote_supported_packet,
   5141     PACKET_multiprocess_feature },
   5142   { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
   5143   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
   5144     PACKET_qXfer_siginfo_read },
   5145   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
   5146     PACKET_qXfer_siginfo_write },
   5147   { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
   5148     PACKET_ConditionalTracepoints },
   5149   { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
   5150     PACKET_ConditionalBreakpoints },
   5151   { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
   5152     PACKET_BreakpointCommands },
   5153   { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
   5154     PACKET_FastTracepoints },
   5155   { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
   5156     PACKET_StaticTracepoints },
   5157   {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
   5158    PACKET_InstallInTrace},
   5159   { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
   5160     PACKET_DisconnectedTracing_feature },
   5161   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
   5162     PACKET_bc },
   5163   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
   5164     PACKET_bs },
   5165   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
   5166     PACKET_TracepointSource },
   5167   { "QAllow", PACKET_DISABLE, remote_supported_packet,
   5168     PACKET_QAllow },
   5169   { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
   5170     PACKET_EnableDisableTracepoints_feature },
   5171   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
   5172     PACKET_qXfer_fdpic },
   5173   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
   5174     PACKET_qXfer_uib },
   5175   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
   5176     PACKET_QDisableRandomization },
   5177   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
   5178   { "QTBuffer:size", PACKET_DISABLE,
   5179     remote_supported_packet, PACKET_QTBuffer_size},
   5180   { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
   5181   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
   5182   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
   5183   { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
   5184   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
   5185     PACKET_qXfer_btrace },
   5186   { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
   5187     PACKET_qXfer_btrace_conf },
   5188   { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
   5189     PACKET_Qbtrace_conf_bts_size },
   5190   { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
   5191   { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
   5192   { "fork-events", PACKET_DISABLE, remote_supported_packet,
   5193     PACKET_fork_event_feature },
   5194   { "vfork-events", PACKET_DISABLE, remote_supported_packet,
   5195     PACKET_vfork_event_feature },
   5196   { "exec-events", PACKET_DISABLE, remote_supported_packet,
   5197     PACKET_exec_event_feature },
   5198   { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
   5199     PACKET_Qbtrace_conf_pt_size },
   5200   { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
   5201   { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
   5202   { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
   5203 };
   5204 
   5205 static char *remote_support_xml;
   5206 
   5207 /* Register string appended to "xmlRegisters=" in qSupported query.  */
   5208 
   5209 void
   5210 register_remote_support_xml (const char *xml)
   5211 {
   5212 #if defined(HAVE_LIBEXPAT)
   5213   if (remote_support_xml == NULL)
   5214     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
   5215   else
   5216     {
   5217       char *copy = xstrdup (remote_support_xml + 13);
   5218       char *p = strtok (copy, ",");
   5219 
   5220       do
   5221 	{
   5222 	  if (strcmp (p, xml) == 0)
   5223 	    {
   5224 	      /* already there */
   5225 	      xfree (copy);
   5226 	      return;
   5227 	    }
   5228 	}
   5229       while ((p = strtok (NULL, ",")) != NULL);
   5230       xfree (copy);
   5231 
   5232       remote_support_xml = reconcat (remote_support_xml,
   5233 				     remote_support_xml, ",", xml,
   5234 				     (char *) NULL);
   5235     }
   5236 #endif
   5237 }
   5238 
   5239 static void
   5240 remote_query_supported_append (std::string *msg, const char *append)
   5241 {
   5242   if (!msg->empty ())
   5243     msg->append (";");
   5244   msg->append (append);
   5245 }
   5246 
   5247 void
   5248 remote_target::remote_query_supported ()
   5249 {
   5250   struct remote_state *rs = get_remote_state ();
   5251   char *next;
   5252   int i;
   5253   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
   5254 
   5255   /* The packet support flags are handled differently for this packet
   5256      than for most others.  We treat an error, a disabled packet, and
   5257      an empty response identically: any features which must be reported
   5258      to be used will be automatically disabled.  An empty buffer
   5259      accomplishes this, since that is also the representation for a list
   5260      containing no features.  */
   5261 
   5262   rs->buf[0] = 0;
   5263   if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
   5264     {
   5265       std::string q;
   5266 
   5267       if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
   5268 	remote_query_supported_append (&q, "multiprocess+");
   5269 
   5270       if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
   5271 	remote_query_supported_append (&q, "swbreak+");
   5272       if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
   5273 	remote_query_supported_append (&q, "hwbreak+");
   5274 
   5275       remote_query_supported_append (&q, "qRelocInsn+");
   5276 
   5277       if (packet_set_cmd_state (PACKET_fork_event_feature)
   5278 	  != AUTO_BOOLEAN_FALSE)
   5279 	remote_query_supported_append (&q, "fork-events+");
   5280       if (packet_set_cmd_state (PACKET_vfork_event_feature)
   5281 	  != AUTO_BOOLEAN_FALSE)
   5282 	remote_query_supported_append (&q, "vfork-events+");
   5283       if (packet_set_cmd_state (PACKET_exec_event_feature)
   5284 	  != AUTO_BOOLEAN_FALSE)
   5285 	remote_query_supported_append (&q, "exec-events+");
   5286 
   5287       if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
   5288 	remote_query_supported_append (&q, "vContSupported+");
   5289 
   5290       if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
   5291 	remote_query_supported_append (&q, "QThreadEvents+");
   5292 
   5293       if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
   5294 	remote_query_supported_append (&q, "no-resumed+");
   5295 
   5296       /* Keep this one last to work around a gdbserver <= 7.10 bug in
   5297 	 the qSupported:xmlRegisters=i386 handling.  */
   5298       if (remote_support_xml != NULL
   5299 	  && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
   5300 	remote_query_supported_append (&q, remote_support_xml);
   5301 
   5302       q = "qSupported:" + q;
   5303       putpkt (q.c_str ());
   5304 
   5305       getpkt (&rs->buf, 0);
   5306 
   5307       /* If an error occured, warn, but do not return - just reset the
   5308 	 buffer to empty and go on to disable features.  */
   5309       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
   5310 	  == PACKET_ERROR)
   5311 	{
   5312 	  warning (_("Remote failure reply: %s"), rs->buf.data ());
   5313 	  rs->buf[0] = 0;
   5314 	}
   5315     }
   5316 
   5317   memset (seen, 0, sizeof (seen));
   5318 
   5319   next = rs->buf.data ();
   5320   while (*next)
   5321     {
   5322       enum packet_support is_supported;
   5323       char *p, *end, *name_end, *value;
   5324 
   5325       /* First separate out this item from the rest of the packet.  If
   5326 	 there's another item after this, we overwrite the separator
   5327 	 (terminated strings are much easier to work with).  */
   5328       p = next;
   5329       end = strchr (p, ';');
   5330       if (end == NULL)
   5331 	{
   5332 	  end = p + strlen (p);
   5333 	  next = end;
   5334 	}
   5335       else
   5336 	{
   5337 	  *end = '\0';
   5338 	  next = end + 1;
   5339 
   5340 	  if (end == p)
   5341 	    {
   5342 	      warning (_("empty item in \"qSupported\" response"));
   5343 	      continue;
   5344 	    }
   5345 	}
   5346 
   5347       name_end = strchr (p, '=');
   5348       if (name_end)
   5349 	{
   5350 	  /* This is a name=value entry.  */
   5351 	  is_supported = PACKET_ENABLE;
   5352 	  value = name_end + 1;
   5353 	  *name_end = '\0';
   5354 	}
   5355       else
   5356 	{
   5357 	  value = NULL;
   5358 	  switch (end[-1])
   5359 	    {
   5360 	    case '+':
   5361 	      is_supported = PACKET_ENABLE;
   5362 	      break;
   5363 
   5364 	    case '-':
   5365 	      is_supported = PACKET_DISABLE;
   5366 	      break;
   5367 
   5368 	    case '?':
   5369 	      is_supported = PACKET_SUPPORT_UNKNOWN;
   5370 	      break;
   5371 
   5372 	    default:
   5373 	      warning (_("unrecognized item \"%s\" "
   5374 			 "in \"qSupported\" response"), p);
   5375 	      continue;
   5376 	    }
   5377 	  end[-1] = '\0';
   5378 	}
   5379 
   5380       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
   5381 	if (strcmp (remote_protocol_features[i].name, p) == 0)
   5382 	  {
   5383 	    const struct protocol_feature *feature;
   5384 
   5385 	    seen[i] = 1;
   5386 	    feature = &remote_protocol_features[i];
   5387 	    feature->func (this, feature, is_supported, value);
   5388 	    break;
   5389 	  }
   5390     }
   5391 
   5392   /* If we increased the packet size, make sure to increase the global
   5393      buffer size also.  We delay this until after parsing the entire
   5394      qSupported packet, because this is the same buffer we were
   5395      parsing.  */
   5396   if (rs->buf.size () < rs->explicit_packet_size)
   5397     rs->buf.resize (rs->explicit_packet_size);
   5398 
   5399   /* Handle the defaults for unmentioned features.  */
   5400   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
   5401     if (!seen[i])
   5402       {
   5403 	const struct protocol_feature *feature;
   5404 
   5405 	feature = &remote_protocol_features[i];
   5406 	feature->func (this, feature, feature->default_support, NULL);
   5407       }
   5408 }
   5409 
   5410 /* Serial QUIT handler for the remote serial descriptor.
   5411 
   5412    Defers handling a Ctrl-C until we're done with the current
   5413    command/response packet sequence, unless:
   5414 
   5415    - We're setting up the connection.  Don't send a remote interrupt
   5416      request, as we're not fully synced yet.  Quit immediately
   5417      instead.
   5418 
   5419    - The target has been resumed in the foreground
   5420      (target_terminal::is_ours is false) with a synchronous resume
   5421      packet, and we're blocked waiting for the stop reply, thus a
   5422      Ctrl-C should be immediately sent to the target.
   5423 
   5424    - We get a second Ctrl-C while still within the same serial read or
   5425      write.  In that case the serial is seemingly wedged --- offer to
   5426      quit/disconnect.
   5427 
   5428    - We see a second Ctrl-C without target response, after having
   5429      previously interrupted the target.  In that case the target/stub
   5430      is probably wedged --- offer to quit/disconnect.
   5431 */
   5432 
   5433 void
   5434 remote_target::remote_serial_quit_handler ()
   5435 {
   5436   struct remote_state *rs = get_remote_state ();
   5437 
   5438   if (check_quit_flag ())
   5439     {
   5440       /* If we're starting up, we're not fully synced yet.  Quit
   5441 	 immediately.  */
   5442       if (rs->starting_up)
   5443 	quit ();
   5444       else if (rs->got_ctrlc_during_io)
   5445 	{
   5446 	  if (query (_("The target is not responding to GDB commands.\n"
   5447 		       "Stop debugging it? ")))
   5448 	    remote_unpush_and_throw ();
   5449 	}
   5450       /* If ^C has already been sent once, offer to disconnect.  */
   5451       else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
   5452 	interrupt_query ();
   5453       /* All-stop protocol, and blocked waiting for stop reply.  Send
   5454 	 an interrupt request.  */
   5455       else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
   5456 	target_interrupt ();
   5457       else
   5458 	rs->got_ctrlc_during_io = 1;
   5459     }
   5460 }
   5461 
   5462 /* The remote_target that is current while the quit handler is
   5463    overridden with remote_serial_quit_handler.  */
   5464 static remote_target *curr_quit_handler_target;
   5465 
   5466 static void
   5467 remote_serial_quit_handler ()
   5468 {
   5469   curr_quit_handler_target->remote_serial_quit_handler ();
   5470 }
   5471 
   5472 /* Remove any of the remote.c targets from target stack.  Upper targets depend
   5473    on it so remove them first.  */
   5474 
   5475 static void
   5476 remote_unpush_target (void)
   5477 {
   5478   pop_all_targets_at_and_above (process_stratum);
   5479 }
   5480 
   5481 static void
   5482 remote_unpush_and_throw (void)
   5483 {
   5484   remote_unpush_target ();
   5485   throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
   5486 }
   5487 
   5488 void
   5489 remote_target::open_1 (const char *name, int from_tty, int extended_p)
   5490 {
   5491   remote_target *curr_remote = get_current_remote_target ();
   5492 
   5493   if (name == 0)
   5494     error (_("To open a remote debug connection, you need to specify what\n"
   5495 	   "serial device is attached to the remote system\n"
   5496 	   "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
   5497 
   5498   /* If we're connected to a running target, target_preopen will kill it.
   5499      Ask this question first, before target_preopen has a chance to kill
   5500      anything.  */
   5501   if (curr_remote != NULL && !have_inferiors ())
   5502     {
   5503       if (from_tty
   5504 	  && !query (_("Already connected to a remote target.  Disconnect? ")))
   5505 	error (_("Still connected."));
   5506     }
   5507 
   5508   /* Here the possibly existing remote target gets unpushed.  */
   5509   target_preopen (from_tty);
   5510 
   5511   remote_fileio_reset ();
   5512   reopen_exec_file ();
   5513   reread_symbols ();
   5514 
   5515   remote_target *remote
   5516     = (extended_p ? new extended_remote_target () : new remote_target ());
   5517   target_ops_up target_holder (remote);
   5518 
   5519   remote_state *rs = remote->get_remote_state ();
   5520 
   5521   /* See FIXME above.  */
   5522   if (!target_async_permitted)
   5523     rs->wait_forever_enabled_p = 1;
   5524 
   5525   rs->remote_desc = remote_serial_open (name);
   5526   if (!rs->remote_desc)
   5527     perror_with_name (name);
   5528 
   5529   if (baud_rate != -1)
   5530     {
   5531       if (serial_setbaudrate (rs->remote_desc, baud_rate))
   5532 	{
   5533 	  /* The requested speed could not be set.  Error out to
   5534 	     top level after closing remote_desc.  Take care to
   5535 	     set remote_desc to NULL to avoid closing remote_desc
   5536 	     more than once.  */
   5537 	  serial_close (rs->remote_desc);
   5538 	  rs->remote_desc = NULL;
   5539 	  perror_with_name (name);
   5540 	}
   5541     }
   5542 
   5543   serial_setparity (rs->remote_desc, serial_parity);
   5544   serial_raw (rs->remote_desc);
   5545 
   5546   /* If there is something sitting in the buffer we might take it as a
   5547      response to a command, which would be bad.  */
   5548   serial_flush_input (rs->remote_desc);
   5549 
   5550   if (from_tty)
   5551     {
   5552       puts_filtered ("Remote debugging using ");
   5553       puts_filtered (name);
   5554       puts_filtered ("\n");
   5555     }
   5556 
   5557   /* Switch to using the remote target now.  */
   5558   push_target (std::move (target_holder));
   5559 
   5560   /* Register extra event sources in the event loop.  */
   5561   rs->remote_async_inferior_event_token
   5562     = create_async_event_handler (remote_async_inferior_event_handler,
   5563 				  remote);
   5564   rs->notif_state = remote_notif_state_allocate (remote);
   5565 
   5566   /* Reset the target state; these things will be queried either by
   5567      remote_query_supported or as they are needed.  */
   5568   reset_all_packet_configs_support ();
   5569   rs->cached_wait_status = 0;
   5570   rs->explicit_packet_size = 0;
   5571   rs->noack_mode = 0;
   5572   rs->extended = extended_p;
   5573   rs->waiting_for_stop_reply = 0;
   5574   rs->ctrlc_pending_p = 0;
   5575   rs->got_ctrlc_during_io = 0;
   5576 
   5577   rs->general_thread = not_sent_ptid;
   5578   rs->continue_thread = not_sent_ptid;
   5579   rs->remote_traceframe_number = -1;
   5580 
   5581   rs->last_resume_exec_dir = EXEC_FORWARD;
   5582 
   5583   /* Probe for ability to use "ThreadInfo" query, as required.  */
   5584   rs->use_threadinfo_query = 1;
   5585   rs->use_threadextra_query = 1;
   5586 
   5587   rs->readahead_cache.invalidate ();
   5588 
   5589   if (target_async_permitted)
   5590     {
   5591       /* FIXME: cagney/1999-09-23: During the initial connection it is
   5592 	 assumed that the target is already ready and able to respond to
   5593 	 requests.  Unfortunately remote_start_remote() eventually calls
   5594 	 wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
   5595 	 around this.  Eventually a mechanism that allows
   5596 	 wait_for_inferior() to expect/get timeouts will be
   5597 	 implemented.  */
   5598       rs->wait_forever_enabled_p = 0;
   5599     }
   5600 
   5601   /* First delete any symbols previously loaded from shared libraries.  */
   5602   no_shared_libraries (NULL, 0);
   5603 
   5604   /* Start the remote connection.  If error() or QUIT, discard this
   5605      target (we'd otherwise be in an inconsistent state) and then
   5606      propogate the error on up the exception chain.  This ensures that
   5607      the caller doesn't stumble along blindly assuming that the
   5608      function succeeded.  The CLI doesn't have this problem but other
   5609      UI's, such as MI do.
   5610 
   5611      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
   5612      this function should return an error indication letting the
   5613      caller restore the previous state.  Unfortunately the command
   5614      ``target remote'' is directly wired to this function making that
   5615      impossible.  On a positive note, the CLI side of this problem has
   5616      been fixed - the function set_cmd_context() makes it possible for
   5617      all the ``target ....'' commands to share a common callback
   5618      function.  See cli-dump.c.  */
   5619   {
   5620 
   5621     TRY
   5622       {
   5623 	remote->start_remote (from_tty, extended_p);
   5624       }
   5625     CATCH (ex, RETURN_MASK_ALL)
   5626       {
   5627 	/* Pop the partially set up target - unless something else did
   5628 	   already before throwing the exception.  */
   5629 	if (ex.error != TARGET_CLOSE_ERROR)
   5630 	  remote_unpush_target ();
   5631 	throw_exception (ex);
   5632       }
   5633     END_CATCH
   5634   }
   5635 
   5636   remote_btrace_reset (rs);
   5637 
   5638   if (target_async_permitted)
   5639     rs->wait_forever_enabled_p = 1;
   5640 }
   5641 
   5642 /* Detach the specified process.  */
   5643 
   5644 void
   5645 remote_target::remote_detach_pid (int pid)
   5646 {
   5647   struct remote_state *rs = get_remote_state ();
   5648 
   5649   /* This should not be necessary, but the handling for D;PID in
   5650      GDBserver versions prior to 8.2 incorrectly assumes that the
   5651      selected process points to the same process we're detaching,
   5652      leading to misbehavior (and possibly GDBserver crashing) when it
   5653      does not.  Since it's easy and cheap, work around it by forcing
   5654      GDBserver to select GDB's current process.  */
   5655   set_general_process ();
   5656 
   5657   if (remote_multi_process_p (rs))
   5658     xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
   5659   else
   5660     strcpy (rs->buf.data (), "D");
   5661 
   5662   putpkt (rs->buf);
   5663   getpkt (&rs->buf, 0);
   5664 
   5665   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
   5666     ;
   5667   else if (rs->buf[0] == '\0')
   5668     error (_("Remote doesn't know how to detach"));
   5669   else
   5670     error (_("Can't detach process."));
   5671 }
   5672 
   5673 /* This detaches a program to which we previously attached, using
   5674    inferior_ptid to identify the process.  After this is done, GDB
   5675    can be used to debug some other program.  We better not have left
   5676    any breakpoints in the target program or it'll die when it hits
   5677    one.  */
   5678 
   5679 void
   5680 remote_target::remote_detach_1 (inferior *inf, int from_tty)
   5681 {
   5682   int pid = inferior_ptid.pid ();
   5683   struct remote_state *rs = get_remote_state ();
   5684   int is_fork_parent;
   5685 
   5686   if (!target_has_execution)
   5687     error (_("No process to detach from."));
   5688 
   5689   target_announce_detach (from_tty);
   5690 
   5691   /* Tell the remote target to detach.  */
   5692   remote_detach_pid (pid);
   5693 
   5694   /* Exit only if this is the only active inferior.  */
   5695   if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
   5696     puts_filtered (_("Ending remote debugging.\n"));
   5697 
   5698   struct thread_info *tp = find_thread_ptid (inferior_ptid);
   5699 
   5700   /* Check to see if we are detaching a fork parent.  Note that if we
   5701      are detaching a fork child, tp == NULL.  */
   5702   is_fork_parent = (tp != NULL
   5703 		    && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
   5704 
   5705   /* If doing detach-on-fork, we don't mourn, because that will delete
   5706      breakpoints that should be available for the followed inferior.  */
   5707   if (!is_fork_parent)
   5708     {
   5709       /* Save the pid as a string before mourning, since that will
   5710 	 unpush the remote target, and we need the string after.  */
   5711       std::string infpid = target_pid_to_str (ptid_t (pid));
   5712 
   5713       target_mourn_inferior (inferior_ptid);
   5714       if (print_inferior_events)
   5715 	printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
   5716 			   inf->num, infpid.c_str ());
   5717     }
   5718   else
   5719     {
   5720       inferior_ptid = null_ptid;
   5721       detach_inferior (current_inferior ());
   5722     }
   5723 }
   5724 
   5725 void
   5726 remote_target::detach (inferior *inf, int from_tty)
   5727 {
   5728   remote_detach_1 (inf, from_tty);
   5729 }
   5730 
   5731 void
   5732 extended_remote_target::detach (inferior *inf, int from_tty)
   5733 {
   5734   remote_detach_1 (inf, from_tty);
   5735 }
   5736 
   5737 /* Target follow-fork function for remote targets.  On entry, and
   5738    at return, the current inferior is the fork parent.
   5739 
   5740    Note that although this is currently only used for extended-remote,
   5741    it is named remote_follow_fork in anticipation of using it for the
   5742    remote target as well.  */
   5743 
   5744 int
   5745 remote_target::follow_fork (int follow_child, int detach_fork)
   5746 {
   5747   struct remote_state *rs = get_remote_state ();
   5748   enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
   5749 
   5750   if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
   5751       || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
   5752     {
   5753       /* When following the parent and detaching the child, we detach
   5754 	 the child here.  For the case of following the child and
   5755 	 detaching the parent, the detach is done in the target-
   5756 	 independent follow fork code in infrun.c.  We can't use
   5757 	 target_detach when detaching an unfollowed child because
   5758 	 the client side doesn't know anything about the child.  */
   5759       if (detach_fork && !follow_child)
   5760 	{
   5761 	  /* Detach the fork child.  */
   5762 	  ptid_t child_ptid;
   5763 	  pid_t child_pid;
   5764 
   5765 	  child_ptid = inferior_thread ()->pending_follow.value.related_pid;
   5766 	  child_pid = child_ptid.pid ();
   5767 
   5768 	  remote_detach_pid (child_pid);
   5769 	}
   5770     }
   5771   return 0;
   5772 }
   5773 
   5774 /* Target follow-exec function for remote targets.  Save EXECD_PATHNAME
   5775    in the program space of the new inferior.  On entry and at return the
   5776    current inferior is the exec'ing inferior.  INF is the new exec'd
   5777    inferior, which may be the same as the exec'ing inferior unless
   5778    follow-exec-mode is "new".  */
   5779 
   5780 void
   5781 remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
   5782 {
   5783   /* We know that this is a target file name, so if it has the "target:"
   5784      prefix we strip it off before saving it in the program space.  */
   5785   if (is_target_filename (execd_pathname))
   5786     execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
   5787 
   5788   set_pspace_remote_exec_file (inf->pspace, execd_pathname);
   5789 }
   5790 
   5791 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
   5792 
   5793 void
   5794 remote_target::disconnect (const char *args, int from_tty)
   5795 {
   5796   if (args)
   5797     error (_("Argument given to \"disconnect\" when remotely debugging."));
   5798 
   5799   /* Make sure we unpush even the extended remote targets.  Calling
   5800      target_mourn_inferior won't unpush, and remote_mourn won't
   5801      unpush if there is more than one inferior left.  */
   5802   unpush_target (this);
   5803   generic_mourn_inferior ();
   5804 
   5805   if (from_tty)
   5806     puts_filtered ("Ending remote debugging.\n");
   5807 }
   5808 
   5809 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
   5810    be chatty about it.  */
   5811 
   5812 void
   5813 extended_remote_target::attach (const char *args, int from_tty)
   5814 {
   5815   struct remote_state *rs = get_remote_state ();
   5816   int pid;
   5817   char *wait_status = NULL;
   5818 
   5819   pid = parse_pid_to_attach (args);
   5820 
   5821   /* Remote PID can be freely equal to getpid, do not check it here the same
   5822      way as in other targets.  */
   5823 
   5824   if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
   5825     error (_("This target does not support attaching to a process"));
   5826 
   5827   if (from_tty)
   5828     {
   5829       char *exec_file = get_exec_file (0);
   5830 
   5831       if (exec_file)
   5832 	printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
   5833 			   target_pid_to_str (ptid_t (pid)));
   5834       else
   5835 	printf_unfiltered (_("Attaching to %s\n"),
   5836 			   target_pid_to_str (ptid_t (pid)));
   5837 
   5838       gdb_flush (gdb_stdout);
   5839     }
   5840 
   5841   xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
   5842   putpkt (rs->buf);
   5843   getpkt (&rs->buf, 0);
   5844 
   5845   switch (packet_ok (rs->buf,
   5846 		     &remote_protocol_packets[PACKET_vAttach]))
   5847     {
   5848     case PACKET_OK:
   5849       if (!target_is_non_stop_p ())
   5850 	{
   5851 	  /* Save the reply for later.  */
   5852 	  wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
   5853 	  strcpy (wait_status, rs->buf.data ());
   5854 	}
   5855       else if (strcmp (rs->buf.data (), "OK") != 0)
   5856 	error (_("Attaching to %s failed with: %s"),
   5857 	       target_pid_to_str (ptid_t (pid)),
   5858 	       rs->buf.data ());
   5859       break;
   5860     case PACKET_UNKNOWN:
   5861       error (_("This target does not support attaching to a process"));
   5862     default:
   5863       error (_("Attaching to %s failed"),
   5864 	     target_pid_to_str (ptid_t (pid)));
   5865     }
   5866 
   5867   set_current_inferior (remote_add_inferior (0, pid, 1, 0));
   5868 
   5869   inferior_ptid = ptid_t (pid);
   5870 
   5871   if (target_is_non_stop_p ())
   5872     {
   5873       struct thread_info *thread;
   5874 
   5875       /* Get list of threads.  */
   5876       update_thread_list ();
   5877 
   5878       thread = first_thread_of_inferior (current_inferior ());
   5879       if (thread)
   5880 	inferior_ptid = thread->ptid;
   5881       else
   5882 	inferior_ptid = ptid_t (pid);
   5883 
   5884       /* Invalidate our notion of the remote current thread.  */
   5885       record_currthread (rs, minus_one_ptid);
   5886     }
   5887   else
   5888     {
   5889       /* Now, if we have thread information, update inferior_ptid.  */
   5890       inferior_ptid = remote_current_thread (inferior_ptid);
   5891 
   5892       /* Add the main thread to the thread list.  */
   5893       thread_info *thr = add_thread_silent (inferior_ptid);
   5894       /* Don't consider the thread stopped until we've processed the
   5895 	 saved stop reply.  */
   5896       set_executing (thr->ptid, true);
   5897     }
   5898 
   5899   /* Next, if the target can specify a description, read it.  We do
   5900      this before anything involving memory or registers.  */
   5901   target_find_description ();
   5902 
   5903   if (!target_is_non_stop_p ())
   5904     {
   5905       /* Use the previously fetched status.  */
   5906       gdb_assert (wait_status != NULL);
   5907 
   5908       if (target_can_async_p ())
   5909 	{
   5910 	  struct notif_event *reply
   5911 	    =  remote_notif_parse (this, &notif_client_stop, wait_status);
   5912 
   5913 	  push_stop_reply ((struct stop_reply *) reply);
   5914 
   5915 	  target_async (1);
   5916 	}
   5917       else
   5918 	{
   5919 	  gdb_assert (wait_status != NULL);
   5920 	  strcpy (rs->buf.data (), wait_status);
   5921 	  rs->cached_wait_status = 1;
   5922 	}
   5923     }
   5924   else
   5925     gdb_assert (wait_status == NULL);
   5926 }
   5927 
   5928 /* Implementation of the to_post_attach method.  */
   5929 
   5930 void
   5931 extended_remote_target::post_attach (int pid)
   5932 {
   5933   /* Get text, data & bss offsets.  */
   5934   get_offsets ();
   5935 
   5936   /* In certain cases GDB might not have had the chance to start
   5937      symbol lookup up until now.  This could happen if the debugged
   5938      binary is not using shared libraries, the vsyscall page is not
   5939      present (on Linux) and the binary itself hadn't changed since the
   5940      debugging process was started.  */
   5941   if (symfile_objfile != NULL)
   5942     remote_check_symbols();
   5943 }
   5944 
   5945 
   5946 /* Check for the availability of vCont.  This function should also check
   5948    the response.  */
   5949 
   5950 void
   5951 remote_target::remote_vcont_probe ()
   5952 {
   5953   remote_state *rs = get_remote_state ();
   5954   char *buf;
   5955 
   5956   strcpy (rs->buf.data (), "vCont?");
   5957   putpkt (rs->buf);
   5958   getpkt (&rs->buf, 0);
   5959   buf = rs->buf.data ();
   5960 
   5961   /* Make sure that the features we assume are supported.  */
   5962   if (startswith (buf, "vCont"))
   5963     {
   5964       char *p = &buf[5];
   5965       int support_c, support_C;
   5966 
   5967       rs->supports_vCont.s = 0;
   5968       rs->supports_vCont.S = 0;
   5969       support_c = 0;
   5970       support_C = 0;
   5971       rs->supports_vCont.t = 0;
   5972       rs->supports_vCont.r = 0;
   5973       while (p && *p == ';')
   5974 	{
   5975 	  p++;
   5976 	  if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
   5977 	    rs->supports_vCont.s = 1;
   5978 	  else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
   5979 	    rs->supports_vCont.S = 1;
   5980 	  else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
   5981 	    support_c = 1;
   5982 	  else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
   5983 	    support_C = 1;
   5984 	  else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
   5985 	    rs->supports_vCont.t = 1;
   5986 	  else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
   5987 	    rs->supports_vCont.r = 1;
   5988 
   5989 	  p = strchr (p, ';');
   5990 	}
   5991 
   5992       /* If c, and C are not all supported, we can't use vCont.  Clearing
   5993 	 BUF will make packet_ok disable the packet.  */
   5994       if (!support_c || !support_C)
   5995 	buf[0] = 0;
   5996     }
   5997 
   5998   packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCont]);
   5999 }
   6000 
   6001 /* Helper function for building "vCont" resumptions.  Write a
   6002    resumption to P.  ENDP points to one-passed-the-end of the buffer
   6003    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
   6004    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
   6005    resumed thread should be single-stepped and/or signalled.  If PTID
   6006    equals minus_one_ptid, then all threads are resumed; if PTID
   6007    represents a process, then all threads of the process are resumed;
   6008    the thread to be stepped and/or signalled is given in the global
   6009    INFERIOR_PTID.  */
   6010 
   6011 char *
   6012 remote_target::append_resumption (char *p, char *endp,
   6013 				  ptid_t ptid, int step, gdb_signal siggnal)
   6014 {
   6015   struct remote_state *rs = get_remote_state ();
   6016 
   6017   if (step && siggnal != GDB_SIGNAL_0)
   6018     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
   6019   else if (step
   6020 	   /* GDB is willing to range step.  */
   6021 	   && use_range_stepping
   6022 	   /* Target supports range stepping.  */
   6023 	   && rs->supports_vCont.r
   6024 	   /* We don't currently support range stepping multiple
   6025 	      threads with a wildcard (though the protocol allows it,
   6026 	      so stubs shouldn't make an active effort to forbid
   6027 	      it).  */
   6028 	   && !(remote_multi_process_p (rs) && ptid.is_pid ()))
   6029     {
   6030       struct thread_info *tp;
   6031 
   6032       if (ptid == minus_one_ptid)
   6033 	{
   6034 	  /* If we don't know about the target thread's tid, then
   6035 	     we're resuming magic_null_ptid (see caller).  */
   6036 	  tp = find_thread_ptid (magic_null_ptid);
   6037 	}
   6038       else
   6039 	tp = find_thread_ptid (ptid);
   6040       gdb_assert (tp != NULL);
   6041 
   6042       if (tp->control.may_range_step)
   6043 	{
   6044 	  int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
   6045 
   6046 	  p += xsnprintf (p, endp - p, ";r%s,%s",
   6047 			  phex_nz (tp->control.step_range_start,
   6048 				   addr_size),
   6049 			  phex_nz (tp->control.step_range_end,
   6050 				   addr_size));
   6051 	}
   6052       else
   6053 	p += xsnprintf (p, endp - p, ";s");
   6054     }
   6055   else if (step)
   6056     p += xsnprintf (p, endp - p, ";s");
   6057   else if (siggnal != GDB_SIGNAL_0)
   6058     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
   6059   else
   6060     p += xsnprintf (p, endp - p, ";c");
   6061 
   6062   if (remote_multi_process_p (rs) && ptid.is_pid ())
   6063     {
   6064       ptid_t nptid;
   6065 
   6066       /* All (-1) threads of process.  */
   6067       nptid = ptid_t (ptid.pid (), -1, 0);
   6068 
   6069       p += xsnprintf (p, endp - p, ":");
   6070       p = write_ptid (p, endp, nptid);
   6071     }
   6072   else if (ptid != minus_one_ptid)
   6073     {
   6074       p += xsnprintf (p, endp - p, ":");
   6075       p = write_ptid (p, endp, ptid);
   6076     }
   6077 
   6078   return p;
   6079 }
   6080 
   6081 /* Clear the thread's private info on resume.  */
   6082 
   6083 static void
   6084 resume_clear_thread_private_info (struct thread_info *thread)
   6085 {
   6086   if (thread->priv != NULL)
   6087     {
   6088       remote_thread_info *priv = get_remote_thread_info (thread);
   6089 
   6090       priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
   6091       priv->watch_data_address = 0;
   6092     }
   6093 }
   6094 
   6095 /* Append a vCont continue-with-signal action for threads that have a
   6096    non-zero stop signal.  */
   6097 
   6098 char *
   6099 remote_target::append_pending_thread_resumptions (char *p, char *endp,
   6100 						  ptid_t ptid)
   6101 {
   6102   for (thread_info *thread : all_non_exited_threads (ptid))
   6103     if (inferior_ptid != thread->ptid
   6104 	&& thread->suspend.stop_signal != GDB_SIGNAL_0)
   6105       {
   6106 	p = append_resumption (p, endp, thread->ptid,
   6107 			       0, thread->suspend.stop_signal);
   6108 	thread->suspend.stop_signal = GDB_SIGNAL_0;
   6109 	resume_clear_thread_private_info (thread);
   6110       }
   6111 
   6112   return p;
   6113 }
   6114 
   6115 /* Set the target running, using the packets that use Hc
   6116    (c/s/C/S).  */
   6117 
   6118 void
   6119 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
   6120 				      gdb_signal siggnal)
   6121 {
   6122   struct remote_state *rs = get_remote_state ();
   6123   char *buf;
   6124 
   6125   rs->last_sent_signal = siggnal;
   6126   rs->last_sent_step = step;
   6127 
   6128   /* The c/s/C/S resume packets use Hc, so set the continue
   6129      thread.  */
   6130   if (ptid == minus_one_ptid)
   6131     set_continue_thread (any_thread_ptid);
   6132   else
   6133     set_continue_thread (ptid);
   6134 
   6135   for (thread_info *thread : all_non_exited_threads ())
   6136     resume_clear_thread_private_info (thread);
   6137 
   6138   buf = rs->buf.data ();
   6139   if (::execution_direction == EXEC_REVERSE)
   6140     {
   6141       /* We don't pass signals to the target in reverse exec mode.  */
   6142       if (info_verbose && siggnal != GDB_SIGNAL_0)
   6143 	warning (_(" - Can't pass signal %d to target in reverse: ignored."),
   6144 		 siggnal);
   6145 
   6146       if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
   6147 	error (_("Remote reverse-step not supported."));
   6148       if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
   6149 	error (_("Remote reverse-continue not supported."));
   6150 
   6151       strcpy (buf, step ? "bs" : "bc");
   6152     }
   6153   else if (siggnal != GDB_SIGNAL_0)
   6154     {
   6155       buf[0] = step ? 'S' : 'C';
   6156       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
   6157       buf[2] = tohex (((int) siggnal) & 0xf);
   6158       buf[3] = '\0';
   6159     }
   6160   else
   6161     strcpy (buf, step ? "s" : "c");
   6162 
   6163   putpkt (buf);
   6164 }
   6165 
   6166 /* Resume the remote inferior by using a "vCont" packet.  The thread
   6167    to be resumed is PTID; STEP and SIGGNAL indicate whether the
   6168    resumed thread should be single-stepped and/or signalled.  If PTID
   6169    equals minus_one_ptid, then all threads are resumed; the thread to
   6170    be stepped and/or signalled is given in the global INFERIOR_PTID.
   6171    This function returns non-zero iff it resumes the inferior.
   6172 
   6173    This function issues a strict subset of all possible vCont commands
   6174    at the moment.  */
   6175 
   6176 int
   6177 remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
   6178 					 enum gdb_signal siggnal)
   6179 {
   6180   struct remote_state *rs = get_remote_state ();
   6181   char *p;
   6182   char *endp;
   6183 
   6184   /* No reverse execution actions defined for vCont.  */
   6185   if (::execution_direction == EXEC_REVERSE)
   6186     return 0;
   6187 
   6188   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
   6189     remote_vcont_probe ();
   6190 
   6191   if (packet_support (PACKET_vCont) == PACKET_DISABLE)
   6192     return 0;
   6193 
   6194   p = rs->buf.data ();
   6195   endp = p + get_remote_packet_size ();
   6196 
   6197   /* If we could generate a wider range of packets, we'd have to worry
   6198      about overflowing BUF.  Should there be a generic
   6199      "multi-part-packet" packet?  */
   6200 
   6201   p += xsnprintf (p, endp - p, "vCont");
   6202 
   6203   if (ptid == magic_null_ptid)
   6204     {
   6205       /* MAGIC_NULL_PTID means that we don't have any active threads,
   6206 	 so we don't have any TID numbers the inferior will
   6207 	 understand.  Make sure to only send forms that do not specify
   6208 	 a TID.  */
   6209       append_resumption (p, endp, minus_one_ptid, step, siggnal);
   6210     }
   6211   else if (ptid == minus_one_ptid || ptid.is_pid ())
   6212     {
   6213       /* Resume all threads (of all processes, or of a single
   6214 	 process), with preference for INFERIOR_PTID.  This assumes
   6215 	 inferior_ptid belongs to the set of all threads we are about
   6216 	 to resume.  */
   6217       if (step || siggnal != GDB_SIGNAL_0)
   6218 	{
   6219 	  /* Step inferior_ptid, with or without signal.  */
   6220 	  p = append_resumption (p, endp, inferior_ptid, step, siggnal);
   6221 	}
   6222 
   6223       /* Also pass down any pending signaled resumption for other
   6224 	 threads not the current.  */
   6225       p = append_pending_thread_resumptions (p, endp, ptid);
   6226 
   6227       /* And continue others without a signal.  */
   6228       append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
   6229     }
   6230   else
   6231     {
   6232       /* Scheduler locking; resume only PTID.  */
   6233       append_resumption (p, endp, ptid, step, siggnal);
   6234     }
   6235 
   6236   gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
   6237   putpkt (rs->buf);
   6238 
   6239   if (target_is_non_stop_p ())
   6240     {
   6241       /* In non-stop, the stub replies to vCont with "OK".  The stop
   6242 	 reply will be reported asynchronously by means of a `%Stop'
   6243 	 notification.  */
   6244       getpkt (&rs->buf, 0);
   6245       if (strcmp (rs->buf.data (), "OK") != 0)
   6246 	error (_("Unexpected vCont reply in non-stop mode: %s"),
   6247 	       rs->buf.data ());
   6248     }
   6249 
   6250   return 1;
   6251 }
   6252 
   6253 /* Tell the remote machine to resume.  */
   6254 
   6255 void
   6256 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
   6257 {
   6258   struct remote_state *rs = get_remote_state ();
   6259 
   6260   /* When connected in non-stop mode, the core resumes threads
   6261      individually.  Resuming remote threads directly in target_resume
   6262      would thus result in sending one packet per thread.  Instead, to
   6263      minimize roundtrip latency, here we just store the resume
   6264      request; the actual remote resumption will be done in
   6265      target_commit_resume / remote_commit_resume, where we'll be able
   6266      to do vCont action coalescing.  */
   6267   if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
   6268     {
   6269       remote_thread_info *remote_thr;
   6270 
   6271       if (minus_one_ptid == ptid || ptid.is_pid ())
   6272 	remote_thr = get_remote_thread_info (inferior_ptid);
   6273       else
   6274 	remote_thr = get_remote_thread_info (ptid);
   6275 
   6276       remote_thr->last_resume_step = step;
   6277       remote_thr->last_resume_sig = siggnal;
   6278       return;
   6279     }
   6280 
   6281   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
   6282      (explained in remote-notif.c:handle_notification) so
   6283      remote_notif_process is not called.  We need find a place where
   6284      it is safe to start a 'vNotif' sequence.  It is good to do it
   6285      before resuming inferior, because inferior was stopped and no RSP
   6286      traffic at that moment.  */
   6287   if (!target_is_non_stop_p ())
   6288     remote_notif_process (rs->notif_state, &notif_client_stop);
   6289 
   6290   rs->last_resume_exec_dir = ::execution_direction;
   6291 
   6292   /* Prefer vCont, and fallback to s/c/S/C, which use Hc.  */
   6293   if (!remote_resume_with_vcont (ptid, step, siggnal))
   6294     remote_resume_with_hc (ptid, step, siggnal);
   6295 
   6296   /* We are about to start executing the inferior, let's register it
   6297      with the event loop.  NOTE: this is the one place where all the
   6298      execution commands end up.  We could alternatively do this in each
   6299      of the execution commands in infcmd.c.  */
   6300   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
   6301      into infcmd.c in order to allow inferior function calls to work
   6302      NOT asynchronously.  */
   6303   if (target_can_async_p ())
   6304     target_async (1);
   6305 
   6306   /* We've just told the target to resume.  The remote server will
   6307      wait for the inferior to stop, and then send a stop reply.  In
   6308      the mean time, we can't start another command/query ourselves
   6309      because the stub wouldn't be ready to process it.  This applies
   6310      only to the base all-stop protocol, however.  In non-stop (which
   6311      only supports vCont), the stub replies with an "OK", and is
   6312      immediate able to process further serial input.  */
   6313   if (!target_is_non_stop_p ())
   6314     rs->waiting_for_stop_reply = 1;
   6315 }
   6316 
   6317 static int is_pending_fork_parent_thread (struct thread_info *thread);
   6318 
   6319 /* Private per-inferior info for target remote processes.  */
   6320 
   6321 struct remote_inferior : public private_inferior
   6322 {
   6323   /* Whether we can send a wildcard vCont for this process.  */
   6324   bool may_wildcard_vcont = true;
   6325 };
   6326 
   6327 /* Get the remote private inferior data associated to INF.  */
   6328 
   6329 static remote_inferior *
   6330 get_remote_inferior (inferior *inf)
   6331 {
   6332   if (inf->priv == NULL)
   6333     inf->priv.reset (new remote_inferior);
   6334 
   6335   return static_cast<remote_inferior *> (inf->priv.get ());
   6336 }
   6337 
   6338 /* Class used to track the construction of a vCont packet in the
   6339    outgoing packet buffer.  This is used to send multiple vCont
   6340    packets if we have more actions than would fit a single packet.  */
   6341 
   6342 class vcont_builder
   6343 {
   6344 public:
   6345   explicit vcont_builder (remote_target *remote)
   6346     : m_remote (remote)
   6347   {
   6348     restart ();
   6349   }
   6350 
   6351   void flush ();
   6352   void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
   6353 
   6354 private:
   6355   void restart ();
   6356 
   6357   /* The remote target.  */
   6358   remote_target *m_remote;
   6359 
   6360   /* Pointer to the first action.  P points here if no action has been
   6361      appended yet.  */
   6362   char *m_first_action;
   6363 
   6364   /* Where the next action will be appended.  */
   6365   char *m_p;
   6366 
   6367   /* The end of the buffer.  Must never write past this.  */
   6368   char *m_endp;
   6369 };
   6370 
   6371 /* Prepare the outgoing buffer for a new vCont packet.  */
   6372 
   6373 void
   6374 vcont_builder::restart ()
   6375 {
   6376   struct remote_state *rs = m_remote->get_remote_state ();
   6377 
   6378   m_p = rs->buf.data ();
   6379   m_endp = m_p + m_remote->get_remote_packet_size ();
   6380   m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
   6381   m_first_action = m_p;
   6382 }
   6383 
   6384 /* If the vCont packet being built has any action, send it to the
   6385    remote end.  */
   6386 
   6387 void
   6388 vcont_builder::flush ()
   6389 {
   6390   struct remote_state *rs;
   6391 
   6392   if (m_p == m_first_action)
   6393     return;
   6394 
   6395   rs = m_remote->get_remote_state ();
   6396   m_remote->putpkt (rs->buf);
   6397   m_remote->getpkt (&rs->buf, 0);
   6398   if (strcmp (rs->buf.data (), "OK") != 0)
   6399     error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
   6400 }
   6401 
   6402 /* The largest action is range-stepping, with its two addresses.  This
   6403    is more than sufficient.  If a new, bigger action is created, it'll
   6404    quickly trigger a failed assertion in append_resumption (and we'll
   6405    just bump this).  */
   6406 #define MAX_ACTION_SIZE 200
   6407 
   6408 /* Append a new vCont action in the outgoing packet being built.  If
   6409    the action doesn't fit the packet along with previous actions, push
   6410    what we've got so far to the remote end and start over a new vCont
   6411    packet (with the new action).  */
   6412 
   6413 void
   6414 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
   6415 {
   6416   char buf[MAX_ACTION_SIZE + 1];
   6417 
   6418   char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
   6419 					    ptid, step, siggnal);
   6420 
   6421   /* Check whether this new action would fit in the vCont packet along
   6422      with previous actions.  If not, send what we've got so far and
   6423      start a new vCont packet.  */
   6424   size_t rsize = endp - buf;
   6425   if (rsize > m_endp - m_p)
   6426     {
   6427       flush ();
   6428       restart ();
   6429 
   6430       /* Should now fit.  */
   6431       gdb_assert (rsize <= m_endp - m_p);
   6432     }
   6433 
   6434   memcpy (m_p, buf, rsize);
   6435   m_p += rsize;
   6436   *m_p = '\0';
   6437 }
   6438 
   6439 /* to_commit_resume implementation.  */
   6440 
   6441 void
   6442 remote_target::commit_resume ()
   6443 {
   6444   int any_process_wildcard;
   6445   int may_global_wildcard_vcont;
   6446 
   6447   /* If connected in all-stop mode, we'd send the remote resume
   6448      request directly from remote_resume.  Likewise if
   6449      reverse-debugging, as there are no defined vCont actions for
   6450      reverse execution.  */
   6451   if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
   6452     return;
   6453 
   6454   /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
   6455      instead of resuming all threads of each process individually.
   6456      However, if any thread of a process must remain halted, we can't
   6457      send wildcard resumes and must send one action per thread.
   6458 
   6459      Care must be taken to not resume threads/processes the server
   6460      side already told us are stopped, but the core doesn't know about
   6461      yet, because the events are still in the vStopped notification
   6462      queue.  For example:
   6463 
   6464        #1 => vCont s:p1.1;c
   6465        #2 <= OK
   6466        #3 <= %Stopped T05 p1.1
   6467        #4 => vStopped
   6468        #5 <= T05 p1.2
   6469        #6 => vStopped
   6470        #7 <= OK
   6471        #8 (infrun handles the stop for p1.1 and continues stepping)
   6472        #9 => vCont s:p1.1;c
   6473 
   6474      The last vCont above would resume thread p1.2 by mistake, because
   6475      the server has no idea that the event for p1.2 had not been
   6476      handled yet.
   6477 
   6478      The server side must similarly ignore resume actions for the
   6479      thread that has a pending %Stopped notification (and any other
   6480      threads with events pending), until GDB acks the notification
   6481      with vStopped.  Otherwise, e.g., the following case is
   6482      mishandled:
   6483 
   6484        #1 => g  (or any other packet)
   6485        #2 <= [registers]
   6486        #3 <= %Stopped T05 p1.2
   6487        #4 => vCont s:p1.1;c
   6488        #5 <= OK
   6489 
   6490      Above, the server must not resume thread p1.2.  GDB can't know
   6491      that p1.2 stopped until it acks the %Stopped notification, and
   6492      since from GDB's perspective all threads should be running, it
   6493      sends a "c" action.
   6494 
   6495      Finally, special care must also be given to handling fork/vfork
   6496      events.  A (v)fork event actually tells us that two processes
   6497      stopped -- the parent and the child.  Until we follow the fork,
   6498      we must not resume the child.  Therefore, if we have a pending
   6499      fork follow, we must not send a global wildcard resume action
   6500      (vCont;c).  We can still send process-wide wildcards though.  */
   6501 
   6502   /* Start by assuming a global wildcard (vCont;c) is possible.  */
   6503   may_global_wildcard_vcont = 1;
   6504 
   6505   /* And assume every process is individually wildcard-able too.  */
   6506   for (inferior *inf : all_non_exited_inferiors ())
   6507     {
   6508       remote_inferior *priv = get_remote_inferior (inf);
   6509 
   6510       priv->may_wildcard_vcont = true;
   6511     }
   6512 
   6513   /* Check for any pending events (not reported or processed yet) and
   6514      disable process and global wildcard resumes appropriately.  */
   6515   check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
   6516 
   6517   for (thread_info *tp : all_non_exited_threads ())
   6518     {
   6519       /* If a thread of a process is not meant to be resumed, then we
   6520 	 can't wildcard that process.  */
   6521       if (!tp->executing)
   6522 	{
   6523 	  get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
   6524 
   6525 	  /* And if we can't wildcard a process, we can't wildcard
   6526 	     everything either.  */
   6527 	  may_global_wildcard_vcont = 0;
   6528 	  continue;
   6529 	}
   6530 
   6531       /* If a thread is the parent of an unfollowed fork, then we
   6532 	 can't do a global wildcard, as that would resume the fork
   6533 	 child.  */
   6534       if (is_pending_fork_parent_thread (tp))
   6535 	may_global_wildcard_vcont = 0;
   6536     }
   6537 
   6538   /* Now let's build the vCont packet(s).  Actions must be appended
   6539      from narrower to wider scopes (thread -> process -> global).  If
   6540      we end up with too many actions for a single packet vcont_builder
   6541      flushes the current vCont packet to the remote side and starts a
   6542      new one.  */
   6543   struct vcont_builder vcont_builder (this);
   6544 
   6545   /* Threads first.  */
   6546   for (thread_info *tp : all_non_exited_threads ())
   6547     {
   6548       remote_thread_info *remote_thr = get_remote_thread_info (tp);
   6549 
   6550       if (!tp->executing || remote_thr->vcont_resumed)
   6551 	continue;
   6552 
   6553       gdb_assert (!thread_is_in_step_over_chain (tp));
   6554 
   6555       if (!remote_thr->last_resume_step
   6556 	  && remote_thr->last_resume_sig == GDB_SIGNAL_0
   6557 	  && get_remote_inferior (tp->inf)->may_wildcard_vcont)
   6558 	{
   6559 	  /* We'll send a wildcard resume instead.  */
   6560 	  remote_thr->vcont_resumed = 1;
   6561 	  continue;
   6562 	}
   6563 
   6564       vcont_builder.push_action (tp->ptid,
   6565 				 remote_thr->last_resume_step,
   6566 				 remote_thr->last_resume_sig);
   6567       remote_thr->vcont_resumed = 1;
   6568     }
   6569 
   6570   /* Now check whether we can send any process-wide wildcard.  This is
   6571      to avoid sending a global wildcard in the case nothing is
   6572      supposed to be resumed.  */
   6573   any_process_wildcard = 0;
   6574 
   6575   for (inferior *inf : all_non_exited_inferiors ())
   6576     {
   6577       if (get_remote_inferior (inf)->may_wildcard_vcont)
   6578 	{
   6579 	  any_process_wildcard = 1;
   6580 	  break;
   6581 	}
   6582     }
   6583 
   6584   if (any_process_wildcard)
   6585     {
   6586       /* If all processes are wildcard-able, then send a single "c"
   6587 	 action, otherwise, send an "all (-1) threads of process"
   6588 	 continue action for each running process, if any.  */
   6589       if (may_global_wildcard_vcont)
   6590 	{
   6591 	  vcont_builder.push_action (minus_one_ptid,
   6592 				     false, GDB_SIGNAL_0);
   6593 	}
   6594       else
   6595 	{
   6596 	  for (inferior *inf : all_non_exited_inferiors ())
   6597 	    {
   6598 	      if (get_remote_inferior (inf)->may_wildcard_vcont)
   6599 		{
   6600 		  vcont_builder.push_action (ptid_t (inf->pid),
   6601 					     false, GDB_SIGNAL_0);
   6602 		}
   6603 	    }
   6604 	}
   6605     }
   6606 
   6607   vcont_builder.flush ();
   6608 }
   6609 
   6610 
   6611 
   6613 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
   6614    thread, all threads of a remote process, or all threads of all
   6615    processes.  */
   6616 
   6617 void
   6618 remote_target::remote_stop_ns (ptid_t ptid)
   6619 {
   6620   struct remote_state *rs = get_remote_state ();
   6621   char *p = rs->buf.data ();
   6622   char *endp = p + get_remote_packet_size ();
   6623 
   6624   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
   6625     remote_vcont_probe ();
   6626 
   6627   if (!rs->supports_vCont.t)
   6628     error (_("Remote server does not support stopping threads"));
   6629 
   6630   if (ptid == minus_one_ptid
   6631       || (!remote_multi_process_p (rs) && ptid.is_pid ()))
   6632     p += xsnprintf (p, endp - p, "vCont;t");
   6633   else
   6634     {
   6635       ptid_t nptid;
   6636 
   6637       p += xsnprintf (p, endp - p, "vCont;t:");
   6638 
   6639       if (ptid.is_pid ())
   6640 	  /* All (-1) threads of process.  */
   6641 	nptid = ptid_t (ptid.pid (), -1, 0);
   6642       else
   6643 	{
   6644 	  /* Small optimization: if we already have a stop reply for
   6645 	     this thread, no use in telling the stub we want this
   6646 	     stopped.  */
   6647 	  if (peek_stop_reply (ptid))
   6648 	    return;
   6649 
   6650 	  nptid = ptid;
   6651 	}
   6652 
   6653       write_ptid (p, endp, nptid);
   6654     }
   6655 
   6656   /* In non-stop, we get an immediate OK reply.  The stop reply will
   6657      come in asynchronously by notification.  */
   6658   putpkt (rs->buf);
   6659   getpkt (&rs->buf, 0);
   6660   if (strcmp (rs->buf.data (), "OK") != 0)
   6661     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid),
   6662 	   rs->buf.data ());
   6663 }
   6664 
   6665 /* All-stop version of target_interrupt.  Sends a break or a ^C to
   6666    interrupt the remote target.  It is undefined which thread of which
   6667    process reports the interrupt.  */
   6668 
   6669 void
   6670 remote_target::remote_interrupt_as ()
   6671 {
   6672   struct remote_state *rs = get_remote_state ();
   6673 
   6674   rs->ctrlc_pending_p = 1;
   6675 
   6676   /* If the inferior is stopped already, but the core didn't know
   6677      about it yet, just ignore the request.  The cached wait status
   6678      will be collected in remote_wait.  */
   6679   if (rs->cached_wait_status)
   6680     return;
   6681 
   6682   /* Send interrupt_sequence to remote target.  */
   6683   send_interrupt_sequence ();
   6684 }
   6685 
   6686 /* Non-stop version of target_interrupt.  Uses `vCtrlC' to interrupt
   6687    the remote target.  It is undefined which thread of which process
   6688    reports the interrupt.  Throws an error if the packet is not
   6689    supported by the server.  */
   6690 
   6691 void
   6692 remote_target::remote_interrupt_ns ()
   6693 {
   6694   struct remote_state *rs = get_remote_state ();
   6695   char *p = rs->buf.data ();
   6696   char *endp = p + get_remote_packet_size ();
   6697 
   6698   xsnprintf (p, endp - p, "vCtrlC");
   6699 
   6700   /* In non-stop, we get an immediate OK reply.  The stop reply will
   6701      come in asynchronously by notification.  */
   6702   putpkt (rs->buf);
   6703   getpkt (&rs->buf, 0);
   6704 
   6705   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
   6706     {
   6707     case PACKET_OK:
   6708       break;
   6709     case PACKET_UNKNOWN:
   6710       error (_("No support for interrupting the remote target."));
   6711     case PACKET_ERROR:
   6712       error (_("Interrupting target failed: %s"), rs->buf.data ());
   6713     }
   6714 }
   6715 
   6716 /* Implement the to_stop function for the remote targets.  */
   6717 
   6718 void
   6719 remote_target::stop (ptid_t ptid)
   6720 {
   6721   if (remote_debug)
   6722     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
   6723 
   6724   if (target_is_non_stop_p ())
   6725     remote_stop_ns (ptid);
   6726   else
   6727     {
   6728       /* We don't currently have a way to transparently pause the
   6729 	 remote target in all-stop mode.  Interrupt it instead.  */
   6730       remote_interrupt_as ();
   6731     }
   6732 }
   6733 
   6734 /* Implement the to_interrupt function for the remote targets.  */
   6735 
   6736 void
   6737 remote_target::interrupt ()
   6738 {
   6739   if (remote_debug)
   6740     fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
   6741 
   6742   if (target_is_non_stop_p ())
   6743     remote_interrupt_ns ();
   6744   else
   6745     remote_interrupt_as ();
   6746 }
   6747 
   6748 /* Implement the to_pass_ctrlc function for the remote targets.  */
   6749 
   6750 void
   6751 remote_target::pass_ctrlc ()
   6752 {
   6753   struct remote_state *rs = get_remote_state ();
   6754 
   6755   if (remote_debug)
   6756     fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
   6757 
   6758   /* If we're starting up, we're not fully synced yet.  Quit
   6759      immediately.  */
   6760   if (rs->starting_up)
   6761     quit ();
   6762   /* If ^C has already been sent once, offer to disconnect.  */
   6763   else if (rs->ctrlc_pending_p)
   6764     interrupt_query ();
   6765   else
   6766     target_interrupt ();
   6767 }
   6768 
   6769 /* Ask the user what to do when an interrupt is received.  */
   6770 
   6771 void
   6772 remote_target::interrupt_query ()
   6773 {
   6774   struct remote_state *rs = get_remote_state ();
   6775 
   6776   if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
   6777     {
   6778       if (query (_("The target is not responding to interrupt requests.\n"
   6779 		   "Stop debugging it? ")))
   6780 	{
   6781 	  remote_unpush_target ();
   6782 	  throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
   6783 	}
   6784     }
   6785   else
   6786     {
   6787       if (query (_("Interrupted while waiting for the program.\n"
   6788 		   "Give up waiting? ")))
   6789 	quit ();
   6790     }
   6791 }
   6792 
   6793 /* Enable/disable target terminal ownership.  Most targets can use
   6794    terminal groups to control terminal ownership.  Remote targets are
   6795    different in that explicit transfer of ownership to/from GDB/target
   6796    is required.  */
   6797 
   6798 void
   6799 remote_target::terminal_inferior ()
   6800 {
   6801   /* NOTE: At this point we could also register our selves as the
   6802      recipient of all input.  Any characters typed could then be
   6803      passed on down to the target.  */
   6804 }
   6805 
   6806 void
   6807 remote_target::terminal_ours ()
   6808 {
   6809 }
   6810 
   6811 static void
   6812 remote_console_output (const char *msg)
   6813 {
   6814   const char *p;
   6815 
   6816   for (p = msg; p[0] && p[1]; p += 2)
   6817     {
   6818       char tb[2];
   6819       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
   6820 
   6821       tb[0] = c;
   6822       tb[1] = 0;
   6823       fputs_unfiltered (tb, gdb_stdtarg);
   6824     }
   6825   gdb_flush (gdb_stdtarg);
   6826 }
   6827 
   6828 DEF_VEC_O(cached_reg_t);
   6829 
   6830 typedef struct stop_reply
   6831 {
   6832   struct notif_event base;
   6833 
   6834   /* The identifier of the thread about this event  */
   6835   ptid_t ptid;
   6836 
   6837   /* The remote state this event is associated with.  When the remote
   6838      connection, represented by a remote_state object, is closed,
   6839      all the associated stop_reply events should be released.  */
   6840   struct remote_state *rs;
   6841 
   6842   struct target_waitstatus ws;
   6843 
   6844   /* The architecture associated with the expedited registers.  */
   6845   gdbarch *arch;
   6846 
   6847   /* Expedited registers.  This makes remote debugging a bit more
   6848      efficient for those targets that provide critical registers as
   6849      part of their normal status mechanism (as another roundtrip to
   6850      fetch them is avoided).  */
   6851   VEC(cached_reg_t) *regcache;
   6852 
   6853   enum target_stop_reason stop_reason;
   6854 
   6855   CORE_ADDR watch_data_address;
   6856 
   6857   int core;
   6858 } *stop_reply_p;
   6859 
   6860 static void
   6861 stop_reply_xfree (struct stop_reply *r)
   6862 {
   6863   notif_event_xfree ((struct notif_event *) r);
   6864 }
   6865 
   6866 /* Return the length of the stop reply queue.  */
   6867 
   6868 int
   6869 remote_target::stop_reply_queue_length ()
   6870 {
   6871   remote_state *rs = get_remote_state ();
   6872   return rs->stop_reply_queue.size ();
   6873 }
   6874 
   6875 void
   6876 remote_notif_stop_parse (remote_target *remote,
   6877 			 struct notif_client *self, const char *buf,
   6878 			 struct notif_event *event)
   6879 {
   6880   remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
   6881 }
   6882 
   6883 static void
   6884 remote_notif_stop_ack (remote_target *remote,
   6885 		       struct notif_client *self, const char *buf,
   6886 		       struct notif_event *event)
   6887 {
   6888   struct stop_reply *stop_reply = (struct stop_reply *) event;
   6889 
   6890   /* acknowledge */
   6891   putpkt (remote, self->ack_command);
   6892 
   6893   if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
   6894     {
   6895       /* We got an unknown stop reply.  */
   6896       error (_("Unknown stop reply"));
   6897     }
   6898 
   6899   remote->push_stop_reply (stop_reply);
   6900 }
   6901 
   6902 static int
   6903 remote_notif_stop_can_get_pending_events (remote_target *remote,
   6904 					  struct notif_client *self)
   6905 {
   6906   /* We can't get pending events in remote_notif_process for
   6907      notification stop, and we have to do this in remote_wait_ns
   6908      instead.  If we fetch all queued events from stub, remote stub
   6909      may exit and we have no chance to process them back in
   6910      remote_wait_ns.  */
   6911   remote_state *rs = remote->get_remote_state ();
   6912   mark_async_event_handler (rs->remote_async_inferior_event_token);
   6913   return 0;
   6914 }
   6915 
   6916 static void
   6917 stop_reply_dtr (struct notif_event *event)
   6918 {
   6919   struct stop_reply *r = (struct stop_reply *) event;
   6920   cached_reg_t *reg;
   6921   int ix;
   6922 
   6923   for (ix = 0;
   6924        VEC_iterate (cached_reg_t, r->regcache, ix, reg);
   6925        ix++)
   6926     xfree (reg->data);
   6927 
   6928   VEC_free (cached_reg_t, r->regcache);
   6929 }
   6930 
   6931 static struct notif_event *
   6932 remote_notif_stop_alloc_reply (void)
   6933 {
   6934   /* We cast to a pointer to the "base class".  */
   6935   struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
   6936 
   6937   r->dtr = stop_reply_dtr;
   6938 
   6939   return r;
   6940 }
   6941 
   6942 /* A client of notification Stop.  */
   6943 
   6944 struct notif_client notif_client_stop =
   6945 {
   6946   "Stop",
   6947   "vStopped",
   6948   remote_notif_stop_parse,
   6949   remote_notif_stop_ack,
   6950   remote_notif_stop_can_get_pending_events,
   6951   remote_notif_stop_alloc_reply,
   6952   REMOTE_NOTIF_STOP,
   6953 };
   6954 
   6955 /* Determine if THREAD_PTID is a pending fork parent thread.  ARG contains
   6956    the pid of the process that owns the threads we want to check, or
   6957    -1 if we want to check all threads.  */
   6958 
   6959 static int
   6960 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
   6961 			ptid_t thread_ptid)
   6962 {
   6963   if (ws->kind == TARGET_WAITKIND_FORKED
   6964       || ws->kind == TARGET_WAITKIND_VFORKED)
   6965     {
   6966       if (event_pid == -1 || event_pid == thread_ptid.pid ())
   6967 	return 1;
   6968     }
   6969 
   6970   return 0;
   6971 }
   6972 
   6973 /* Return the thread's pending status used to determine whether the
   6974    thread is a fork parent stopped at a fork event.  */
   6975 
   6976 static struct target_waitstatus *
   6977 thread_pending_fork_status (struct thread_info *thread)
   6978 {
   6979   if (thread->suspend.waitstatus_pending_p)
   6980     return &thread->suspend.waitstatus;
   6981   else
   6982     return &thread->pending_follow;
   6983 }
   6984 
   6985 /* Determine if THREAD is a pending fork parent thread.  */
   6986 
   6987 static int
   6988 is_pending_fork_parent_thread (struct thread_info *thread)
   6989 {
   6990   struct target_waitstatus *ws = thread_pending_fork_status (thread);
   6991   int pid = -1;
   6992 
   6993   return is_pending_fork_parent (ws, pid, thread->ptid);
   6994 }
   6995 
   6996 /* If CONTEXT contains any fork child threads that have not been
   6997    reported yet, remove them from the CONTEXT list.  If such a
   6998    thread exists it is because we are stopped at a fork catchpoint
   6999    and have not yet called follow_fork, which will set up the
   7000    host-side data structures for the new process.  */
   7001 
   7002 void
   7003 remote_target::remove_new_fork_children (threads_listing_context *context)
   7004 {
   7005   int pid = -1;
   7006   struct notif_client *notif = &notif_client_stop;
   7007 
   7008   /* For any threads stopped at a fork event, remove the corresponding
   7009      fork child threads from the CONTEXT list.  */
   7010   for (thread_info *thread : all_non_exited_threads ())
   7011     {
   7012       struct target_waitstatus *ws = thread_pending_fork_status (thread);
   7013 
   7014       if (is_pending_fork_parent (ws, pid, thread->ptid))
   7015 	context->remove_thread (ws->value.related_pid);
   7016     }
   7017 
   7018   /* Check for any pending fork events (not reported or processed yet)
   7019      in process PID and remove those fork child threads from the
   7020      CONTEXT list as well.  */
   7021   remote_notif_get_pending_events (notif);
   7022   for (auto &event : get_remote_state ()->stop_reply_queue)
   7023     if (event->ws.kind == TARGET_WAITKIND_FORKED
   7024 	|| event->ws.kind == TARGET_WAITKIND_VFORKED
   7025 	|| event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
   7026       context->remove_thread (event->ws.value.related_pid);
   7027 }
   7028 
   7029 /* Check whether any event pending in the vStopped queue would prevent
   7030    a global or process wildcard vCont action.  Clear
   7031    *may_global_wildcard if we can't do a global wildcard (vCont;c),
   7032    and clear the event inferior's may_wildcard_vcont flag if we can't
   7033    do a process-wide wildcard resume (vCont;c:pPID.-1).  */
   7034 
   7035 void
   7036 remote_target::check_pending_events_prevent_wildcard_vcont
   7037   (int *may_global_wildcard)
   7038 {
   7039   struct notif_client *notif = &notif_client_stop;
   7040 
   7041   remote_notif_get_pending_events (notif);
   7042   for (auto &event : get_remote_state ()->stop_reply_queue)
   7043     {
   7044       if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
   7045 	  || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
   7046 	continue;
   7047 
   7048       if (event->ws.kind == TARGET_WAITKIND_FORKED
   7049 	  || event->ws.kind == TARGET_WAITKIND_VFORKED)
   7050 	*may_global_wildcard = 0;
   7051 
   7052       struct inferior *inf = find_inferior_ptid (event->ptid);
   7053 
   7054       /* This may be the first time we heard about this process.
   7055 	 Regardless, we must not do a global wildcard resume, otherwise
   7056 	 we'd resume this process too.  */
   7057       *may_global_wildcard = 0;
   7058       if (inf != NULL)
   7059 	get_remote_inferior (inf)->may_wildcard_vcont = false;
   7060     }
   7061 }
   7062 
   7063 /* Discard all pending stop replies of inferior INF.  */
   7064 
   7065 void
   7066 remote_target::discard_pending_stop_replies (struct inferior *inf)
   7067 {
   7068   struct stop_reply *reply;
   7069   struct remote_state *rs = get_remote_state ();
   7070   struct remote_notif_state *rns = rs->notif_state;
   7071 
   7072   /* This function can be notified when an inferior exists.  When the
   7073      target is not remote, the notification state is NULL.  */
   7074   if (rs->remote_desc == NULL)
   7075     return;
   7076 
   7077   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
   7078 
   7079   /* Discard the in-flight notification.  */
   7080   if (reply != NULL && reply->ptid.pid () == inf->pid)
   7081     {
   7082       stop_reply_xfree (reply);
   7083       rns->pending_event[notif_client_stop.id] = NULL;
   7084     }
   7085 
   7086   /* Discard the stop replies we have already pulled with
   7087      vStopped.  */
   7088   auto iter = std::remove_if (rs->stop_reply_queue.begin (),
   7089 			      rs->stop_reply_queue.end (),
   7090 			      [=] (const stop_reply_up &event)
   7091 			      {
   7092 				return event->ptid.pid () == inf->pid;
   7093 			      });
   7094   rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
   7095 }
   7096 
   7097 /* Discard the stop replies for RS in stop_reply_queue.  */
   7098 
   7099 void
   7100 remote_target::discard_pending_stop_replies_in_queue ()
   7101 {
   7102   remote_state *rs = get_remote_state ();
   7103 
   7104   /* Discard the stop replies we have already pulled with
   7105      vStopped.  */
   7106   auto iter = std::remove_if (rs->stop_reply_queue.begin (),
   7107 			      rs->stop_reply_queue.end (),
   7108 			      [=] (const stop_reply_up &event)
   7109 			      {
   7110 				return event->rs == rs;
   7111 			      });
   7112   rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
   7113 }
   7114 
   7115 /* Remove the first reply in 'stop_reply_queue' which matches
   7116    PTID.  */
   7117 
   7118 struct stop_reply *
   7119 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
   7120 {
   7121   remote_state *rs = get_remote_state ();
   7122 
   7123   auto iter = std::find_if (rs->stop_reply_queue.begin (),
   7124 			    rs->stop_reply_queue.end (),
   7125 			    [=] (const stop_reply_up &event)
   7126 			    {
   7127 			      return event->ptid.matches (ptid);
   7128 			    });
   7129   struct stop_reply *result;
   7130   if (iter == rs->stop_reply_queue.end ())
   7131     result = nullptr;
   7132   else
   7133     {
   7134       result = iter->release ();
   7135       rs->stop_reply_queue.erase (iter);
   7136     }
   7137 
   7138   if (notif_debug)
   7139     fprintf_unfiltered (gdb_stdlog,
   7140 			"notif: discard queued event: 'Stop' in %s\n",
   7141 			target_pid_to_str (ptid));
   7142 
   7143   return result;
   7144 }
   7145 
   7146 /* Look for a queued stop reply belonging to PTID.  If one is found,
   7147    remove it from the queue, and return it.  Returns NULL if none is
   7148    found.  If there are still queued events left to process, tell the
   7149    event loop to get back to target_wait soon.  */
   7150 
   7151 struct stop_reply *
   7152 remote_target::queued_stop_reply (ptid_t ptid)
   7153 {
   7154   remote_state *rs = get_remote_state ();
   7155   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
   7156 
   7157   if (!rs->stop_reply_queue.empty ())
   7158     {
   7159       /* There's still at least an event left.  */
   7160       mark_async_event_handler (rs->remote_async_inferior_event_token);
   7161     }
   7162 
   7163   return r;
   7164 }
   7165 
   7166 /* Push a fully parsed stop reply in the stop reply queue.  Since we
   7167    know that we now have at least one queued event left to pass to the
   7168    core side, tell the event loop to get back to target_wait soon.  */
   7169 
   7170 void
   7171 remote_target::push_stop_reply (struct stop_reply *new_event)
   7172 {
   7173   remote_state *rs = get_remote_state ();
   7174   rs->stop_reply_queue.push_back (stop_reply_up (new_event));
   7175 
   7176   if (notif_debug)
   7177     fprintf_unfiltered (gdb_stdlog,
   7178 			"notif: push 'Stop' %s to queue %d\n",
   7179 			target_pid_to_str (new_event->ptid),
   7180 			int (rs->stop_reply_queue.size ()));
   7181 
   7182   mark_async_event_handler (rs->remote_async_inferior_event_token);
   7183 }
   7184 
   7185 /* Returns true if we have a stop reply for PTID.  */
   7186 
   7187 int
   7188 remote_target::peek_stop_reply (ptid_t ptid)
   7189 {
   7190   remote_state *rs = get_remote_state ();
   7191   for (auto &event : rs->stop_reply_queue)
   7192     if (ptid == event->ptid
   7193 	&& event->ws.kind == TARGET_WAITKIND_STOPPED)
   7194       return 1;
   7195   return 0;
   7196 }
   7197 
   7198 /* Helper for remote_parse_stop_reply.  Return nonzero if the substring
   7199    starting with P and ending with PEND matches PREFIX.  */
   7200 
   7201 static int
   7202 strprefix (const char *p, const char *pend, const char *prefix)
   7203 {
   7204   for ( ; p < pend; p++, prefix++)
   7205     if (*p != *prefix)
   7206       return 0;
   7207   return *prefix == '\0';
   7208 }
   7209 
   7210 /* Parse the stop reply in BUF.  Either the function succeeds, and the
   7211    result is stored in EVENT, or throws an error.  */
   7212 
   7213 void
   7214 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
   7215 {
   7216   remote_arch_state *rsa = NULL;
   7217   ULONGEST addr;
   7218   const char *p;
   7219   int skipregs = 0;
   7220 
   7221   event->ptid = null_ptid;
   7222   event->rs = get_remote_state ();
   7223   event->ws.kind = TARGET_WAITKIND_IGNORE;
   7224   event->ws.value.integer = 0;
   7225   event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
   7226   event->regcache = NULL;
   7227   event->core = -1;
   7228 
   7229   switch (buf[0])
   7230     {
   7231     case 'T':		/* Status with PC, SP, FP, ...	*/
   7232       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
   7233       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
   7234 	    ss = signal number
   7235 	    n... = register number
   7236 	    r... = register contents
   7237       */
   7238 
   7239       p = &buf[3];	/* after Txx */
   7240       while (*p)
   7241 	{
   7242 	  const char *p1;
   7243 	  int fieldsize;
   7244 
   7245 	  p1 = strchr (p, ':');
   7246 	  if (p1 == NULL)
   7247 	    error (_("Malformed packet(a) (missing colon): %s\n\
   7248 Packet: '%s'\n"),
   7249 		   p, buf);
   7250 	  if (p == p1)
   7251 	    error (_("Malformed packet(a) (missing register number): %s\n\
   7252 Packet: '%s'\n"),
   7253 		   p, buf);
   7254 
   7255 	  /* Some "registers" are actually extended stop information.
   7256 	     Note if you're adding a new entry here: GDB 7.9 and
   7257 	     earlier assume that all register "numbers" that start
   7258 	     with an hex digit are real register numbers.  Make sure
   7259 	     the server only sends such a packet if it knows the
   7260 	     client understands it.  */
   7261 
   7262 	  if (strprefix (p, p1, "thread"))
   7263 	    event->ptid = read_ptid (++p1, &p);
   7264 	  else if (strprefix (p, p1, "syscall_entry"))
   7265 	    {
   7266 	      ULONGEST sysno;
   7267 
   7268 	      event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
   7269 	      p = unpack_varlen_hex (++p1, &sysno);
   7270 	      event->ws.value.syscall_number = (int) sysno;
   7271 	    }
   7272 	  else if (strprefix (p, p1, "syscall_return"))
   7273 	    {
   7274 	      ULONGEST sysno;
   7275 
   7276 	      event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
   7277 	      p = unpack_varlen_hex (++p1, &sysno);
   7278 	      event->ws.value.syscall_number = (int) sysno;
   7279 	    }
   7280 	  else if (strprefix (p, p1, "watch")
   7281 		   || strprefix (p, p1, "rwatch")
   7282 		   || strprefix (p, p1, "awatch"))
   7283 	    {
   7284 	      event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
   7285 	      p = unpack_varlen_hex (++p1, &addr);
   7286 	      event->watch_data_address = (CORE_ADDR) addr;
   7287 	    }
   7288 	  else if (strprefix (p, p1, "swbreak"))
   7289 	    {
   7290 	      event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
   7291 
   7292 	      /* Make sure the stub doesn't forget to indicate support
   7293 		 with qSupported.  */
   7294 	      if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
   7295 		error (_("Unexpected swbreak stop reason"));
   7296 
   7297 	      /* The value part is documented as "must be empty",
   7298 		 though we ignore it, in case we ever decide to make
   7299 		 use of it in a backward compatible way.  */
   7300 	      p = strchrnul (p1 + 1, ';');
   7301 	    }
   7302 	  else if (strprefix (p, p1, "hwbreak"))
   7303 	    {
   7304 	      event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
   7305 
   7306 	      /* Make sure the stub doesn't forget to indicate support
   7307 		 with qSupported.  */
   7308 	      if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
   7309 		error (_("Unexpected hwbreak stop reason"));
   7310 
   7311 	      /* See above.  */
   7312 	      p = strchrnul (p1 + 1, ';');
   7313 	    }
   7314 	  else if (strprefix (p, p1, "library"))
   7315 	    {
   7316 	      event->ws.kind = TARGET_WAITKIND_LOADED;
   7317 	      p = strchrnul (p1 + 1, ';');
   7318 	    }
   7319 	  else if (strprefix (p, p1, "replaylog"))
   7320 	    {
   7321 	      event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
   7322 	      /* p1 will indicate "begin" or "end", but it makes
   7323 		 no difference for now, so ignore it.  */
   7324 	      p = strchrnul (p1 + 1, ';');
   7325 	    }
   7326 	  else if (strprefix (p, p1, "core"))
   7327 	    {
   7328 	      ULONGEST c;
   7329 
   7330 	      p = unpack_varlen_hex (++p1, &c);
   7331 	      event->core = c;
   7332 	    }
   7333 	  else if (strprefix (p, p1, "fork"))
   7334 	    {
   7335 	      event->ws.value.related_pid = read_ptid (++p1, &p);
   7336 	      event->ws.kind = TARGET_WAITKIND_FORKED;
   7337 	    }
   7338 	  else if (strprefix (p, p1, "vfork"))
   7339 	    {
   7340 	      event->ws.value.related_pid = read_ptid (++p1, &p);
   7341 	      event->ws.kind = TARGET_WAITKIND_VFORKED;
   7342 	    }
   7343 	  else if (strprefix (p, p1, "vforkdone"))
   7344 	    {
   7345 	      event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
   7346 	      p = strchrnul (p1 + 1, ';');
   7347 	    }
   7348 	  else if (strprefix (p, p1, "exec"))
   7349 	    {
   7350 	      ULONGEST ignored;
   7351 	      int pathlen;
   7352 
   7353 	      /* Determine the length of the execd pathname.  */
   7354 	      p = unpack_varlen_hex (++p1, &ignored);
   7355 	      pathlen = (p - p1) / 2;
   7356 
   7357 	      /* Save the pathname for event reporting and for
   7358 		 the next run command.  */
   7359 	      char *pathname = (char *) xmalloc (pathlen + 1);
   7360 	      struct cleanup *old_chain = make_cleanup (xfree, pathname);
   7361 	      hex2bin (p1, (gdb_byte *) pathname, pathlen);
   7362 	      pathname[pathlen] = '\0';
   7363 	      discard_cleanups (old_chain);
   7364 
   7365 	      /* This is freed during event handling.  */
   7366 	      event->ws.value.execd_pathname = pathname;
   7367 	      event->ws.kind = TARGET_WAITKIND_EXECD;
   7368 
   7369 	      /* Skip the registers included in this packet, since
   7370 		 they may be for an architecture different from the
   7371 		 one used by the original program.  */
   7372 	      skipregs = 1;
   7373 	    }
   7374 	  else if (strprefix (p, p1, "create"))
   7375 	    {
   7376 	      event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
   7377 	      p = strchrnul (p1 + 1, ';');
   7378 	    }
   7379 	  else
   7380 	    {
   7381 	      ULONGEST pnum;
   7382 	      const char *p_temp;
   7383 
   7384 	      if (skipregs)
   7385 		{
   7386 		  p = strchrnul (p1 + 1, ';');
   7387 		  p++;
   7388 		  continue;
   7389 		}
   7390 
   7391 	      /* Maybe a real ``P'' register number.  */
   7392 	      p_temp = unpack_varlen_hex (p, &pnum);
   7393 	      /* If the first invalid character is the colon, we got a
   7394 		 register number.  Otherwise, it's an unknown stop
   7395 		 reason.  */
   7396 	      if (p_temp == p1)
   7397 		{
   7398 		  /* If we haven't parsed the event's thread yet, find
   7399 		     it now, in order to find the architecture of the
   7400 		     reported expedited registers.  */
   7401 		  if (event->ptid == null_ptid)
   7402 		    {
   7403 		      const char *thr = strstr (p1 + 1, ";thread:");
   7404 		      if (thr != NULL)
   7405 			event->ptid = read_ptid (thr + strlen (";thread:"),
   7406 						 NULL);
   7407 		      else
   7408 			{
   7409 			  /* Either the current thread hasn't changed,
   7410 			     or the inferior is not multi-threaded.
   7411 			     The event must be for the thread we last
   7412 			     set as (or learned as being) current.  */
   7413 			  event->ptid = event->rs->general_thread;
   7414 			}
   7415 		    }
   7416 
   7417 		  if (rsa == NULL)
   7418 		    {
   7419 		      inferior *inf = (event->ptid == null_ptid
   7420 				       ? NULL
   7421 				       : find_inferior_ptid (event->ptid));
   7422 		      /* If this is the first time we learn anything
   7423 			 about this process, skip the registers
   7424 			 included in this packet, since we don't yet
   7425 			 know which architecture to use to parse them.
   7426 			 We'll determine the architecture later when
   7427 			 we process the stop reply and retrieve the
   7428 			 target description, via
   7429 			 remote_notice_new_inferior ->
   7430 			 post_create_inferior.  */
   7431 		      if (inf == NULL)
   7432 			{
   7433 			  p = strchrnul (p1 + 1, ';');
   7434 			  p++;
   7435 			  continue;
   7436 			}
   7437 
   7438 		      event->arch = inf->gdbarch;
   7439 		      rsa = event->rs->get_remote_arch_state (event->arch);
   7440 		    }
   7441 
   7442 		  packet_reg *reg
   7443 		    = packet_reg_from_pnum (event->arch, rsa, pnum);
   7444 		  cached_reg_t cached_reg;
   7445 
   7446 		  if (reg == NULL)
   7447 		    error (_("Remote sent bad register number %s: %s\n\
   7448 Packet: '%s'\n"),
   7449 			   hex_string (pnum), p, buf);
   7450 
   7451 		  cached_reg.num = reg->regnum;
   7452 		  cached_reg.data = (gdb_byte *)
   7453 		    xmalloc (register_size (event->arch, reg->regnum));
   7454 
   7455 		  p = p1 + 1;
   7456 		  fieldsize = hex2bin (p, cached_reg.data,
   7457 				       register_size (event->arch, reg->regnum));
   7458 		  p += 2 * fieldsize;
   7459 		  if (fieldsize < register_size (event->arch, reg->regnum))
   7460 		    warning (_("Remote reply is too short: %s"), buf);
   7461 
   7462 		  VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
   7463 		}
   7464 	      else
   7465 		{
   7466 		  /* Not a number.  Silently skip unknown optional
   7467 		     info.  */
   7468 		  p = strchrnul (p1 + 1, ';');
   7469 		}
   7470 	    }
   7471 
   7472 	  if (*p != ';')
   7473 	    error (_("Remote register badly formatted: %s\nhere: %s"),
   7474 		   buf, p);
   7475 	  ++p;
   7476 	}
   7477 
   7478       if (event->ws.kind != TARGET_WAITKIND_IGNORE)
   7479 	break;
   7480 
   7481       /* fall through */
   7482     case 'S':		/* Old style status, just signal only.  */
   7483       {
   7484 	int sig;
   7485 
   7486 	event->ws.kind = TARGET_WAITKIND_STOPPED;
   7487 	sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
   7488 	if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
   7489 	  event->ws.value.sig = (enum gdb_signal) sig;
   7490 	else
   7491 	  event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
   7492       }
   7493       break;
   7494     case 'w':		/* Thread exited.  */
   7495       {
   7496 	ULONGEST value;
   7497 
   7498 	event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
   7499 	p = unpack_varlen_hex (&buf[1], &value);
   7500 	event->ws.value.integer = value;
   7501 	if (*p != ';')
   7502 	  error (_("stop reply packet badly formatted: %s"), buf);
   7503 	event->ptid = read_ptid (++p, NULL);
   7504 	break;
   7505       }
   7506     case 'W':		/* Target exited.  */
   7507     case 'X':
   7508       {
   7509 	int pid;
   7510 	ULONGEST value;
   7511 
   7512 	/* GDB used to accept only 2 hex chars here.  Stubs should
   7513 	   only send more if they detect GDB supports multi-process
   7514 	   support.  */
   7515 	p = unpack_varlen_hex (&buf[1], &value);
   7516 
   7517 	if (buf[0] == 'W')
   7518 	  {
   7519 	    /* The remote process exited.  */
   7520 	    event->ws.kind = TARGET_WAITKIND_EXITED;
   7521 	    event->ws.value.integer = value;
   7522 	  }
   7523 	else
   7524 	  {
   7525 	    /* The remote process exited with a signal.  */
   7526 	    event->ws.kind = TARGET_WAITKIND_SIGNALLED;
   7527 	    if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
   7528 	      event->ws.value.sig = (enum gdb_signal) value;
   7529 	    else
   7530 	      event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
   7531 	  }
   7532 
   7533 	/* If no process is specified, assume inferior_ptid.  */
   7534 	pid = inferior_ptid.pid ();
   7535 	if (*p == '\0')
   7536 	  ;
   7537 	else if (*p == ';')
   7538 	  {
   7539 	    p++;
   7540 
   7541 	    if (*p == '\0')
   7542 	      ;
   7543 	    else if (startswith (p, "process:"))
   7544 	      {
   7545 		ULONGEST upid;
   7546 
   7547 		p += sizeof ("process:") - 1;
   7548 		unpack_varlen_hex (p, &upid);
   7549 		pid = upid;
   7550 	      }
   7551 	    else
   7552 	      error (_("unknown stop reply packet: %s"), buf);
   7553 	  }
   7554 	else
   7555 	  error (_("unknown stop reply packet: %s"), buf);
   7556 	event->ptid = ptid_t (pid);
   7557       }
   7558       break;
   7559     case 'N':
   7560       event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
   7561       event->ptid = minus_one_ptid;
   7562       break;
   7563     }
   7564 
   7565   if (target_is_non_stop_p () && event->ptid == null_ptid)
   7566     error (_("No process or thread specified in stop reply: %s"), buf);
   7567 }
   7568 
   7569 /* When the stub wants to tell GDB about a new notification reply, it
   7570    sends a notification (%Stop, for example).  Those can come it at
   7571    any time, hence, we have to make sure that any pending
   7572    putpkt/getpkt sequence we're making is finished, before querying
   7573    the stub for more events with the corresponding ack command
   7574    (vStopped, for example).  E.g., if we started a vStopped sequence
   7575    immediately upon receiving the notification, something like this
   7576    could happen:
   7577 
   7578     1.1) --> Hg 1
   7579     1.2) <-- OK
   7580     1.3) --> g
   7581     1.4) <-- %Stop
   7582     1.5) --> vStopped
   7583     1.6) <-- (registers reply to step #1.3)
   7584 
   7585    Obviously, the reply in step #1.6 would be unexpected to a vStopped
   7586    query.
   7587 
   7588    To solve this, whenever we parse a %Stop notification successfully,
   7589    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
   7590    doing whatever we were doing:
   7591 
   7592     2.1) --> Hg 1
   7593     2.2) <-- OK
   7594     2.3) --> g
   7595     2.4) <-- %Stop
   7596       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
   7597     2.5) <-- (registers reply to step #2.3)
   7598 
   7599    Eventualy after step #2.5, we return to the event loop, which
   7600    notices there's an event on the
   7601    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
   7602    associated callback --- the function below.  At this point, we're
   7603    always safe to start a vStopped sequence. :
   7604 
   7605     2.6) --> vStopped
   7606     2.7) <-- T05 thread:2
   7607     2.8) --> vStopped
   7608     2.9) --> OK
   7609 */
   7610 
   7611 void
   7612 remote_target::remote_notif_get_pending_events (notif_client *nc)
   7613 {
   7614   struct remote_state *rs = get_remote_state ();
   7615 
   7616   if (rs->notif_state->pending_event[nc->id] != NULL)
   7617     {
   7618       if (notif_debug)
   7619 	fprintf_unfiltered (gdb_stdlog,
   7620 			    "notif: process: '%s' ack pending event\n",
   7621 			    nc->name);
   7622 
   7623       /* acknowledge */
   7624       nc->ack (this, nc, rs->buf.data (),
   7625 	       rs->notif_state->pending_event[nc->id]);
   7626       rs->notif_state->pending_event[nc->id] = NULL;
   7627 
   7628       while (1)
   7629 	{
   7630 	  getpkt (&rs->buf, 0);
   7631 	  if (strcmp (rs->buf.data (), "OK") == 0)
   7632 	    break;
   7633 	  else
   7634 	    remote_notif_ack (this, nc, rs->buf.data ());
   7635 	}
   7636     }
   7637   else
   7638     {
   7639       if (notif_debug)
   7640 	fprintf_unfiltered (gdb_stdlog,
   7641 			    "notif: process: '%s' no pending reply\n",
   7642 			    nc->name);
   7643     }
   7644 }
   7645 
   7646 /* Wrapper around remote_target::remote_notif_get_pending_events to
   7647    avoid having to export the whole remote_target class.  */
   7648 
   7649 void
   7650 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
   7651 {
   7652   remote->remote_notif_get_pending_events (nc);
   7653 }
   7654 
   7655 /* Called when it is decided that STOP_REPLY holds the info of the
   7656    event that is to be returned to the core.  This function always
   7657    destroys STOP_REPLY.  */
   7658 
   7659 ptid_t
   7660 remote_target::process_stop_reply (struct stop_reply *stop_reply,
   7661 				   struct target_waitstatus *status)
   7662 {
   7663   ptid_t ptid;
   7664 
   7665   *status = stop_reply->ws;
   7666   ptid = stop_reply->ptid;
   7667 
   7668   /* If no thread/process was reported by the stub, assume the current
   7669      inferior.  */
   7670   if (ptid == null_ptid)
   7671     ptid = inferior_ptid;
   7672 
   7673   if (status->kind != TARGET_WAITKIND_EXITED
   7674       && status->kind != TARGET_WAITKIND_SIGNALLED
   7675       && status->kind != TARGET_WAITKIND_NO_RESUMED)
   7676     {
   7677       /* Expedited registers.  */
   7678       if (stop_reply->regcache)
   7679 	{
   7680 	  struct regcache *regcache
   7681 	    = get_thread_arch_regcache (ptid, stop_reply->arch);
   7682 	  cached_reg_t *reg;
   7683 	  int ix;
   7684 
   7685 	  for (ix = 0;
   7686 	       VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
   7687 	       ix++)
   7688 	  {
   7689 	    regcache->raw_supply (reg->num, reg->data);
   7690 	    xfree (reg->data);
   7691 	  }
   7692 
   7693 	  VEC_free (cached_reg_t, stop_reply->regcache);
   7694 	}
   7695 
   7696       remote_notice_new_inferior (ptid, 0);
   7697       remote_thread_info *remote_thr = get_remote_thread_info (ptid);
   7698       remote_thr->core = stop_reply->core;
   7699       remote_thr->stop_reason = stop_reply->stop_reason;
   7700       remote_thr->watch_data_address = stop_reply->watch_data_address;
   7701       remote_thr->vcont_resumed = 0;
   7702     }
   7703 
   7704   stop_reply_xfree (stop_reply);
   7705   return ptid;
   7706 }
   7707 
   7708 /* The non-stop mode version of target_wait.  */
   7709 
   7710 ptid_t
   7711 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
   7712 {
   7713   struct remote_state *rs = get_remote_state ();
   7714   struct stop_reply *stop_reply;
   7715   int ret;
   7716   int is_notif = 0;
   7717 
   7718   /* If in non-stop mode, get out of getpkt even if a
   7719      notification is received.	*/
   7720 
   7721   ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
   7722   while (1)
   7723     {
   7724       if (ret != -1 && !is_notif)
   7725 	switch (rs->buf[0])
   7726 	  {
   7727 	  case 'E':		/* Error of some sort.	*/
   7728 	    /* We're out of sync with the target now.  Did it continue
   7729 	       or not?  We can't tell which thread it was in non-stop,
   7730 	       so just ignore this.  */
   7731 	    warning (_("Remote failure reply: %s"), rs->buf.data ());
   7732 	    break;
   7733 	  case 'O':		/* Console output.  */
   7734 	    remote_console_output (&rs->buf[1]);
   7735 	    break;
   7736 	  default:
   7737 	    warning (_("Invalid remote reply: %s"), rs->buf.data ());
   7738 	    break;
   7739 	  }
   7740 
   7741       /* Acknowledge a pending stop reply that may have arrived in the
   7742 	 mean time.  */
   7743       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
   7744 	remote_notif_get_pending_events (&notif_client_stop);
   7745 
   7746       /* If indeed we noticed a stop reply, we're done.  */
   7747       stop_reply = queued_stop_reply (ptid);
   7748       if (stop_reply != NULL)
   7749 	return process_stop_reply (stop_reply, status);
   7750 
   7751       /* Still no event.  If we're just polling for an event, then
   7752 	 return to the event loop.  */
   7753       if (options & TARGET_WNOHANG)
   7754 	{
   7755 	  status->kind = TARGET_WAITKIND_IGNORE;
   7756 	  return minus_one_ptid;
   7757 	}
   7758 
   7759       /* Otherwise do a blocking wait.  */
   7760       ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
   7761     }
   7762 }
   7763 
   7764 /* Wait until the remote machine stops, then return, storing status in
   7765    STATUS just as `wait' would.  */
   7766 
   7767 ptid_t
   7768 remote_target::wait_as (ptid_t ptid, target_waitstatus *status, int options)
   7769 {
   7770   struct remote_state *rs = get_remote_state ();
   7771   ptid_t event_ptid = null_ptid;
   7772   char *buf;
   7773   struct stop_reply *stop_reply;
   7774 
   7775  again:
   7776 
   7777   status->kind = TARGET_WAITKIND_IGNORE;
   7778   status->value.integer = 0;
   7779 
   7780   stop_reply = queued_stop_reply (ptid);
   7781   if (stop_reply != NULL)
   7782     return process_stop_reply (stop_reply, status);
   7783 
   7784   if (rs->cached_wait_status)
   7785     /* Use the cached wait status, but only once.  */
   7786     rs->cached_wait_status = 0;
   7787   else
   7788     {
   7789       int ret;
   7790       int is_notif;
   7791       int forever = ((options & TARGET_WNOHANG) == 0
   7792 		     && rs->wait_forever_enabled_p);
   7793 
   7794       if (!rs->waiting_for_stop_reply)
   7795 	{
   7796 	  status->kind = TARGET_WAITKIND_NO_RESUMED;
   7797 	  return minus_one_ptid;
   7798 	}
   7799 
   7800       /* FIXME: cagney/1999-09-27: If we're in async mode we should
   7801 	 _never_ wait for ever -> test on target_is_async_p().
   7802 	 However, before we do that we need to ensure that the caller
   7803 	 knows how to take the target into/out of async mode.  */
   7804       ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
   7805 
   7806       /* GDB gets a notification.  Return to core as this event is
   7807 	 not interesting.  */
   7808       if (ret != -1 && is_notif)
   7809 	return minus_one_ptid;
   7810 
   7811       if (ret == -1 && (options & TARGET_WNOHANG) != 0)
   7812 	return minus_one_ptid;
   7813     }
   7814 
   7815   buf = rs->buf.data ();
   7816 
   7817   /* Assume that the target has acknowledged Ctrl-C unless we receive
   7818      an 'F' or 'O' packet.  */
   7819   if (buf[0] != 'F' && buf[0] != 'O')
   7820     rs->ctrlc_pending_p = 0;
   7821 
   7822   switch (buf[0])
   7823     {
   7824     case 'E':		/* Error of some sort.	*/
   7825       /* We're out of sync with the target now.  Did it continue or
   7826 	 not?  Not is more likely, so report a stop.  */
   7827       rs->waiting_for_stop_reply = 0;
   7828 
   7829       warning (_("Remote failure reply: %s"), buf);
   7830       status->kind = TARGET_WAITKIND_STOPPED;
   7831       status->value.sig = GDB_SIGNAL_0;
   7832       break;
   7833     case 'F':		/* File-I/O request.  */
   7834       /* GDB may access the inferior memory while handling the File-I/O
   7835 	 request, but we don't want GDB accessing memory while waiting
   7836 	 for a stop reply.  See the comments in putpkt_binary.  Set
   7837 	 waiting_for_stop_reply to 0 temporarily.  */
   7838       rs->waiting_for_stop_reply = 0;
   7839       remote_fileio_request (this, buf, rs->ctrlc_pending_p);
   7840       rs->ctrlc_pending_p = 0;
   7841       /* GDB handled the File-I/O request, and the target is running
   7842 	 again.  Keep waiting for events.  */
   7843       rs->waiting_for_stop_reply = 1;
   7844       break;
   7845     case 'N': case 'T': case 'S': case 'X': case 'W':
   7846       {
   7847 	/* There is a stop reply to handle.  */
   7848 	rs->waiting_for_stop_reply = 0;
   7849 
   7850 	stop_reply
   7851 	  = (struct stop_reply *) remote_notif_parse (this,
   7852 						      &notif_client_stop,
   7853 						      rs->buf.data ());
   7854 
   7855 	event_ptid = process_stop_reply (stop_reply, status);
   7856 	break;
   7857       }
   7858     case 'O':		/* Console output.  */
   7859       remote_console_output (buf + 1);
   7860       break;
   7861     case '\0':
   7862       if (rs->last_sent_signal != GDB_SIGNAL_0)
   7863 	{
   7864 	  /* Zero length reply means that we tried 'S' or 'C' and the
   7865 	     remote system doesn't support it.  */
   7866 	  target_terminal::ours_for_output ();
   7867 	  printf_filtered
   7868 	    ("Can't send signals to this remote system.  %s not sent.\n",
   7869 	     gdb_signal_to_name (rs->last_sent_signal));
   7870 	  rs->last_sent_signal = GDB_SIGNAL_0;
   7871 	  target_terminal::inferior ();
   7872 
   7873 	  strcpy (buf, rs->last_sent_step ? "s" : "c");
   7874 	  putpkt (buf);
   7875 	  break;
   7876 	}
   7877       /* fallthrough */
   7878     default:
   7879       warning (_("Invalid remote reply: %s"), buf);
   7880       break;
   7881     }
   7882 
   7883   if (status->kind == TARGET_WAITKIND_NO_RESUMED)
   7884     return minus_one_ptid;
   7885   else if (status->kind == TARGET_WAITKIND_IGNORE)
   7886     {
   7887       /* Nothing interesting happened.  If we're doing a non-blocking
   7888 	 poll, we're done.  Otherwise, go back to waiting.  */
   7889       if (options & TARGET_WNOHANG)
   7890 	return minus_one_ptid;
   7891       else
   7892 	goto again;
   7893     }
   7894   else if (status->kind != TARGET_WAITKIND_EXITED
   7895 	   && status->kind != TARGET_WAITKIND_SIGNALLED)
   7896     {
   7897       if (event_ptid != null_ptid)
   7898 	record_currthread (rs, event_ptid);
   7899       else
   7900 	event_ptid = inferior_ptid;
   7901     }
   7902   else
   7903     /* A process exit.  Invalidate our notion of current thread.  */
   7904     record_currthread (rs, minus_one_ptid);
   7905 
   7906   return event_ptid;
   7907 }
   7908 
   7909 /* Wait until the remote machine stops, then return, storing status in
   7910    STATUS just as `wait' would.  */
   7911 
   7912 ptid_t
   7913 remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
   7914 {
   7915   ptid_t event_ptid;
   7916 
   7917   if (target_is_non_stop_p ())
   7918     event_ptid = wait_ns (ptid, status, options);
   7919   else
   7920     event_ptid = wait_as (ptid, status, options);
   7921 
   7922   if (target_is_async_p ())
   7923     {
   7924       remote_state *rs = get_remote_state ();
   7925 
   7926       /* If there are are events left in the queue tell the event loop
   7927 	 to return here.  */
   7928       if (!rs->stop_reply_queue.empty ())
   7929 	mark_async_event_handler (rs->remote_async_inferior_event_token);
   7930     }
   7931 
   7932   return event_ptid;
   7933 }
   7934 
   7935 /* Fetch a single register using a 'p' packet.  */
   7936 
   7937 int
   7938 remote_target::fetch_register_using_p (struct regcache *regcache,
   7939 				       packet_reg *reg)
   7940 {
   7941   struct gdbarch *gdbarch = regcache->arch ();
   7942   struct remote_state *rs = get_remote_state ();
   7943   char *buf, *p;
   7944   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
   7945   int i;
   7946 
   7947   if (packet_support (PACKET_p) == PACKET_DISABLE)
   7948     return 0;
   7949 
   7950   if (reg->pnum == -1)
   7951     return 0;
   7952 
   7953   p = rs->buf.data ();
   7954   *p++ = 'p';
   7955   p += hexnumstr (p, reg->pnum);
   7956   *p++ = '\0';
   7957   putpkt (rs->buf);
   7958   getpkt (&rs->buf, 0);
   7959 
   7960   buf = rs->buf.data ();
   7961 
   7962   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_p]))
   7963     {
   7964     case PACKET_OK:
   7965       break;
   7966     case PACKET_UNKNOWN:
   7967       return 0;
   7968     case PACKET_ERROR:
   7969       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
   7970 	     gdbarch_register_name (regcache->arch (),
   7971 				    reg->regnum),
   7972 	     buf);
   7973     }
   7974 
   7975   /* If this register is unfetchable, tell the regcache.  */
   7976   if (buf[0] == 'x')
   7977     {
   7978       regcache->raw_supply (reg->regnum, NULL);
   7979       return 1;
   7980     }
   7981 
   7982   /* Otherwise, parse and supply the value.  */
   7983   p = buf;
   7984   i = 0;
   7985   while (p[0] != 0)
   7986     {
   7987       if (p[1] == 0)
   7988 	error (_("fetch_register_using_p: early buf termination"));
   7989 
   7990       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
   7991       p += 2;
   7992     }
   7993   regcache->raw_supply (reg->regnum, regp);
   7994   return 1;
   7995 }
   7996 
   7997 /* Fetch the registers included in the target's 'g' packet.  */
   7998 
   7999 int
   8000 remote_target::send_g_packet ()
   8001 {
   8002   struct remote_state *rs = get_remote_state ();
   8003   int buf_len;
   8004 
   8005   xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
   8006   putpkt (rs->buf);
   8007   getpkt (&rs->buf, 0);
   8008   if (packet_check_result (rs->buf) == PACKET_ERROR)
   8009     error (_("Could not read registers; remote failure reply '%s'"),
   8010            rs->buf.data ());
   8011 
   8012   /* We can get out of synch in various cases.  If the first character
   8013      in the buffer is not a hex character, assume that has happened
   8014      and try to fetch another packet to read.  */
   8015   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
   8016 	 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
   8017 	 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
   8018 	 && rs->buf[0] != 'x')	/* New: unavailable register value.  */
   8019     {
   8020       if (remote_debug)
   8021 	fprintf_unfiltered (gdb_stdlog,
   8022 			    "Bad register packet; fetching a new packet\n");
   8023       getpkt (&rs->buf, 0);
   8024     }
   8025 
   8026   buf_len = strlen (rs->buf.data ());
   8027 
   8028   /* Sanity check the received packet.  */
   8029   if (buf_len % 2 != 0)
   8030     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
   8031 
   8032   return buf_len / 2;
   8033 }
   8034 
   8035 void
   8036 remote_target::process_g_packet (struct regcache *regcache)
   8037 {
   8038   struct gdbarch *gdbarch = regcache->arch ();
   8039   struct remote_state *rs = get_remote_state ();
   8040   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
   8041   int i, buf_len;
   8042   char *p;
   8043   char *regs;
   8044 
   8045   buf_len = strlen (rs->buf.data ());
   8046 
   8047   /* Further sanity checks, with knowledge of the architecture.  */
   8048   if (buf_len > 2 * rsa->sizeof_g_packet)
   8049     error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
   8050 	     "bytes): %s"),
   8051 	   rsa->sizeof_g_packet, buf_len / 2,
   8052 	   rs->buf.data ());
   8053 
   8054   /* Save the size of the packet sent to us by the target.  It is used
   8055      as a heuristic when determining the max size of packets that the
   8056      target can safely receive.  */
   8057   if (rsa->actual_register_packet_size == 0)
   8058     rsa->actual_register_packet_size = buf_len;
   8059 
   8060   /* If this is smaller than we guessed the 'g' packet would be,
   8061      update our records.  A 'g' reply that doesn't include a register's
   8062      value implies either that the register is not available, or that
   8063      the 'p' packet must be used.  */
   8064   if (buf_len < 2 * rsa->sizeof_g_packet)
   8065     {
   8066       long sizeof_g_packet = buf_len / 2;
   8067 
   8068       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
   8069 	{
   8070 	  long offset = rsa->regs[i].offset;
   8071 	  long reg_size = register_size (gdbarch, i);
   8072 
   8073 	  if (rsa->regs[i].pnum == -1)
   8074 	    continue;
   8075 
   8076 	  if (offset >= sizeof_g_packet)
   8077 	    rsa->regs[i].in_g_packet = 0;
   8078 	  else if (offset + reg_size > sizeof_g_packet)
   8079 	    error (_("Truncated register %d in remote 'g' packet"), i);
   8080 	  else
   8081 	    rsa->regs[i].in_g_packet = 1;
   8082 	}
   8083 
   8084       /* Looks valid enough, we can assume this is the correct length
   8085          for a 'g' packet.  It's important not to adjust
   8086          rsa->sizeof_g_packet if we have truncated registers otherwise
   8087          this "if" won't be run the next time the method is called
   8088          with a packet of the same size and one of the internal errors
   8089          below will trigger instead.  */
   8090       rsa->sizeof_g_packet = sizeof_g_packet;
   8091     }
   8092 
   8093   regs = (char *) alloca (rsa->sizeof_g_packet);
   8094 
   8095   /* Unimplemented registers read as all bits zero.  */
   8096   memset (regs, 0, rsa->sizeof_g_packet);
   8097 
   8098   /* Reply describes registers byte by byte, each byte encoded as two
   8099      hex characters.  Suck them all up, then supply them to the
   8100      register cacheing/storage mechanism.  */
   8101 
   8102   p = rs->buf.data ();
   8103   for (i = 0; i < rsa->sizeof_g_packet; i++)
   8104     {
   8105       if (p[0] == 0 || p[1] == 0)
   8106 	/* This shouldn't happen - we adjusted sizeof_g_packet above.  */
   8107 	internal_error (__FILE__, __LINE__,
   8108 			_("unexpected end of 'g' packet reply"));
   8109 
   8110       if (p[0] == 'x' && p[1] == 'x')
   8111 	regs[i] = 0;		/* 'x' */
   8112       else
   8113 	regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
   8114       p += 2;
   8115     }
   8116 
   8117   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
   8118     {
   8119       struct packet_reg *r = &rsa->regs[i];
   8120       long reg_size = register_size (gdbarch, i);
   8121 
   8122       if (r->in_g_packet)
   8123 	{
   8124 	  if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
   8125 	    /* This shouldn't happen - we adjusted in_g_packet above.  */
   8126 	    internal_error (__FILE__, __LINE__,
   8127 			    _("unexpected end of 'g' packet reply"));
   8128 	  else if (rs->buf[r->offset * 2] == 'x')
   8129 	    {
   8130 	      gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
   8131 	      /* The register isn't available, mark it as such (at
   8132 		 the same time setting the value to zero).  */
   8133 	      regcache->raw_supply (r->regnum, NULL);
   8134 	    }
   8135 	  else
   8136 	    regcache->raw_supply (r->regnum, regs + r->offset);
   8137 	}
   8138     }
   8139 }
   8140 
   8141 void
   8142 remote_target::fetch_registers_using_g (struct regcache *regcache)
   8143 {
   8144   send_g_packet ();
   8145   process_g_packet (regcache);
   8146 }
   8147 
   8148 /* Make the remote selected traceframe match GDB's selected
   8149    traceframe.  */
   8150 
   8151 void
   8152 remote_target::set_remote_traceframe ()
   8153 {
   8154   int newnum;
   8155   struct remote_state *rs = get_remote_state ();
   8156 
   8157   if (rs->remote_traceframe_number == get_traceframe_number ())
   8158     return;
   8159 
   8160   /* Avoid recursion, remote_trace_find calls us again.  */
   8161   rs->remote_traceframe_number = get_traceframe_number ();
   8162 
   8163   newnum = target_trace_find (tfind_number,
   8164 			      get_traceframe_number (), 0, 0, NULL);
   8165 
   8166   /* Should not happen.  If it does, all bets are off.  */
   8167   if (newnum != get_traceframe_number ())
   8168     warning (_("could not set remote traceframe"));
   8169 }
   8170 
   8171 void
   8172 remote_target::fetch_registers (struct regcache *regcache, int regnum)
   8173 {
   8174   struct gdbarch *gdbarch = regcache->arch ();
   8175   struct remote_state *rs = get_remote_state ();
   8176   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
   8177   int i;
   8178 
   8179   set_remote_traceframe ();
   8180   set_general_thread (regcache->ptid ());
   8181 
   8182   if (regnum >= 0)
   8183     {
   8184       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
   8185 
   8186       gdb_assert (reg != NULL);
   8187 
   8188       /* If this register might be in the 'g' packet, try that first -
   8189 	 we are likely to read more than one register.  If this is the
   8190 	 first 'g' packet, we might be overly optimistic about its
   8191 	 contents, so fall back to 'p'.  */
   8192       if (reg->in_g_packet)
   8193 	{
   8194 	  fetch_registers_using_g (regcache);
   8195 	  if (reg->in_g_packet)
   8196 	    return;
   8197 	}
   8198 
   8199       if (fetch_register_using_p (regcache, reg))
   8200 	return;
   8201 
   8202       /* This register is not available.  */
   8203       regcache->raw_supply (reg->regnum, NULL);
   8204 
   8205       return;
   8206     }
   8207 
   8208   fetch_registers_using_g (regcache);
   8209 
   8210   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
   8211     if (!rsa->regs[i].in_g_packet)
   8212       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
   8213 	{
   8214 	  /* This register is not available.  */
   8215 	  regcache->raw_supply (i, NULL);
   8216 	}
   8217 }
   8218 
   8219 /* Prepare to store registers.  Since we may send them all (using a
   8220    'G' request), we have to read out the ones we don't want to change
   8221    first.  */
   8222 
   8223 void
   8224 remote_target::prepare_to_store (struct regcache *regcache)
   8225 {
   8226   struct remote_state *rs = get_remote_state ();
   8227   remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
   8228   int i;
   8229 
   8230   /* Make sure the entire registers array is valid.  */
   8231   switch (packet_support (PACKET_P))
   8232     {
   8233     case PACKET_DISABLE:
   8234     case PACKET_SUPPORT_UNKNOWN:
   8235       /* Make sure all the necessary registers are cached.  */
   8236       for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
   8237 	if (rsa->regs[i].in_g_packet)
   8238 	  regcache->raw_update (rsa->regs[i].regnum);
   8239       break;
   8240     case PACKET_ENABLE:
   8241       break;
   8242     }
   8243 }
   8244 
   8245 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
   8246    packet was not recognized.  */
   8247 
   8248 int
   8249 remote_target::store_register_using_P (const struct regcache *regcache,
   8250 				       packet_reg *reg)
   8251 {
   8252   struct gdbarch *gdbarch = regcache->arch ();
   8253   struct remote_state *rs = get_remote_state ();
   8254   /* Try storing a single register.  */
   8255   char *buf = rs->buf.data ();
   8256   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
   8257   char *p;
   8258 
   8259   if (packet_support (PACKET_P) == PACKET_DISABLE)
   8260     return 0;
   8261 
   8262   if (reg->pnum == -1)
   8263     return 0;
   8264 
   8265   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
   8266   p = buf + strlen (buf);
   8267   regcache->raw_collect (reg->regnum, regp);
   8268   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
   8269   putpkt (rs->buf);
   8270   getpkt (&rs->buf, 0);
   8271 
   8272   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
   8273     {
   8274     case PACKET_OK:
   8275       return 1;
   8276     case PACKET_ERROR:
   8277       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
   8278 	     gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
   8279     case PACKET_UNKNOWN:
   8280       return 0;
   8281     default:
   8282       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
   8283     }
   8284 }
   8285 
   8286 /* Store register REGNUM, or all registers if REGNUM == -1, from the
   8287    contents of the register cache buffer.  FIXME: ignores errors.  */
   8288 
   8289 void
   8290 remote_target::store_registers_using_G (const struct regcache *regcache)
   8291 {
   8292   struct remote_state *rs = get_remote_state ();
   8293   remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
   8294   gdb_byte *regs;
   8295   char *p;
   8296 
   8297   /* Extract all the registers in the regcache copying them into a
   8298      local buffer.  */
   8299   {
   8300     int i;
   8301 
   8302     regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
   8303     memset (regs, 0, rsa->sizeof_g_packet);
   8304     for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
   8305       {
   8306 	struct packet_reg *r = &rsa->regs[i];
   8307 
   8308 	if (r->in_g_packet)
   8309 	  regcache->raw_collect (r->regnum, regs + r->offset);
   8310       }
   8311   }
   8312 
   8313   /* Command describes registers byte by byte,
   8314      each byte encoded as two hex characters.  */
   8315   p = rs->buf.data ();
   8316   *p++ = 'G';
   8317   bin2hex (regs, p, rsa->sizeof_g_packet);
   8318   putpkt (rs->buf);
   8319   getpkt (&rs->buf, 0);
   8320   if (packet_check_result (rs->buf) == PACKET_ERROR)
   8321     error (_("Could not write registers; remote failure reply '%s'"),
   8322 	   rs->buf.data ());
   8323 }
   8324 
   8325 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
   8326    of the register cache buffer.  FIXME: ignores errors.  */
   8327 
   8328 void
   8329 remote_target::store_registers (struct regcache *regcache, int regnum)
   8330 {
   8331   struct gdbarch *gdbarch = regcache->arch ();
   8332   struct remote_state *rs = get_remote_state ();
   8333   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
   8334   int i;
   8335 
   8336   set_remote_traceframe ();
   8337   set_general_thread (regcache->ptid ());
   8338 
   8339   if (regnum >= 0)
   8340     {
   8341       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
   8342 
   8343       gdb_assert (reg != NULL);
   8344 
   8345       /* Always prefer to store registers using the 'P' packet if
   8346 	 possible; we often change only a small number of registers.
   8347 	 Sometimes we change a larger number; we'd need help from a
   8348 	 higher layer to know to use 'G'.  */
   8349       if (store_register_using_P (regcache, reg))
   8350 	return;
   8351 
   8352       /* For now, don't complain if we have no way to write the
   8353 	 register.  GDB loses track of unavailable registers too
   8354 	 easily.  Some day, this may be an error.  We don't have
   8355 	 any way to read the register, either...  */
   8356       if (!reg->in_g_packet)
   8357 	return;
   8358 
   8359       store_registers_using_G (regcache);
   8360       return;
   8361     }
   8362 
   8363   store_registers_using_G (regcache);
   8364 
   8365   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
   8366     if (!rsa->regs[i].in_g_packet)
   8367       if (!store_register_using_P (regcache, &rsa->regs[i]))
   8368 	/* See above for why we do not issue an error here.  */
   8369 	continue;
   8370 }
   8371 
   8372 
   8374 /* Return the number of hex digits in num.  */
   8375 
   8376 static int
   8377 hexnumlen (ULONGEST num)
   8378 {
   8379   int i;
   8380 
   8381   for (i = 0; num != 0; i++)
   8382     num >>= 4;
   8383 
   8384   return std::max (i, 1);
   8385 }
   8386 
   8387 /* Set BUF to the minimum number of hex digits representing NUM.  */
   8388 
   8389 static int
   8390 hexnumstr (char *buf, ULONGEST num)
   8391 {
   8392   int len = hexnumlen (num);
   8393 
   8394   return hexnumnstr (buf, num, len);
   8395 }
   8396 
   8397 
   8398 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
   8399 
   8400 static int
   8401 hexnumnstr (char *buf, ULONGEST num, int width)
   8402 {
   8403   int i;
   8404 
   8405   buf[width] = '\0';
   8406 
   8407   for (i = width - 1; i >= 0; i--)
   8408     {
   8409       buf[i] = "0123456789abcdef"[(num & 0xf)];
   8410       num >>= 4;
   8411     }
   8412 
   8413   return width;
   8414 }
   8415 
   8416 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
   8417 
   8418 static CORE_ADDR
   8419 remote_address_masked (CORE_ADDR addr)
   8420 {
   8421   unsigned int address_size = remote_address_size;
   8422 
   8423   /* If "remoteaddresssize" was not set, default to target address size.  */
   8424   if (!address_size)
   8425     address_size = gdbarch_addr_bit (target_gdbarch ());
   8426 
   8427   if (address_size > 0
   8428       && address_size < (sizeof (ULONGEST) * 8))
   8429     {
   8430       /* Only create a mask when that mask can safely be constructed
   8431          in a ULONGEST variable.  */
   8432       ULONGEST mask = 1;
   8433 
   8434       mask = (mask << address_size) - 1;
   8435       addr &= mask;
   8436     }
   8437   return addr;
   8438 }
   8439 
   8440 /* Determine whether the remote target supports binary downloading.
   8441    This is accomplished by sending a no-op memory write of zero length
   8442    to the target at the specified address. It does not suffice to send
   8443    the whole packet, since many stubs strip the eighth bit and
   8444    subsequently compute a wrong checksum, which causes real havoc with
   8445    remote_write_bytes.
   8446 
   8447    NOTE: This can still lose if the serial line is not eight-bit
   8448    clean.  In cases like this, the user should clear "remote
   8449    X-packet".  */
   8450 
   8451 void
   8452 remote_target::check_binary_download (CORE_ADDR addr)
   8453 {
   8454   struct remote_state *rs = get_remote_state ();
   8455 
   8456   switch (packet_support (PACKET_X))
   8457     {
   8458     case PACKET_DISABLE:
   8459       break;
   8460     case PACKET_ENABLE:
   8461       break;
   8462     case PACKET_SUPPORT_UNKNOWN:
   8463       {
   8464 	char *p;
   8465 
   8466 	p = rs->buf.data ();
   8467 	*p++ = 'X';
   8468 	p += hexnumstr (p, (ULONGEST) addr);
   8469 	*p++ = ',';
   8470 	p += hexnumstr (p, (ULONGEST) 0);
   8471 	*p++ = ':';
   8472 	*p = '\0';
   8473 
   8474 	putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
   8475 	getpkt (&rs->buf, 0);
   8476 
   8477 	if (rs->buf[0] == '\0')
   8478 	  {
   8479 	    if (remote_debug)
   8480 	      fprintf_unfiltered (gdb_stdlog,
   8481 				  "binary downloading NOT "
   8482 				  "supported by target\n");
   8483 	    remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
   8484 	  }
   8485 	else
   8486 	  {
   8487 	    if (remote_debug)
   8488 	      fprintf_unfiltered (gdb_stdlog,
   8489 				  "binary downloading supported by target\n");
   8490 	    remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
   8491 	  }
   8492 	break;
   8493       }
   8494     }
   8495 }
   8496 
   8497 /* Helper function to resize the payload in order to try to get a good
   8498    alignment.  We try to write an amount of data such that the next write will
   8499    start on an address aligned on REMOTE_ALIGN_WRITES.  */
   8500 
   8501 static int
   8502 align_for_efficient_write (int todo, CORE_ADDR memaddr)
   8503 {
   8504   return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
   8505 }
   8506 
   8507 /* Write memory data directly to the remote machine.
   8508    This does not inform the data cache; the data cache uses this.
   8509    HEADER is the starting part of the packet.
   8510    MEMADDR is the address in the remote memory space.
   8511    MYADDR is the address of the buffer in our space.
   8512    LEN_UNITS is the number of addressable units to write.
   8513    UNIT_SIZE is the length in bytes of an addressable unit.
   8514    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
   8515    should send data as binary ('X'), or hex-encoded ('M').
   8516 
   8517    The function creates packet of the form
   8518        <HEADER><ADDRESS>,<LENGTH>:<DATA>
   8519 
   8520    where encoding of <DATA> is terminated by PACKET_FORMAT.
   8521 
   8522    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
   8523    are omitted.
   8524 
   8525    Return the transferred status, error or OK (an
   8526    'enum target_xfer_status' value).  Save the number of addressable units
   8527    transferred in *XFERED_LEN_UNITS.  Only transfer a single packet.
   8528 
   8529    On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
   8530    exchange between gdb and the stub could look like (?? in place of the
   8531    checksum):
   8532 
   8533    -> $m1000,4#??
   8534    <- aaaabbbbccccdddd
   8535 
   8536    -> $M1000,3:eeeeffffeeee#??
   8537    <- OK
   8538 
   8539    -> $m1000,4#??
   8540    <- eeeeffffeeeedddd  */
   8541 
   8542 target_xfer_status
   8543 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
   8544 				       const gdb_byte *myaddr,
   8545 				       ULONGEST len_units,
   8546 				       int unit_size,
   8547 				       ULONGEST *xfered_len_units,
   8548 				       char packet_format, int use_length)
   8549 {
   8550   struct remote_state *rs = get_remote_state ();
   8551   char *p;
   8552   char *plen = NULL;
   8553   int plenlen = 0;
   8554   int todo_units;
   8555   int units_written;
   8556   int payload_capacity_bytes;
   8557   int payload_length_bytes;
   8558 
   8559   if (packet_format != 'X' && packet_format != 'M')
   8560     internal_error (__FILE__, __LINE__,
   8561 		    _("remote_write_bytes_aux: bad packet format"));
   8562 
   8563   if (len_units == 0)
   8564     return TARGET_XFER_EOF;
   8565 
   8566   payload_capacity_bytes = get_memory_write_packet_size ();
   8567 
   8568   /* The packet buffer will be large enough for the payload;
   8569      get_memory_packet_size ensures this.  */
   8570   rs->buf[0] = '\0';
   8571 
   8572   /* Compute the size of the actual payload by subtracting out the
   8573      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
   8574 
   8575   payload_capacity_bytes -= strlen ("$,:#NN");
   8576   if (!use_length)
   8577     /* The comma won't be used.  */
   8578     payload_capacity_bytes += 1;
   8579   payload_capacity_bytes -= strlen (header);
   8580   payload_capacity_bytes -= hexnumlen (memaddr);
   8581 
   8582   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
   8583 
   8584   strcat (rs->buf.data (), header);
   8585   p = rs->buf.data () + strlen (header);
   8586 
   8587   /* Compute a best guess of the number of bytes actually transfered.  */
   8588   if (packet_format == 'X')
   8589     {
   8590       /* Best guess at number of bytes that will fit.  */
   8591       todo_units = std::min (len_units,
   8592 			     (ULONGEST) payload_capacity_bytes / unit_size);
   8593       if (use_length)
   8594 	payload_capacity_bytes -= hexnumlen (todo_units);
   8595       todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
   8596     }
   8597   else
   8598     {
   8599       /* Number of bytes that will fit.  */
   8600       todo_units
   8601 	= std::min (len_units,
   8602 		    (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
   8603       if (use_length)
   8604 	payload_capacity_bytes -= hexnumlen (todo_units);
   8605       todo_units = std::min (todo_units,
   8606 			     (payload_capacity_bytes / unit_size) / 2);
   8607     }
   8608 
   8609   if (todo_units <= 0)
   8610     internal_error (__FILE__, __LINE__,
   8611 		    _("minimum packet size too small to write data"));
   8612 
   8613   /* If we already need another packet, then try to align the end
   8614      of this packet to a useful boundary.  */
   8615   if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
   8616     todo_units = align_for_efficient_write (todo_units, memaddr);
   8617 
   8618   /* Append "<memaddr>".  */
   8619   memaddr = remote_address_masked (memaddr);
   8620   p += hexnumstr (p, (ULONGEST) memaddr);
   8621 
   8622   if (use_length)
   8623     {
   8624       /* Append ",".  */
   8625       *p++ = ',';
   8626 
   8627       /* Append the length and retain its location and size.  It may need to be
   8628          adjusted once the packet body has been created.  */
   8629       plen = p;
   8630       plenlen = hexnumstr (p, (ULONGEST) todo_units);
   8631       p += plenlen;
   8632     }
   8633 
   8634   /* Append ":".  */
   8635   *p++ = ':';
   8636   *p = '\0';
   8637 
   8638   /* Append the packet body.  */
   8639   if (packet_format == 'X')
   8640     {
   8641       /* Binary mode.  Send target system values byte by byte, in
   8642 	 increasing byte addresses.  Only escape certain critical
   8643 	 characters.  */
   8644       payload_length_bytes =
   8645 	  remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
   8646 				&units_written, payload_capacity_bytes);
   8647 
   8648       /* If not all TODO units fit, then we'll need another packet.  Make
   8649 	 a second try to keep the end of the packet aligned.  Don't do
   8650 	 this if the packet is tiny.  */
   8651       if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
   8652 	{
   8653 	  int new_todo_units;
   8654 
   8655 	  new_todo_units = align_for_efficient_write (units_written, memaddr);
   8656 
   8657 	  if (new_todo_units != units_written)
   8658 	    payload_length_bytes =
   8659 		remote_escape_output (myaddr, new_todo_units, unit_size,
   8660 				      (gdb_byte *) p, &units_written,
   8661 				      payload_capacity_bytes);
   8662 	}
   8663 
   8664       p += payload_length_bytes;
   8665       if (use_length && units_written < todo_units)
   8666 	{
   8667 	  /* Escape chars have filled up the buffer prematurely,
   8668 	     and we have actually sent fewer units than planned.
   8669 	     Fix-up the length field of the packet.  Use the same
   8670 	     number of characters as before.  */
   8671 	  plen += hexnumnstr (plen, (ULONGEST) units_written,
   8672 			      plenlen);
   8673 	  *plen = ':';  /* overwrite \0 from hexnumnstr() */
   8674 	}
   8675     }
   8676   else
   8677     {
   8678       /* Normal mode: Send target system values byte by byte, in
   8679 	 increasing byte addresses.  Each byte is encoded as a two hex
   8680 	 value.  */
   8681       p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
   8682       units_written = todo_units;
   8683     }
   8684 
   8685   putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
   8686   getpkt (&rs->buf, 0);
   8687 
   8688   if (rs->buf[0] == 'E')
   8689     return TARGET_XFER_E_IO;
   8690 
   8691   /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
   8692      send fewer units than we'd planned.  */
   8693   *xfered_len_units = (ULONGEST) units_written;
   8694   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
   8695 }
   8696 
   8697 /* Write memory data directly to the remote machine.
   8698    This does not inform the data cache; the data cache uses this.
   8699    MEMADDR is the address in the remote memory space.
   8700    MYADDR is the address of the buffer in our space.
   8701    LEN is the number of bytes.
   8702 
   8703    Return the transferred status, error or OK (an
   8704    'enum target_xfer_status' value).  Save the number of bytes
   8705    transferred in *XFERED_LEN.  Only transfer a single packet.  */
   8706 
   8707 target_xfer_status
   8708 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
   8709 				   ULONGEST len, int unit_size,
   8710 				   ULONGEST *xfered_len)
   8711 {
   8712   const char *packet_format = NULL;
   8713 
   8714   /* Check whether the target supports binary download.  */
   8715   check_binary_download (memaddr);
   8716 
   8717   switch (packet_support (PACKET_X))
   8718     {
   8719     case PACKET_ENABLE:
   8720       packet_format = "X";
   8721       break;
   8722     case PACKET_DISABLE:
   8723       packet_format = "M";
   8724       break;
   8725     case PACKET_SUPPORT_UNKNOWN:
   8726       internal_error (__FILE__, __LINE__,
   8727 		      _("remote_write_bytes: bad internal state"));
   8728     default:
   8729       internal_error (__FILE__, __LINE__, _("bad switch"));
   8730     }
   8731 
   8732   return remote_write_bytes_aux (packet_format,
   8733 				 memaddr, myaddr, len, unit_size, xfered_len,
   8734 				 packet_format[0], 1);
   8735 }
   8736 
   8737 /* Read memory data directly from the remote machine.
   8738    This does not use the data cache; the data cache uses this.
   8739    MEMADDR is the address in the remote memory space.
   8740    MYADDR is the address of the buffer in our space.
   8741    LEN_UNITS is the number of addressable memory units to read..
   8742    UNIT_SIZE is the length in bytes of an addressable unit.
   8743 
   8744    Return the transferred status, error or OK (an
   8745    'enum target_xfer_status' value).  Save the number of bytes
   8746    transferred in *XFERED_LEN_UNITS.
   8747 
   8748    See the comment of remote_write_bytes_aux for an example of
   8749    memory read/write exchange between gdb and the stub.  */
   8750 
   8751 target_xfer_status
   8752 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
   8753 				    ULONGEST len_units,
   8754 				    int unit_size, ULONGEST *xfered_len_units)
   8755 {
   8756   struct remote_state *rs = get_remote_state ();
   8757   int buf_size_bytes;		/* Max size of packet output buffer.  */
   8758   char *p;
   8759   int todo_units;
   8760   int decoded_bytes;
   8761 
   8762   buf_size_bytes = get_memory_read_packet_size ();
   8763   /* The packet buffer will be large enough for the payload;
   8764      get_memory_packet_size ensures this.  */
   8765 
   8766   /* Number of units that will fit.  */
   8767   todo_units = std::min (len_units,
   8768 			 (ULONGEST) (buf_size_bytes / unit_size) / 2);
   8769 
   8770   /* Construct "m"<memaddr>","<len>".  */
   8771   memaddr = remote_address_masked (memaddr);
   8772   p = rs->buf.data ();
   8773   *p++ = 'm';
   8774   p += hexnumstr (p, (ULONGEST) memaddr);
   8775   *p++ = ',';
   8776   p += hexnumstr (p, (ULONGEST) todo_units);
   8777   *p = '\0';
   8778   putpkt (rs->buf);
   8779   getpkt (&rs->buf, 0);
   8780   if (rs->buf[0] == 'E'
   8781       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
   8782       && rs->buf[3] == '\0')
   8783     return TARGET_XFER_E_IO;
   8784   /* Reply describes memory byte by byte, each byte encoded as two hex
   8785      characters.  */
   8786   p = rs->buf.data ();
   8787   decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
   8788   /* Return what we have.  Let higher layers handle partial reads.  */
   8789   *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
   8790   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
   8791 }
   8792 
   8793 /* Using the set of read-only target sections of remote, read live
   8794    read-only memory.
   8795 
   8796    For interface/parameters/return description see target.h,
   8797    to_xfer_partial.  */
   8798 
   8799 target_xfer_status
   8800 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
   8801 						  ULONGEST memaddr,
   8802 						  ULONGEST len,
   8803 						  int unit_size,
   8804 						  ULONGEST *xfered_len)
   8805 {
   8806   struct target_section *secp;
   8807   struct target_section_table *table;
   8808 
   8809   secp = target_section_by_addr (this, memaddr);
   8810   if (secp != NULL
   8811       && (bfd_get_section_flags (secp->the_bfd_section->owner,
   8812 				 secp->the_bfd_section)
   8813 	  & SEC_READONLY))
   8814     {
   8815       struct target_section *p;
   8816       ULONGEST memend = memaddr + len;
   8817 
   8818       table = target_get_section_table (this);
   8819 
   8820       for (p = table->sections; p < table->sections_end; p++)
   8821 	{
   8822 	  if (memaddr >= p->addr)
   8823 	    {
   8824 	      if (memend <= p->endaddr)
   8825 		{
   8826 		  /* Entire transfer is within this section.  */
   8827 		  return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
   8828 					      xfered_len);
   8829 		}
   8830 	      else if (memaddr >= p->endaddr)
   8831 		{
   8832 		  /* This section ends before the transfer starts.  */
   8833 		  continue;
   8834 		}
   8835 	      else
   8836 		{
   8837 		  /* This section overlaps the transfer.  Just do half.  */
   8838 		  len = p->endaddr - memaddr;
   8839 		  return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
   8840 					      xfered_len);
   8841 		}
   8842 	    }
   8843 	}
   8844     }
   8845 
   8846   return TARGET_XFER_EOF;
   8847 }
   8848 
   8849 /* Similar to remote_read_bytes_1, but it reads from the remote stub
   8850    first if the requested memory is unavailable in traceframe.
   8851    Otherwise, fall back to remote_read_bytes_1.  */
   8852 
   8853 target_xfer_status
   8854 remote_target::remote_read_bytes (CORE_ADDR memaddr,
   8855 				  gdb_byte *myaddr, ULONGEST len, int unit_size,
   8856 				  ULONGEST *xfered_len)
   8857 {
   8858   if (len == 0)
   8859     return TARGET_XFER_EOF;
   8860 
   8861   if (get_traceframe_number () != -1)
   8862     {
   8863       std::vector<mem_range> available;
   8864 
   8865       /* If we fail to get the set of available memory, then the
   8866 	 target does not support querying traceframe info, and so we
   8867 	 attempt reading from the traceframe anyway (assuming the
   8868 	 target implements the old QTro packet then).  */
   8869       if (traceframe_available_memory (&available, memaddr, len))
   8870 	{
   8871 	  if (available.empty () || available[0].start != memaddr)
   8872 	    {
   8873 	      enum target_xfer_status res;
   8874 
   8875 	      /* Don't read into the traceframe's available
   8876 		 memory.  */
   8877 	      if (!available.empty ())
   8878 		{
   8879 		  LONGEST oldlen = len;
   8880 
   8881 		  len = available[0].start - memaddr;
   8882 		  gdb_assert (len <= oldlen);
   8883 		}
   8884 
   8885 	      /* This goes through the topmost target again.  */
   8886 	      res = remote_xfer_live_readonly_partial (myaddr, memaddr,
   8887 						       len, unit_size, xfered_len);
   8888 	      if (res == TARGET_XFER_OK)
   8889 		return TARGET_XFER_OK;
   8890 	      else
   8891 		{
   8892 		  /* No use trying further, we know some memory starting
   8893 		     at MEMADDR isn't available.  */
   8894 		  *xfered_len = len;
   8895 		  return (*xfered_len != 0) ?
   8896 		    TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
   8897 		}
   8898 	    }
   8899 
   8900 	  /* Don't try to read more than how much is available, in
   8901 	     case the target implements the deprecated QTro packet to
   8902 	     cater for older GDBs (the target's knowledge of read-only
   8903 	     sections may be outdated by now).  */
   8904 	  len = available[0].length;
   8905 	}
   8906     }
   8907 
   8908   return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
   8909 }
   8910 
   8911 
   8912 
   8914 /* Sends a packet with content determined by the printf format string
   8915    FORMAT and the remaining arguments, then gets the reply.  Returns
   8916    whether the packet was a success, a failure, or unknown.  */
   8917 
   8918 packet_result
   8919 remote_target::remote_send_printf (const char *format, ...)
   8920 {
   8921   struct remote_state *rs = get_remote_state ();
   8922   int max_size = get_remote_packet_size ();
   8923   va_list ap;
   8924 
   8925   va_start (ap, format);
   8926 
   8927   rs->buf[0] = '\0';
   8928   int size = vsnprintf (rs->buf.data (), max_size, format, ap);
   8929 
   8930   va_end (ap);
   8931 
   8932   if (size >= max_size)
   8933     internal_error (__FILE__, __LINE__, _("Too long remote packet."));
   8934 
   8935   if (putpkt (rs->buf) < 0)
   8936     error (_("Communication problem with target."));
   8937 
   8938   rs->buf[0] = '\0';
   8939   getpkt (&rs->buf, 0);
   8940 
   8941   return packet_check_result (rs->buf);
   8942 }
   8943 
   8944 /* Flash writing can take quite some time.  We'll set
   8945    effectively infinite timeout for flash operations.
   8946    In future, we'll need to decide on a better approach.  */
   8947 static const int remote_flash_timeout = 1000;
   8948 
   8949 void
   8950 remote_target::flash_erase (ULONGEST address, LONGEST length)
   8951 {
   8952   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
   8953   enum packet_result ret;
   8954   scoped_restore restore_timeout
   8955     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
   8956 
   8957   ret = remote_send_printf ("vFlashErase:%s,%s",
   8958 			    phex (address, addr_size),
   8959 			    phex (length, 4));
   8960   switch (ret)
   8961     {
   8962     case PACKET_UNKNOWN:
   8963       error (_("Remote target does not support flash erase"));
   8964     case PACKET_ERROR:
   8965       error (_("Error erasing flash with vFlashErase packet"));
   8966     default:
   8967       break;
   8968     }
   8969 }
   8970 
   8971 target_xfer_status
   8972 remote_target::remote_flash_write (ULONGEST address,
   8973 				   ULONGEST length, ULONGEST *xfered_len,
   8974 				   const gdb_byte *data)
   8975 {
   8976   scoped_restore restore_timeout
   8977     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
   8978   return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
   8979 				 xfered_len,'X', 0);
   8980 }
   8981 
   8982 void
   8983 remote_target::flash_done ()
   8984 {
   8985   int ret;
   8986 
   8987   scoped_restore restore_timeout
   8988     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
   8989 
   8990   ret = remote_send_printf ("vFlashDone");
   8991 
   8992   switch (ret)
   8993     {
   8994     case PACKET_UNKNOWN:
   8995       error (_("Remote target does not support vFlashDone"));
   8996     case PACKET_ERROR:
   8997       error (_("Error finishing flash operation"));
   8998     default:
   8999       break;
   9000     }
   9001 }
   9002 
   9003 void
   9004 remote_target::files_info ()
   9005 {
   9006   puts_filtered ("Debugging a target over a serial line.\n");
   9007 }
   9008 
   9009 /* Stuff for dealing with the packets which are part of this protocol.
   9011    See comment at top of file for details.  */
   9012 
   9013 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
   9014    error to higher layers.  Called when a serial error is detected.
   9015    The exception message is STRING, followed by a colon and a blank,
   9016    the system error message for errno at function entry and final dot
   9017    for output compatibility with throw_perror_with_name.  */
   9018 
   9019 static void
   9020 unpush_and_perror (const char *string)
   9021 {
   9022   int saved_errno = errno;
   9023 
   9024   remote_unpush_target ();
   9025   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
   9026 	       safe_strerror (saved_errno));
   9027 }
   9028 
   9029 /* Read a single character from the remote end.  The current quit
   9030    handler is overridden to avoid quitting in the middle of packet
   9031    sequence, as that would break communication with the remote server.
   9032    See remote_serial_quit_handler for more detail.  */
   9033 
   9034 int
   9035 remote_target::readchar (int timeout)
   9036 {
   9037   int ch;
   9038   struct remote_state *rs = get_remote_state ();
   9039 
   9040   {
   9041     scoped_restore restore_quit_target
   9042       = make_scoped_restore (&curr_quit_handler_target, this);
   9043     scoped_restore restore_quit
   9044       = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
   9045 
   9046     rs->got_ctrlc_during_io = 0;
   9047 
   9048     ch = serial_readchar (rs->remote_desc, timeout);
   9049 
   9050     if (rs->got_ctrlc_during_io)
   9051       set_quit_flag ();
   9052   }
   9053 
   9054   if (ch >= 0)
   9055     return ch;
   9056 
   9057   switch ((enum serial_rc) ch)
   9058     {
   9059     case SERIAL_EOF:
   9060       remote_unpush_target ();
   9061       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
   9062       /* no return */
   9063     case SERIAL_ERROR:
   9064       unpush_and_perror (_("Remote communication error.  "
   9065 			   "Target disconnected."));
   9066       /* no return */
   9067     case SERIAL_TIMEOUT:
   9068       break;
   9069     }
   9070   return ch;
   9071 }
   9072 
   9073 /* Wrapper for serial_write that closes the target and throws if
   9074    writing fails.  The current quit handler is overridden to avoid
   9075    quitting in the middle of packet sequence, as that would break
   9076    communication with the remote server.  See
   9077    remote_serial_quit_handler for more detail.  */
   9078 
   9079 void
   9080 remote_target::remote_serial_write (const char *str, int len)
   9081 {
   9082   struct remote_state *rs = get_remote_state ();
   9083 
   9084   scoped_restore restore_quit_target
   9085     = make_scoped_restore (&curr_quit_handler_target, this);
   9086   scoped_restore restore_quit
   9087     = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
   9088 
   9089   rs->got_ctrlc_during_io = 0;
   9090 
   9091   if (serial_write (rs->remote_desc, str, len))
   9092     {
   9093       unpush_and_perror (_("Remote communication error.  "
   9094 			   "Target disconnected."));
   9095     }
   9096 
   9097   if (rs->got_ctrlc_during_io)
   9098     set_quit_flag ();
   9099 }
   9100 
   9101 /* Return a string representing an escaped version of BUF, of len N.
   9102    E.g. \n is converted to \\n, \t to \\t, etc.  */
   9103 
   9104 static std::string
   9105 escape_buffer (const char *buf, int n)
   9106 {
   9107   string_file stb;
   9108 
   9109   stb.putstrn (buf, n, '\\');
   9110   return std::move (stb.string ());
   9111 }
   9112 
   9113 /* Display a null-terminated packet on stdout, for debugging, using C
   9114    string notation.  */
   9115 
   9116 static void
   9117 print_packet (const char *buf)
   9118 {
   9119   puts_filtered ("\"");
   9120   fputstr_filtered (buf, '"', gdb_stdout);
   9121   puts_filtered ("\"");
   9122 }
   9123 
   9124 int
   9125 remote_target::putpkt (const char *buf)
   9126 {
   9127   return putpkt_binary (buf, strlen (buf));
   9128 }
   9129 
   9130 /* Wrapper around remote_target::putpkt to avoid exporting
   9131    remote_target.  */
   9132 
   9133 int
   9134 putpkt (remote_target *remote, const char *buf)
   9135 {
   9136   return remote->putpkt (buf);
   9137 }
   9138 
   9139 /* Send a packet to the remote machine, with error checking.  The data
   9140    of the packet is in BUF.  The string in BUF can be at most
   9141    get_remote_packet_size () - 5 to account for the $, # and checksum,
   9142    and for a possible /0 if we are debugging (remote_debug) and want
   9143    to print the sent packet as a string.  */
   9144 
   9145 int
   9146 remote_target::putpkt_binary (const char *buf, int cnt)
   9147 {
   9148   struct remote_state *rs = get_remote_state ();
   9149   int i;
   9150   unsigned char csum = 0;
   9151   gdb::def_vector<char> data (cnt + 6);
   9152   char *buf2 = data.data ();
   9153 
   9154   int ch;
   9155   int tcount = 0;
   9156   char *p;
   9157 
   9158   /* Catch cases like trying to read memory or listing threads while
   9159      we're waiting for a stop reply.  The remote server wouldn't be
   9160      ready to handle this request, so we'd hang and timeout.  We don't
   9161      have to worry about this in synchronous mode, because in that
   9162      case it's not possible to issue a command while the target is
   9163      running.  This is not a problem in non-stop mode, because in that
   9164      case, the stub is always ready to process serial input.  */
   9165   if (!target_is_non_stop_p ()
   9166       && target_is_async_p ()
   9167       && rs->waiting_for_stop_reply)
   9168     {
   9169       error (_("Cannot execute this command while the target is running.\n"
   9170 	       "Use the \"interrupt\" command to stop the target\n"
   9171 	       "and then try again."));
   9172     }
   9173 
   9174   /* We're sending out a new packet.  Make sure we don't look at a
   9175      stale cached response.  */
   9176   rs->cached_wait_status = 0;
   9177 
   9178   /* Copy the packet into buffer BUF2, encapsulating it
   9179      and giving it a checksum.  */
   9180 
   9181   p = buf2;
   9182   *p++ = '$';
   9183 
   9184   for (i = 0; i < cnt; i++)
   9185     {
   9186       csum += buf[i];
   9187       *p++ = buf[i];
   9188     }
   9189   *p++ = '#';
   9190   *p++ = tohex ((csum >> 4) & 0xf);
   9191   *p++ = tohex (csum & 0xf);
   9192 
   9193   /* Send it over and over until we get a positive ack.  */
   9194 
   9195   while (1)
   9196     {
   9197       int started_error_output = 0;
   9198 
   9199       if (remote_debug)
   9200 	{
   9201 	  *p = '\0';
   9202 
   9203 	  int len = (int) (p - buf2);
   9204 
   9205 	  std::string str
   9206 	    = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
   9207 
   9208 	  fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
   9209 
   9210 	  if (len > REMOTE_DEBUG_MAX_CHAR)
   9211 	    fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
   9212 				len - REMOTE_DEBUG_MAX_CHAR);
   9213 
   9214 	  fprintf_unfiltered (gdb_stdlog, "...");
   9215 
   9216 	  gdb_flush (gdb_stdlog);
   9217 	}
   9218       remote_serial_write (buf2, p - buf2);
   9219 
   9220       /* If this is a no acks version of the remote protocol, send the
   9221 	 packet and move on.  */
   9222       if (rs->noack_mode)
   9223         break;
   9224 
   9225       /* Read until either a timeout occurs (-2) or '+' is read.
   9226 	 Handle any notification that arrives in the mean time.  */
   9227       while (1)
   9228 	{
   9229 	  ch = readchar (remote_timeout);
   9230 
   9231 	  if (remote_debug)
   9232 	    {
   9233 	      switch (ch)
   9234 		{
   9235 		case '+':
   9236 		case '-':
   9237 		case SERIAL_TIMEOUT:
   9238 		case '$':
   9239 		case '%':
   9240 		  if (started_error_output)
   9241 		    {
   9242 		      putchar_unfiltered ('\n');
   9243 		      started_error_output = 0;
   9244 		    }
   9245 		}
   9246 	    }
   9247 
   9248 	  switch (ch)
   9249 	    {
   9250 	    case '+':
   9251 	      if (remote_debug)
   9252 		fprintf_unfiltered (gdb_stdlog, "Ack\n");
   9253 	      return 1;
   9254 	    case '-':
   9255 	      if (remote_debug)
   9256 		fprintf_unfiltered (gdb_stdlog, "Nak\n");
   9257 	      /* FALLTHROUGH */
   9258 	    case SERIAL_TIMEOUT:
   9259 	      tcount++;
   9260 	      if (tcount > 3)
   9261 		return 0;
   9262 	      break;		/* Retransmit buffer.  */
   9263 	    case '$':
   9264 	      {
   9265 	        if (remote_debug)
   9266 		  fprintf_unfiltered (gdb_stdlog,
   9267 				      "Packet instead of Ack, ignoring it\n");
   9268 		/* It's probably an old response sent because an ACK
   9269 		   was lost.  Gobble up the packet and ack it so it
   9270 		   doesn't get retransmitted when we resend this
   9271 		   packet.  */
   9272 		skip_frame ();
   9273 		remote_serial_write ("+", 1);
   9274 		continue;	/* Now, go look for +.  */
   9275 	      }
   9276 
   9277 	    case '%':
   9278 	      {
   9279 		int val;
   9280 
   9281 		/* If we got a notification, handle it, and go back to looking
   9282 		   for an ack.  */
   9283 		/* We've found the start of a notification.  Now
   9284 		   collect the data.  */
   9285 		val = read_frame (&rs->buf);
   9286 		if (val >= 0)
   9287 		  {
   9288 		    if (remote_debug)
   9289 		      {
   9290 			std::string str = escape_buffer (rs->buf.data (), val);
   9291 
   9292 			fprintf_unfiltered (gdb_stdlog,
   9293 					    "  Notification received: %s\n",
   9294 					    str.c_str ());
   9295 		      }
   9296 		    handle_notification (rs->notif_state, rs->buf.data ());
   9297 		    /* We're in sync now, rewait for the ack.  */
   9298 		    tcount = 0;
   9299 		  }
   9300 		else
   9301 		  {
   9302 		    if (remote_debug)
   9303 		      {
   9304 			if (!started_error_output)
   9305 			  {
   9306 			    started_error_output = 1;
   9307 			    fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
   9308 			  }
   9309 			fputc_unfiltered (ch & 0177, gdb_stdlog);
   9310 			fprintf_unfiltered (gdb_stdlog, "%s", rs->buf.data ());
   9311 		      }
   9312 		  }
   9313 		continue;
   9314 	      }
   9315 	      /* fall-through */
   9316 	    default:
   9317 	      if (remote_debug)
   9318 		{
   9319 		  if (!started_error_output)
   9320 		    {
   9321 		      started_error_output = 1;
   9322 		      fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
   9323 		    }
   9324 		  fputc_unfiltered (ch & 0177, gdb_stdlog);
   9325 		}
   9326 	      continue;
   9327 	    }
   9328 	  break;		/* Here to retransmit.  */
   9329 	}
   9330 
   9331 #if 0
   9332       /* This is wrong.  If doing a long backtrace, the user should be
   9333          able to get out next time we call QUIT, without anything as
   9334          violent as interrupt_query.  If we want to provide a way out of
   9335          here without getting to the next QUIT, it should be based on
   9336          hitting ^C twice as in remote_wait.  */
   9337       if (quit_flag)
   9338 	{
   9339 	  quit_flag = 0;
   9340 	  interrupt_query ();
   9341 	}
   9342 #endif
   9343     }
   9344 
   9345   return 0;
   9346 }
   9347 
   9348 /* Come here after finding the start of a frame when we expected an
   9349    ack.  Do our best to discard the rest of this packet.  */
   9350 
   9351 void
   9352 remote_target::skip_frame ()
   9353 {
   9354   int c;
   9355 
   9356   while (1)
   9357     {
   9358       c = readchar (remote_timeout);
   9359       switch (c)
   9360 	{
   9361 	case SERIAL_TIMEOUT:
   9362 	  /* Nothing we can do.  */
   9363 	  return;
   9364 	case '#':
   9365 	  /* Discard the two bytes of checksum and stop.  */
   9366 	  c = readchar (remote_timeout);
   9367 	  if (c >= 0)
   9368 	    c = readchar (remote_timeout);
   9369 
   9370 	  return;
   9371 	case '*':		/* Run length encoding.  */
   9372 	  /* Discard the repeat count.  */
   9373 	  c = readchar (remote_timeout);
   9374 	  if (c < 0)
   9375 	    return;
   9376 	  break;
   9377 	default:
   9378 	  /* A regular character.  */
   9379 	  break;
   9380 	}
   9381     }
   9382 }
   9383 
   9384 /* Come here after finding the start of the frame.  Collect the rest
   9385    into *BUF, verifying the checksum, length, and handling run-length
   9386    compression.  NUL terminate the buffer.  If there is not enough room,
   9387    expand *BUF.
   9388 
   9389    Returns -1 on error, number of characters in buffer (ignoring the
   9390    trailing NULL) on success. (could be extended to return one of the
   9391    SERIAL status indications).  */
   9392 
   9393 long
   9394 remote_target::read_frame (gdb::char_vector *buf_p)
   9395 {
   9396   unsigned char csum;
   9397   long bc;
   9398   int c;
   9399   char *buf = buf_p->data ();
   9400   struct remote_state *rs = get_remote_state ();
   9401 
   9402   csum = 0;
   9403   bc = 0;
   9404 
   9405   while (1)
   9406     {
   9407       c = readchar (remote_timeout);
   9408       switch (c)
   9409 	{
   9410 	case SERIAL_TIMEOUT:
   9411 	  if (remote_debug)
   9412 	    fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
   9413 	  return -1;
   9414 	case '$':
   9415 	  if (remote_debug)
   9416 	    fputs_filtered ("Saw new packet start in middle of old one\n",
   9417 			    gdb_stdlog);
   9418 	  return -1;		/* Start a new packet, count retries.  */
   9419 	case '#':
   9420 	  {
   9421 	    unsigned char pktcsum;
   9422 	    int check_0 = 0;
   9423 	    int check_1 = 0;
   9424 
   9425 	    buf[bc] = '\0';
   9426 
   9427 	    check_0 = readchar (remote_timeout);
   9428 	    if (check_0 >= 0)
   9429 	      check_1 = readchar (remote_timeout);
   9430 
   9431 	    if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
   9432 	      {
   9433 		if (remote_debug)
   9434 		  fputs_filtered ("Timeout in checksum, retrying\n",
   9435 				  gdb_stdlog);
   9436 		return -1;
   9437 	      }
   9438 	    else if (check_0 < 0 || check_1 < 0)
   9439 	      {
   9440 		if (remote_debug)
   9441 		  fputs_filtered ("Communication error in checksum\n",
   9442 				  gdb_stdlog);
   9443 		return -1;
   9444 	      }
   9445 
   9446 	    /* Don't recompute the checksum; with no ack packets we
   9447 	       don't have any way to indicate a packet retransmission
   9448 	       is necessary.  */
   9449 	    if (rs->noack_mode)
   9450 	      return bc;
   9451 
   9452 	    pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
   9453 	    if (csum == pktcsum)
   9454               return bc;
   9455 
   9456 	    if (remote_debug)
   9457 	      {
   9458 		std::string str = escape_buffer (buf, bc);
   9459 
   9460 		fprintf_unfiltered (gdb_stdlog,
   9461 				    "Bad checksum, sentsum=0x%x, "
   9462 				    "csum=0x%x, buf=%s\n",
   9463 				    pktcsum, csum, str.c_str ());
   9464 	      }
   9465 	    /* Number of characters in buffer ignoring trailing
   9466                NULL.  */
   9467 	    return -1;
   9468 	  }
   9469 	case '*':		/* Run length encoding.  */
   9470           {
   9471 	    int repeat;
   9472 
   9473  	    csum += c;
   9474 	    c = readchar (remote_timeout);
   9475 	    csum += c;
   9476 	    repeat = c - ' ' + 3;	/* Compute repeat count.  */
   9477 
   9478 	    /* The character before ``*'' is repeated.  */
   9479 
   9480 	    if (repeat > 0 && repeat <= 255 && bc > 0)
   9481 	      {
   9482 		if (bc + repeat - 1 >= buf_p->size () - 1)
   9483 		  {
   9484 		    /* Make some more room in the buffer.  */
   9485 		    buf_p->resize (buf_p->size () + repeat);
   9486 		    buf = buf_p->data ();
   9487 		  }
   9488 
   9489 		memset (&buf[bc], buf[bc - 1], repeat);
   9490 		bc += repeat;
   9491 		continue;
   9492 	      }
   9493 
   9494 	    buf[bc] = '\0';
   9495 	    printf_filtered (_("Invalid run length encoding: %s\n"), buf);
   9496 	    return -1;
   9497 	  }
   9498 	default:
   9499 	  if (bc >= buf_p->size () - 1)
   9500 	    {
   9501 	      /* Make some more room in the buffer.  */
   9502 	      buf_p->resize (buf_p->size () * 2);
   9503 	      buf = buf_p->data ();
   9504 	    }
   9505 
   9506 	  buf[bc++] = c;
   9507 	  csum += c;
   9508 	  continue;
   9509 	}
   9510     }
   9511 }
   9512 
   9513 /* Read a packet from the remote machine, with error checking, and
   9514    store it in *BUF.  Resize *BUF if necessary to hold the result.  If
   9515    FOREVER, wait forever rather than timing out; this is used (in
   9516    synchronous mode) to wait for a target that is is executing user
   9517    code to stop.  */
   9518 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
   9519    don't have to change all the calls to getpkt to deal with the
   9520    return value, because at the moment I don't know what the right
   9521    thing to do it for those.  */
   9522 
   9523 void
   9524 remote_target::getpkt (gdb::char_vector *buf, int forever)
   9525 {
   9526   getpkt_sane (buf, forever);
   9527 }
   9528 
   9529 
   9530 /* Read a packet from the remote machine, with error checking, and
   9531    store it in *BUF.  Resize *BUF if necessary to hold the result.  If
   9532    FOREVER, wait forever rather than timing out; this is used (in
   9533    synchronous mode) to wait for a target that is is executing user
   9534    code to stop.  If FOREVER == 0, this function is allowed to time
   9535    out gracefully and return an indication of this to the caller.
   9536    Otherwise return the number of bytes read.  If EXPECTING_NOTIF,
   9537    consider receiving a notification enough reason to return to the
   9538    caller.  *IS_NOTIF is an output boolean that indicates whether *BUF
   9539    holds a notification or not (a regular packet).  */
   9540 
   9541 int
   9542 remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
   9543 				       int forever, int expecting_notif,
   9544 				       int *is_notif)
   9545 {
   9546   struct remote_state *rs = get_remote_state ();
   9547   int c;
   9548   int tries;
   9549   int timeout;
   9550   int val = -1;
   9551 
   9552   /* We're reading a new response.  Make sure we don't look at a
   9553      previously cached response.  */
   9554   rs->cached_wait_status = 0;
   9555 
   9556   strcpy (buf->data (), "timeout");
   9557 
   9558   if (forever)
   9559     timeout = watchdog > 0 ? watchdog : -1;
   9560   else if (expecting_notif)
   9561     timeout = 0; /* There should already be a char in the buffer.  If
   9562 		    not, bail out.  */
   9563   else
   9564     timeout = remote_timeout;
   9565 
   9566 #define MAX_TRIES 3
   9567 
   9568   /* Process any number of notifications, and then return when
   9569      we get a packet.  */
   9570   for (;;)
   9571     {
   9572       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
   9573 	 times.  */
   9574       for (tries = 1; tries <= MAX_TRIES; tries++)
   9575 	{
   9576 	  /* This can loop forever if the remote side sends us
   9577 	     characters continuously, but if it pauses, we'll get
   9578 	     SERIAL_TIMEOUT from readchar because of timeout.  Then
   9579 	     we'll count that as a retry.
   9580 
   9581 	     Note that even when forever is set, we will only wait
   9582 	     forever prior to the start of a packet.  After that, we
   9583 	     expect characters to arrive at a brisk pace.  They should
   9584 	     show up within remote_timeout intervals.  */
   9585 	  do
   9586 	    c = readchar (timeout);
   9587 	  while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
   9588 
   9589 	  if (c == SERIAL_TIMEOUT)
   9590 	    {
   9591 	      if (expecting_notif)
   9592 		return -1; /* Don't complain, it's normal to not get
   9593 			      anything in this case.  */
   9594 
   9595 	      if (forever)	/* Watchdog went off?  Kill the target.  */
   9596 		{
   9597 		  remote_unpush_target ();
   9598 		  throw_error (TARGET_CLOSE_ERROR,
   9599 			       _("Watchdog timeout has expired.  "
   9600 				 "Target detached."));
   9601 		}
   9602 	      if (remote_debug)
   9603 		fputs_filtered ("Timed out.\n", gdb_stdlog);
   9604 	    }
   9605 	  else
   9606 	    {
   9607 	      /* We've found the start of a packet or notification.
   9608 		 Now collect the data.  */
   9609 	      val = read_frame (buf);
   9610 	      if (val >= 0)
   9611 		break;
   9612 	    }
   9613 
   9614 	  remote_serial_write ("-", 1);
   9615 	}
   9616 
   9617       if (tries > MAX_TRIES)
   9618 	{
   9619 	  /* We have tried hard enough, and just can't receive the
   9620 	     packet/notification.  Give up.  */
   9621 	  printf_unfiltered (_("Ignoring packet error, continuing...\n"));
   9622 
   9623 	  /* Skip the ack char if we're in no-ack mode.  */
   9624 	  if (!rs->noack_mode)
   9625 	    remote_serial_write ("+", 1);
   9626 	  return -1;
   9627 	}
   9628 
   9629       /* If we got an ordinary packet, return that to our caller.  */
   9630       if (c == '$')
   9631 	{
   9632 	  if (remote_debug)
   9633 	    {
   9634 	      std::string str
   9635 		= escape_buffer (buf->data (),
   9636 				 std::min (val, REMOTE_DEBUG_MAX_CHAR));
   9637 
   9638 	      fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
   9639 				  str.c_str ());
   9640 
   9641 	      if (val > REMOTE_DEBUG_MAX_CHAR)
   9642 		fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
   9643 				    val - REMOTE_DEBUG_MAX_CHAR);
   9644 
   9645 	      fprintf_unfiltered (gdb_stdlog, "\n");
   9646 	    }
   9647 
   9648 	  /* Skip the ack char if we're in no-ack mode.  */
   9649 	  if (!rs->noack_mode)
   9650 	    remote_serial_write ("+", 1);
   9651 	  if (is_notif != NULL)
   9652 	    *is_notif = 0;
   9653 	  return val;
   9654 	}
   9655 
   9656        /* If we got a notification, handle it, and go back to looking
   9657 	 for a packet.  */
   9658       else
   9659 	{
   9660 	  gdb_assert (c == '%');
   9661 
   9662 	  if (remote_debug)
   9663 	    {
   9664 	      std::string str = escape_buffer (buf->data (), val);
   9665 
   9666 	      fprintf_unfiltered (gdb_stdlog,
   9667 				  "  Notification received: %s\n",
   9668 				  str.c_str ());
   9669 	    }
   9670 	  if (is_notif != NULL)
   9671 	    *is_notif = 1;
   9672 
   9673 	  handle_notification (rs->notif_state, buf->data ());
   9674 
   9675 	  /* Notifications require no acknowledgement.  */
   9676 
   9677 	  if (expecting_notif)
   9678 	    return val;
   9679 	}
   9680     }
   9681 }
   9682 
   9683 int
   9684 remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
   9685 {
   9686   return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
   9687 }
   9688 
   9689 int
   9690 remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
   9691 				     int *is_notif)
   9692 {
   9693   return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
   9694 }
   9695 
   9696 /* Kill any new fork children of process PID that haven't been
   9697    processed by follow_fork.  */
   9698 
   9699 void
   9700 remote_target::kill_new_fork_children (int pid)
   9701 {
   9702   remote_state *rs = get_remote_state ();
   9703   struct notif_client *notif = &notif_client_stop;
   9704 
   9705   /* Kill the fork child threads of any threads in process PID
   9706      that are stopped at a fork event.  */
   9707   for (thread_info *thread : all_non_exited_threads ())
   9708     {
   9709       struct target_waitstatus *ws = &thread->pending_follow;
   9710 
   9711       if (is_pending_fork_parent (ws, pid, thread->ptid))
   9712 	{
   9713 	  int child_pid = ws->value.related_pid.pid ();
   9714 	  int res;
   9715 
   9716 	  res = remote_vkill (child_pid);
   9717 	  if (res != 0)
   9718 	    error (_("Can't kill fork child process %d"), child_pid);
   9719 	}
   9720     }
   9721 
   9722   /* Check for any pending fork events (not reported or processed yet)
   9723      in process PID and kill those fork child threads as well.  */
   9724   remote_notif_get_pending_events (notif);
   9725   for (auto &event : rs->stop_reply_queue)
   9726     if (is_pending_fork_parent (&event->ws, pid, event->ptid))
   9727       {
   9728 	int child_pid = event->ws.value.related_pid.pid ();
   9729 	int res;
   9730 
   9731 	res = remote_vkill (child_pid);
   9732 	if (res != 0)
   9733 	  error (_("Can't kill fork child process %d"), child_pid);
   9734       }
   9735 }
   9736 
   9737 
   9738 /* Target hook to kill the current inferior.  */
   9740 
   9741 void
   9742 remote_target::kill ()
   9743 {
   9744   int res = -1;
   9745   int pid = inferior_ptid.pid ();
   9746   struct remote_state *rs = get_remote_state ();
   9747 
   9748   if (packet_support (PACKET_vKill) != PACKET_DISABLE)
   9749     {
   9750       /* If we're stopped while forking and we haven't followed yet,
   9751 	 kill the child task.  We need to do this before killing the
   9752 	 parent task because if this is a vfork then the parent will
   9753 	 be sleeping.  */
   9754       kill_new_fork_children (pid);
   9755 
   9756       res = remote_vkill (pid);
   9757       if (res == 0)
   9758 	{
   9759 	  target_mourn_inferior (inferior_ptid);
   9760 	  return;
   9761 	}
   9762     }
   9763 
   9764   /* If we are in 'target remote' mode and we are killing the only
   9765      inferior, then we will tell gdbserver to exit and unpush the
   9766      target.  */
   9767   if (res == -1 && !remote_multi_process_p (rs)
   9768       && number_of_live_inferiors () == 1)
   9769     {
   9770       remote_kill_k ();
   9771 
   9772       /* We've killed the remote end, we get to mourn it.  If we are
   9773 	 not in extended mode, mourning the inferior also unpushes
   9774 	 remote_ops from the target stack, which closes the remote
   9775 	 connection.  */
   9776       target_mourn_inferior (inferior_ptid);
   9777 
   9778       return;
   9779     }
   9780 
   9781   error (_("Can't kill process"));
   9782 }
   9783 
   9784 /* Send a kill request to the target using the 'vKill' packet.  */
   9785 
   9786 int
   9787 remote_target::remote_vkill (int pid)
   9788 {
   9789   if (packet_support (PACKET_vKill) == PACKET_DISABLE)
   9790     return -1;
   9791 
   9792   remote_state *rs = get_remote_state ();
   9793 
   9794   /* Tell the remote target to detach.  */
   9795   xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
   9796   putpkt (rs->buf);
   9797   getpkt (&rs->buf, 0);
   9798 
   9799   switch (packet_ok (rs->buf,
   9800 		     &remote_protocol_packets[PACKET_vKill]))
   9801     {
   9802     case PACKET_OK:
   9803       return 0;
   9804     case PACKET_ERROR:
   9805       return 1;
   9806     case PACKET_UNKNOWN:
   9807       return -1;
   9808     default:
   9809       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
   9810     }
   9811 }
   9812 
   9813 /* Send a kill request to the target using the 'k' packet.  */
   9814 
   9815 void
   9816 remote_target::remote_kill_k ()
   9817 {
   9818   /* Catch errors so the user can quit from gdb even when we
   9819      aren't on speaking terms with the remote system.  */
   9820   TRY
   9821     {
   9822       putpkt ("k");
   9823     }
   9824   CATCH (ex, RETURN_MASK_ERROR)
   9825     {
   9826       if (ex.error == TARGET_CLOSE_ERROR)
   9827 	{
   9828 	  /* If we got an (EOF) error that caused the target
   9829 	     to go away, then we're done, that's what we wanted.
   9830 	     "k" is susceptible to cause a premature EOF, given
   9831 	     that the remote server isn't actually required to
   9832 	     reply to "k", and it can happen that it doesn't
   9833 	     even get to reply ACK to the "k".  */
   9834 	  return;
   9835 	}
   9836 
   9837       /* Otherwise, something went wrong.  We didn't actually kill
   9838 	 the target.  Just propagate the exception, and let the
   9839 	 user or higher layers decide what to do.  */
   9840       throw_exception (ex);
   9841     }
   9842   END_CATCH
   9843 }
   9844 
   9845 void
   9846 remote_target::mourn_inferior ()
   9847 {
   9848   struct remote_state *rs = get_remote_state ();
   9849 
   9850   /* We're no longer interested in notification events of an inferior
   9851      that exited or was killed/detached.  */
   9852   discard_pending_stop_replies (current_inferior ());
   9853 
   9854   /* In 'target remote' mode with one inferior, we close the connection.  */
   9855   if (!rs->extended && number_of_live_inferiors () <= 1)
   9856     {
   9857       unpush_target (this);
   9858 
   9859       /* remote_close takes care of doing most of the clean up.  */
   9860       generic_mourn_inferior ();
   9861       return;
   9862     }
   9863 
   9864   /* In case we got here due to an error, but we're going to stay
   9865      connected.  */
   9866   rs->waiting_for_stop_reply = 0;
   9867 
   9868   /* If the current general thread belonged to the process we just
   9869      detached from or has exited, the remote side current general
   9870      thread becomes undefined.  Considering a case like this:
   9871 
   9872      - We just got here due to a detach.
   9873      - The process that we're detaching from happens to immediately
   9874        report a global breakpoint being hit in non-stop mode, in the
   9875        same thread we had selected before.
   9876      - GDB attaches to this process again.
   9877      - This event happens to be the next event we handle.
   9878 
   9879      GDB would consider that the current general thread didn't need to
   9880      be set on the stub side (with Hg), since for all it knew,
   9881      GENERAL_THREAD hadn't changed.
   9882 
   9883      Notice that although in all-stop mode, the remote server always
   9884      sets the current thread to the thread reporting the stop event,
   9885      that doesn't happen in non-stop mode; in non-stop, the stub *must
   9886      not* change the current thread when reporting a breakpoint hit,
   9887      due to the decoupling of event reporting and event handling.
   9888 
   9889      To keep things simple, we always invalidate our notion of the
   9890      current thread.  */
   9891   record_currthread (rs, minus_one_ptid);
   9892 
   9893   /* Call common code to mark the inferior as not running.  */
   9894   generic_mourn_inferior ();
   9895 
   9896   if (!have_inferiors ())
   9897     {
   9898       if (!remote_multi_process_p (rs))
   9899 	{
   9900 	  /* Check whether the target is running now - some remote stubs
   9901 	     automatically restart after kill.	*/
   9902 	  putpkt ("?");
   9903 	  getpkt (&rs->buf, 0);
   9904 
   9905 	  if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
   9906 	    {
   9907 	      /* Assume that the target has been restarted.  Set
   9908 		 inferior_ptid so that bits of core GDB realizes
   9909 		 there's something here, e.g., so that the user can
   9910 		 say "kill" again.  */
   9911 	      inferior_ptid = magic_null_ptid;
   9912 	    }
   9913 	}
   9914     }
   9915 }
   9916 
   9917 bool
   9918 extended_remote_target::supports_disable_randomization ()
   9919 {
   9920   return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
   9921 }
   9922 
   9923 void
   9924 remote_target::extended_remote_disable_randomization (int val)
   9925 {
   9926   struct remote_state *rs = get_remote_state ();
   9927   char *reply;
   9928 
   9929   xsnprintf (rs->buf.data (), get_remote_packet_size (),
   9930 	     "QDisableRandomization:%x", val);
   9931   putpkt (rs->buf);
   9932   reply = remote_get_noisy_reply ();
   9933   if (*reply == '\0')
   9934     error (_("Target does not support QDisableRandomization."));
   9935   if (strcmp (reply, "OK") != 0)
   9936     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
   9937 }
   9938 
   9939 int
   9940 remote_target::extended_remote_run (const std::string &args)
   9941 {
   9942   struct remote_state *rs = get_remote_state ();
   9943   int len;
   9944   const char *remote_exec_file = get_remote_exec_file ();
   9945 
   9946   /* If the user has disabled vRun support, or we have detected that
   9947      support is not available, do not try it.  */
   9948   if (packet_support (PACKET_vRun) == PACKET_DISABLE)
   9949     return -1;
   9950 
   9951   strcpy (rs->buf.data (), "vRun;");
   9952   len = strlen (rs->buf.data ());
   9953 
   9954   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
   9955     error (_("Remote file name too long for run packet"));
   9956   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
   9957 		      strlen (remote_exec_file));
   9958 
   9959   if (!args.empty ())
   9960     {
   9961       int i;
   9962 
   9963       gdb_argv argv (args.c_str ());
   9964       for (i = 0; argv[i] != NULL; i++)
   9965 	{
   9966 	  if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
   9967 	    error (_("Argument list too long for run packet"));
   9968 	  rs->buf[len++] = ';';
   9969 	  len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
   9970 			      strlen (argv[i]));
   9971 	}
   9972     }
   9973 
   9974   rs->buf[len++] = '\0';
   9975 
   9976   putpkt (rs->buf);
   9977   getpkt (&rs->buf, 0);
   9978 
   9979   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
   9980     {
   9981     case PACKET_OK:
   9982       /* We have a wait response.  All is well.  */
   9983       return 0;
   9984     case PACKET_UNKNOWN:
   9985       return -1;
   9986     case PACKET_ERROR:
   9987       if (remote_exec_file[0] == '\0')
   9988 	error (_("Running the default executable on the remote target failed; "
   9989 		 "try \"set remote exec-file\"?"));
   9990       else
   9991 	error (_("Running \"%s\" on the remote target failed"),
   9992 	       remote_exec_file);
   9993     default:
   9994       gdb_assert_not_reached (_("bad switch"));
   9995     }
   9996 }
   9997 
   9998 /* Helper function to send set/unset environment packets.  ACTION is
   9999    either "set" or "unset".  PACKET is either "QEnvironmentHexEncoded"
   10000    or "QEnvironmentUnsetVariable".  VALUE is the variable to be
   10001    sent.  */
   10002 
   10003 void
   10004 remote_target::send_environment_packet (const char *action,
   10005 					const char *packet,
   10006 					const char *value)
   10007 {
   10008   remote_state *rs = get_remote_state ();
   10009 
   10010   /* Convert the environment variable to an hex string, which
   10011      is the best format to be transmitted over the wire.  */
   10012   std::string encoded_value = bin2hex ((const gdb_byte *) value,
   10013 					 strlen (value));
   10014 
   10015   xsnprintf (rs->buf.data (), get_remote_packet_size (),
   10016 	     "%s:%s", packet, encoded_value.c_str ());
   10017 
   10018   putpkt (rs->buf);
   10019   getpkt (&rs->buf, 0);
   10020   if (strcmp (rs->buf.data (), "OK") != 0)
   10021     warning (_("Unable to %s environment variable '%s' on remote."),
   10022 	     action, value);
   10023 }
   10024 
   10025 /* Helper function to handle the QEnvironment* packets.  */
   10026 
   10027 void
   10028 remote_target::extended_remote_environment_support ()
   10029 {
   10030   remote_state *rs = get_remote_state ();
   10031 
   10032   if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
   10033     {
   10034       putpkt ("QEnvironmentReset");
   10035       getpkt (&rs->buf, 0);
   10036       if (strcmp (rs->buf.data (), "OK") != 0)
   10037 	warning (_("Unable to reset environment on remote."));
   10038     }
   10039 
   10040   gdb_environ *e = &current_inferior ()->environment;
   10041 
   10042   if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
   10043     for (const std::string &el : e->user_set_env ())
   10044       send_environment_packet ("set", "QEnvironmentHexEncoded",
   10045 			       el.c_str ());
   10046 
   10047   if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
   10048     for (const std::string &el : e->user_unset_env ())
   10049       send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
   10050 }
   10051 
   10052 /* Helper function to set the current working directory for the
   10053    inferior in the remote target.  */
   10054 
   10055 void
   10056 remote_target::extended_remote_set_inferior_cwd ()
   10057 {
   10058   if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
   10059     {
   10060       const char *inferior_cwd = get_inferior_cwd ();
   10061       remote_state *rs = get_remote_state ();
   10062 
   10063       if (inferior_cwd != NULL)
   10064 	{
   10065 	  std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
   10066 					 strlen (inferior_cwd));
   10067 
   10068 	  xsnprintf (rs->buf.data (), get_remote_packet_size (),
   10069 		     "QSetWorkingDir:%s", hexpath.c_str ());
   10070 	}
   10071       else
   10072 	{
   10073 	  /* An empty inferior_cwd means that the user wants us to
   10074 	     reset the remote server's inferior's cwd.  */
   10075 	  xsnprintf (rs->buf.data (), get_remote_packet_size (),
   10076 		     "QSetWorkingDir:");
   10077 	}
   10078 
   10079       putpkt (rs->buf);
   10080       getpkt (&rs->buf, 0);
   10081       if (packet_ok (rs->buf,
   10082 		     &remote_protocol_packets[PACKET_QSetWorkingDir])
   10083 	  != PACKET_OK)
   10084 	error (_("\
   10085 Remote replied unexpectedly while setting the inferior's working\n\
   10086 directory: %s"),
   10087 	       rs->buf.data ());
   10088 
   10089     }
   10090 }
   10091 
   10092 /* In the extended protocol we want to be able to do things like
   10093    "run" and have them basically work as expected.  So we need
   10094    a special create_inferior function.  We support changing the
   10095    executable file and the command line arguments, but not the
   10096    environment.  */
   10097 
   10098 void
   10099 extended_remote_target::create_inferior (const char *exec_file,
   10100 					 const std::string &args,
   10101 					 char **env, int from_tty)
   10102 {
   10103   int run_worked;
   10104   char *stop_reply;
   10105   struct remote_state *rs = get_remote_state ();
   10106   const char *remote_exec_file = get_remote_exec_file ();
   10107 
   10108   /* If running asynchronously, register the target file descriptor
   10109      with the event loop.  */
   10110   if (target_can_async_p ())
   10111     target_async (1);
   10112 
   10113   /* Disable address space randomization if requested (and supported).  */
   10114   if (supports_disable_randomization ())
   10115     extended_remote_disable_randomization (disable_randomization);
   10116 
   10117   /* If startup-with-shell is on, we inform gdbserver to start the
   10118      remote inferior using a shell.  */
   10119   if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
   10120     {
   10121       xsnprintf (rs->buf.data (), get_remote_packet_size (),
   10122 		 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
   10123       putpkt (rs->buf);
   10124       getpkt (&rs->buf, 0);
   10125       if (strcmp (rs->buf.data (), "OK") != 0)
   10126 	error (_("\
   10127 Remote replied unexpectedly while setting startup-with-shell: %s"),
   10128 	       rs->buf.data ());
   10129     }
   10130 
   10131   extended_remote_environment_support ();
   10132 
   10133   extended_remote_set_inferior_cwd ();
   10134 
   10135   /* Now restart the remote server.  */
   10136   run_worked = extended_remote_run (args) != -1;
   10137   if (!run_worked)
   10138     {
   10139       /* vRun was not supported.  Fail if we need it to do what the
   10140 	 user requested.  */
   10141       if (remote_exec_file[0])
   10142 	error (_("Remote target does not support \"set remote exec-file\""));
   10143       if (!args.empty ())
   10144 	error (_("Remote target does not support \"set args\" or run ARGS"));
   10145 
   10146       /* Fall back to "R".  */
   10147       extended_remote_restart ();
   10148     }
   10149 
   10150   /* vRun's success return is a stop reply.  */
   10151   stop_reply = run_worked ? rs->buf.data () : NULL;
   10152   add_current_inferior_and_thread (stop_reply);
   10153 
   10154   /* Get updated offsets, if the stub uses qOffsets.  */
   10155   get_offsets ();
   10156 }
   10157 
   10158 
   10160 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
   10161    the list of conditions (in agent expression bytecode format), if any, the
   10162    target needs to evaluate.  The output is placed into the packet buffer
   10163    started from BUF and ended at BUF_END.  */
   10164 
   10165 static int
   10166 remote_add_target_side_condition (struct gdbarch *gdbarch,
   10167 				  struct bp_target_info *bp_tgt, char *buf,
   10168 				  char *buf_end)
   10169 {
   10170   if (bp_tgt->conditions.empty ())
   10171     return 0;
   10172 
   10173   buf += strlen (buf);
   10174   xsnprintf (buf, buf_end - buf, "%s", ";");
   10175   buf++;
   10176 
   10177   /* Send conditions to the target.  */
   10178   for (agent_expr *aexpr : bp_tgt->conditions)
   10179     {
   10180       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
   10181       buf += strlen (buf);
   10182       for (int i = 0; i < aexpr->len; ++i)
   10183 	buf = pack_hex_byte (buf, aexpr->buf[i]);
   10184       *buf = '\0';
   10185     }
   10186   return 0;
   10187 }
   10188 
   10189 static void
   10190 remote_add_target_side_commands (struct gdbarch *gdbarch,
   10191 				 struct bp_target_info *bp_tgt, char *buf)
   10192 {
   10193   if (bp_tgt->tcommands.empty ())
   10194     return;
   10195 
   10196   buf += strlen (buf);
   10197 
   10198   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
   10199   buf += strlen (buf);
   10200 
   10201   /* Concatenate all the agent expressions that are commands into the
   10202      cmds parameter.  */
   10203   for (agent_expr *aexpr : bp_tgt->tcommands)
   10204     {
   10205       sprintf (buf, "X%x,", aexpr->len);
   10206       buf += strlen (buf);
   10207       for (int i = 0; i < aexpr->len; ++i)
   10208 	buf = pack_hex_byte (buf, aexpr->buf[i]);
   10209       *buf = '\0';
   10210     }
   10211 }
   10212 
   10213 /* Insert a breakpoint.  On targets that have software breakpoint
   10214    support, we ask the remote target to do the work; on targets
   10215    which don't, we insert a traditional memory breakpoint.  */
   10216 
   10217 int
   10218 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
   10219 				  struct bp_target_info *bp_tgt)
   10220 {
   10221   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
   10222      If it succeeds, then set the support to PACKET_ENABLE.  If it
   10223      fails, and the user has explicitly requested the Z support then
   10224      report an error, otherwise, mark it disabled and go on.  */
   10225 
   10226   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
   10227     {
   10228       CORE_ADDR addr = bp_tgt->reqstd_address;
   10229       struct remote_state *rs;
   10230       char *p, *endbuf;
   10231 
   10232       /* Make sure the remote is pointing at the right process, if
   10233 	 necessary.  */
   10234       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
   10235 	set_general_process ();
   10236 
   10237       rs = get_remote_state ();
   10238       p = rs->buf.data ();
   10239       endbuf = p + get_remote_packet_size ();
   10240 
   10241       *(p++) = 'Z';
   10242       *(p++) = '0';
   10243       *(p++) = ',';
   10244       addr = (ULONGEST) remote_address_masked (addr);
   10245       p += hexnumstr (p, addr);
   10246       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
   10247 
   10248       if (supports_evaluation_of_breakpoint_conditions ())
   10249 	remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
   10250 
   10251       if (can_run_breakpoint_commands ())
   10252 	remote_add_target_side_commands (gdbarch, bp_tgt, p);
   10253 
   10254       putpkt (rs->buf);
   10255       getpkt (&rs->buf, 0);
   10256 
   10257       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
   10258 	{
   10259 	case PACKET_ERROR:
   10260 	  return -1;
   10261 	case PACKET_OK:
   10262 	  return 0;
   10263 	case PACKET_UNKNOWN:
   10264 	  break;
   10265 	}
   10266     }
   10267 
   10268   /* If this breakpoint has target-side commands but this stub doesn't
   10269      support Z0 packets, throw error.  */
   10270   if (!bp_tgt->tcommands.empty ())
   10271     throw_error (NOT_SUPPORTED_ERROR, _("\
   10272 Target doesn't support breakpoints that have target side commands."));
   10273 
   10274   return memory_insert_breakpoint (this, gdbarch, bp_tgt);
   10275 }
   10276 
   10277 int
   10278 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
   10279 				  struct bp_target_info *bp_tgt,
   10280 				  enum remove_bp_reason reason)
   10281 {
   10282   CORE_ADDR addr = bp_tgt->placed_address;
   10283   struct remote_state *rs = get_remote_state ();
   10284 
   10285   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
   10286     {
   10287       char *p = rs->buf.data ();
   10288       char *endbuf = p + get_remote_packet_size ();
   10289 
   10290       /* Make sure the remote is pointing at the right process, if
   10291 	 necessary.  */
   10292       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
   10293 	set_general_process ();
   10294 
   10295       *(p++) = 'z';
   10296       *(p++) = '0';
   10297       *(p++) = ',';
   10298 
   10299       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
   10300       p += hexnumstr (p, addr);
   10301       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
   10302 
   10303       putpkt (rs->buf);
   10304       getpkt (&rs->buf, 0);
   10305 
   10306       return (rs->buf[0] == 'E');
   10307     }
   10308 
   10309   return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
   10310 }
   10311 
   10312 static enum Z_packet_type
   10313 watchpoint_to_Z_packet (int type)
   10314 {
   10315   switch (type)
   10316     {
   10317     case hw_write:
   10318       return Z_PACKET_WRITE_WP;
   10319       break;
   10320     case hw_read:
   10321       return Z_PACKET_READ_WP;
   10322       break;
   10323     case hw_access:
   10324       return Z_PACKET_ACCESS_WP;
   10325       break;
   10326     default:
   10327       internal_error (__FILE__, __LINE__,
   10328 		      _("hw_bp_to_z: bad watchpoint type %d"), type);
   10329     }
   10330 }
   10331 
   10332 int
   10333 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
   10334 				  enum target_hw_bp_type type, struct expression *cond)
   10335 {
   10336   struct remote_state *rs = get_remote_state ();
   10337   char *endbuf = rs->buf.data () + get_remote_packet_size ();
   10338   char *p;
   10339   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
   10340 
   10341   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
   10342     return 1;
   10343 
   10344   /* Make sure the remote is pointing at the right process, if
   10345      necessary.  */
   10346   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
   10347     set_general_process ();
   10348 
   10349   xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
   10350   p = strchr (rs->buf.data (), '\0');
   10351   addr = remote_address_masked (addr);
   10352   p += hexnumstr (p, (ULONGEST) addr);
   10353   xsnprintf (p, endbuf - p, ",%x", len);
   10354 
   10355   putpkt (rs->buf);
   10356   getpkt (&rs->buf, 0);
   10357 
   10358   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
   10359     {
   10360     case PACKET_ERROR:
   10361       return -1;
   10362     case PACKET_UNKNOWN:
   10363       return 1;
   10364     case PACKET_OK:
   10365       return 0;
   10366     }
   10367   internal_error (__FILE__, __LINE__,
   10368 		  _("remote_insert_watchpoint: reached end of function"));
   10369 }
   10370 
   10371 bool
   10372 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
   10373 					     CORE_ADDR start, int length)
   10374 {
   10375   CORE_ADDR diff = remote_address_masked (addr - start);
   10376 
   10377   return diff < length;
   10378 }
   10379 
   10380 
   10381 int
   10382 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
   10383 				  enum target_hw_bp_type type, struct expression *cond)
   10384 {
   10385   struct remote_state *rs = get_remote_state ();
   10386   char *endbuf = rs->buf.data () + get_remote_packet_size ();
   10387   char *p;
   10388   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
   10389 
   10390   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
   10391     return -1;
   10392 
   10393   /* Make sure the remote is pointing at the right process, if
   10394      necessary.  */
   10395   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
   10396     set_general_process ();
   10397 
   10398   xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
   10399   p = strchr (rs->buf.data (), '\0');
   10400   addr = remote_address_masked (addr);
   10401   p += hexnumstr (p, (ULONGEST) addr);
   10402   xsnprintf (p, endbuf - p, ",%x", len);
   10403   putpkt (rs->buf);
   10404   getpkt (&rs->buf, 0);
   10405 
   10406   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
   10407     {
   10408     case PACKET_ERROR:
   10409     case PACKET_UNKNOWN:
   10410       return -1;
   10411     case PACKET_OK:
   10412       return 0;
   10413     }
   10414   internal_error (__FILE__, __LINE__,
   10415 		  _("remote_remove_watchpoint: reached end of function"));
   10416 }
   10417 
   10418 
   10419 int remote_hw_watchpoint_limit = -1;
   10420 int remote_hw_watchpoint_length_limit = -1;
   10421 int remote_hw_breakpoint_limit = -1;
   10422 
   10423 int
   10424 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
   10425 {
   10426   if (remote_hw_watchpoint_length_limit == 0)
   10427     return 0;
   10428   else if (remote_hw_watchpoint_length_limit < 0)
   10429     return 1;
   10430   else if (len <= remote_hw_watchpoint_length_limit)
   10431     return 1;
   10432   else
   10433     return 0;
   10434 }
   10435 
   10436 int
   10437 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
   10438 {
   10439   if (type == bp_hardware_breakpoint)
   10440     {
   10441       if (remote_hw_breakpoint_limit == 0)
   10442 	return 0;
   10443       else if (remote_hw_breakpoint_limit < 0)
   10444 	return 1;
   10445       else if (cnt <= remote_hw_breakpoint_limit)
   10446 	return 1;
   10447     }
   10448   else
   10449     {
   10450       if (remote_hw_watchpoint_limit == 0)
   10451 	return 0;
   10452       else if (remote_hw_watchpoint_limit < 0)
   10453 	return 1;
   10454       else if (ot)
   10455 	return -1;
   10456       else if (cnt <= remote_hw_watchpoint_limit)
   10457 	return 1;
   10458     }
   10459   return -1;
   10460 }
   10461 
   10462 /* The to_stopped_by_sw_breakpoint method of target remote.  */
   10463 
   10464 bool
   10465 remote_target::stopped_by_sw_breakpoint ()
   10466 {
   10467   struct thread_info *thread = inferior_thread ();
   10468 
   10469   return (thread->priv != NULL
   10470 	  && (get_remote_thread_info (thread)->stop_reason
   10471 	      == TARGET_STOPPED_BY_SW_BREAKPOINT));
   10472 }
   10473 
   10474 /* The to_supports_stopped_by_sw_breakpoint method of target
   10475    remote.  */
   10476 
   10477 bool
   10478 remote_target::supports_stopped_by_sw_breakpoint ()
   10479 {
   10480   return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
   10481 }
   10482 
   10483 /* The to_stopped_by_hw_breakpoint method of target remote.  */
   10484 
   10485 bool
   10486 remote_target::stopped_by_hw_breakpoint ()
   10487 {
   10488   struct thread_info *thread = inferior_thread ();
   10489 
   10490   return (thread->priv != NULL
   10491 	  && (get_remote_thread_info (thread)->stop_reason
   10492 	      == TARGET_STOPPED_BY_HW_BREAKPOINT));
   10493 }
   10494 
   10495 /* The to_supports_stopped_by_hw_breakpoint method of target
   10496    remote.  */
   10497 
   10498 bool
   10499 remote_target::supports_stopped_by_hw_breakpoint ()
   10500 {
   10501   return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
   10502 }
   10503 
   10504 bool
   10505 remote_target::stopped_by_watchpoint ()
   10506 {
   10507   struct thread_info *thread = inferior_thread ();
   10508 
   10509   return (thread->priv != NULL
   10510 	  && (get_remote_thread_info (thread)->stop_reason
   10511 	      == TARGET_STOPPED_BY_WATCHPOINT));
   10512 }
   10513 
   10514 bool
   10515 remote_target::stopped_data_address (CORE_ADDR *addr_p)
   10516 {
   10517   struct thread_info *thread = inferior_thread ();
   10518 
   10519   if (thread->priv != NULL
   10520       && (get_remote_thread_info (thread)->stop_reason
   10521 	  == TARGET_STOPPED_BY_WATCHPOINT))
   10522     {
   10523       *addr_p = get_remote_thread_info (thread)->watch_data_address;
   10524       return true;
   10525     }
   10526 
   10527   return false;
   10528 }
   10529 
   10530 
   10531 int
   10532 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
   10533 				     struct bp_target_info *bp_tgt)
   10534 {
   10535   CORE_ADDR addr = bp_tgt->reqstd_address;
   10536   struct remote_state *rs;
   10537   char *p, *endbuf;
   10538   char *message;
   10539 
   10540   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
   10541     return -1;
   10542 
   10543   /* Make sure the remote is pointing at the right process, if
   10544      necessary.  */
   10545   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
   10546     set_general_process ();
   10547 
   10548   rs = get_remote_state ();
   10549   p = rs->buf.data ();
   10550   endbuf = p + get_remote_packet_size ();
   10551 
   10552   *(p++) = 'Z';
   10553   *(p++) = '1';
   10554   *(p++) = ',';
   10555 
   10556   addr = remote_address_masked (addr);
   10557   p += hexnumstr (p, (ULONGEST) addr);
   10558   xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
   10559 
   10560   if (supports_evaluation_of_breakpoint_conditions ())
   10561     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
   10562 
   10563   if (can_run_breakpoint_commands ())
   10564     remote_add_target_side_commands (gdbarch, bp_tgt, p);
   10565 
   10566   putpkt (rs->buf);
   10567   getpkt (&rs->buf, 0);
   10568 
   10569   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
   10570     {
   10571     case PACKET_ERROR:
   10572       if (rs->buf[1] == '.')
   10573         {
   10574           message = strchr (&rs->buf[2], '.');
   10575           if (message)
   10576             error (_("Remote failure reply: %s"), message + 1);
   10577         }
   10578       return -1;
   10579     case PACKET_UNKNOWN:
   10580       return -1;
   10581     case PACKET_OK:
   10582       return 0;
   10583     }
   10584   internal_error (__FILE__, __LINE__,
   10585 		  _("remote_insert_hw_breakpoint: reached end of function"));
   10586 }
   10587 
   10588 
   10589 int
   10590 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
   10591 				     struct bp_target_info *bp_tgt)
   10592 {
   10593   CORE_ADDR addr;
   10594   struct remote_state *rs = get_remote_state ();
   10595   char *p = rs->buf.data ();
   10596   char *endbuf = p + get_remote_packet_size ();
   10597 
   10598   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
   10599     return -1;
   10600 
   10601   /* Make sure the remote is pointing at the right process, if
   10602      necessary.  */
   10603   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
   10604     set_general_process ();
   10605 
   10606   *(p++) = 'z';
   10607   *(p++) = '1';
   10608   *(p++) = ',';
   10609 
   10610   addr = remote_address_masked (bp_tgt->placed_address);
   10611   p += hexnumstr (p, (ULONGEST) addr);
   10612   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->kind);
   10613 
   10614   putpkt (rs->buf);
   10615   getpkt (&rs->buf, 0);
   10616 
   10617   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
   10618     {
   10619     case PACKET_ERROR:
   10620     case PACKET_UNKNOWN:
   10621       return -1;
   10622     case PACKET_OK:
   10623       return 0;
   10624     }
   10625   internal_error (__FILE__, __LINE__,
   10626 		  _("remote_remove_hw_breakpoint: reached end of function"));
   10627 }
   10628 
   10629 /* Verify memory using the "qCRC:" request.  */
   10630 
   10631 int
   10632 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
   10633 {
   10634   struct remote_state *rs = get_remote_state ();
   10635   unsigned long host_crc, target_crc;
   10636   char *tmp;
   10637 
   10638   /* It doesn't make sense to use qCRC if the remote target is
   10639      connected but not running.  */
   10640   if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
   10641     {
   10642       enum packet_result result;
   10643 
   10644       /* Make sure the remote is pointing at the right process.  */
   10645       set_general_process ();
   10646 
   10647       /* FIXME: assumes lma can fit into long.  */
   10648       xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
   10649 		 (long) lma, (long) size);
   10650       putpkt (rs->buf);
   10651 
   10652       /* Be clever; compute the host_crc before waiting for target
   10653 	 reply.  */
   10654       host_crc = xcrc32 (data, size, 0xffffffff);
   10655 
   10656       getpkt (&rs->buf, 0);
   10657 
   10658       result = packet_ok (rs->buf,
   10659 			  &remote_protocol_packets[PACKET_qCRC]);
   10660       if (result == PACKET_ERROR)
   10661 	return -1;
   10662       else if (result == PACKET_OK)
   10663 	{
   10664 	  for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
   10665 	    target_crc = target_crc * 16 + fromhex (*tmp);
   10666 
   10667 	  return (host_crc == target_crc);
   10668 	}
   10669     }
   10670 
   10671   return simple_verify_memory (this, data, lma, size);
   10672 }
   10673 
   10674 /* compare-sections command
   10675 
   10676    With no arguments, compares each loadable section in the exec bfd
   10677    with the same memory range on the target, and reports mismatches.
   10678    Useful for verifying the image on the target against the exec file.  */
   10679 
   10680 static void
   10681 compare_sections_command (const char *args, int from_tty)
   10682 {
   10683   asection *s;
   10684   const char *sectname;
   10685   bfd_size_type size;
   10686   bfd_vma lma;
   10687   int matched = 0;
   10688   int mismatched = 0;
   10689   int res;
   10690   int read_only = 0;
   10691 
   10692   if (!exec_bfd)
   10693     error (_("command cannot be used without an exec file"));
   10694 
   10695   if (args != NULL && strcmp (args, "-r") == 0)
   10696     {
   10697       read_only = 1;
   10698       args = NULL;
   10699     }
   10700 
   10701   for (s = exec_bfd->sections; s; s = s->next)
   10702     {
   10703       if (!(s->flags & SEC_LOAD))
   10704 	continue;		/* Skip non-loadable section.  */
   10705 
   10706       if (read_only && (s->flags & SEC_READONLY) == 0)
   10707 	continue;		/* Skip writeable sections */
   10708 
   10709       size = bfd_get_section_size (s);
   10710       if (size == 0)
   10711 	continue;		/* Skip zero-length section.  */
   10712 
   10713       sectname = bfd_get_section_name (exec_bfd, s);
   10714       if (args && strcmp (args, sectname) != 0)
   10715 	continue;		/* Not the section selected by user.  */
   10716 
   10717       matched = 1;		/* Do this section.  */
   10718       lma = s->lma;
   10719 
   10720       gdb::byte_vector sectdata (size);
   10721       bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
   10722 
   10723       res = target_verify_memory (sectdata.data (), lma, size);
   10724 
   10725       if (res == -1)
   10726 	error (_("target memory fault, section %s, range %s -- %s"), sectname,
   10727 	       paddress (target_gdbarch (), lma),
   10728 	       paddress (target_gdbarch (), lma + size));
   10729 
   10730       printf_filtered ("Section %s, range %s -- %s: ", sectname,
   10731 		       paddress (target_gdbarch (), lma),
   10732 		       paddress (target_gdbarch (), lma + size));
   10733       if (res)
   10734 	printf_filtered ("matched.\n");
   10735       else
   10736 	{
   10737 	  printf_filtered ("MIS-MATCHED!\n");
   10738 	  mismatched++;
   10739 	}
   10740     }
   10741   if (mismatched > 0)
   10742     warning (_("One or more sections of the target image does not match\n\
   10743 the loaded file\n"));
   10744   if (args && !matched)
   10745     printf_filtered (_("No loaded section named '%s'.\n"), args);
   10746 }
   10747 
   10748 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
   10749    into remote target.  The number of bytes written to the remote
   10750    target is returned, or -1 for error.  */
   10751 
   10752 target_xfer_status
   10753 remote_target::remote_write_qxfer (const char *object_name,
   10754 				   const char *annex, const gdb_byte *writebuf,
   10755 				   ULONGEST offset, LONGEST len,
   10756 				   ULONGEST *xfered_len,
   10757 				   struct packet_config *packet)
   10758 {
   10759   int i, buf_len;
   10760   ULONGEST n;
   10761   struct remote_state *rs = get_remote_state ();
   10762   int max_size = get_memory_write_packet_size ();
   10763 
   10764   if (packet_config_support (packet) == PACKET_DISABLE)
   10765     return TARGET_XFER_E_IO;
   10766 
   10767   /* Insert header.  */
   10768   i = snprintf (rs->buf.data (), max_size,
   10769 		"qXfer:%s:write:%s:%s:",
   10770 		object_name, annex ? annex : "",
   10771 		phex_nz (offset, sizeof offset));
   10772   max_size -= (i + 1);
   10773 
   10774   /* Escape as much data as fits into rs->buf.  */
   10775   buf_len = remote_escape_output
   10776     (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
   10777 
   10778   if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
   10779       || getpkt_sane (&rs->buf, 0) < 0
   10780       || packet_ok (rs->buf, packet) != PACKET_OK)
   10781     return TARGET_XFER_E_IO;
   10782 
   10783   unpack_varlen_hex (rs->buf.data (), &n);
   10784 
   10785   *xfered_len = n;
   10786   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
   10787 }
   10788 
   10789 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
   10790    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
   10791    number of bytes read is returned, or 0 for EOF, or -1 for error.
   10792    The number of bytes read may be less than LEN without indicating an
   10793    EOF.  PACKET is checked and updated to indicate whether the remote
   10794    target supports this object.  */
   10795 
   10796 target_xfer_status
   10797 remote_target::remote_read_qxfer (const char *object_name,
   10798 				  const char *annex,
   10799 				  gdb_byte *readbuf, ULONGEST offset,
   10800 				  LONGEST len,
   10801 				  ULONGEST *xfered_len,
   10802 				  struct packet_config *packet)
   10803 {
   10804   struct remote_state *rs = get_remote_state ();
   10805   LONGEST i, n, packet_len;
   10806 
   10807   if (packet_config_support (packet) == PACKET_DISABLE)
   10808     return TARGET_XFER_E_IO;
   10809 
   10810   /* Check whether we've cached an end-of-object packet that matches
   10811      this request.  */
   10812   if (rs->finished_object)
   10813     {
   10814       if (strcmp (object_name, rs->finished_object) == 0
   10815 	  && strcmp (annex ? annex : "", rs->finished_annex) == 0
   10816 	  && offset == rs->finished_offset)
   10817 	return TARGET_XFER_EOF;
   10818 
   10819 
   10820       /* Otherwise, we're now reading something different.  Discard
   10821 	 the cache.  */
   10822       xfree (rs->finished_object);
   10823       xfree (rs->finished_annex);
   10824       rs->finished_object = NULL;
   10825       rs->finished_annex = NULL;
   10826     }
   10827 
   10828   /* Request only enough to fit in a single packet.  The actual data
   10829      may not, since we don't know how much of it will need to be escaped;
   10830      the target is free to respond with slightly less data.  We subtract
   10831      five to account for the response type and the protocol frame.  */
   10832   n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
   10833   snprintf (rs->buf.data (), get_remote_packet_size () - 4,
   10834 	    "qXfer:%s:read:%s:%s,%s",
   10835 	    object_name, annex ? annex : "",
   10836 	    phex_nz (offset, sizeof offset),
   10837 	    phex_nz (n, sizeof n));
   10838   i = putpkt (rs->buf);
   10839   if (i < 0)
   10840     return TARGET_XFER_E_IO;
   10841 
   10842   rs->buf[0] = '\0';
   10843   packet_len = getpkt_sane (&rs->buf, 0);
   10844   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
   10845     return TARGET_XFER_E_IO;
   10846 
   10847   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
   10848     error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
   10849 
   10850   /* 'm' means there is (or at least might be) more data after this
   10851      batch.  That does not make sense unless there's at least one byte
   10852      of data in this reply.  */
   10853   if (rs->buf[0] == 'm' && packet_len == 1)
   10854     error (_("Remote qXfer reply contained no data."));
   10855 
   10856   /* Got some data.  */
   10857   i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
   10858 			     packet_len - 1, readbuf, n);
   10859 
   10860   /* 'l' is an EOF marker, possibly including a final block of data,
   10861      or possibly empty.  If we have the final block of a non-empty
   10862      object, record this fact to bypass a subsequent partial read.  */
   10863   if (rs->buf[0] == 'l' && offset + i > 0)
   10864     {
   10865       rs->finished_object = xstrdup (object_name);
   10866       rs->finished_annex = xstrdup (annex ? annex : "");
   10867       rs->finished_offset = offset + i;
   10868     }
   10869 
   10870   if (i == 0)
   10871     return TARGET_XFER_EOF;
   10872   else
   10873     {
   10874       *xfered_len = i;
   10875       return TARGET_XFER_OK;
   10876     }
   10877 }
   10878 
   10879 enum target_xfer_status
   10880 remote_target::xfer_partial (enum target_object object,
   10881 			     const char *annex, gdb_byte *readbuf,
   10882 			     const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
   10883 			     ULONGEST *xfered_len)
   10884 {
   10885   struct remote_state *rs;
   10886   int i;
   10887   char *p2;
   10888   char query_type;
   10889   int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
   10890 
   10891   set_remote_traceframe ();
   10892   set_general_thread (inferior_ptid);
   10893 
   10894   rs = get_remote_state ();
   10895 
   10896   /* Handle memory using the standard memory routines.  */
   10897   if (object == TARGET_OBJECT_MEMORY)
   10898     {
   10899       /* If the remote target is connected but not running, we should
   10900 	 pass this request down to a lower stratum (e.g. the executable
   10901 	 file).  */
   10902       if (!target_has_execution)
   10903 	return TARGET_XFER_EOF;
   10904 
   10905       if (writebuf != NULL)
   10906 	return remote_write_bytes (offset, writebuf, len, unit_size,
   10907 				   xfered_len);
   10908       else
   10909 	return remote_read_bytes (offset, readbuf, len, unit_size,
   10910 				  xfered_len);
   10911     }
   10912 
   10913   /* Handle SPU memory using qxfer packets.  */
   10914   if (object == TARGET_OBJECT_SPU)
   10915     {
   10916       if (readbuf)
   10917 	return remote_read_qxfer ("spu", annex, readbuf, offset, len,
   10918 				  xfered_len, &remote_protocol_packets
   10919 				  [PACKET_qXfer_spu_read]);
   10920       else
   10921 	return remote_write_qxfer ("spu", annex, writebuf, offset, len,
   10922 				   xfered_len, &remote_protocol_packets
   10923 				   [PACKET_qXfer_spu_write]);
   10924     }
   10925 
   10926   /* Handle extra signal info using qxfer packets.  */
   10927   if (object == TARGET_OBJECT_SIGNAL_INFO)
   10928     {
   10929       if (readbuf)
   10930 	return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
   10931 				  xfered_len, &remote_protocol_packets
   10932 				  [PACKET_qXfer_siginfo_read]);
   10933       else
   10934 	return remote_write_qxfer ("siginfo", annex,
   10935 				   writebuf, offset, len, xfered_len,
   10936 				   &remote_protocol_packets
   10937 				   [PACKET_qXfer_siginfo_write]);
   10938     }
   10939 
   10940   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
   10941     {
   10942       if (readbuf)
   10943 	return remote_read_qxfer ("statictrace", annex,
   10944 				  readbuf, offset, len, xfered_len,
   10945 				  &remote_protocol_packets
   10946 				  [PACKET_qXfer_statictrace_read]);
   10947       else
   10948 	return TARGET_XFER_E_IO;
   10949     }
   10950 
   10951   /* Only handle flash writes.  */
   10952   if (writebuf != NULL)
   10953     {
   10954       switch (object)
   10955 	{
   10956 	case TARGET_OBJECT_FLASH:
   10957 	  return remote_flash_write (offset, len, xfered_len,
   10958 				     writebuf);
   10959 
   10960 	default:
   10961 	  return TARGET_XFER_E_IO;
   10962 	}
   10963     }
   10964 
   10965   /* Map pre-existing objects onto letters.  DO NOT do this for new
   10966      objects!!!  Instead specify new query packets.  */
   10967   switch (object)
   10968     {
   10969     case TARGET_OBJECT_AVR:
   10970       query_type = 'R';
   10971       break;
   10972 
   10973     case TARGET_OBJECT_AUXV:
   10974       gdb_assert (annex == NULL);
   10975       return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
   10976 				xfered_len,
   10977 				&remote_protocol_packets[PACKET_qXfer_auxv]);
   10978 
   10979     case TARGET_OBJECT_AVAILABLE_FEATURES:
   10980       return remote_read_qxfer
   10981 	("features", annex, readbuf, offset, len, xfered_len,
   10982 	 &remote_protocol_packets[PACKET_qXfer_features]);
   10983 
   10984     case TARGET_OBJECT_LIBRARIES:
   10985       return remote_read_qxfer
   10986 	("libraries", annex, readbuf, offset, len, xfered_len,
   10987 	 &remote_protocol_packets[PACKET_qXfer_libraries]);
   10988 
   10989     case TARGET_OBJECT_LIBRARIES_SVR4:
   10990       return remote_read_qxfer
   10991 	("libraries-svr4", annex, readbuf, offset, len, xfered_len,
   10992 	 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
   10993 
   10994     case TARGET_OBJECT_MEMORY_MAP:
   10995       gdb_assert (annex == NULL);
   10996       return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
   10997 				 xfered_len,
   10998 				&remote_protocol_packets[PACKET_qXfer_memory_map]);
   10999 
   11000     case TARGET_OBJECT_OSDATA:
   11001       /* Should only get here if we're connected.  */
   11002       gdb_assert (rs->remote_desc);
   11003       return remote_read_qxfer
   11004 	("osdata", annex, readbuf, offset, len, xfered_len,
   11005         &remote_protocol_packets[PACKET_qXfer_osdata]);
   11006 
   11007     case TARGET_OBJECT_THREADS:
   11008       gdb_assert (annex == NULL);
   11009       return remote_read_qxfer ("threads", annex, readbuf, offset, len,
   11010 				xfered_len,
   11011 				&remote_protocol_packets[PACKET_qXfer_threads]);
   11012 
   11013     case TARGET_OBJECT_TRACEFRAME_INFO:
   11014       gdb_assert (annex == NULL);
   11015       return remote_read_qxfer
   11016 	("traceframe-info", annex, readbuf, offset, len, xfered_len,
   11017 	 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
   11018 
   11019     case TARGET_OBJECT_FDPIC:
   11020       return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
   11021 				xfered_len,
   11022 				&remote_protocol_packets[PACKET_qXfer_fdpic]);
   11023 
   11024     case TARGET_OBJECT_OPENVMS_UIB:
   11025       return remote_read_qxfer ("uib", annex, readbuf, offset, len,
   11026 				xfered_len,
   11027 				&remote_protocol_packets[PACKET_qXfer_uib]);
   11028 
   11029     case TARGET_OBJECT_BTRACE:
   11030       return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
   11031 				xfered_len,
   11032         &remote_protocol_packets[PACKET_qXfer_btrace]);
   11033 
   11034     case TARGET_OBJECT_BTRACE_CONF:
   11035       return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
   11036 				len, xfered_len,
   11037 	&remote_protocol_packets[PACKET_qXfer_btrace_conf]);
   11038 
   11039     case TARGET_OBJECT_EXEC_FILE:
   11040       return remote_read_qxfer ("exec-file", annex, readbuf, offset,
   11041 				len, xfered_len,
   11042 	&remote_protocol_packets[PACKET_qXfer_exec_file]);
   11043 
   11044     default:
   11045       return TARGET_XFER_E_IO;
   11046     }
   11047 
   11048   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
   11049      large enough let the caller deal with it.  */
   11050   if (len < get_remote_packet_size ())
   11051     return TARGET_XFER_E_IO;
   11052   len = get_remote_packet_size ();
   11053 
   11054   /* Except for querying the minimum buffer size, target must be open.  */
   11055   if (!rs->remote_desc)
   11056     error (_("remote query is only available after target open"));
   11057 
   11058   gdb_assert (annex != NULL);
   11059   gdb_assert (readbuf != NULL);
   11060 
   11061   p2 = rs->buf.data ();
   11062   *p2++ = 'q';
   11063   *p2++ = query_type;
   11064 
   11065   /* We used one buffer char for the remote protocol q command and
   11066      another for the query type.  As the remote protocol encapsulation
   11067      uses 4 chars plus one extra in case we are debugging
   11068      (remote_debug), we have PBUFZIZ - 7 left to pack the query
   11069      string.  */
   11070   i = 0;
   11071   while (annex[i] && (i < (get_remote_packet_size () - 8)))
   11072     {
   11073       /* Bad caller may have sent forbidden characters.  */
   11074       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
   11075       *p2++ = annex[i];
   11076       i++;
   11077     }
   11078   *p2 = '\0';
   11079   gdb_assert (annex[i] == '\0');
   11080 
   11081   i = putpkt (rs->buf);
   11082   if (i < 0)
   11083     return TARGET_XFER_E_IO;
   11084 
   11085   getpkt (&rs->buf, 0);
   11086   strcpy ((char *) readbuf, rs->buf.data ());
   11087 
   11088   *xfered_len = strlen ((char *) readbuf);
   11089   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
   11090 }
   11091 
   11092 /* Implementation of to_get_memory_xfer_limit.  */
   11093 
   11094 ULONGEST
   11095 remote_target::get_memory_xfer_limit ()
   11096 {
   11097   return get_memory_write_packet_size ();
   11098 }
   11099 
   11100 int
   11101 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
   11102 			      const gdb_byte *pattern, ULONGEST pattern_len,
   11103 			      CORE_ADDR *found_addrp)
   11104 {
   11105   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
   11106   struct remote_state *rs = get_remote_state ();
   11107   int max_size = get_memory_write_packet_size ();
   11108   struct packet_config *packet =
   11109     &remote_protocol_packets[PACKET_qSearch_memory];
   11110   /* Number of packet bytes used to encode the pattern;
   11111      this could be more than PATTERN_LEN due to escape characters.  */
   11112   int escaped_pattern_len;
   11113   /* Amount of pattern that was encodable in the packet.  */
   11114   int used_pattern_len;
   11115   int i;
   11116   int found;
   11117   ULONGEST found_addr;
   11118 
   11119   /* Don't go to the target if we don't have to.  This is done before
   11120      checking packet_config_support to avoid the possibility that a
   11121      success for this edge case means the facility works in
   11122      general.  */
   11123   if (pattern_len > search_space_len)
   11124     return 0;
   11125   if (pattern_len == 0)
   11126     {
   11127       *found_addrp = start_addr;
   11128       return 1;
   11129     }
   11130 
   11131   /* If we already know the packet isn't supported, fall back to the simple
   11132      way of searching memory.  */
   11133 
   11134   if (packet_config_support (packet) == PACKET_DISABLE)
   11135     {
   11136       /* Target doesn't provided special support, fall back and use the
   11137 	 standard support (copy memory and do the search here).  */
   11138       return simple_search_memory (this, start_addr, search_space_len,
   11139 				   pattern, pattern_len, found_addrp);
   11140     }
   11141 
   11142   /* Make sure the remote is pointing at the right process.  */
   11143   set_general_process ();
   11144 
   11145   /* Insert header.  */
   11146   i = snprintf (rs->buf.data (), max_size,
   11147 		"qSearch:memory:%s;%s;",
   11148 		phex_nz (start_addr, addr_size),
   11149 		phex_nz (search_space_len, sizeof (search_space_len)));
   11150   max_size -= (i + 1);
   11151 
   11152   /* Escape as much data as fits into rs->buf.  */
   11153   escaped_pattern_len =
   11154     remote_escape_output (pattern, pattern_len, 1,
   11155 			  (gdb_byte *) rs->buf.data () + i,
   11156 			  &used_pattern_len, max_size);
   11157 
   11158   /* Bail if the pattern is too large.  */
   11159   if (used_pattern_len != pattern_len)
   11160     error (_("Pattern is too large to transmit to remote target."));
   11161 
   11162   if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
   11163       || getpkt_sane (&rs->buf, 0) < 0
   11164       || packet_ok (rs->buf, packet) != PACKET_OK)
   11165     {
   11166       /* The request may not have worked because the command is not
   11167 	 supported.  If so, fall back to the simple way.  */
   11168       if (packet_config_support (packet) == PACKET_DISABLE)
   11169 	{
   11170 	  return simple_search_memory (this, start_addr, search_space_len,
   11171 				       pattern, pattern_len, found_addrp);
   11172 	}
   11173       return -1;
   11174     }
   11175 
   11176   if (rs->buf[0] == '0')
   11177     found = 0;
   11178   else if (rs->buf[0] == '1')
   11179     {
   11180       found = 1;
   11181       if (rs->buf[1] != ',')
   11182 	error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
   11183       unpack_varlen_hex (&rs->buf[2], &found_addr);
   11184       *found_addrp = found_addr;
   11185     }
   11186   else
   11187     error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
   11188 
   11189   return found;
   11190 }
   11191 
   11192 void
   11193 remote_target::rcmd (const char *command, struct ui_file *outbuf)
   11194 {
   11195   struct remote_state *rs = get_remote_state ();
   11196   char *p = rs->buf.data ();
   11197 
   11198   if (!rs->remote_desc)
   11199     error (_("remote rcmd is only available after target open"));
   11200 
   11201   /* Send a NULL command across as an empty command.  */
   11202   if (command == NULL)
   11203     command = "";
   11204 
   11205   /* The query prefix.  */
   11206   strcpy (rs->buf.data (), "qRcmd,");
   11207   p = strchr (rs->buf.data (), '\0');
   11208 
   11209   if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
   11210       > get_remote_packet_size ())
   11211     error (_("\"monitor\" command ``%s'' is too long."), command);
   11212 
   11213   /* Encode the actual command.  */
   11214   bin2hex ((const gdb_byte *) command, p, strlen (command));
   11215 
   11216   if (putpkt (rs->buf) < 0)
   11217     error (_("Communication problem with target."));
   11218 
   11219   /* get/display the response */
   11220   while (1)
   11221     {
   11222       char *buf;
   11223 
   11224       /* XXX - see also remote_get_noisy_reply().  */
   11225       QUIT;			/* Allow user to bail out with ^C.  */
   11226       rs->buf[0] = '\0';
   11227       if (getpkt_sane (&rs->buf, 0) == -1)
   11228         {
   11229           /* Timeout.  Continue to (try to) read responses.
   11230              This is better than stopping with an error, assuming the stub
   11231              is still executing the (long) monitor command.
   11232              If needed, the user can interrupt gdb using C-c, obtaining
   11233              an effect similar to stop on timeout.  */
   11234           continue;
   11235         }
   11236       buf = rs->buf.data ();
   11237       if (buf[0] == '\0')
   11238 	error (_("Target does not support this command."));
   11239       if (buf[0] == 'O' && buf[1] != 'K')
   11240 	{
   11241 	  remote_console_output (buf + 1); /* 'O' message from stub.  */
   11242 	  continue;
   11243 	}
   11244       if (strcmp (buf, "OK") == 0)
   11245 	break;
   11246       if (strlen (buf) == 3 && buf[0] == 'E'
   11247 	  && isdigit (buf[1]) && isdigit (buf[2]))
   11248 	{
   11249 	  error (_("Protocol error with Rcmd"));
   11250 	}
   11251       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
   11252 	{
   11253 	  char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
   11254 
   11255 	  fputc_unfiltered (c, outbuf);
   11256 	}
   11257       break;
   11258     }
   11259 }
   11260 
   11261 std::vector<mem_region>
   11262 remote_target::memory_map ()
   11263 {
   11264   std::vector<mem_region> result;
   11265   gdb::optional<gdb::char_vector> text
   11266     = target_read_stralloc (current_top_target (), TARGET_OBJECT_MEMORY_MAP, NULL);
   11267 
   11268   if (text)
   11269     result = parse_memory_map (text->data ());
   11270 
   11271   return result;
   11272 }
   11273 
   11274 static void
   11275 packet_command (const char *args, int from_tty)
   11276 {
   11277   remote_target *remote = get_current_remote_target ();
   11278 
   11279   if (remote == nullptr)
   11280     error (_("command can only be used with remote target"));
   11281 
   11282   remote->packet_command (args, from_tty);
   11283 }
   11284 
   11285 void
   11286 remote_target::packet_command (const char *args, int from_tty)
   11287 {
   11288   if (!args)
   11289     error (_("remote-packet command requires packet text as argument"));
   11290 
   11291   puts_filtered ("sending: ");
   11292   print_packet (args);
   11293   puts_filtered ("\n");
   11294   putpkt (args);
   11295 
   11296   remote_state *rs = get_remote_state ();
   11297 
   11298   getpkt (&rs->buf, 0);
   11299   puts_filtered ("received: ");
   11300   print_packet (rs->buf.data ());
   11301   puts_filtered ("\n");
   11302 }
   11303 
   11304 #if 0
   11305 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
   11306 
   11307 static void display_thread_info (struct gdb_ext_thread_info *info);
   11308 
   11309 static void threadset_test_cmd (char *cmd, int tty);
   11310 
   11311 static void threadalive_test (char *cmd, int tty);
   11312 
   11313 static void threadlist_test_cmd (char *cmd, int tty);
   11314 
   11315 int get_and_display_threadinfo (threadref *ref);
   11316 
   11317 static void threadinfo_test_cmd (char *cmd, int tty);
   11318 
   11319 static int thread_display_step (threadref *ref, void *context);
   11320 
   11321 static void threadlist_update_test_cmd (char *cmd, int tty);
   11322 
   11323 static void init_remote_threadtests (void);
   11324 
   11325 #define SAMPLE_THREAD  0x05060708	/* Truncated 64 bit threadid.  */
   11326 
   11327 static void
   11328 threadset_test_cmd (const char *cmd, int tty)
   11329 {
   11330   int sample_thread = SAMPLE_THREAD;
   11331 
   11332   printf_filtered (_("Remote threadset test\n"));
   11333   set_general_thread (sample_thread);
   11334 }
   11335 
   11336 
   11337 static void
   11338 threadalive_test (const char *cmd, int tty)
   11339 {
   11340   int sample_thread = SAMPLE_THREAD;
   11341   int pid = inferior_ptid.pid ();
   11342   ptid_t ptid = ptid_t (pid, sample_thread, 0);
   11343 
   11344   if (remote_thread_alive (ptid))
   11345     printf_filtered ("PASS: Thread alive test\n");
   11346   else
   11347     printf_filtered ("FAIL: Thread alive test\n");
   11348 }
   11349 
   11350 void output_threadid (char *title, threadref *ref);
   11351 
   11352 void
   11353 output_threadid (char *title, threadref *ref)
   11354 {
   11355   char hexid[20];
   11356 
   11357   pack_threadid (&hexid[0], ref);	/* Convert threead id into hex.  */
   11358   hexid[16] = 0;
   11359   printf_filtered ("%s  %s\n", title, (&hexid[0]));
   11360 }
   11361 
   11362 static void
   11363 threadlist_test_cmd (const char *cmd, int tty)
   11364 {
   11365   int startflag = 1;
   11366   threadref nextthread;
   11367   int done, result_count;
   11368   threadref threadlist[3];
   11369 
   11370   printf_filtered ("Remote Threadlist test\n");
   11371   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
   11372 			      &result_count, &threadlist[0]))
   11373     printf_filtered ("FAIL: threadlist test\n");
   11374   else
   11375     {
   11376       threadref *scan = threadlist;
   11377       threadref *limit = scan + result_count;
   11378 
   11379       while (scan < limit)
   11380 	output_threadid (" thread ", scan++);
   11381     }
   11382 }
   11383 
   11384 void
   11385 display_thread_info (struct gdb_ext_thread_info *info)
   11386 {
   11387   output_threadid ("Threadid: ", &info->threadid);
   11388   printf_filtered ("Name: %s\n ", info->shortname);
   11389   printf_filtered ("State: %s\n", info->display);
   11390   printf_filtered ("other: %s\n\n", info->more_display);
   11391 }
   11392 
   11393 int
   11394 get_and_display_threadinfo (threadref *ref)
   11395 {
   11396   int result;
   11397   int set;
   11398   struct gdb_ext_thread_info threadinfo;
   11399 
   11400   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
   11401     | TAG_MOREDISPLAY | TAG_DISPLAY;
   11402   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
   11403     display_thread_info (&threadinfo);
   11404   return result;
   11405 }
   11406 
   11407 static void
   11408 threadinfo_test_cmd (const char *cmd, int tty)
   11409 {
   11410   int athread = SAMPLE_THREAD;
   11411   threadref thread;
   11412   int set;
   11413 
   11414   int_to_threadref (&thread, athread);
   11415   printf_filtered ("Remote Threadinfo test\n");
   11416   if (!get_and_display_threadinfo (&thread))
   11417     printf_filtered ("FAIL cannot get thread info\n");
   11418 }
   11419 
   11420 static int
   11421 thread_display_step (threadref *ref, void *context)
   11422 {
   11423   /* output_threadid(" threadstep ",ref); *//* simple test */
   11424   return get_and_display_threadinfo (ref);
   11425 }
   11426 
   11427 static void
   11428 threadlist_update_test_cmd (const char *cmd, int tty)
   11429 {
   11430   printf_filtered ("Remote Threadlist update test\n");
   11431   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
   11432 }
   11433 
   11434 static void
   11435 init_remote_threadtests (void)
   11436 {
   11437   add_com ("tlist", class_obscure, threadlist_test_cmd,
   11438 	   _("Fetch and print the remote list of "
   11439 	     "thread identifiers, one pkt only"));
   11440   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
   11441 	   _("Fetch and display info about one thread"));
   11442   add_com ("tset", class_obscure, threadset_test_cmd,
   11443 	   _("Test setting to a different thread"));
   11444   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
   11445 	   _("Iterate through updating all remote thread info"));
   11446   add_com ("talive", class_obscure, threadalive_test,
   11447 	   _(" Remote thread alive test "));
   11448 }
   11449 
   11450 #endif /* 0 */
   11451 
   11452 /* Convert a thread ID to a string.  Returns the string in a static
   11453    buffer.  */
   11454 
   11455 const char *
   11456 remote_target::pid_to_str (ptid_t ptid)
   11457 {
   11458   static char buf[64];
   11459   struct remote_state *rs = get_remote_state ();
   11460 
   11461   if (ptid == null_ptid)
   11462     return normal_pid_to_str (ptid);
   11463   else if (ptid.is_pid ())
   11464     {
   11465       /* Printing an inferior target id.  */
   11466 
   11467       /* When multi-process extensions are off, there's no way in the
   11468 	 remote protocol to know the remote process id, if there's any
   11469 	 at all.  There's one exception --- when we're connected with
   11470 	 target extended-remote, and we manually attached to a process
   11471 	 with "attach PID".  We don't record anywhere a flag that
   11472 	 allows us to distinguish that case from the case of
   11473 	 connecting with extended-remote and the stub already being
   11474 	 attached to a process, and reporting yes to qAttached, hence
   11475 	 no smart special casing here.  */
   11476       if (!remote_multi_process_p (rs))
   11477 	{
   11478 	  xsnprintf (buf, sizeof buf, "Remote target");
   11479 	  return buf;
   11480 	}
   11481 
   11482       return normal_pid_to_str (ptid);
   11483     }
   11484   else
   11485     {
   11486       if (magic_null_ptid == ptid)
   11487 	xsnprintf (buf, sizeof buf, "Thread <main>");
   11488       else if (remote_multi_process_p (rs))
   11489 	if (ptid.lwp () == 0)
   11490 	  return normal_pid_to_str (ptid);
   11491 	else
   11492 	  xsnprintf (buf, sizeof buf, "Thread %d.%ld",
   11493 		     ptid.pid (), ptid.lwp ());
   11494       else
   11495 	xsnprintf (buf, sizeof buf, "Thread %ld",
   11496 		   ptid.lwp ());
   11497       return buf;
   11498     }
   11499 }
   11500 
   11501 /* Get the address of the thread local variable in OBJFILE which is
   11502    stored at OFFSET within the thread local storage for thread PTID.  */
   11503 
   11504 CORE_ADDR
   11505 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
   11506 					 CORE_ADDR offset)
   11507 {
   11508   if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
   11509     {
   11510       struct remote_state *rs = get_remote_state ();
   11511       char *p = rs->buf.data ();
   11512       char *endp = p + get_remote_packet_size ();
   11513       enum packet_result result;
   11514 
   11515       strcpy (p, "qGetTLSAddr:");
   11516       p += strlen (p);
   11517       p = write_ptid (p, endp, ptid);
   11518       *p++ = ',';
   11519       p += hexnumstr (p, offset);
   11520       *p++ = ',';
   11521       p += hexnumstr (p, lm);
   11522       *p++ = '\0';
   11523 
   11524       putpkt (rs->buf);
   11525       getpkt (&rs->buf, 0);
   11526       result = packet_ok (rs->buf,
   11527 			  &remote_protocol_packets[PACKET_qGetTLSAddr]);
   11528       if (result == PACKET_OK)
   11529 	{
   11530 	  ULONGEST addr;
   11531 
   11532 	  unpack_varlen_hex (rs->buf.data (), &addr);
   11533 	  return addr;
   11534 	}
   11535       else if (result == PACKET_UNKNOWN)
   11536 	throw_error (TLS_GENERIC_ERROR,
   11537 		     _("Remote target doesn't support qGetTLSAddr packet"));
   11538       else
   11539 	throw_error (TLS_GENERIC_ERROR,
   11540 		     _("Remote target failed to process qGetTLSAddr request"));
   11541     }
   11542   else
   11543     throw_error (TLS_GENERIC_ERROR,
   11544 		 _("TLS not supported or disabled on this target"));
   11545   /* Not reached.  */
   11546   return 0;
   11547 }
   11548 
   11549 /* Provide thread local base, i.e. Thread Information Block address.
   11550    Returns 1 if ptid is found and thread_local_base is non zero.  */
   11551 
   11552 bool
   11553 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
   11554 {
   11555   if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
   11556     {
   11557       struct remote_state *rs = get_remote_state ();
   11558       char *p = rs->buf.data ();
   11559       char *endp = p + get_remote_packet_size ();
   11560       enum packet_result result;
   11561 
   11562       strcpy (p, "qGetTIBAddr:");
   11563       p += strlen (p);
   11564       p = write_ptid (p, endp, ptid);
   11565       *p++ = '\0';
   11566 
   11567       putpkt (rs->buf);
   11568       getpkt (&rs->buf, 0);
   11569       result = packet_ok (rs->buf,
   11570 			  &remote_protocol_packets[PACKET_qGetTIBAddr]);
   11571       if (result == PACKET_OK)
   11572 	{
   11573 	  ULONGEST val;
   11574 	  unpack_varlen_hex (rs->buf.data (), &val);
   11575 	  if (addr)
   11576 	    *addr = (CORE_ADDR) val;
   11577 	  return true;
   11578 	}
   11579       else if (result == PACKET_UNKNOWN)
   11580 	error (_("Remote target doesn't support qGetTIBAddr packet"));
   11581       else
   11582 	error (_("Remote target failed to process qGetTIBAddr request"));
   11583     }
   11584   else
   11585     error (_("qGetTIBAddr not supported or disabled on this target"));
   11586   /* Not reached.  */
   11587   return false;
   11588 }
   11589 
   11590 /* Support for inferring a target description based on the current
   11591    architecture and the size of a 'g' packet.  While the 'g' packet
   11592    can have any size (since optional registers can be left off the
   11593    end), some sizes are easily recognizable given knowledge of the
   11594    approximate architecture.  */
   11595 
   11596 struct remote_g_packet_guess
   11597 {
   11598   remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
   11599     : bytes (bytes_),
   11600       tdesc (tdesc_)
   11601   {
   11602   }
   11603 
   11604   int bytes;
   11605   const struct target_desc *tdesc;
   11606 };
   11607 
   11608 struct remote_g_packet_data : public allocate_on_obstack
   11609 {
   11610   std::vector<remote_g_packet_guess> guesses;
   11611 };
   11612 
   11613 static struct gdbarch_data *remote_g_packet_data_handle;
   11614 
   11615 static void *
   11616 remote_g_packet_data_init (struct obstack *obstack)
   11617 {
   11618   return new (obstack) remote_g_packet_data;
   11619 }
   11620 
   11621 void
   11622 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
   11623 				const struct target_desc *tdesc)
   11624 {
   11625   struct remote_g_packet_data *data
   11626     = ((struct remote_g_packet_data *)
   11627        gdbarch_data (gdbarch, remote_g_packet_data_handle));
   11628 
   11629   gdb_assert (tdesc != NULL);
   11630 
   11631   for (const remote_g_packet_guess &guess : data->guesses)
   11632     if (guess.bytes == bytes)
   11633       internal_error (__FILE__, __LINE__,
   11634 		      _("Duplicate g packet description added for size %d"),
   11635 		      bytes);
   11636 
   11637   data->guesses.emplace_back (bytes, tdesc);
   11638 }
   11639 
   11640 /* Return true if remote_read_description would do anything on this target
   11641    and architecture, false otherwise.  */
   11642 
   11643 static bool
   11644 remote_read_description_p (struct target_ops *target)
   11645 {
   11646   struct remote_g_packet_data *data
   11647     = ((struct remote_g_packet_data *)
   11648        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
   11649 
   11650   return !data->guesses.empty ();
   11651 }
   11652 
   11653 const struct target_desc *
   11654 remote_target::read_description ()
   11655 {
   11656   struct remote_g_packet_data *data
   11657     = ((struct remote_g_packet_data *)
   11658        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
   11659 
   11660   /* Do not try this during initial connection, when we do not know
   11661      whether there is a running but stopped thread.  */
   11662   if (!target_has_execution || inferior_ptid == null_ptid)
   11663     return beneath ()->read_description ();
   11664 
   11665   if (!data->guesses.empty ())
   11666     {
   11667       int bytes = send_g_packet ();
   11668 
   11669       for (const remote_g_packet_guess &guess : data->guesses)
   11670 	if (guess.bytes == bytes)
   11671 	  return guess.tdesc;
   11672 
   11673       /* We discard the g packet.  A minor optimization would be to
   11674 	 hold on to it, and fill the register cache once we have selected
   11675 	 an architecture, but it's too tricky to do safely.  */
   11676     }
   11677 
   11678   return beneath ()->read_description ();
   11679 }
   11680 
   11681 /* Remote file transfer support.  This is host-initiated I/O, not
   11682    target-initiated; for target-initiated, see remote-fileio.c.  */
   11683 
   11684 /* If *LEFT is at least the length of STRING, copy STRING to
   11685    *BUFFER, update *BUFFER to point to the new end of the buffer, and
   11686    decrease *LEFT.  Otherwise raise an error.  */
   11687 
   11688 static void
   11689 remote_buffer_add_string (char **buffer, int *left, const char *string)
   11690 {
   11691   int len = strlen (string);
   11692 
   11693   if (len > *left)
   11694     error (_("Packet too long for target."));
   11695 
   11696   memcpy (*buffer, string, len);
   11697   *buffer += len;
   11698   *left -= len;
   11699 
   11700   /* NUL-terminate the buffer as a convenience, if there is
   11701      room.  */
   11702   if (*left)
   11703     **buffer = '\0';
   11704 }
   11705 
   11706 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
   11707    *BUFFER, update *BUFFER to point to the new end of the buffer, and
   11708    decrease *LEFT.  Otherwise raise an error.  */
   11709 
   11710 static void
   11711 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
   11712 			 int len)
   11713 {
   11714   if (2 * len > *left)
   11715     error (_("Packet too long for target."));
   11716 
   11717   bin2hex (bytes, *buffer, len);
   11718   *buffer += 2 * len;
   11719   *left -= 2 * len;
   11720 
   11721   /* NUL-terminate the buffer as a convenience, if there is
   11722      room.  */
   11723   if (*left)
   11724     **buffer = '\0';
   11725 }
   11726 
   11727 /* If *LEFT is large enough, convert VALUE to hex and add it to
   11728    *BUFFER, update *BUFFER to point to the new end of the buffer, and
   11729    decrease *LEFT.  Otherwise raise an error.  */
   11730 
   11731 static void
   11732 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
   11733 {
   11734   int len = hexnumlen (value);
   11735 
   11736   if (len > *left)
   11737     error (_("Packet too long for target."));
   11738 
   11739   hexnumstr (*buffer, value);
   11740   *buffer += len;
   11741   *left -= len;
   11742 
   11743   /* NUL-terminate the buffer as a convenience, if there is
   11744      room.  */
   11745   if (*left)
   11746     **buffer = '\0';
   11747 }
   11748 
   11749 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
   11750    value, *REMOTE_ERRNO to the remote error number or zero if none
   11751    was included, and *ATTACHMENT to point to the start of the annex
   11752    if any.  The length of the packet isn't needed here; there may
   11753    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
   11754 
   11755    Return 0 if the packet could be parsed, -1 if it could not.  If
   11756    -1 is returned, the other variables may not be initialized.  */
   11757 
   11758 static int
   11759 remote_hostio_parse_result (char *buffer, int *retcode,
   11760 			    int *remote_errno, char **attachment)
   11761 {
   11762   char *p, *p2;
   11763 
   11764   *remote_errno = 0;
   11765   *attachment = NULL;
   11766 
   11767   if (buffer[0] != 'F')
   11768     return -1;
   11769 
   11770   errno = 0;
   11771   *retcode = strtol (&buffer[1], &p, 16);
   11772   if (errno != 0 || p == &buffer[1])
   11773     return -1;
   11774 
   11775   /* Check for ",errno".  */
   11776   if (*p == ',')
   11777     {
   11778       errno = 0;
   11779       *remote_errno = strtol (p + 1, &p2, 16);
   11780       if (errno != 0 || p + 1 == p2)
   11781 	return -1;
   11782       p = p2;
   11783     }
   11784 
   11785   /* Check for ";attachment".  If there is no attachment, the
   11786      packet should end here.  */
   11787   if (*p == ';')
   11788     {
   11789       *attachment = p + 1;
   11790       return 0;
   11791     }
   11792   else if (*p == '\0')
   11793     return 0;
   11794   else
   11795     return -1;
   11796 }
   11797 
   11798 /* Send a prepared I/O packet to the target and read its response.
   11799    The prepared packet is in the global RS->BUF before this function
   11800    is called, and the answer is there when we return.
   11801 
   11802    COMMAND_BYTES is the length of the request to send, which may include
   11803    binary data.  WHICH_PACKET is the packet configuration to check
   11804    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
   11805    is set to the error number and -1 is returned.  Otherwise the value
   11806    returned by the function is returned.
   11807 
   11808    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
   11809    attachment is expected; an error will be reported if there's a
   11810    mismatch.  If one is found, *ATTACHMENT will be set to point into
   11811    the packet buffer and *ATTACHMENT_LEN will be set to the
   11812    attachment's length.  */
   11813 
   11814 int
   11815 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
   11816 					   int *remote_errno, char **attachment,
   11817 					   int *attachment_len)
   11818 {
   11819   struct remote_state *rs = get_remote_state ();
   11820   int ret, bytes_read;
   11821   char *attachment_tmp;
   11822 
   11823   if (packet_support (which_packet) == PACKET_DISABLE)
   11824     {
   11825       *remote_errno = FILEIO_ENOSYS;
   11826       return -1;
   11827     }
   11828 
   11829   putpkt_binary (rs->buf.data (), command_bytes);
   11830   bytes_read = getpkt_sane (&rs->buf, 0);
   11831 
   11832   /* If it timed out, something is wrong.  Don't try to parse the
   11833      buffer.  */
   11834   if (bytes_read < 0)
   11835     {
   11836       *remote_errno = FILEIO_EINVAL;
   11837       return -1;
   11838     }
   11839 
   11840   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
   11841     {
   11842     case PACKET_ERROR:
   11843       *remote_errno = FILEIO_EINVAL;
   11844       return -1;
   11845     case PACKET_UNKNOWN:
   11846       *remote_errno = FILEIO_ENOSYS;
   11847       return -1;
   11848     case PACKET_OK:
   11849       break;
   11850     }
   11851 
   11852   if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
   11853 				  &attachment_tmp))
   11854     {
   11855       *remote_errno = FILEIO_EINVAL;
   11856       return -1;
   11857     }
   11858 
   11859   /* Make sure we saw an attachment if and only if we expected one.  */
   11860   if ((attachment_tmp == NULL && attachment != NULL)
   11861       || (attachment_tmp != NULL && attachment == NULL))
   11862     {
   11863       *remote_errno = FILEIO_EINVAL;
   11864       return -1;
   11865     }
   11866 
   11867   /* If an attachment was found, it must point into the packet buffer;
   11868      work out how many bytes there were.  */
   11869   if (attachment_tmp != NULL)
   11870     {
   11871       *attachment = attachment_tmp;
   11872       *attachment_len = bytes_read - (*attachment - rs->buf.data ());
   11873     }
   11874 
   11875   return ret;
   11876 }
   11877 
   11878 /* See declaration.h.  */
   11879 
   11880 void
   11881 readahead_cache::invalidate ()
   11882 {
   11883   this->fd = -1;
   11884 }
   11885 
   11886 /* See declaration.h.  */
   11887 
   11888 void
   11889 readahead_cache::invalidate_fd (int fd)
   11890 {
   11891   if (this->fd == fd)
   11892     this->fd = -1;
   11893 }
   11894 
   11895 /* Set the filesystem remote_hostio functions that take FILENAME
   11896    arguments will use.  Return 0 on success, or -1 if an error
   11897    occurs (and set *REMOTE_ERRNO).  */
   11898 
   11899 int
   11900 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
   11901 					     int *remote_errno)
   11902 {
   11903   struct remote_state *rs = get_remote_state ();
   11904   int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
   11905   char *p = rs->buf.data ();
   11906   int left = get_remote_packet_size () - 1;
   11907   char arg[9];
   11908   int ret;
   11909 
   11910   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
   11911     return 0;
   11912 
   11913   if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
   11914     return 0;
   11915 
   11916   remote_buffer_add_string (&p, &left, "vFile:setfs:");
   11917 
   11918   xsnprintf (arg, sizeof (arg), "%x", required_pid);
   11919   remote_buffer_add_string (&p, &left, arg);
   11920 
   11921   ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
   11922 				    remote_errno, NULL, NULL);
   11923 
   11924   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
   11925     return 0;
   11926 
   11927   if (ret == 0)
   11928     rs->fs_pid = required_pid;
   11929 
   11930   return ret;
   11931 }
   11932 
   11933 /* Implementation of to_fileio_open.  */
   11934 
   11935 int
   11936 remote_target::remote_hostio_open (inferior *inf, const char *filename,
   11937 				   int flags, int mode, int warn_if_slow,
   11938 				   int *remote_errno)
   11939 {
   11940   struct remote_state *rs = get_remote_state ();
   11941   char *p = rs->buf.data ();
   11942   int left = get_remote_packet_size () - 1;
   11943 
   11944   if (warn_if_slow)
   11945     {
   11946       static int warning_issued = 0;
   11947 
   11948       printf_unfiltered (_("Reading %s from remote target...\n"),
   11949 			 filename);
   11950 
   11951       if (!warning_issued)
   11952 	{
   11953 	  warning (_("File transfers from remote targets can be slow."
   11954 		     " Use \"set sysroot\" to access files locally"
   11955 		     " instead."));
   11956 	  warning_issued = 1;
   11957 	}
   11958     }
   11959 
   11960   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
   11961     return -1;
   11962 
   11963   remote_buffer_add_string (&p, &left, "vFile:open:");
   11964 
   11965   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
   11966 			   strlen (filename));
   11967   remote_buffer_add_string (&p, &left, ",");
   11968 
   11969   remote_buffer_add_int (&p, &left, flags);
   11970   remote_buffer_add_string (&p, &left, ",");
   11971 
   11972   remote_buffer_add_int (&p, &left, mode);
   11973 
   11974   return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
   11975 				     remote_errno, NULL, NULL);
   11976 }
   11977 
   11978 int
   11979 remote_target::fileio_open (struct inferior *inf, const char *filename,
   11980 			    int flags, int mode, int warn_if_slow,
   11981 			    int *remote_errno)
   11982 {
   11983   return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
   11984 			     remote_errno);
   11985 }
   11986 
   11987 /* Implementation of to_fileio_pwrite.  */
   11988 
   11989 int
   11990 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
   11991 				     ULONGEST offset, int *remote_errno)
   11992 {
   11993   struct remote_state *rs = get_remote_state ();
   11994   char *p = rs->buf.data ();
   11995   int left = get_remote_packet_size ();
   11996   int out_len;
   11997 
   11998   rs->readahead_cache.invalidate_fd (fd);
   11999 
   12000   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
   12001 
   12002   remote_buffer_add_int (&p, &left, fd);
   12003   remote_buffer_add_string (&p, &left, ",");
   12004 
   12005   remote_buffer_add_int (&p, &left, offset);
   12006   remote_buffer_add_string (&p, &left, ",");
   12007 
   12008   p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
   12009 			     (get_remote_packet_size ()
   12010 			      - (p - rs->buf.data ())));
   12011 
   12012   return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
   12013 				     remote_errno, NULL, NULL);
   12014 }
   12015 
   12016 int
   12017 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
   12018 			      ULONGEST offset, int *remote_errno)
   12019 {
   12020   return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
   12021 }
   12022 
   12023 /* Helper for the implementation of to_fileio_pread.  Read the file
   12024    from the remote side with vFile:pread.  */
   12025 
   12026 int
   12027 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
   12028 					  ULONGEST offset, int *remote_errno)
   12029 {
   12030   struct remote_state *rs = get_remote_state ();
   12031   char *p = rs->buf.data ();
   12032   char *attachment;
   12033   int left = get_remote_packet_size ();
   12034   int ret, attachment_len;
   12035   int read_len;
   12036 
   12037   remote_buffer_add_string (&p, &left, "vFile:pread:");
   12038 
   12039   remote_buffer_add_int (&p, &left, fd);
   12040   remote_buffer_add_string (&p, &left, ",");
   12041 
   12042   remote_buffer_add_int (&p, &left, len);
   12043   remote_buffer_add_string (&p, &left, ",");
   12044 
   12045   remote_buffer_add_int (&p, &left, offset);
   12046 
   12047   ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
   12048 				    remote_errno, &attachment,
   12049 				    &attachment_len);
   12050 
   12051   if (ret < 0)
   12052     return ret;
   12053 
   12054   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
   12055 				    read_buf, len);
   12056   if (read_len != ret)
   12057     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
   12058 
   12059   return ret;
   12060 }
   12061 
   12062 /* See declaration.h.  */
   12063 
   12064 int
   12065 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
   12066 			ULONGEST offset)
   12067 {
   12068   if (this->fd == fd
   12069       && this->offset <= offset
   12070       && offset < this->offset + this->bufsize)
   12071     {
   12072       ULONGEST max = this->offset + this->bufsize;
   12073 
   12074       if (offset + len > max)
   12075 	len = max - offset;
   12076 
   12077       memcpy (read_buf, this->buf + offset - this->offset, len);
   12078       return len;
   12079     }
   12080 
   12081   return 0;
   12082 }
   12083 
   12084 /* Implementation of to_fileio_pread.  */
   12085 
   12086 int
   12087 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
   12088 				    ULONGEST offset, int *remote_errno)
   12089 {
   12090   int ret;
   12091   struct remote_state *rs = get_remote_state ();
   12092   readahead_cache *cache = &rs->readahead_cache;
   12093 
   12094   ret = cache->pread (fd, read_buf, len, offset);
   12095   if (ret > 0)
   12096     {
   12097       cache->hit_count++;
   12098 
   12099       if (remote_debug)
   12100 	fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
   12101 			    pulongest (cache->hit_count));
   12102       return ret;
   12103     }
   12104 
   12105   cache->miss_count++;
   12106   if (remote_debug)
   12107     fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
   12108 			pulongest (cache->miss_count));
   12109 
   12110   cache->fd = fd;
   12111   cache->offset = offset;
   12112   cache->bufsize = get_remote_packet_size ();
   12113   cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
   12114 
   12115   ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
   12116 				   cache->offset, remote_errno);
   12117   if (ret <= 0)
   12118     {
   12119       cache->invalidate_fd (fd);
   12120       return ret;
   12121     }
   12122 
   12123   cache->bufsize = ret;
   12124   return cache->pread (fd, read_buf, len, offset);
   12125 }
   12126 
   12127 int
   12128 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
   12129 			     ULONGEST offset, int *remote_errno)
   12130 {
   12131   return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
   12132 }
   12133 
   12134 /* Implementation of to_fileio_close.  */
   12135 
   12136 int
   12137 remote_target::remote_hostio_close (int fd, int *remote_errno)
   12138 {
   12139   struct remote_state *rs = get_remote_state ();
   12140   char *p = rs->buf.data ();
   12141   int left = get_remote_packet_size () - 1;
   12142 
   12143   rs->readahead_cache.invalidate_fd (fd);
   12144 
   12145   remote_buffer_add_string (&p, &left, "vFile:close:");
   12146 
   12147   remote_buffer_add_int (&p, &left, fd);
   12148 
   12149   return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
   12150 				     remote_errno, NULL, NULL);
   12151 }
   12152 
   12153 int
   12154 remote_target::fileio_close (int fd, int *remote_errno)
   12155 {
   12156   return remote_hostio_close (fd, remote_errno);
   12157 }
   12158 
   12159 /* Implementation of to_fileio_unlink.  */
   12160 
   12161 int
   12162 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
   12163 				     int *remote_errno)
   12164 {
   12165   struct remote_state *rs = get_remote_state ();
   12166   char *p = rs->buf.data ();
   12167   int left = get_remote_packet_size () - 1;
   12168 
   12169   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
   12170     return -1;
   12171 
   12172   remote_buffer_add_string (&p, &left, "vFile:unlink:");
   12173 
   12174   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
   12175 			   strlen (filename));
   12176 
   12177   return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
   12178 				     remote_errno, NULL, NULL);
   12179 }
   12180 
   12181 int
   12182 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
   12183 			      int *remote_errno)
   12184 {
   12185   return remote_hostio_unlink (inf, filename, remote_errno);
   12186 }
   12187 
   12188 /* Implementation of to_fileio_readlink.  */
   12189 
   12190 gdb::optional<std::string>
   12191 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
   12192 				int *remote_errno)
   12193 {
   12194   struct remote_state *rs = get_remote_state ();
   12195   char *p = rs->buf.data ();
   12196   char *attachment;
   12197   int left = get_remote_packet_size ();
   12198   int len, attachment_len;
   12199   int read_len;
   12200 
   12201   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
   12202     return {};
   12203 
   12204   remote_buffer_add_string (&p, &left, "vFile:readlink:");
   12205 
   12206   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
   12207 			   strlen (filename));
   12208 
   12209   len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
   12210 				    remote_errno, &attachment,
   12211 				    &attachment_len);
   12212 
   12213   if (len < 0)
   12214     return {};
   12215 
   12216   std::string ret (len, '\0');
   12217 
   12218   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
   12219 				    (gdb_byte *) &ret[0], len);
   12220   if (read_len != len)
   12221     error (_("Readlink returned %d, but %d bytes."), len, read_len);
   12222 
   12223   return ret;
   12224 }
   12225 
   12226 /* Implementation of to_fileio_fstat.  */
   12227 
   12228 int
   12229 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
   12230 {
   12231   struct remote_state *rs = get_remote_state ();
   12232   char *p = rs->buf.data ();
   12233   int left = get_remote_packet_size ();
   12234   int attachment_len, ret;
   12235   char *attachment;
   12236   struct fio_stat fst;
   12237   int read_len;
   12238 
   12239   remote_buffer_add_string (&p, &left, "vFile:fstat:");
   12240 
   12241   remote_buffer_add_int (&p, &left, fd);
   12242 
   12243   ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
   12244 				    remote_errno, &attachment,
   12245 				    &attachment_len);
   12246   if (ret < 0)
   12247     {
   12248       if (*remote_errno != FILEIO_ENOSYS)
   12249 	return ret;
   12250 
   12251       /* Strictly we should return -1, ENOSYS here, but when
   12252 	 "set sysroot remote:" was implemented in August 2008
   12253 	 BFD's need for a stat function was sidestepped with
   12254 	 this hack.  This was not remedied until March 2015
   12255 	 so we retain the previous behavior to avoid breaking
   12256 	 compatibility.
   12257 
   12258 	 Note that the memset is a March 2015 addition; older
   12259 	 GDBs set st_size *and nothing else* so the structure
   12260 	 would have garbage in all other fields.  This might
   12261 	 break something but retaining the previous behavior
   12262 	 here would be just too wrong.  */
   12263 
   12264       memset (st, 0, sizeof (struct stat));
   12265       st->st_size = INT_MAX;
   12266       return 0;
   12267     }
   12268 
   12269   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
   12270 				    (gdb_byte *) &fst, sizeof (fst));
   12271 
   12272   if (read_len != ret)
   12273     error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
   12274 
   12275   if (read_len != sizeof (fst))
   12276     error (_("vFile:fstat returned %d bytes, but expecting %d."),
   12277 	   read_len, (int) sizeof (fst));
   12278 
   12279   remote_fileio_to_host_stat (&fst, st);
   12280 
   12281   return 0;
   12282 }
   12283 
   12284 /* Implementation of to_filesystem_is_local.  */
   12285 
   12286 bool
   12287 remote_target::filesystem_is_local ()
   12288 {
   12289   /* Valgrind GDB presents itself as a remote target but works
   12290      on the local filesystem: it does not implement remote get
   12291      and users are not expected to set a sysroot.  To handle
   12292      this case we treat the remote filesystem as local if the
   12293      sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
   12294      does not support vFile:open.  */
   12295   if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
   12296     {
   12297       enum packet_support ps = packet_support (PACKET_vFile_open);
   12298 
   12299       if (ps == PACKET_SUPPORT_UNKNOWN)
   12300 	{
   12301 	  int fd, remote_errno;
   12302 
   12303 	  /* Try opening a file to probe support.  The supplied
   12304 	     filename is irrelevant, we only care about whether
   12305 	     the stub recognizes the packet or not.  */
   12306 	  fd = remote_hostio_open (NULL, "just probing",
   12307 				   FILEIO_O_RDONLY, 0700, 0,
   12308 				   &remote_errno);
   12309 
   12310 	  if (fd >= 0)
   12311 	    remote_hostio_close (fd, &remote_errno);
   12312 
   12313 	  ps = packet_support (PACKET_vFile_open);
   12314 	}
   12315 
   12316       if (ps == PACKET_DISABLE)
   12317 	{
   12318 	  static int warning_issued = 0;
   12319 
   12320 	  if (!warning_issued)
   12321 	    {
   12322 	      warning (_("remote target does not support file"
   12323 			 " transfer, attempting to access files"
   12324 			 " from local filesystem."));
   12325 	      warning_issued = 1;
   12326 	    }
   12327 
   12328 	  return true;
   12329 	}
   12330     }
   12331 
   12332   return false;
   12333 }
   12334 
   12335 static int
   12336 remote_fileio_errno_to_host (int errnum)
   12337 {
   12338   switch (errnum)
   12339     {
   12340       case FILEIO_EPERM:
   12341         return EPERM;
   12342       case FILEIO_ENOENT:
   12343         return ENOENT;
   12344       case FILEIO_EINTR:
   12345         return EINTR;
   12346       case FILEIO_EIO:
   12347         return EIO;
   12348       case FILEIO_EBADF:
   12349         return EBADF;
   12350       case FILEIO_EACCES:
   12351         return EACCES;
   12352       case FILEIO_EFAULT:
   12353         return EFAULT;
   12354       case FILEIO_EBUSY:
   12355         return EBUSY;
   12356       case FILEIO_EEXIST:
   12357         return EEXIST;
   12358       case FILEIO_ENODEV:
   12359         return ENODEV;
   12360       case FILEIO_ENOTDIR:
   12361         return ENOTDIR;
   12362       case FILEIO_EISDIR:
   12363         return EISDIR;
   12364       case FILEIO_EINVAL:
   12365         return EINVAL;
   12366       case FILEIO_ENFILE:
   12367         return ENFILE;
   12368       case FILEIO_EMFILE:
   12369         return EMFILE;
   12370       case FILEIO_EFBIG:
   12371         return EFBIG;
   12372       case FILEIO_ENOSPC:
   12373         return ENOSPC;
   12374       case FILEIO_ESPIPE:
   12375         return ESPIPE;
   12376       case FILEIO_EROFS:
   12377         return EROFS;
   12378       case FILEIO_ENOSYS:
   12379         return ENOSYS;
   12380       case FILEIO_ENAMETOOLONG:
   12381         return ENAMETOOLONG;
   12382     }
   12383   return -1;
   12384 }
   12385 
   12386 static char *
   12387 remote_hostio_error (int errnum)
   12388 {
   12389   int host_error = remote_fileio_errno_to_host (errnum);
   12390 
   12391   if (host_error == -1)
   12392     error (_("Unknown remote I/O error %d"), errnum);
   12393   else
   12394     error (_("Remote I/O error: %s"), safe_strerror (host_error));
   12395 }
   12396 
   12397 /* A RAII wrapper around a remote file descriptor.  */
   12398 
   12399 class scoped_remote_fd
   12400 {
   12401 public:
   12402   scoped_remote_fd (remote_target *remote, int fd)
   12403     : m_remote (remote), m_fd (fd)
   12404   {
   12405   }
   12406 
   12407   ~scoped_remote_fd ()
   12408   {
   12409     if (m_fd != -1)
   12410       {
   12411 	try
   12412 	  {
   12413 	    int remote_errno;
   12414 	    m_remote->remote_hostio_close (m_fd, &remote_errno);
   12415 	  }
   12416 	catch (...)
   12417 	  {
   12418 	    /* Swallow exception before it escapes the dtor.  If
   12419 	       something goes wrong, likely the connection is gone,
   12420 	       and there's nothing else that can be done.  */
   12421 	  }
   12422       }
   12423   }
   12424 
   12425   DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
   12426 
   12427   /* Release ownership of the file descriptor, and return it.  */
   12428   int release () noexcept
   12429   {
   12430     int fd = m_fd;
   12431     m_fd = -1;
   12432     return fd;
   12433   }
   12434 
   12435   /* Return the owned file descriptor.  */
   12436   int get () const noexcept
   12437   {
   12438     return m_fd;
   12439   }
   12440 
   12441 private:
   12442   /* The remote target.  */
   12443   remote_target *m_remote;
   12444 
   12445   /* The owned remote I/O file descriptor.  */
   12446   int m_fd;
   12447 };
   12448 
   12449 void
   12450 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
   12451 {
   12452   remote_target *remote = get_current_remote_target ();
   12453 
   12454   if (remote == nullptr)
   12455     error (_("command can only be used with remote target"));
   12456 
   12457   remote->remote_file_put (local_file, remote_file, from_tty);
   12458 }
   12459 
   12460 void
   12461 remote_target::remote_file_put (const char *local_file, const char *remote_file,
   12462 				int from_tty)
   12463 {
   12464   int retcode, remote_errno, bytes, io_size;
   12465   int bytes_in_buffer;
   12466   int saw_eof;
   12467   ULONGEST offset;
   12468 
   12469   gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
   12470   if (file == NULL)
   12471     perror_with_name (local_file);
   12472 
   12473   scoped_remote_fd fd
   12474     (this, remote_hostio_open (NULL,
   12475 			       remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
   12476 					     | FILEIO_O_TRUNC),
   12477 			       0700, 0, &remote_errno));
   12478   if (fd.get () == -1)
   12479     remote_hostio_error (remote_errno);
   12480 
   12481   /* Send up to this many bytes at once.  They won't all fit in the
   12482      remote packet limit, so we'll transfer slightly fewer.  */
   12483   io_size = get_remote_packet_size ();
   12484   gdb::byte_vector buffer (io_size);
   12485 
   12486   bytes_in_buffer = 0;
   12487   saw_eof = 0;
   12488   offset = 0;
   12489   while (bytes_in_buffer || !saw_eof)
   12490     {
   12491       if (!saw_eof)
   12492 	{
   12493 	  bytes = fread (buffer.data () + bytes_in_buffer, 1,
   12494 			 io_size - bytes_in_buffer,
   12495 			 file.get ());
   12496 	  if (bytes == 0)
   12497 	    {
   12498 	      if (ferror (file.get ()))
   12499 		error (_("Error reading %s."), local_file);
   12500 	      else
   12501 		{
   12502 		  /* EOF.  Unless there is something still in the
   12503 		     buffer from the last iteration, we are done.  */
   12504 		  saw_eof = 1;
   12505 		  if (bytes_in_buffer == 0)
   12506 		    break;
   12507 		}
   12508 	    }
   12509 	}
   12510       else
   12511 	bytes = 0;
   12512 
   12513       bytes += bytes_in_buffer;
   12514       bytes_in_buffer = 0;
   12515 
   12516       retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
   12517 				      offset, &remote_errno);
   12518 
   12519       if (retcode < 0)
   12520 	remote_hostio_error (remote_errno);
   12521       else if (retcode == 0)
   12522 	error (_("Remote write of %d bytes returned 0!"), bytes);
   12523       else if (retcode < bytes)
   12524 	{
   12525 	  /* Short write.  Save the rest of the read data for the next
   12526 	     write.  */
   12527 	  bytes_in_buffer = bytes - retcode;
   12528 	  memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
   12529 	}
   12530 
   12531       offset += retcode;
   12532     }
   12533 
   12534   if (remote_hostio_close (fd.release (), &remote_errno))
   12535     remote_hostio_error (remote_errno);
   12536 
   12537   if (from_tty)
   12538     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
   12539 }
   12540 
   12541 void
   12542 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
   12543 {
   12544   remote_target *remote = get_current_remote_target ();
   12545 
   12546   if (remote == nullptr)
   12547     error (_("command can only be used with remote target"));
   12548 
   12549   remote->remote_file_get (remote_file, local_file, from_tty);
   12550 }
   12551 
   12552 void
   12553 remote_target::remote_file_get (const char *remote_file, const char *local_file,
   12554 				int from_tty)
   12555 {
   12556   int remote_errno, bytes, io_size;
   12557   ULONGEST offset;
   12558 
   12559   scoped_remote_fd fd
   12560     (this, remote_hostio_open (NULL,
   12561 			       remote_file, FILEIO_O_RDONLY, 0, 0,
   12562 			       &remote_errno));
   12563   if (fd.get () == -1)
   12564     remote_hostio_error (remote_errno);
   12565 
   12566   gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
   12567   if (file == NULL)
   12568     perror_with_name (local_file);
   12569 
   12570   /* Send up to this many bytes at once.  They won't all fit in the
   12571      remote packet limit, so we'll transfer slightly fewer.  */
   12572   io_size = get_remote_packet_size ();
   12573   gdb::byte_vector buffer (io_size);
   12574 
   12575   offset = 0;
   12576   while (1)
   12577     {
   12578       bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
   12579 				   &remote_errno);
   12580       if (bytes == 0)
   12581 	/* Success, but no bytes, means end-of-file.  */
   12582 	break;
   12583       if (bytes == -1)
   12584 	remote_hostio_error (remote_errno);
   12585 
   12586       offset += bytes;
   12587 
   12588       bytes = fwrite (buffer.data (), 1, bytes, file.get ());
   12589       if (bytes == 0)
   12590 	perror_with_name (local_file);
   12591     }
   12592 
   12593   if (remote_hostio_close (fd.release (), &remote_errno))
   12594     remote_hostio_error (remote_errno);
   12595 
   12596   if (from_tty)
   12597     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
   12598 }
   12599 
   12600 void
   12601 remote_file_delete (const char *remote_file, int from_tty)
   12602 {
   12603   remote_target *remote = get_current_remote_target ();
   12604 
   12605   if (remote == nullptr)
   12606     error (_("command can only be used with remote target"));
   12607 
   12608   remote->remote_file_delete (remote_file, from_tty);
   12609 }
   12610 
   12611 void
   12612 remote_target::remote_file_delete (const char *remote_file, int from_tty)
   12613 {
   12614   int retcode, remote_errno;
   12615 
   12616   retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
   12617   if (retcode == -1)
   12618     remote_hostio_error (remote_errno);
   12619 
   12620   if (from_tty)
   12621     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
   12622 }
   12623 
   12624 static void
   12625 remote_put_command (const char *args, int from_tty)
   12626 {
   12627   if (args == NULL)
   12628     error_no_arg (_("file to put"));
   12629 
   12630   gdb_argv argv (args);
   12631   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
   12632     error (_("Invalid parameters to remote put"));
   12633 
   12634   remote_file_put (argv[0], argv[1], from_tty);
   12635 }
   12636 
   12637 static void
   12638 remote_get_command (const char *args, int from_tty)
   12639 {
   12640   if (args == NULL)
   12641     error_no_arg (_("file to get"));
   12642 
   12643   gdb_argv argv (args);
   12644   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
   12645     error (_("Invalid parameters to remote get"));
   12646 
   12647   remote_file_get (argv[0], argv[1], from_tty);
   12648 }
   12649 
   12650 static void
   12651 remote_delete_command (const char *args, int from_tty)
   12652 {
   12653   if (args == NULL)
   12654     error_no_arg (_("file to delete"));
   12655 
   12656   gdb_argv argv (args);
   12657   if (argv[0] == NULL || argv[1] != NULL)
   12658     error (_("Invalid parameters to remote delete"));
   12659 
   12660   remote_file_delete (argv[0], from_tty);
   12661 }
   12662 
   12663 static void
   12664 remote_command (const char *args, int from_tty)
   12665 {
   12666   help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
   12667 }
   12668 
   12669 bool
   12670 remote_target::can_execute_reverse ()
   12671 {
   12672   if (packet_support (PACKET_bs) == PACKET_ENABLE
   12673       || packet_support (PACKET_bc) == PACKET_ENABLE)
   12674     return true;
   12675   else
   12676     return false;
   12677 }
   12678 
   12679 bool
   12680 remote_target::supports_non_stop ()
   12681 {
   12682   return true;
   12683 }
   12684 
   12685 bool
   12686 remote_target::supports_disable_randomization ()
   12687 {
   12688   /* Only supported in extended mode.  */
   12689   return false;
   12690 }
   12691 
   12692 bool
   12693 remote_target::supports_multi_process ()
   12694 {
   12695   struct remote_state *rs = get_remote_state ();
   12696 
   12697   return remote_multi_process_p (rs);
   12698 }
   12699 
   12700 static int
   12701 remote_supports_cond_tracepoints ()
   12702 {
   12703   return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
   12704 }
   12705 
   12706 bool
   12707 remote_target::supports_evaluation_of_breakpoint_conditions ()
   12708 {
   12709   return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
   12710 }
   12711 
   12712 static int
   12713 remote_supports_fast_tracepoints ()
   12714 {
   12715   return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
   12716 }
   12717 
   12718 static int
   12719 remote_supports_static_tracepoints ()
   12720 {
   12721   return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
   12722 }
   12723 
   12724 static int
   12725 remote_supports_install_in_trace ()
   12726 {
   12727   return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
   12728 }
   12729 
   12730 bool
   12731 remote_target::supports_enable_disable_tracepoint ()
   12732 {
   12733   return (packet_support (PACKET_EnableDisableTracepoints_feature)
   12734 	  == PACKET_ENABLE);
   12735 }
   12736 
   12737 bool
   12738 remote_target::supports_string_tracing ()
   12739 {
   12740   return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
   12741 }
   12742 
   12743 bool
   12744 remote_target::can_run_breakpoint_commands ()
   12745 {
   12746   return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
   12747 }
   12748 
   12749 void
   12750 remote_target::trace_init ()
   12751 {
   12752   struct remote_state *rs = get_remote_state ();
   12753 
   12754   putpkt ("QTinit");
   12755   remote_get_noisy_reply ();
   12756   if (strcmp (rs->buf.data (), "OK") != 0)
   12757     error (_("Target does not support this command."));
   12758 }
   12759 
   12760 /* Recursive routine to walk through command list including loops, and
   12761    download packets for each command.  */
   12762 
   12763 void
   12764 remote_target::remote_download_command_source (int num, ULONGEST addr,
   12765 					       struct command_line *cmds)
   12766 {
   12767   struct remote_state *rs = get_remote_state ();
   12768   struct command_line *cmd;
   12769 
   12770   for (cmd = cmds; cmd; cmd = cmd->next)
   12771     {
   12772       QUIT;	/* Allow user to bail out with ^C.  */
   12773       strcpy (rs->buf.data (), "QTDPsrc:");
   12774       encode_source_string (num, addr, "cmd", cmd->line,
   12775 			    rs->buf.data () + strlen (rs->buf.data ()),
   12776 			    rs->buf.size () - strlen (rs->buf.data ()));
   12777       putpkt (rs->buf);
   12778       remote_get_noisy_reply ();
   12779       if (strcmp (rs->buf.data (), "OK"))
   12780 	warning (_("Target does not support source download."));
   12781 
   12782       if (cmd->control_type == while_control
   12783 	  || cmd->control_type == while_stepping_control)
   12784 	{
   12785 	  remote_download_command_source (num, addr, cmd->body_list_0.get ());
   12786 
   12787 	  QUIT;	/* Allow user to bail out with ^C.  */
   12788 	  strcpy (rs->buf.data (), "QTDPsrc:");
   12789 	  encode_source_string (num, addr, "cmd", "end",
   12790 				rs->buf.data () + strlen (rs->buf.data ()),
   12791 				rs->buf.size () - strlen (rs->buf.data ()));
   12792 	  putpkt (rs->buf);
   12793 	  remote_get_noisy_reply ();
   12794 	  if (strcmp (rs->buf.data (), "OK"))
   12795 	    warning (_("Target does not support source download."));
   12796 	}
   12797     }
   12798 }
   12799 
   12800 void
   12801 remote_target::download_tracepoint (struct bp_location *loc)
   12802 {
   12803   CORE_ADDR tpaddr;
   12804   char addrbuf[40];
   12805   std::vector<std::string> tdp_actions;
   12806   std::vector<std::string> stepping_actions;
   12807   char *pkt;
   12808   struct breakpoint *b = loc->owner;
   12809   struct tracepoint *t = (struct tracepoint *) b;
   12810   struct remote_state *rs = get_remote_state ();
   12811   int ret;
   12812   const char *err_msg = _("Tracepoint packet too large for target.");
   12813   size_t size_left;
   12814 
   12815   /* We use a buffer other than rs->buf because we'll build strings
   12816      across multiple statements, and other statements in between could
   12817      modify rs->buf.  */
   12818   gdb::char_vector buf (get_remote_packet_size ());
   12819 
   12820   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
   12821 
   12822   tpaddr = loc->address;
   12823   sprintf_vma (addrbuf, tpaddr);
   12824   ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
   12825 		  b->number, addrbuf, /* address */
   12826 		  (b->enable_state == bp_enabled ? 'E' : 'D'),
   12827 		  t->step_count, t->pass_count);
   12828 
   12829   if (ret < 0 || ret >= buf.size ())
   12830     error ("%s", err_msg);
   12831 
   12832   /* Fast tracepoints are mostly handled by the target, but we can
   12833      tell the target how big of an instruction block should be moved
   12834      around.  */
   12835   if (b->type == bp_fast_tracepoint)
   12836     {
   12837       /* Only test for support at download time; we may not know
   12838 	 target capabilities at definition time.  */
   12839       if (remote_supports_fast_tracepoints ())
   12840 	{
   12841 	  if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
   12842 						NULL))
   12843 	    {
   12844 	      size_left = buf.size () - strlen (buf.data ());
   12845 	      ret = snprintf (buf.data () + strlen (buf.data ()),
   12846 			      size_left, ":F%x",
   12847 			      gdb_insn_length (loc->gdbarch, tpaddr));
   12848 
   12849 	      if (ret < 0 || ret >= size_left)
   12850 		error ("%s", err_msg);
   12851 	    }
   12852 	  else
   12853 	    /* If it passed validation at definition but fails now,
   12854 	       something is very wrong.  */
   12855 	    internal_error (__FILE__, __LINE__,
   12856 			    _("Fast tracepoint not "
   12857 			      "valid during download"));
   12858 	}
   12859       else
   12860 	/* Fast tracepoints are functionally identical to regular
   12861 	   tracepoints, so don't take lack of support as a reason to
   12862 	   give up on the trace run.  */
   12863 	warning (_("Target does not support fast tracepoints, "
   12864 		   "downloading %d as regular tracepoint"), b->number);
   12865     }
   12866   else if (b->type == bp_static_tracepoint)
   12867     {
   12868       /* Only test for support at download time; we may not know
   12869 	 target capabilities at definition time.  */
   12870       if (remote_supports_static_tracepoints ())
   12871 	{
   12872 	  struct static_tracepoint_marker marker;
   12873 
   12874 	  if (target_static_tracepoint_marker_at (tpaddr, &marker))
   12875 	    {
   12876 	      size_left = buf.size () - strlen (buf.data ());
   12877 	      ret = snprintf (buf.data () + strlen (buf.data ()),
   12878 			      size_left, ":S");
   12879 
   12880 	      if (ret < 0 || ret >= size_left)
   12881 		error ("%s", err_msg);
   12882 	    }
   12883 	  else
   12884 	    error (_("Static tracepoint not valid during download"));
   12885 	}
   12886       else
   12887 	/* Fast tracepoints are functionally identical to regular
   12888 	   tracepoints, so don't take lack of support as a reason
   12889 	   to give up on the trace run.  */
   12890 	error (_("Target does not support static tracepoints"));
   12891     }
   12892   /* If the tracepoint has a conditional, make it into an agent
   12893      expression and append to the definition.  */
   12894   if (loc->cond)
   12895     {
   12896       /* Only test support at download time, we may not know target
   12897 	 capabilities at definition time.  */
   12898       if (remote_supports_cond_tracepoints ())
   12899 	{
   12900 	  agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
   12901 						   loc->cond.get ());
   12902 
   12903 	  size_left = buf.size () - strlen (buf.data ());
   12904 
   12905 	  ret = snprintf (buf.data () + strlen (buf.data ()),
   12906 			  size_left, ":X%x,", aexpr->len);
   12907 
   12908 	  if (ret < 0 || ret >= size_left)
   12909 	    error ("%s", err_msg);
   12910 
   12911 	  size_left = buf.size () - strlen (buf.data ());
   12912 
   12913 	  /* Two bytes to encode each aexpr byte, plus the terminating
   12914 	     null byte.  */
   12915 	  if (aexpr->len * 2 + 1 > size_left)
   12916 	    error ("%s", err_msg);
   12917 
   12918 	  pkt = buf.data () + strlen (buf.data ());
   12919 
   12920 	  for (int ndx = 0; ndx < aexpr->len; ++ndx)
   12921 	    pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
   12922 	  *pkt = '\0';
   12923 	}
   12924       else
   12925 	warning (_("Target does not support conditional tracepoints, "
   12926 		   "ignoring tp %d cond"), b->number);
   12927     }
   12928 
   12929   if (b->commands || *default_collect)
   12930     {
   12931       size_left = buf.size () - strlen (buf.data ());
   12932 
   12933       ret = snprintf (buf.data () + strlen (buf.data ()),
   12934 		      size_left, "-");
   12935 
   12936       if (ret < 0 || ret >= size_left)
   12937 	error ("%s", err_msg);
   12938     }
   12939 
   12940   putpkt (buf.data ());
   12941   remote_get_noisy_reply ();
   12942   if (strcmp (rs->buf.data (), "OK"))
   12943     error (_("Target does not support tracepoints."));
   12944 
   12945   /* do_single_steps (t); */
   12946   for (auto action_it = tdp_actions.begin ();
   12947        action_it != tdp_actions.end (); action_it++)
   12948     {
   12949       QUIT;	/* Allow user to bail out with ^C.  */
   12950 
   12951       bool has_more = ((action_it + 1) != tdp_actions.end ()
   12952 		       || !stepping_actions.empty ());
   12953 
   12954       ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
   12955 		      b->number, addrbuf, /* address */
   12956 		      action_it->c_str (),
   12957 		      has_more ? '-' : 0);
   12958 
   12959       if (ret < 0 || ret >= buf.size ())
   12960 	error ("%s", err_msg);
   12961 
   12962       putpkt (buf.data ());
   12963       remote_get_noisy_reply ();
   12964       if (strcmp (rs->buf.data (), "OK"))
   12965 	error (_("Error on target while setting tracepoints."));
   12966     }
   12967 
   12968   for (auto action_it = stepping_actions.begin ();
   12969        action_it != stepping_actions.end (); action_it++)
   12970     {
   12971       QUIT;	/* Allow user to bail out with ^C.  */
   12972 
   12973       bool is_first = action_it == stepping_actions.begin ();
   12974       bool has_more = (action_it + 1) != stepping_actions.end ();
   12975 
   12976       ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
   12977 		      b->number, addrbuf, /* address */
   12978 		      is_first ? "S" : "",
   12979 		      action_it->c_str (),
   12980 		      has_more ? "-" : "");
   12981 
   12982       if (ret < 0 || ret >= buf.size ())
   12983 	error ("%s", err_msg);
   12984 
   12985       putpkt (buf.data ());
   12986       remote_get_noisy_reply ();
   12987       if (strcmp (rs->buf.data (), "OK"))
   12988 	error (_("Error on target while setting tracepoints."));
   12989     }
   12990 
   12991   if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
   12992     {
   12993       if (b->location != NULL)
   12994 	{
   12995 	  ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
   12996 
   12997 	  if (ret < 0 || ret >= buf.size ())
   12998 	    error ("%s", err_msg);
   12999 
   13000 	  encode_source_string (b->number, loc->address, "at",
   13001 				event_location_to_string (b->location.get ()),
   13002 				buf.data () + strlen (buf.data ()),
   13003 				buf.size () - strlen (buf.data ()));
   13004 	  putpkt (buf.data ());
   13005 	  remote_get_noisy_reply ();
   13006 	  if (strcmp (rs->buf.data (), "OK"))
   13007 	    warning (_("Target does not support source download."));
   13008 	}
   13009       if (b->cond_string)
   13010 	{
   13011 	  ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
   13012 
   13013 	  if (ret < 0 || ret >= buf.size ())
   13014 	    error ("%s", err_msg);
   13015 
   13016 	  encode_source_string (b->number, loc->address,
   13017 				"cond", b->cond_string,
   13018 				buf.data () + strlen (buf.data ()),
   13019 				buf.size () - strlen (buf.data ()));
   13020 	  putpkt (buf.data ());
   13021 	  remote_get_noisy_reply ();
   13022 	  if (strcmp (rs->buf.data (), "OK"))
   13023 	    warning (_("Target does not support source download."));
   13024 	}
   13025       remote_download_command_source (b->number, loc->address,
   13026 				      breakpoint_commands (b));
   13027     }
   13028 }
   13029 
   13030 bool
   13031 remote_target::can_download_tracepoint ()
   13032 {
   13033   struct remote_state *rs = get_remote_state ();
   13034   struct trace_status *ts;
   13035   int status;
   13036 
   13037   /* Don't try to install tracepoints until we've relocated our
   13038      symbols, and fetched and merged the target's tracepoint list with
   13039      ours.  */
   13040   if (rs->starting_up)
   13041     return false;
   13042 
   13043   ts = current_trace_status ();
   13044   status = get_trace_status (ts);
   13045 
   13046   if (status == -1 || !ts->running_known || !ts->running)
   13047     return false;
   13048 
   13049   /* If we are in a tracing experiment, but remote stub doesn't support
   13050      installing tracepoint in trace, we have to return.  */
   13051   if (!remote_supports_install_in_trace ())
   13052     return false;
   13053 
   13054   return true;
   13055 }
   13056 
   13057 
   13058 void
   13059 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
   13060 {
   13061   struct remote_state *rs = get_remote_state ();
   13062   char *p;
   13063 
   13064   xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
   13065 	     tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
   13066 	     tsv.builtin);
   13067   p = rs->buf.data () + strlen (rs->buf.data ());
   13068   if ((p - rs->buf.data ()) + tsv.name.length () * 2
   13069       >= get_remote_packet_size ())
   13070     error (_("Trace state variable name too long for tsv definition packet"));
   13071   p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
   13072   *p++ = '\0';
   13073   putpkt (rs->buf);
   13074   remote_get_noisy_reply ();
   13075   if (rs->buf[0] == '\0')
   13076     error (_("Target does not support this command."));
   13077   if (strcmp (rs->buf.data (), "OK") != 0)
   13078     error (_("Error on target while downloading trace state variable."));
   13079 }
   13080 
   13081 void
   13082 remote_target::enable_tracepoint (struct bp_location *location)
   13083 {
   13084   struct remote_state *rs = get_remote_state ();
   13085   char addr_buf[40];
   13086 
   13087   sprintf_vma (addr_buf, location->address);
   13088   xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
   13089 	     location->owner->number, addr_buf);
   13090   putpkt (rs->buf);
   13091   remote_get_noisy_reply ();
   13092   if (rs->buf[0] == '\0')
   13093     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
   13094   if (strcmp (rs->buf.data (), "OK") != 0)
   13095     error (_("Error on target while enabling tracepoint."));
   13096 }
   13097 
   13098 void
   13099 remote_target::disable_tracepoint (struct bp_location *location)
   13100 {
   13101   struct remote_state *rs = get_remote_state ();
   13102   char addr_buf[40];
   13103 
   13104   sprintf_vma (addr_buf, location->address);
   13105   xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
   13106 	     location->owner->number, addr_buf);
   13107   putpkt (rs->buf);
   13108   remote_get_noisy_reply ();
   13109   if (rs->buf[0] == '\0')
   13110     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
   13111   if (strcmp (rs->buf.data (), "OK") != 0)
   13112     error (_("Error on target while disabling tracepoint."));
   13113 }
   13114 
   13115 void
   13116 remote_target::trace_set_readonly_regions ()
   13117 {
   13118   asection *s;
   13119   bfd *abfd = NULL;
   13120   bfd_size_type size;
   13121   bfd_vma vma;
   13122   int anysecs = 0;
   13123   int offset = 0;
   13124 
   13125   if (!exec_bfd)
   13126     return;			/* No information to give.  */
   13127 
   13128   struct remote_state *rs = get_remote_state ();
   13129 
   13130   strcpy (rs->buf.data (), "QTro");
   13131   offset = strlen (rs->buf.data ());
   13132   for (s = exec_bfd->sections; s; s = s->next)
   13133     {
   13134       char tmp1[40], tmp2[40];
   13135       int sec_length;
   13136 
   13137       if ((s->flags & SEC_LOAD) == 0 ||
   13138       /*  (s->flags & SEC_CODE) == 0 || */
   13139 	  (s->flags & SEC_READONLY) == 0)
   13140 	continue;
   13141 
   13142       anysecs = 1;
   13143       vma = bfd_get_section_vma (abfd, s);
   13144       size = bfd_get_section_size (s);
   13145       sprintf_vma (tmp1, vma);
   13146       sprintf_vma (tmp2, vma + size);
   13147       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
   13148       if (offset + sec_length + 1 > rs->buf.size ())
   13149 	{
   13150 	  if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
   13151 	    warning (_("\
   13152 Too many sections for read-only sections definition packet."));
   13153 	  break;
   13154 	}
   13155       xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
   13156 		 tmp1, tmp2);
   13157       offset += sec_length;
   13158     }
   13159   if (anysecs)
   13160     {
   13161       putpkt (rs->buf);
   13162       getpkt (&rs->buf, 0);
   13163     }
   13164 }
   13165 
   13166 void
   13167 remote_target::trace_start ()
   13168 {
   13169   struct remote_state *rs = get_remote_state ();
   13170 
   13171   putpkt ("QTStart");
   13172   remote_get_noisy_reply ();
   13173   if (rs->buf[0] == '\0')
   13174     error (_("Target does not support this command."));
   13175   if (strcmp (rs->buf.data (), "OK") != 0)
   13176     error (_("Bogus reply from target: %s"), rs->buf.data ());
   13177 }
   13178 
   13179 int
   13180 remote_target::get_trace_status (struct trace_status *ts)
   13181 {
   13182   /* Initialize it just to avoid a GCC false warning.  */
   13183   char *p = NULL;
   13184   /* FIXME we need to get register block size some other way.  */
   13185   extern int trace_regblock_size;
   13186   enum packet_result result;
   13187   struct remote_state *rs = get_remote_state ();
   13188 
   13189   if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
   13190     return -1;
   13191 
   13192   trace_regblock_size
   13193     = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
   13194 
   13195   putpkt ("qTStatus");
   13196 
   13197   TRY
   13198     {
   13199       p = remote_get_noisy_reply ();
   13200     }
   13201   CATCH (ex, RETURN_MASK_ERROR)
   13202     {
   13203       if (ex.error != TARGET_CLOSE_ERROR)
   13204 	{
   13205 	  exception_fprintf (gdb_stderr, ex, "qTStatus: ");
   13206 	  return -1;
   13207 	}
   13208       throw_exception (ex);
   13209     }
   13210   END_CATCH
   13211 
   13212   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
   13213 
   13214   /* If the remote target doesn't do tracing, flag it.  */
   13215   if (result == PACKET_UNKNOWN)
   13216     return -1;
   13217 
   13218   /* We're working with a live target.  */
   13219   ts->filename = NULL;
   13220 
   13221   if (*p++ != 'T')
   13222     error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
   13223 
   13224   /* Function 'parse_trace_status' sets default value of each field of
   13225      'ts' at first, so we don't have to do it here.  */
   13226   parse_trace_status (p, ts);
   13227 
   13228   return ts->running;
   13229 }
   13230 
   13231 void
   13232 remote_target::get_tracepoint_status (struct breakpoint *bp,
   13233 				      struct uploaded_tp *utp)
   13234 {
   13235   struct remote_state *rs = get_remote_state ();
   13236   char *reply;
   13237   struct bp_location *loc;
   13238   struct tracepoint *tp = (struct tracepoint *) bp;
   13239   size_t size = get_remote_packet_size ();
   13240 
   13241   if (tp)
   13242     {
   13243       tp->hit_count = 0;
   13244       tp->traceframe_usage = 0;
   13245       for (loc = tp->loc; loc; loc = loc->next)
   13246 	{
   13247 	  /* If the tracepoint was never downloaded, don't go asking for
   13248 	     any status.  */
   13249 	  if (tp->number_on_target == 0)
   13250 	    continue;
   13251 	  xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
   13252 		     phex_nz (loc->address, 0));
   13253 	  putpkt (rs->buf);
   13254 	  reply = remote_get_noisy_reply ();
   13255 	  if (reply && *reply)
   13256 	    {
   13257 	      if (*reply == 'V')
   13258 		parse_tracepoint_status (reply + 1, bp, utp);
   13259 	    }
   13260 	}
   13261     }
   13262   else if (utp)
   13263     {
   13264       utp->hit_count = 0;
   13265       utp->traceframe_usage = 0;
   13266       xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
   13267 		 phex_nz (utp->addr, 0));
   13268       putpkt (rs->buf);
   13269       reply = remote_get_noisy_reply ();
   13270       if (reply && *reply)
   13271 	{
   13272 	  if (*reply == 'V')
   13273 	    parse_tracepoint_status (reply + 1, bp, utp);
   13274 	}
   13275     }
   13276 }
   13277 
   13278 void
   13279 remote_target::trace_stop ()
   13280 {
   13281   struct remote_state *rs = get_remote_state ();
   13282 
   13283   putpkt ("QTStop");
   13284   remote_get_noisy_reply ();
   13285   if (rs->buf[0] == '\0')
   13286     error (_("Target does not support this command."));
   13287   if (strcmp (rs->buf.data (), "OK") != 0)
   13288     error (_("Bogus reply from target: %s"), rs->buf.data ());
   13289 }
   13290 
   13291 int
   13292 remote_target::trace_find (enum trace_find_type type, int num,
   13293 			   CORE_ADDR addr1, CORE_ADDR addr2,
   13294 			   int *tpp)
   13295 {
   13296   struct remote_state *rs = get_remote_state ();
   13297   char *endbuf = rs->buf.data () + get_remote_packet_size ();
   13298   char *p, *reply;
   13299   int target_frameno = -1, target_tracept = -1;
   13300 
   13301   /* Lookups other than by absolute frame number depend on the current
   13302      trace selected, so make sure it is correct on the remote end
   13303      first.  */
   13304   if (type != tfind_number)
   13305     set_remote_traceframe ();
   13306 
   13307   p = rs->buf.data ();
   13308   strcpy (p, "QTFrame:");
   13309   p = strchr (p, '\0');
   13310   switch (type)
   13311     {
   13312     case tfind_number:
   13313       xsnprintf (p, endbuf - p, "%x", num);
   13314       break;
   13315     case tfind_pc:
   13316       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
   13317       break;
   13318     case tfind_tp:
   13319       xsnprintf (p, endbuf - p, "tdp:%x", num);
   13320       break;
   13321     case tfind_range:
   13322       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
   13323 		 phex_nz (addr2, 0));
   13324       break;
   13325     case tfind_outside:
   13326       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
   13327 		 phex_nz (addr2, 0));
   13328       break;
   13329     default:
   13330       error (_("Unknown trace find type %d"), type);
   13331     }
   13332 
   13333   putpkt (rs->buf);
   13334   reply = remote_get_noisy_reply ();
   13335   if (*reply == '\0')
   13336     error (_("Target does not support this command."));
   13337 
   13338   while (reply && *reply)
   13339     switch (*reply)
   13340       {
   13341       case 'F':
   13342 	p = ++reply;
   13343 	target_frameno = (int) strtol (p, &reply, 16);
   13344 	if (reply == p)
   13345 	  error (_("Unable to parse trace frame number"));
   13346 	/* Don't update our remote traceframe number cache on failure
   13347 	   to select a remote traceframe.  */
   13348 	if (target_frameno == -1)
   13349 	  return -1;
   13350 	break;
   13351       case 'T':
   13352 	p = ++reply;
   13353 	target_tracept = (int) strtol (p, &reply, 16);
   13354 	if (reply == p)
   13355 	  error (_("Unable to parse tracepoint number"));
   13356 	break;
   13357       case 'O':		/* "OK"? */
   13358 	if (reply[1] == 'K' && reply[2] == '\0')
   13359 	  reply += 2;
   13360 	else
   13361 	  error (_("Bogus reply from target: %s"), reply);
   13362 	break;
   13363       default:
   13364 	error (_("Bogus reply from target: %s"), reply);
   13365       }
   13366   if (tpp)
   13367     *tpp = target_tracept;
   13368 
   13369   rs->remote_traceframe_number = target_frameno;
   13370   return target_frameno;
   13371 }
   13372 
   13373 bool
   13374 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
   13375 {
   13376   struct remote_state *rs = get_remote_state ();
   13377   char *reply;
   13378   ULONGEST uval;
   13379 
   13380   set_remote_traceframe ();
   13381 
   13382   xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
   13383   putpkt (rs->buf);
   13384   reply = remote_get_noisy_reply ();
   13385   if (reply && *reply)
   13386     {
   13387       if (*reply == 'V')
   13388 	{
   13389 	  unpack_varlen_hex (reply + 1, &uval);
   13390 	  *val = (LONGEST) uval;
   13391 	  return true;
   13392 	}
   13393     }
   13394   return false;
   13395 }
   13396 
   13397 int
   13398 remote_target::save_trace_data (const char *filename)
   13399 {
   13400   struct remote_state *rs = get_remote_state ();
   13401   char *p, *reply;
   13402 
   13403   p = rs->buf.data ();
   13404   strcpy (p, "QTSave:");
   13405   p += strlen (p);
   13406   if ((p - rs->buf.data ()) + strlen (filename) * 2
   13407       >= get_remote_packet_size ())
   13408     error (_("Remote file name too long for trace save packet"));
   13409   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
   13410   *p++ = '\0';
   13411   putpkt (rs->buf);
   13412   reply = remote_get_noisy_reply ();
   13413   if (*reply == '\0')
   13414     error (_("Target does not support this command."));
   13415   if (strcmp (reply, "OK") != 0)
   13416     error (_("Bogus reply from target: %s"), reply);
   13417   return 0;
   13418 }
   13419 
   13420 /* This is basically a memory transfer, but needs to be its own packet
   13421    because we don't know how the target actually organizes its trace
   13422    memory, plus we want to be able to ask for as much as possible, but
   13423    not be unhappy if we don't get as much as we ask for.  */
   13424 
   13425 LONGEST
   13426 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
   13427 {
   13428   struct remote_state *rs = get_remote_state ();
   13429   char *reply;
   13430   char *p;
   13431   int rslt;
   13432 
   13433   p = rs->buf.data ();
   13434   strcpy (p, "qTBuffer:");
   13435   p += strlen (p);
   13436   p += hexnumstr (p, offset);
   13437   *p++ = ',';
   13438   p += hexnumstr (p, len);
   13439   *p++ = '\0';
   13440 
   13441   putpkt (rs->buf);
   13442   reply = remote_get_noisy_reply ();
   13443   if (reply && *reply)
   13444     {
   13445       /* 'l' by itself means we're at the end of the buffer and
   13446 	 there is nothing more to get.  */
   13447       if (*reply == 'l')
   13448 	return 0;
   13449 
   13450       /* Convert the reply into binary.  Limit the number of bytes to
   13451 	 convert according to our passed-in buffer size, rather than
   13452 	 what was returned in the packet; if the target is
   13453 	 unexpectedly generous and gives us a bigger reply than we
   13454 	 asked for, we don't want to crash.  */
   13455       rslt = hex2bin (reply, buf, len);
   13456       return rslt;
   13457     }
   13458 
   13459   /* Something went wrong, flag as an error.  */
   13460   return -1;
   13461 }
   13462 
   13463 void
   13464 remote_target::set_disconnected_tracing (int val)
   13465 {
   13466   struct remote_state *rs = get_remote_state ();
   13467 
   13468   if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
   13469     {
   13470       char *reply;
   13471 
   13472       xsnprintf (rs->buf.data (), get_remote_packet_size (),
   13473 		 "QTDisconnected:%x", val);
   13474       putpkt (rs->buf);
   13475       reply = remote_get_noisy_reply ();
   13476       if (*reply == '\0')
   13477 	error (_("Target does not support this command."));
   13478       if (strcmp (reply, "OK") != 0)
   13479         error (_("Bogus reply from target: %s"), reply);
   13480     }
   13481   else if (val)
   13482     warning (_("Target does not support disconnected tracing."));
   13483 }
   13484 
   13485 int
   13486 remote_target::core_of_thread (ptid_t ptid)
   13487 {
   13488   struct thread_info *info = find_thread_ptid (ptid);
   13489 
   13490   if (info != NULL && info->priv != NULL)
   13491     return get_remote_thread_info (info)->core;
   13492 
   13493   return -1;
   13494 }
   13495 
   13496 void
   13497 remote_target::set_circular_trace_buffer (int val)
   13498 {
   13499   struct remote_state *rs = get_remote_state ();
   13500   char *reply;
   13501 
   13502   xsnprintf (rs->buf.data (), get_remote_packet_size (),
   13503 	     "QTBuffer:circular:%x", val);
   13504   putpkt (rs->buf);
   13505   reply = remote_get_noisy_reply ();
   13506   if (*reply == '\0')
   13507     error (_("Target does not support this command."));
   13508   if (strcmp (reply, "OK") != 0)
   13509     error (_("Bogus reply from target: %s"), reply);
   13510 }
   13511 
   13512 traceframe_info_up
   13513 remote_target::traceframe_info ()
   13514 {
   13515   gdb::optional<gdb::char_vector> text
   13516     = target_read_stralloc (current_top_target (), TARGET_OBJECT_TRACEFRAME_INFO,
   13517 			    NULL);
   13518   if (text)
   13519     return parse_traceframe_info (text->data ());
   13520 
   13521   return NULL;
   13522 }
   13523 
   13524 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
   13525    instruction on which a fast tracepoint may be placed.  Returns -1
   13526    if the packet is not supported, and 0 if the minimum instruction
   13527    length is unknown.  */
   13528 
   13529 int
   13530 remote_target::get_min_fast_tracepoint_insn_len ()
   13531 {
   13532   struct remote_state *rs = get_remote_state ();
   13533   char *reply;
   13534 
   13535   /* If we're not debugging a process yet, the IPA can't be
   13536      loaded.  */
   13537   if (!target_has_execution)
   13538     return 0;
   13539 
   13540   /* Make sure the remote is pointing at the right process.  */
   13541   set_general_process ();
   13542 
   13543   xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
   13544   putpkt (rs->buf);
   13545   reply = remote_get_noisy_reply ();
   13546   if (*reply == '\0')
   13547     return -1;
   13548   else
   13549     {
   13550       ULONGEST min_insn_len;
   13551 
   13552       unpack_varlen_hex (reply, &min_insn_len);
   13553 
   13554       return (int) min_insn_len;
   13555     }
   13556 }
   13557 
   13558 void
   13559 remote_target::set_trace_buffer_size (LONGEST val)
   13560 {
   13561   if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
   13562     {
   13563       struct remote_state *rs = get_remote_state ();
   13564       char *buf = rs->buf.data ();
   13565       char *endbuf = buf + get_remote_packet_size ();
   13566       enum packet_result result;
   13567 
   13568       gdb_assert (val >= 0 || val == -1);
   13569       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
   13570       /* Send -1 as literal "-1" to avoid host size dependency.  */
   13571       if (val < 0)
   13572 	{
   13573 	  *buf++ = '-';
   13574           buf += hexnumstr (buf, (ULONGEST) -val);
   13575 	}
   13576       else
   13577 	buf += hexnumstr (buf, (ULONGEST) val);
   13578 
   13579       putpkt (rs->buf);
   13580       remote_get_noisy_reply ();
   13581       result = packet_ok (rs->buf,
   13582 		  &remote_protocol_packets[PACKET_QTBuffer_size]);
   13583 
   13584       if (result != PACKET_OK)
   13585 	warning (_("Bogus reply from target: %s"), rs->buf.data ());
   13586     }
   13587 }
   13588 
   13589 bool
   13590 remote_target::set_trace_notes (const char *user, const char *notes,
   13591 				const char *stop_notes)
   13592 {
   13593   struct remote_state *rs = get_remote_state ();
   13594   char *reply;
   13595   char *buf = rs->buf.data ();
   13596   char *endbuf = buf + get_remote_packet_size ();
   13597   int nbytes;
   13598 
   13599   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
   13600   if (user)
   13601     {
   13602       buf += xsnprintf (buf, endbuf - buf, "user:");
   13603       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
   13604       buf += 2 * nbytes;
   13605       *buf++ = ';';
   13606     }
   13607   if (notes)
   13608     {
   13609       buf += xsnprintf (buf, endbuf - buf, "notes:");
   13610       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
   13611       buf += 2 * nbytes;
   13612       *buf++ = ';';
   13613     }
   13614   if (stop_notes)
   13615     {
   13616       buf += xsnprintf (buf, endbuf - buf, "tstop:");
   13617       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
   13618       buf += 2 * nbytes;
   13619       *buf++ = ';';
   13620     }
   13621   /* Ensure the buffer is terminated.  */
   13622   *buf = '\0';
   13623 
   13624   putpkt (rs->buf);
   13625   reply = remote_get_noisy_reply ();
   13626   if (*reply == '\0')
   13627     return false;
   13628 
   13629   if (strcmp (reply, "OK") != 0)
   13630     error (_("Bogus reply from target: %s"), reply);
   13631 
   13632   return true;
   13633 }
   13634 
   13635 bool
   13636 remote_target::use_agent (bool use)
   13637 {
   13638   if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
   13639     {
   13640       struct remote_state *rs = get_remote_state ();
   13641 
   13642       /* If the stub supports QAgent.  */
   13643       xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
   13644       putpkt (rs->buf);
   13645       getpkt (&rs->buf, 0);
   13646 
   13647       if (strcmp (rs->buf.data (), "OK") == 0)
   13648 	{
   13649 	  ::use_agent = use;
   13650 	  return true;
   13651 	}
   13652     }
   13653 
   13654   return false;
   13655 }
   13656 
   13657 bool
   13658 remote_target::can_use_agent ()
   13659 {
   13660   return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
   13661 }
   13662 
   13663 struct btrace_target_info
   13664 {
   13665   /* The ptid of the traced thread.  */
   13666   ptid_t ptid;
   13667 
   13668   /* The obtained branch trace configuration.  */
   13669   struct btrace_config conf;
   13670 };
   13671 
   13672 /* Reset our idea of our target's btrace configuration.  */
   13673 
   13674 static void
   13675 remote_btrace_reset (remote_state *rs)
   13676 {
   13677   memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
   13678 }
   13679 
   13680 /* Synchronize the configuration with the target.  */
   13681 
   13682 void
   13683 remote_target::btrace_sync_conf (const btrace_config *conf)
   13684 {
   13685   struct packet_config *packet;
   13686   struct remote_state *rs;
   13687   char *buf, *pos, *endbuf;
   13688 
   13689   rs = get_remote_state ();
   13690   buf = rs->buf.data ();
   13691   endbuf = buf + get_remote_packet_size ();
   13692 
   13693   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
   13694   if (packet_config_support (packet) == PACKET_ENABLE
   13695       && conf->bts.size != rs->btrace_config.bts.size)
   13696     {
   13697       pos = buf;
   13698       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
   13699                         conf->bts.size);
   13700 
   13701       putpkt (buf);
   13702       getpkt (&rs->buf, 0);
   13703 
   13704       if (packet_ok (buf, packet) == PACKET_ERROR)
   13705 	{
   13706 	  if (buf[0] == 'E' && buf[1] == '.')
   13707 	    error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
   13708 	  else
   13709 	    error (_("Failed to configure the BTS buffer size."));
   13710 	}
   13711 
   13712       rs->btrace_config.bts.size = conf->bts.size;
   13713     }
   13714 
   13715   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
   13716   if (packet_config_support (packet) == PACKET_ENABLE
   13717       && conf->pt.size != rs->btrace_config.pt.size)
   13718     {
   13719       pos = buf;
   13720       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
   13721                         conf->pt.size);
   13722 
   13723       putpkt (buf);
   13724       getpkt (&rs->buf, 0);
   13725 
   13726       if (packet_ok (buf, packet) == PACKET_ERROR)
   13727 	{
   13728 	  if (buf[0] == 'E' && buf[1] == '.')
   13729 	    error (_("Failed to configure the trace buffer size: %s"), buf + 2);
   13730 	  else
   13731 	    error (_("Failed to configure the trace buffer size."));
   13732 	}
   13733 
   13734       rs->btrace_config.pt.size = conf->pt.size;
   13735     }
   13736 }
   13737 
   13738 /* Read the current thread's btrace configuration from the target and
   13739    store it into CONF.  */
   13740 
   13741 static void
   13742 btrace_read_config (struct btrace_config *conf)
   13743 {
   13744   gdb::optional<gdb::char_vector> xml
   13745     = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE_CONF, "");
   13746   if (xml)
   13747     parse_xml_btrace_conf (conf, xml->data ());
   13748 }
   13749 
   13750 /* Maybe reopen target btrace.  */
   13751 
   13752 void
   13753 remote_target::remote_btrace_maybe_reopen ()
   13754 {
   13755   struct remote_state *rs = get_remote_state ();
   13756   int btrace_target_pushed = 0;
   13757 #if !defined (HAVE_LIBIPT)
   13758   int warned = 0;
   13759 #endif
   13760 
   13761   scoped_restore_current_thread restore_thread;
   13762 
   13763   for (thread_info *tp : all_non_exited_threads ())
   13764     {
   13765       set_general_thread (tp->ptid);
   13766 
   13767       memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
   13768       btrace_read_config (&rs->btrace_config);
   13769 
   13770       if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
   13771 	continue;
   13772 
   13773 #if !defined (HAVE_LIBIPT)
   13774       if (rs->btrace_config.format == BTRACE_FORMAT_PT)
   13775 	{
   13776 	  if (!warned)
   13777 	    {
   13778 	      warned = 1;
   13779 	      warning (_("Target is recording using Intel Processor Trace "
   13780 			 "but support was disabled at compile time."));
   13781 	    }
   13782 
   13783 	  continue;
   13784 	}
   13785 #endif /* !defined (HAVE_LIBIPT) */
   13786 
   13787       /* Push target, once, but before anything else happens.  This way our
   13788 	 changes to the threads will be cleaned up by unpushing the target
   13789 	 in case btrace_read_config () throws.  */
   13790       if (!btrace_target_pushed)
   13791 	{
   13792 	  btrace_target_pushed = 1;
   13793 	  record_btrace_push_target ();
   13794 	  printf_filtered (_("Target is recording using %s.\n"),
   13795 			   btrace_format_string (rs->btrace_config.format));
   13796 	}
   13797 
   13798       tp->btrace.target = XCNEW (struct btrace_target_info);
   13799       tp->btrace.target->ptid = tp->ptid;
   13800       tp->btrace.target->conf = rs->btrace_config;
   13801     }
   13802 }
   13803 
   13804 /* Enable branch tracing.  */
   13805 
   13806 struct btrace_target_info *
   13807 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
   13808 {
   13809   struct btrace_target_info *tinfo = NULL;
   13810   struct packet_config *packet = NULL;
   13811   struct remote_state *rs = get_remote_state ();
   13812   char *buf = rs->buf.data ();
   13813   char *endbuf = buf + get_remote_packet_size ();
   13814 
   13815   switch (conf->format)
   13816     {
   13817       case BTRACE_FORMAT_BTS:
   13818 	packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
   13819 	break;
   13820 
   13821       case BTRACE_FORMAT_PT:
   13822 	packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
   13823 	break;
   13824     }
   13825 
   13826   if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
   13827     error (_("Target does not support branch tracing."));
   13828 
   13829   btrace_sync_conf (conf);
   13830 
   13831   set_general_thread (ptid);
   13832 
   13833   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
   13834   putpkt (rs->buf);
   13835   getpkt (&rs->buf, 0);
   13836 
   13837   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
   13838     {
   13839       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
   13840 	error (_("Could not enable branch tracing for %s: %s"),
   13841 	       target_pid_to_str (ptid), &rs->buf[2]);
   13842       else
   13843 	error (_("Could not enable branch tracing for %s."),
   13844 	       target_pid_to_str (ptid));
   13845     }
   13846 
   13847   tinfo = XCNEW (struct btrace_target_info);
   13848   tinfo->ptid = ptid;
   13849 
   13850   /* If we fail to read the configuration, we lose some information, but the
   13851      tracing itself is not impacted.  */
   13852   TRY
   13853     {
   13854       btrace_read_config (&tinfo->conf);
   13855     }
   13856   CATCH (err, RETURN_MASK_ERROR)
   13857     {
   13858       if (err.message != NULL)
   13859 	warning ("%s", err.message);
   13860     }
   13861   END_CATCH
   13862 
   13863   return tinfo;
   13864 }
   13865 
   13866 /* Disable branch tracing.  */
   13867 
   13868 void
   13869 remote_target::disable_btrace (struct btrace_target_info *tinfo)
   13870 {
   13871   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
   13872   struct remote_state *rs = get_remote_state ();
   13873   char *buf = rs->buf.data ();
   13874   char *endbuf = buf + get_remote_packet_size ();
   13875 
   13876   if (packet_config_support (packet) != PACKET_ENABLE)
   13877     error (_("Target does not support branch tracing."));
   13878 
   13879   set_general_thread (tinfo->ptid);
   13880 
   13881   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
   13882   putpkt (rs->buf);
   13883   getpkt (&rs->buf, 0);
   13884 
   13885   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
   13886     {
   13887       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
   13888 	error (_("Could not disable branch tracing for %s: %s"),
   13889 	       target_pid_to_str (tinfo->ptid), &rs->buf[2]);
   13890       else
   13891 	error (_("Could not disable branch tracing for %s."),
   13892 	       target_pid_to_str (tinfo->ptid));
   13893     }
   13894 
   13895   xfree (tinfo);
   13896 }
   13897 
   13898 /* Teardown branch tracing.  */
   13899 
   13900 void
   13901 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
   13902 {
   13903   /* We must not talk to the target during teardown.  */
   13904   xfree (tinfo);
   13905 }
   13906 
   13907 /* Read the branch trace.  */
   13908 
   13909 enum btrace_error
   13910 remote_target::read_btrace (struct btrace_data *btrace,
   13911 			    struct btrace_target_info *tinfo,
   13912 			    enum btrace_read_type type)
   13913 {
   13914   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
   13915   const char *annex;
   13916 
   13917   if (packet_config_support (packet) != PACKET_ENABLE)
   13918     error (_("Target does not support branch tracing."));
   13919 
   13920 #if !defined(HAVE_LIBEXPAT)
   13921   error (_("Cannot process branch tracing result. XML parsing not supported."));
   13922 #endif
   13923 
   13924   switch (type)
   13925     {
   13926     case BTRACE_READ_ALL:
   13927       annex = "all";
   13928       break;
   13929     case BTRACE_READ_NEW:
   13930       annex = "new";
   13931       break;
   13932     case BTRACE_READ_DELTA:
   13933       annex = "delta";
   13934       break;
   13935     default:
   13936       internal_error (__FILE__, __LINE__,
   13937 		      _("Bad branch tracing read type: %u."),
   13938 		      (unsigned int) type);
   13939     }
   13940 
   13941   gdb::optional<gdb::char_vector> xml
   13942     = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE, annex);
   13943   if (!xml)
   13944     return BTRACE_ERR_UNKNOWN;
   13945 
   13946   parse_xml_btrace (btrace, xml->data ());
   13947 
   13948   return BTRACE_ERR_NONE;
   13949 }
   13950 
   13951 const struct btrace_config *
   13952 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
   13953 {
   13954   return &tinfo->conf;
   13955 }
   13956 
   13957 bool
   13958 remote_target::augmented_libraries_svr4_read ()
   13959 {
   13960   return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
   13961 	  == PACKET_ENABLE);
   13962 }
   13963 
   13964 /* Implementation of to_load.  */
   13965 
   13966 void
   13967 remote_target::load (const char *name, int from_tty)
   13968 {
   13969   generic_load (name, from_tty);
   13970 }
   13971 
   13972 /* Accepts an integer PID; returns a string representing a file that
   13973    can be opened on the remote side to get the symbols for the child
   13974    process.  Returns NULL if the operation is not supported.  */
   13975 
   13976 char *
   13977 remote_target::pid_to_exec_file (int pid)
   13978 {
   13979   static gdb::optional<gdb::char_vector> filename;
   13980   struct inferior *inf;
   13981   char *annex = NULL;
   13982 
   13983   if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
   13984     return NULL;
   13985 
   13986   inf = find_inferior_pid (pid);
   13987   if (inf == NULL)
   13988     internal_error (__FILE__, __LINE__,
   13989 		    _("not currently attached to process %d"), pid);
   13990 
   13991   if (!inf->fake_pid_p)
   13992     {
   13993       const int annex_size = 9;
   13994 
   13995       annex = (char *) alloca (annex_size);
   13996       xsnprintf (annex, annex_size, "%x", pid);
   13997     }
   13998 
   13999   filename = target_read_stralloc (current_top_target (),
   14000 				   TARGET_OBJECT_EXEC_FILE, annex);
   14001 
   14002   return filename ? filename->data () : nullptr;
   14003 }
   14004 
   14005 /* Implement the to_can_do_single_step target_ops method.  */
   14006 
   14007 int
   14008 remote_target::can_do_single_step ()
   14009 {
   14010   /* We can only tell whether target supports single step or not by
   14011      supported s and S vCont actions if the stub supports vContSupported
   14012      feature.  If the stub doesn't support vContSupported feature,
   14013      we have conservatively to think target doesn't supports single
   14014      step.  */
   14015   if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
   14016     {
   14017       struct remote_state *rs = get_remote_state ();
   14018 
   14019       if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
   14020 	remote_vcont_probe ();
   14021 
   14022       return rs->supports_vCont.s && rs->supports_vCont.S;
   14023     }
   14024   else
   14025     return 0;
   14026 }
   14027 
   14028 /* Implementation of the to_execution_direction method for the remote
   14029    target.  */
   14030 
   14031 enum exec_direction_kind
   14032 remote_target::execution_direction ()
   14033 {
   14034   struct remote_state *rs = get_remote_state ();
   14035 
   14036   return rs->last_resume_exec_dir;
   14037 }
   14038 
   14039 /* Return pointer to the thread_info struct which corresponds to
   14040    THREAD_HANDLE (having length HANDLE_LEN).  */
   14041 
   14042 thread_info *
   14043 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
   14044 					     int handle_len,
   14045 					     inferior *inf)
   14046 {
   14047   for (thread_info *tp : all_non_exited_threads ())
   14048     {
   14049       remote_thread_info *priv = get_remote_thread_info (tp);
   14050 
   14051       if (tp->inf == inf && priv != NULL)
   14052         {
   14053 	  if (handle_len != priv->thread_handle.size ())
   14054 	    error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
   14055 	           handle_len, priv->thread_handle.size ());
   14056 	  if (memcmp (thread_handle, priv->thread_handle.data (),
   14057 	              handle_len) == 0)
   14058 	    return tp;
   14059 	}
   14060     }
   14061 
   14062   return NULL;
   14063 }
   14064 
   14065 bool
   14066 remote_target::can_async_p ()
   14067 {
   14068   struct remote_state *rs = get_remote_state ();
   14069 
   14070   /* We don't go async if the user has explicitly prevented it with the
   14071      "maint set target-async" command.  */
   14072   if (!target_async_permitted)
   14073     return false;
   14074 
   14075   /* We're async whenever the serial device is.  */
   14076   return serial_can_async_p (rs->remote_desc);
   14077 }
   14078 
   14079 bool
   14080 remote_target::is_async_p ()
   14081 {
   14082   struct remote_state *rs = get_remote_state ();
   14083 
   14084   if (!target_async_permitted)
   14085     /* We only enable async when the user specifically asks for it.  */
   14086     return false;
   14087 
   14088   /* We're async whenever the serial device is.  */
   14089   return serial_is_async_p (rs->remote_desc);
   14090 }
   14091 
   14092 /* Pass the SERIAL event on and up to the client.  One day this code
   14093    will be able to delay notifying the client of an event until the
   14094    point where an entire packet has been received.  */
   14095 
   14096 static serial_event_ftype remote_async_serial_handler;
   14097 
   14098 static void
   14099 remote_async_serial_handler (struct serial *scb, void *context)
   14100 {
   14101   /* Don't propogate error information up to the client.  Instead let
   14102      the client find out about the error by querying the target.  */
   14103   inferior_event_handler (INF_REG_EVENT, NULL);
   14104 }
   14105 
   14106 static void
   14107 remote_async_inferior_event_handler (gdb_client_data data)
   14108 {
   14109   inferior_event_handler (INF_REG_EVENT, data);
   14110 }
   14111 
   14112 void
   14113 remote_target::async (int enable)
   14114 {
   14115   struct remote_state *rs = get_remote_state ();
   14116 
   14117   if (enable)
   14118     {
   14119       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
   14120 
   14121       /* If there are pending events in the stop reply queue tell the
   14122 	 event loop to process them.  */
   14123       if (!rs->stop_reply_queue.empty ())
   14124 	mark_async_event_handler (rs->remote_async_inferior_event_token);
   14125       /* For simplicity, below we clear the pending events token
   14126 	 without remembering whether it is marked, so here we always
   14127 	 mark it.  If there's actually no pending notification to
   14128 	 process, this ends up being a no-op (other than a spurious
   14129 	 event-loop wakeup).  */
   14130       if (target_is_non_stop_p ())
   14131 	mark_async_event_handler (rs->notif_state->get_pending_events_token);
   14132     }
   14133   else
   14134     {
   14135       serial_async (rs->remote_desc, NULL, NULL);
   14136       /* If the core is disabling async, it doesn't want to be
   14137 	 disturbed with target events.  Clear all async event sources
   14138 	 too.  */
   14139       clear_async_event_handler (rs->remote_async_inferior_event_token);
   14140       if (target_is_non_stop_p ())
   14141 	clear_async_event_handler (rs->notif_state->get_pending_events_token);
   14142     }
   14143 }
   14144 
   14145 /* Implementation of the to_thread_events method.  */
   14146 
   14147 void
   14148 remote_target::thread_events (int enable)
   14149 {
   14150   struct remote_state *rs = get_remote_state ();
   14151   size_t size = get_remote_packet_size ();
   14152 
   14153   if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
   14154     return;
   14155 
   14156   xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
   14157   putpkt (rs->buf);
   14158   getpkt (&rs->buf, 0);
   14159 
   14160   switch (packet_ok (rs->buf,
   14161 		     &remote_protocol_packets[PACKET_QThreadEvents]))
   14162     {
   14163     case PACKET_OK:
   14164       if (strcmp (rs->buf.data (), "OK") != 0)
   14165 	error (_("Remote refused setting thread events: %s"), rs->buf.data ());
   14166       break;
   14167     case PACKET_ERROR:
   14168       warning (_("Remote failure reply: %s"), rs->buf.data ());
   14169       break;
   14170     case PACKET_UNKNOWN:
   14171       break;
   14172     }
   14173 }
   14174 
   14175 static void
   14176 set_remote_cmd (const char *args, int from_tty)
   14177 {
   14178   help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
   14179 }
   14180 
   14181 static void
   14182 show_remote_cmd (const char *args, int from_tty)
   14183 {
   14184   /* We can't just use cmd_show_list here, because we want to skip
   14185      the redundant "show remote Z-packet" and the legacy aliases.  */
   14186   struct cmd_list_element *list = remote_show_cmdlist;
   14187   struct ui_out *uiout = current_uiout;
   14188 
   14189   ui_out_emit_tuple tuple_emitter (uiout, "showlist");
   14190   for (; list != NULL; list = list->next)
   14191     if (strcmp (list->name, "Z-packet") == 0)
   14192       continue;
   14193     else if (list->type == not_set_cmd)
   14194       /* Alias commands are exactly like the original, except they
   14195 	 don't have the normal type.  */
   14196       continue;
   14197     else
   14198       {
   14199 	ui_out_emit_tuple option_emitter (uiout, "option");
   14200 
   14201 	uiout->field_string ("name", list->name);
   14202 	uiout->text (":  ");
   14203 	if (list->type == show_cmd)
   14204 	  do_show_command (NULL, from_tty, list);
   14205 	else
   14206 	  cmd_func (list, NULL, from_tty);
   14207       }
   14208 }
   14209 
   14210 
   14211 /* Function to be called whenever a new objfile (shlib) is detected.  */
   14212 static void
   14213 remote_new_objfile (struct objfile *objfile)
   14214 {
   14215   remote_target *remote = get_current_remote_target ();
   14216 
   14217   if (remote != NULL)			/* Have a remote connection.  */
   14218     remote->remote_check_symbols ();
   14219 }
   14220 
   14221 /* Pull all the tracepoints defined on the target and create local
   14222    data structures representing them.  We don't want to create real
   14223    tracepoints yet, we don't want to mess up the user's existing
   14224    collection.  */
   14225 
   14226 int
   14227 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
   14228 {
   14229   struct remote_state *rs = get_remote_state ();
   14230   char *p;
   14231 
   14232   /* Ask for a first packet of tracepoint definition.  */
   14233   putpkt ("qTfP");
   14234   getpkt (&rs->buf, 0);
   14235   p = rs->buf.data ();
   14236   while (*p && *p != 'l')
   14237     {
   14238       parse_tracepoint_definition (p, utpp);
   14239       /* Ask for another packet of tracepoint definition.  */
   14240       putpkt ("qTsP");
   14241       getpkt (&rs->buf, 0);
   14242       p = rs->buf.data ();
   14243     }
   14244   return 0;
   14245 }
   14246 
   14247 int
   14248 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
   14249 {
   14250   struct remote_state *rs = get_remote_state ();
   14251   char *p;
   14252 
   14253   /* Ask for a first packet of variable definition.  */
   14254   putpkt ("qTfV");
   14255   getpkt (&rs->buf, 0);
   14256   p = rs->buf.data ();
   14257   while (*p && *p != 'l')
   14258     {
   14259       parse_tsv_definition (p, utsvp);
   14260       /* Ask for another packet of variable definition.  */
   14261       putpkt ("qTsV");
   14262       getpkt (&rs->buf, 0);
   14263       p = rs->buf.data ();
   14264     }
   14265   return 0;
   14266 }
   14267 
   14268 /* The "set/show range-stepping" show hook.  */
   14269 
   14270 static void
   14271 show_range_stepping (struct ui_file *file, int from_tty,
   14272 		     struct cmd_list_element *c,
   14273 		     const char *value)
   14274 {
   14275   fprintf_filtered (file,
   14276 		    _("Debugger's willingness to use range stepping "
   14277 		      "is %s.\n"), value);
   14278 }
   14279 
   14280 /* Return true if the vCont;r action is supported by the remote
   14281    stub.  */
   14282 
   14283 bool
   14284 remote_target::vcont_r_supported ()
   14285 {
   14286   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
   14287     remote_vcont_probe ();
   14288 
   14289   return (packet_support (PACKET_vCont) == PACKET_ENABLE
   14290 	  && get_remote_state ()->supports_vCont.r);
   14291 }
   14292 
   14293 /* The "set/show range-stepping" set hook.  */
   14294 
   14295 static void
   14296 set_range_stepping (const char *ignore_args, int from_tty,
   14297 		    struct cmd_list_element *c)
   14298 {
   14299   /* When enabling, check whether range stepping is actually supported
   14300      by the target, and warn if not.  */
   14301   if (use_range_stepping)
   14302     {
   14303       remote_target *remote = get_current_remote_target ();
   14304       if (remote == NULL
   14305 	  || !remote->vcont_r_supported ())
   14306 	warning (_("Range stepping is not supported by the current target"));
   14307     }
   14308 }
   14309 
   14310 void
   14311 _initialize_remote (void)
   14312 {
   14313   struct cmd_list_element *cmd;
   14314   const char *cmd_name;
   14315 
   14316   /* architecture specific data */
   14317   remote_g_packet_data_handle =
   14318     gdbarch_data_register_pre_init (remote_g_packet_data_init);
   14319 
   14320   remote_pspace_data
   14321     = register_program_space_data_with_cleanup (NULL,
   14322 						remote_pspace_data_cleanup);
   14323 
   14324   add_target (remote_target_info, remote_target::open);
   14325   add_target (extended_remote_target_info, extended_remote_target::open);
   14326 
   14327   /* Hook into new objfile notification.  */
   14328   gdb::observers::new_objfile.attach (remote_new_objfile);
   14329 
   14330 #if 0
   14331   init_remote_threadtests ();
   14332 #endif
   14333 
   14334   /* set/show remote ...  */
   14335 
   14336   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
   14337 Remote protocol specific variables\n\
   14338 Configure various remote-protocol specific variables such as\n\
   14339 the packets being used"),
   14340 		  &remote_set_cmdlist, "set remote ",
   14341 		  0 /* allow-unknown */, &setlist);
   14342   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
   14343 Remote protocol specific variables\n\
   14344 Configure various remote-protocol specific variables such as\n\
   14345 the packets being used"),
   14346 		  &remote_show_cmdlist, "show remote ",
   14347 		  0 /* allow-unknown */, &showlist);
   14348 
   14349   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
   14350 Compare section data on target to the exec file.\n\
   14351 Argument is a single section name (default: all loaded sections).\n\
   14352 To compare only read-only loaded sections, specify the -r option."),
   14353 	   &cmdlist);
   14354 
   14355   add_cmd ("packet", class_maintenance, packet_command, _("\
   14356 Send an arbitrary packet to a remote target.\n\
   14357    maintenance packet TEXT\n\
   14358 If GDB is talking to an inferior via the GDB serial protocol, then\n\
   14359 this command sends the string TEXT to the inferior, and displays the\n\
   14360 response packet.  GDB supplies the initial `$' character, and the\n\
   14361 terminating `#' character and checksum."),
   14362 	   &maintenancelist);
   14363 
   14364   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
   14365 Set whether to send break if interrupted."), _("\
   14366 Show whether to send break if interrupted."), _("\
   14367 If set, a break, instead of a cntrl-c, is sent to the remote target."),
   14368 			   set_remotebreak, show_remotebreak,
   14369 			   &setlist, &showlist);
   14370   cmd_name = "remotebreak";
   14371   cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
   14372   deprecate_cmd (cmd, "set remote interrupt-sequence");
   14373   cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
   14374   cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
   14375   deprecate_cmd (cmd, "show remote interrupt-sequence");
   14376 
   14377   add_setshow_enum_cmd ("interrupt-sequence", class_support,
   14378 			interrupt_sequence_modes, &interrupt_sequence_mode,
   14379 			_("\
   14380 Set interrupt sequence to remote target."), _("\
   14381 Show interrupt sequence to remote target."), _("\
   14382 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
   14383 			NULL, show_interrupt_sequence,
   14384 			&remote_set_cmdlist,
   14385 			&remote_show_cmdlist);
   14386 
   14387   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
   14388 			   &interrupt_on_connect, _("\
   14389 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("		\
   14390 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("		\
   14391 If set, interrupt sequence is sent to remote target."),
   14392 			   NULL, NULL,
   14393 			   &remote_set_cmdlist, &remote_show_cmdlist);
   14394 
   14395   /* Install commands for configuring memory read/write packets.  */
   14396 
   14397   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
   14398 Set the maximum number of bytes per memory write packet (deprecated)."),
   14399 	   &setlist);
   14400   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
   14401 Show the maximum number of bytes per memory write packet (deprecated)."),
   14402 	   &showlist);
   14403   add_cmd ("memory-write-packet-size", no_class,
   14404 	   set_memory_write_packet_size, _("\
   14405 Set the maximum number of bytes per memory-write packet.\n\
   14406 Specify the number of bytes in a packet or 0 (zero) for the\n\
   14407 default packet size.  The actual limit is further reduced\n\
   14408 dependent on the target.  Specify ``fixed'' to disable the\n\
   14409 further restriction and ``limit'' to enable that restriction."),
   14410 	   &remote_set_cmdlist);
   14411   add_cmd ("memory-read-packet-size", no_class,
   14412 	   set_memory_read_packet_size, _("\
   14413 Set the maximum number of bytes per memory-read packet.\n\
   14414 Specify the number of bytes in a packet or 0 (zero) for the\n\
   14415 default packet size.  The actual limit is further reduced\n\
   14416 dependent on the target.  Specify ``fixed'' to disable the\n\
   14417 further restriction and ``limit'' to enable that restriction."),
   14418 	   &remote_set_cmdlist);
   14419   add_cmd ("memory-write-packet-size", no_class,
   14420 	   show_memory_write_packet_size,
   14421 	   _("Show the maximum number of bytes per memory-write packet."),
   14422 	   &remote_show_cmdlist);
   14423   add_cmd ("memory-read-packet-size", no_class,
   14424 	   show_memory_read_packet_size,
   14425 	   _("Show the maximum number of bytes per memory-read packet."),
   14426 	   &remote_show_cmdlist);
   14427 
   14428   add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
   14429 			    &remote_hw_watchpoint_limit, _("\
   14430 Set the maximum number of target hardware watchpoints."), _("\
   14431 Show the maximum number of target hardware watchpoints."), _("\
   14432 Specify \"unlimited\" for unlimited hardware watchpoints."),
   14433 			    NULL, show_hardware_watchpoint_limit,
   14434 			    &remote_set_cmdlist,
   14435 			    &remote_show_cmdlist);
   14436   add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
   14437 			    no_class,
   14438 			    &remote_hw_watchpoint_length_limit, _("\
   14439 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
   14440 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
   14441 Specify \"unlimited\" to allow watchpoints of unlimited size."),
   14442 			    NULL, show_hardware_watchpoint_length_limit,
   14443 			    &remote_set_cmdlist, &remote_show_cmdlist);
   14444   add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
   14445 			    &remote_hw_breakpoint_limit, _("\
   14446 Set the maximum number of target hardware breakpoints."), _("\
   14447 Show the maximum number of target hardware breakpoints."), _("\
   14448 Specify \"unlimited\" for unlimited hardware breakpoints."),
   14449 			    NULL, show_hardware_breakpoint_limit,
   14450 			    &remote_set_cmdlist, &remote_show_cmdlist);
   14451 
   14452   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
   14453 			     &remote_address_size, _("\
   14454 Set the maximum size of the address (in bits) in a memory packet."), _("\
   14455 Show the maximum size of the address (in bits) in a memory packet."), NULL,
   14456 			     NULL,
   14457 			     NULL, /* FIXME: i18n: */
   14458 			     &setlist, &showlist);
   14459 
   14460   init_all_packet_configs ();
   14461 
   14462   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
   14463 			 "X", "binary-download", 1);
   14464 
   14465   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
   14466 			 "vCont", "verbose-resume", 0);
   14467 
   14468   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
   14469 			 "QPassSignals", "pass-signals", 0);
   14470 
   14471   add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
   14472 			 "QCatchSyscalls", "catch-syscalls", 0);
   14473 
   14474   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
   14475 			 "QProgramSignals", "program-signals", 0);
   14476 
   14477   add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
   14478 			 "QSetWorkingDir", "set-working-dir", 0);
   14479 
   14480   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
   14481 			 "QStartupWithShell", "startup-with-shell", 0);
   14482 
   14483   add_packet_config_cmd (&remote_protocol_packets
   14484 			 [PACKET_QEnvironmentHexEncoded],
   14485 			 "QEnvironmentHexEncoded", "environment-hex-encoded",
   14486 			 0);
   14487 
   14488   add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
   14489 			 "QEnvironmentReset", "environment-reset",
   14490 			 0);
   14491 
   14492   add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
   14493 			 "QEnvironmentUnset", "environment-unset",
   14494 			 0);
   14495 
   14496   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
   14497 			 "qSymbol", "symbol-lookup", 0);
   14498 
   14499   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
   14500 			 "P", "set-register", 1);
   14501 
   14502   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
   14503 			 "p", "fetch-register", 1);
   14504 
   14505   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
   14506 			 "Z0", "software-breakpoint", 0);
   14507 
   14508   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
   14509 			 "Z1", "hardware-breakpoint", 0);
   14510 
   14511   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
   14512 			 "Z2", "write-watchpoint", 0);
   14513 
   14514   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
   14515 			 "Z3", "read-watchpoint", 0);
   14516 
   14517   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
   14518 			 "Z4", "access-watchpoint", 0);
   14519 
   14520   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
   14521 			 "qXfer:auxv:read", "read-aux-vector", 0);
   14522 
   14523   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
   14524 			 "qXfer:exec-file:read", "pid-to-exec-file", 0);
   14525 
   14526   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
   14527 			 "qXfer:features:read", "target-features", 0);
   14528 
   14529   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
   14530 			 "qXfer:libraries:read", "library-info", 0);
   14531 
   14532   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
   14533 			 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
   14534 
   14535   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
   14536 			 "qXfer:memory-map:read", "memory-map", 0);
   14537 
   14538   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
   14539                          "qXfer:spu:read", "read-spu-object", 0);
   14540 
   14541   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
   14542                          "qXfer:spu:write", "write-spu-object", 0);
   14543 
   14544   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
   14545                         "qXfer:osdata:read", "osdata", 0);
   14546 
   14547   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
   14548 			 "qXfer:threads:read", "threads", 0);
   14549 
   14550   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
   14551                          "qXfer:siginfo:read", "read-siginfo-object", 0);
   14552 
   14553   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
   14554                          "qXfer:siginfo:write", "write-siginfo-object", 0);
   14555 
   14556   add_packet_config_cmd
   14557     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
   14558      "qXfer:traceframe-info:read", "traceframe-info", 0);
   14559 
   14560   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
   14561 			 "qXfer:uib:read", "unwind-info-block", 0);
   14562 
   14563   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
   14564 			 "qGetTLSAddr", "get-thread-local-storage-address",
   14565 			 0);
   14566 
   14567   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
   14568 			 "qGetTIBAddr", "get-thread-information-block-address",
   14569 			 0);
   14570 
   14571   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
   14572 			 "bc", "reverse-continue", 0);
   14573 
   14574   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
   14575 			 "bs", "reverse-step", 0);
   14576 
   14577   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
   14578 			 "qSupported", "supported-packets", 0);
   14579 
   14580   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
   14581 			 "qSearch:memory", "search-memory", 0);
   14582 
   14583   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
   14584 			 "qTStatus", "trace-status", 0);
   14585 
   14586   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
   14587 			 "vFile:setfs", "hostio-setfs", 0);
   14588 
   14589   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
   14590 			 "vFile:open", "hostio-open", 0);
   14591 
   14592   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
   14593 			 "vFile:pread", "hostio-pread", 0);
   14594 
   14595   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
   14596 			 "vFile:pwrite", "hostio-pwrite", 0);
   14597 
   14598   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
   14599 			 "vFile:close", "hostio-close", 0);
   14600 
   14601   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
   14602 			 "vFile:unlink", "hostio-unlink", 0);
   14603 
   14604   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
   14605 			 "vFile:readlink", "hostio-readlink", 0);
   14606 
   14607   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
   14608 			 "vFile:fstat", "hostio-fstat", 0);
   14609 
   14610   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
   14611 			 "vAttach", "attach", 0);
   14612 
   14613   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
   14614 			 "vRun", "run", 0);
   14615 
   14616   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
   14617 			 "QStartNoAckMode", "noack", 0);
   14618 
   14619   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
   14620 			 "vKill", "kill", 0);
   14621 
   14622   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
   14623 			 "qAttached", "query-attached", 0);
   14624 
   14625   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
   14626 			 "ConditionalTracepoints",
   14627 			 "conditional-tracepoints", 0);
   14628 
   14629   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
   14630 			 "ConditionalBreakpoints",
   14631 			 "conditional-breakpoints", 0);
   14632 
   14633   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
   14634 			 "BreakpointCommands",
   14635 			 "breakpoint-commands", 0);
   14636 
   14637   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
   14638 			 "FastTracepoints", "fast-tracepoints", 0);
   14639 
   14640   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
   14641 			 "TracepointSource", "TracepointSource", 0);
   14642 
   14643   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
   14644 			 "QAllow", "allow", 0);
   14645 
   14646   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
   14647 			 "StaticTracepoints", "static-tracepoints", 0);
   14648 
   14649   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
   14650 			 "InstallInTrace", "install-in-trace", 0);
   14651 
   14652   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
   14653                          "qXfer:statictrace:read", "read-sdata-object", 0);
   14654 
   14655   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
   14656 			 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
   14657 
   14658   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
   14659 			 "QDisableRandomization", "disable-randomization", 0);
   14660 
   14661   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
   14662 			 "QAgent", "agent", 0);
   14663 
   14664   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
   14665 			 "QTBuffer:size", "trace-buffer-size", 0);
   14666 
   14667   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
   14668        "Qbtrace:off", "disable-btrace", 0);
   14669 
   14670   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
   14671        "Qbtrace:bts", "enable-btrace-bts", 0);
   14672 
   14673   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
   14674        "Qbtrace:pt", "enable-btrace-pt", 0);
   14675 
   14676   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
   14677        "qXfer:btrace", "read-btrace", 0);
   14678 
   14679   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
   14680        "qXfer:btrace-conf", "read-btrace-conf", 0);
   14681 
   14682   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
   14683        "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
   14684 
   14685   add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
   14686        "multiprocess-feature", "multiprocess-feature", 0);
   14687 
   14688   add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
   14689                          "swbreak-feature", "swbreak-feature", 0);
   14690 
   14691   add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
   14692                          "hwbreak-feature", "hwbreak-feature", 0);
   14693 
   14694   add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
   14695 			 "fork-event-feature", "fork-event-feature", 0);
   14696 
   14697   add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
   14698 			 "vfork-event-feature", "vfork-event-feature", 0);
   14699 
   14700   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
   14701        "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
   14702 
   14703   add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
   14704 			 "vContSupported", "verbose-resume-supported", 0);
   14705 
   14706   add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
   14707 			 "exec-event-feature", "exec-event-feature", 0);
   14708 
   14709   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
   14710 			 "vCtrlC", "ctrl-c", 0);
   14711 
   14712   add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
   14713 			 "QThreadEvents", "thread-events", 0);
   14714 
   14715   add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
   14716 			 "N stop reply", "no-resumed-stop-reply", 0);
   14717 
   14718   /* Assert that we've registered "set remote foo-packet" commands
   14719      for all packet configs.  */
   14720   {
   14721     int i;
   14722 
   14723     for (i = 0; i < PACKET_MAX; i++)
   14724       {
   14725 	/* Ideally all configs would have a command associated.  Some
   14726 	   still don't though.  */
   14727 	int excepted;
   14728 
   14729 	switch (i)
   14730 	  {
   14731 	  case PACKET_QNonStop:
   14732 	  case PACKET_EnableDisableTracepoints_feature:
   14733 	  case PACKET_tracenz_feature:
   14734 	  case PACKET_DisconnectedTracing_feature:
   14735 	  case PACKET_augmented_libraries_svr4_read_feature:
   14736 	  case PACKET_qCRC:
   14737 	    /* Additions to this list need to be well justified:
   14738 	       pre-existing packets are OK; new packets are not.  */
   14739 	    excepted = 1;
   14740 	    break;
   14741 	  default:
   14742 	    excepted = 0;
   14743 	    break;
   14744 	  }
   14745 
   14746 	/* This catches both forgetting to add a config command, and
   14747 	   forgetting to remove a packet from the exception list.  */
   14748 	gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
   14749       }
   14750   }
   14751 
   14752   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
   14753      Z sub-packet has its own set and show commands, but users may
   14754      have sets to this variable in their .gdbinit files (or in their
   14755      documentation).  */
   14756   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
   14757 				&remote_Z_packet_detect, _("\
   14758 Set use of remote protocol `Z' packets"), _("\
   14759 Show use of remote protocol `Z' packets "), _("\
   14760 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
   14761 packets."),
   14762 				set_remote_protocol_Z_packet_cmd,
   14763 				show_remote_protocol_Z_packet_cmd,
   14764 				/* FIXME: i18n: Use of remote protocol
   14765 				   `Z' packets is %s.  */
   14766 				&remote_set_cmdlist, &remote_show_cmdlist);
   14767 
   14768   add_prefix_cmd ("remote", class_files, remote_command, _("\
   14769 Manipulate files on the remote system\n\
   14770 Transfer files to and from the remote target system."),
   14771 		  &remote_cmdlist, "remote ",
   14772 		  0 /* allow-unknown */, &cmdlist);
   14773 
   14774   add_cmd ("put", class_files, remote_put_command,
   14775 	   _("Copy a local file to the remote system."),
   14776 	   &remote_cmdlist);
   14777 
   14778   add_cmd ("get", class_files, remote_get_command,
   14779 	   _("Copy a remote file to the local system."),
   14780 	   &remote_cmdlist);
   14781 
   14782   add_cmd ("delete", class_files, remote_delete_command,
   14783 	   _("Delete a remote file."),
   14784 	   &remote_cmdlist);
   14785 
   14786   add_setshow_string_noescape_cmd ("exec-file", class_files,
   14787 				   &remote_exec_file_var, _("\
   14788 Set the remote pathname for \"run\""), _("\
   14789 Show the remote pathname for \"run\""), NULL,
   14790 				   set_remote_exec_file,
   14791 				   show_remote_exec_file,
   14792 				   &remote_set_cmdlist,
   14793 				   &remote_show_cmdlist);
   14794 
   14795   add_setshow_boolean_cmd ("range-stepping", class_run,
   14796 			   &use_range_stepping, _("\
   14797 Enable or disable range stepping."), _("\
   14798 Show whether target-assisted range stepping is enabled."), _("\
   14799 If on, and the target supports it, when stepping a source line, GDB\n\
   14800 tells the target to step the corresponding range of addresses itself instead\n\
   14801 of issuing multiple single-steps.  This speeds up source level\n\
   14802 stepping.  If off, GDB always issues single-steps, even if range\n\
   14803 stepping is supported by the target.  The default is on."),
   14804 			   set_range_stepping,
   14805 			   show_range_stepping,
   14806 			   &setlist,
   14807 			   &showlist);
   14808 
   14809   /* Eventually initialize fileio.  See fileio.c */
   14810   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
   14811 
   14812   /* Take advantage of the fact that the TID field is not used, to tag
   14813      special ptids with it set to != 0.  */
   14814   magic_null_ptid = ptid_t (42000, -1, 1);
   14815   not_sent_ptid = ptid_t (42000, -2, 1);
   14816   any_thread_ptid = ptid_t (42000, 0, 1);
   14817 }
   14818