Home | History | Annotate | Line # | Download | only in gdb
remote.c revision 1.1.1.9
      1 /* Remote target communications for serial-line targets in custom GDB protocol
      2 
      3    Copyright (C) 1988-2024 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 <ctype.h>
     23 #include <fcntl.h>
     24 #include "inferior.h"
     25 #include "infrun.h"
     26 #include "bfd.h"
     27 #include "symfile.h"
     28 #include "target.h"
     29 #include "process-stratum-target.h"
     30 #include "cli/cli-cmds.h"
     31 #include "objfiles.h"
     32 #include "gdbthread.h"
     33 #include "remote.h"
     34 #include "remote-notif.h"
     35 #include "regcache.h"
     36 #include "value.h"
     37 #include "observable.h"
     38 #include "solib.h"
     39 #include "cli/cli-decode.h"
     40 #include "cli/cli-setshow.h"
     41 #include "target-descriptions.h"
     42 #include "gdb_bfd.h"
     43 #include "gdbsupport/filestuff.h"
     44 #include "gdbsupport/rsp-low.h"
     45 #include "disasm.h"
     46 #include "location.h"
     47 
     48 #include "gdbsupport/gdb_sys_time.h"
     49 
     50 #include "gdbsupport/event-loop.h"
     51 #include "event-top.h"
     52 #include "inf-loop.h"
     53 
     54 #include <signal.h>
     55 #include "serial.h"
     56 
     57 #include "gdbcore.h"
     58 
     59 #include "remote-fileio.h"
     60 #include "gdbsupport/fileio.h"
     61 #include <sys/stat.h>
     62 #include "xml-support.h"
     63 
     64 #include "memory-map.h"
     65 
     66 #include "tracepoint.h"
     67 #include "ax.h"
     68 #include "ax-gdb.h"
     69 #include "gdbsupport/agent.h"
     70 #include "btrace.h"
     71 #include "record-btrace.h"
     72 #include "gdbsupport/scoped_restore.h"
     73 #include "gdbsupport/environ.h"
     74 #include "gdbsupport/byte-vector.h"
     75 #include "gdbsupport/search.h"
     76 #include <algorithm>
     77 #include <iterator>
     78 #include <unordered_map>
     79 #include "async-event.h"
     80 #include "gdbsupport/selftest.h"
     81 
     82 /* The remote target.  */
     83 
     84 static const char remote_doc[] = N_("\
     85 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
     86 Specify the serial device it is connected to\n\
     87 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
     88 
     89 /* See remote.h  */
     90 
     91 bool remote_debug = false;
     92 
     93 #define OPAQUETHREADBYTES 8
     94 
     95 /* a 64 bit opaque identifier */
     96 typedef unsigned char threadref[OPAQUETHREADBYTES];
     97 
     98 struct gdb_ext_thread_info;
     99 struct threads_listing_context;
    100 typedef int (*rmt_thread_action) (threadref *ref, void *context);
    101 struct protocol_feature;
    102 struct packet_reg;
    103 
    104 struct stop_reply;
    105 typedef std::unique_ptr<stop_reply> stop_reply_up;
    106 
    107 /* Generic configuration support for packets the stub optionally
    108    supports.  Allows the user to specify the use of the packet as well
    109    as allowing GDB to auto-detect support in the remote stub.  */
    110 
    111 enum packet_support
    112   {
    113     PACKET_SUPPORT_UNKNOWN = 0,
    114     PACKET_ENABLE,
    115     PACKET_DISABLE
    116   };
    117 
    118 /* Convert the packet support auto_boolean to a name used for gdb printing.  */
    119 
    120 static const char *
    121 get_packet_support_name (auto_boolean support)
    122 {
    123   switch (support)
    124     {
    125       case AUTO_BOOLEAN_TRUE:
    126 	return "on";
    127       case AUTO_BOOLEAN_FALSE:
    128 	return "off";
    129       case AUTO_BOOLEAN_AUTO:
    130 	return "auto";
    131       default:
    132 	gdb_assert_not_reached ("invalid var_auto_boolean");
    133     }
    134 }
    135 
    136 /* Convert the target type (future remote target or currently connected target)
    137    to a name used for gdb printing.  */
    138 
    139 static const char *
    140 get_target_type_name (bool target_connected)
    141 {
    142   if (target_connected)
    143     return _("on the current remote target");
    144   else
    145     return _("on future remote targets");
    146 }
    147 
    148 /* Analyze a packet's return value and update the packet config
    149    accordingly.  */
    150 
    151 enum packet_status
    152 {
    153   PACKET_ERROR,
    154   PACKET_OK,
    155   PACKET_UNKNOWN
    156 };
    157 
    158 /* Keeps packet's return value. If packet's return value is PACKET_ERROR,
    159    err_msg contains an error message string from E.string or the number
    160    stored as a string from E.num.  */
    161 class packet_result
    162 {
    163 private:
    164   /* Private ctors for internal use.  Clients should use the public
    165      factory static methods instead.  */
    166 
    167   /* Construct a PACKET_ERROR packet_result.  */
    168   packet_result (const char *err_msg, bool textual_err_msg)
    169     : m_status (PACKET_ERROR),
    170       m_err_msg (err_msg),
    171       m_textual_err_msg (textual_err_msg)
    172   {}
    173 
    174   /* Construct an PACKET_OK/PACKET_UNKNOWN packet_result.  */
    175   explicit packet_result (enum packet_status status)
    176     : m_status (status)
    177   {
    178     gdb_assert (status != PACKET_ERROR);
    179   }
    180 
    181 public:
    182   enum packet_status status () const
    183   {
    184     return this->m_status;
    185   }
    186 
    187   const char *err_msg () const
    188   {
    189     gdb_assert (this->m_status == PACKET_ERROR);
    190     return this->m_err_msg.c_str ();
    191   }
    192 
    193   bool textual_err_msg () const
    194   {
    195     gdb_assert (this->m_status == PACKET_ERROR);
    196     return this->m_textual_err_msg;
    197   }
    198 
    199   static packet_result make_numeric_error (const char *err_msg)
    200   {
    201     return packet_result (err_msg, false);
    202   }
    203 
    204   static packet_result make_textual_error (const char *err_msg)
    205   {
    206     return packet_result (err_msg, true);
    207   }
    208 
    209   static packet_result make_ok ()
    210   {
    211     return packet_result (PACKET_OK);
    212   }
    213 
    214   static packet_result make_unknown ()
    215   {
    216     return packet_result (PACKET_UNKNOWN);
    217   }
    218 
    219 private:
    220   enum packet_status m_status;
    221   std::string m_err_msg;
    222 
    223   /* True if we have a textual error message, from an "E.MESSAGE"
    224      response.  */
    225   bool m_textual_err_msg = false;
    226 };
    227 
    228 /* Enumeration of packets for a remote target.  */
    229 
    230 enum {
    231   PACKET_vCont = 0,
    232   PACKET_X,
    233   PACKET_qSymbol,
    234   PACKET_P,
    235   PACKET_p,
    236   PACKET_Z0,
    237   PACKET_Z1,
    238   PACKET_Z2,
    239   PACKET_Z3,
    240   PACKET_Z4,
    241   PACKET_vFile_setfs,
    242   PACKET_vFile_open,
    243   PACKET_vFile_pread,
    244   PACKET_vFile_pwrite,
    245   PACKET_vFile_close,
    246   PACKET_vFile_unlink,
    247   PACKET_vFile_readlink,
    248   PACKET_vFile_fstat,
    249   PACKET_qXfer_auxv,
    250   PACKET_qXfer_features,
    251   PACKET_qXfer_exec_file,
    252   PACKET_qXfer_libraries,
    253   PACKET_qXfer_libraries_svr4,
    254   PACKET_qXfer_memory_map,
    255   PACKET_qXfer_osdata,
    256   PACKET_qXfer_threads,
    257   PACKET_qXfer_statictrace_read,
    258   PACKET_qXfer_traceframe_info,
    259   PACKET_qXfer_uib,
    260   PACKET_qGetTIBAddr,
    261   PACKET_qGetTLSAddr,
    262   PACKET_qSupported,
    263   PACKET_qTStatus,
    264   PACKET_QPassSignals,
    265   PACKET_QCatchSyscalls,
    266   PACKET_QProgramSignals,
    267   PACKET_QSetWorkingDir,
    268   PACKET_QStartupWithShell,
    269   PACKET_QEnvironmentHexEncoded,
    270   PACKET_QEnvironmentReset,
    271   PACKET_QEnvironmentUnset,
    272   PACKET_qCRC,
    273   PACKET_qSearch_memory,
    274   PACKET_vAttach,
    275   PACKET_vRun,
    276   PACKET_QStartNoAckMode,
    277   PACKET_vKill,
    278   PACKET_qXfer_siginfo_read,
    279   PACKET_qXfer_siginfo_write,
    280   PACKET_qAttached,
    281 
    282   /* Support for conditional tracepoints.  */
    283   PACKET_ConditionalTracepoints,
    284 
    285   /* Support for target-side breakpoint conditions.  */
    286   PACKET_ConditionalBreakpoints,
    287 
    288   /* Support for target-side breakpoint commands.  */
    289   PACKET_BreakpointCommands,
    290 
    291   /* Support for fast tracepoints.  */
    292   PACKET_FastTracepoints,
    293 
    294   /* Support for static tracepoints.  */
    295   PACKET_StaticTracepoints,
    296 
    297   /* Support for installing tracepoints while a trace experiment is
    298      running.  */
    299   PACKET_InstallInTrace,
    300 
    301   PACKET_bc,
    302   PACKET_bs,
    303   PACKET_TracepointSource,
    304   PACKET_QAllow,
    305   PACKET_qXfer_fdpic,
    306   PACKET_QDisableRandomization,
    307   PACKET_QAgent,
    308   PACKET_QTBuffer_size,
    309   PACKET_Qbtrace_off,
    310   PACKET_Qbtrace_bts,
    311   PACKET_Qbtrace_pt,
    312   PACKET_qXfer_btrace,
    313 
    314   /* Support for the QNonStop packet.  */
    315   PACKET_QNonStop,
    316 
    317   /* Support for the QThreadEvents packet.  */
    318   PACKET_QThreadEvents,
    319 
    320   /* Support for the QThreadOptions packet.  */
    321   PACKET_QThreadOptions,
    322 
    323   /* Support for multi-process extensions.  */
    324   PACKET_multiprocess_feature,
    325 
    326   /* Support for enabling and disabling tracepoints while a trace
    327      experiment is running.  */
    328   PACKET_EnableDisableTracepoints_feature,
    329 
    330   /* Support for collecting strings using the tracenz bytecode.  */
    331   PACKET_tracenz_feature,
    332 
    333   /* Support for continuing to run a trace experiment while GDB is
    334      disconnected.  */
    335   PACKET_DisconnectedTracing_feature,
    336 
    337   /* Support for qXfer:libraries-svr4:read with a non-empty annex.  */
    338   PACKET_augmented_libraries_svr4_read_feature,
    339 
    340   /* Support for the qXfer:btrace-conf:read packet.  */
    341   PACKET_qXfer_btrace_conf,
    342 
    343   /* Support for the Qbtrace-conf:bts:size packet.  */
    344   PACKET_Qbtrace_conf_bts_size,
    345 
    346   /* Support for swbreak+ feature.  */
    347   PACKET_swbreak_feature,
    348 
    349   /* Support for hwbreak+ feature.  */
    350   PACKET_hwbreak_feature,
    351 
    352   /* Support for fork events.  */
    353   PACKET_fork_event_feature,
    354 
    355   /* Support for vfork events.  */
    356   PACKET_vfork_event_feature,
    357 
    358   /* Support for the Qbtrace-conf:pt:size packet.  */
    359   PACKET_Qbtrace_conf_pt_size,
    360 
    361   /* Support for exec events.  */
    362   PACKET_exec_event_feature,
    363 
    364   /* Support for query supported vCont actions.  */
    365   PACKET_vContSupported,
    366 
    367   /* Support remote CTRL-C.  */
    368   PACKET_vCtrlC,
    369 
    370   /* Support TARGET_WAITKIND_NO_RESUMED.  */
    371   PACKET_no_resumed,
    372 
    373   /* Support for memory tagging, allocation tag fetch/store
    374      packets and the tag violation stop replies.  */
    375   PACKET_memory_tagging_feature,
    376 
    377   /* Support for the qIsAddressTagged packet.  */
    378   PACKET_qIsAddressTagged,
    379 
    380   PACKET_MAX
    381 };
    382 
    383 struct threads_listing_context;
    384 
    385 /* Stub vCont actions support.
    386 
    387    Each field is a boolean flag indicating whether the stub reports
    388    support for the corresponding action.  */
    389 
    390 struct vCont_action_support
    391 {
    392   /* vCont;t */
    393   bool t = false;
    394 
    395   /* vCont;r */
    396   bool r = false;
    397 
    398   /* vCont;s */
    399   bool s = false;
    400 
    401   /* vCont;S */
    402   bool S = false;
    403 };
    404 
    405 /* About this many threadids fit in a packet.  */
    406 
    407 #define MAXTHREADLISTRESULTS 32
    408 
    409 /* Data for the vFile:pread readahead cache.  */
    410 
    411 struct readahead_cache
    412 {
    413   /* Invalidate the readahead cache.  */
    414   void invalidate ();
    415 
    416   /* Invalidate the readahead cache if it is holding data for FD.  */
    417   void invalidate_fd (int fd);
    418 
    419   /* Serve pread from the readahead cache.  Returns number of bytes
    420      read, or 0 if the request can't be served from the cache.  */
    421   int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
    422 
    423   /* The file descriptor for the file that is being cached.  -1 if the
    424      cache is invalid.  */
    425   int fd = -1;
    426 
    427   /* The offset into the file that the cache buffer corresponds
    428      to.  */
    429   ULONGEST offset = 0;
    430 
    431   /* The buffer holding the cache contents.  */
    432   gdb::byte_vector buf;
    433 
    434   /* Cache hit and miss counters.  */
    435   ULONGEST hit_count = 0;
    436   ULONGEST miss_count = 0;
    437 };
    438 
    439 /* Description of the remote protocol for a given architecture.  */
    440 
    441 struct packet_reg
    442 {
    443   long offset; /* Offset into G packet.  */
    444   long regnum; /* GDB's internal register number.  */
    445   LONGEST pnum; /* Remote protocol register number.  */
    446   int in_g_packet; /* Always part of G packet.  */
    447   /* long size in bytes;  == register_size (arch, regnum);
    448      at present.  */
    449   /* char *name; == gdbarch_register_name (arch, regnum);
    450      at present.  */
    451 };
    452 
    453 struct remote_arch_state
    454 {
    455   explicit remote_arch_state (struct gdbarch *gdbarch);
    456 
    457   /* Description of the remote protocol registers.  */
    458   long sizeof_g_packet;
    459 
    460   /* Description of the remote protocol registers indexed by REGNUM
    461      (making an array gdbarch_num_regs in size).  */
    462   std::unique_ptr<packet_reg[]> regs;
    463 
    464   /* This is the size (in chars) of the first response to the ``g''
    465      packet.  It is used as a heuristic when determining the maximum
    466      size of memory-read and memory-write packets.  A target will
    467      typically only reserve a buffer large enough to hold the ``g''
    468      packet.  The size does not include packet overhead (headers and
    469      trailers).  */
    470   long actual_register_packet_size;
    471 
    472   /* This is the maximum size (in chars) of a non read/write packet.
    473      It is also used as a cap on the size of read/write packets.  */
    474   long remote_packet_size;
    475 };
    476 
    477 /* Description of the remote protocol state for the currently
    478    connected target.  This is per-target state, and independent of the
    479    selected architecture.  */
    480 
    481 class remote_state
    482 {
    483 public:
    484 
    485   remote_state ();
    486   ~remote_state ();
    487 
    488   /* Get the remote arch state for GDBARCH.  */
    489   struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
    490 
    491   void create_async_event_handler ()
    492   {
    493     gdb_assert (m_async_event_handler_token == nullptr);
    494     m_async_event_handler_token
    495       = ::create_async_event_handler ([] (gdb_client_data data)
    496 				      {
    497 					inferior_event_handler (INF_REG_EVENT);
    498 				      },
    499 				      nullptr, "remote");
    500   }
    501 
    502   void mark_async_event_handler ()
    503   {
    504     gdb_assert (this->is_async_p ());
    505     ::mark_async_event_handler (m_async_event_handler_token);
    506   }
    507 
    508   void clear_async_event_handler ()
    509   { ::clear_async_event_handler (m_async_event_handler_token); }
    510 
    511   bool async_event_handler_marked () const
    512   { return ::async_event_handler_marked (m_async_event_handler_token); }
    513 
    514   void delete_async_event_handler ()
    515   {
    516     if (m_async_event_handler_token != nullptr)
    517       ::delete_async_event_handler (&m_async_event_handler_token);
    518   }
    519 
    520   bool is_async_p () const
    521   {
    522     /* We're async whenever the serial device is.  */
    523     gdb_assert (this->remote_desc != nullptr);
    524     return serial_is_async_p (this->remote_desc);
    525   }
    526 
    527   bool can_async_p () const
    528   {
    529     /* We can async whenever the serial device can.  */
    530     gdb_assert (this->remote_desc != nullptr);
    531     return serial_can_async_p (this->remote_desc);
    532   }
    533 
    534 public: /* data */
    535 
    536   /* A buffer to use for incoming packets, and its current size.  The
    537      buffer is grown dynamically for larger incoming packets.
    538      Outgoing packets may also be constructed in this buffer.
    539      The size of the buffer is always at least REMOTE_PACKET_SIZE;
    540      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
    541      packets.  */
    542   gdb::char_vector buf;
    543 
    544   /* True if we're going through initial connection setup (finding out
    545      about the remote side's threads, relocating symbols, etc.).  */
    546   bool starting_up = false;
    547 
    548   /* If we negotiated packet size explicitly (and thus can bypass
    549      heuristics for the largest packet size that will not overflow
    550      a buffer in the stub), this will be set to that packet size.
    551      Otherwise zero, meaning to use the guessed size.  */
    552   long explicit_packet_size = 0;
    553 
    554   /* True, if in no ack mode.  That is, neither GDB nor the stub will
    555      expect acks from each other.  The connection is assumed to be
    556      reliable.  */
    557   bool noack_mode = false;
    558 
    559   /* True if we're connected in extended remote mode.  */
    560   bool extended = false;
    561 
    562   /* True if we resumed the target and we're waiting for the target to
    563      stop.  In the mean time, we can't start another command/query.
    564      The remote server wouldn't be ready to process it, so we'd
    565      timeout waiting for a reply that would never come and eventually
    566      we'd close the connection.  This can happen in asynchronous mode
    567      because we allow GDB commands while the target is running.  */
    568   bool waiting_for_stop_reply = false;
    569 
    570   /* The status of the stub support for the various vCont actions.  */
    571   vCont_action_support supports_vCont;
    572 
    573   /* True if the user has pressed Ctrl-C, but the target hasn't
    574      responded to that.  */
    575   bool ctrlc_pending_p = false;
    576 
    577   /* True if we saw a Ctrl-C while reading or writing from/to the
    578      remote descriptor.  At that point it is not safe to send a remote
    579      interrupt packet, so we instead remember we saw the Ctrl-C and
    580      process it once we're done with sending/receiving the current
    581      packet, which should be shortly.  If however that takes too long,
    582      and the user presses Ctrl-C again, we offer to disconnect.  */
    583   bool got_ctrlc_during_io = false;
    584 
    585   /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
    586      remote_open knows that we don't have a file open when the program
    587      starts.  */
    588   struct serial *remote_desc = nullptr;
    589 
    590   /* These are the threads which we last sent to the remote system.  The
    591      TID member will be -1 for all or -2 for not sent yet.  */
    592   ptid_t general_thread = null_ptid;
    593   ptid_t continue_thread = null_ptid;
    594 
    595   /* This is the traceframe which we last selected on the remote system.
    596      It will be -1 if no traceframe is selected.  */
    597   int remote_traceframe_number = -1;
    598 
    599   char *last_pass_packet = nullptr;
    600 
    601   /* The last QProgramSignals packet sent to the target.  We bypass
    602      sending a new program signals list down to the target if the new
    603      packet is exactly the same as the last we sent.  IOW, we only let
    604      the target know about program signals list changes.  */
    605   char *last_program_signals_packet = nullptr;
    606 
    607   /* Similarly, the last QThreadEvents state we sent to the
    608      target.  */
    609   bool last_thread_events = false;
    610 
    611   gdb_signal last_sent_signal = GDB_SIGNAL_0;
    612 
    613   bool last_sent_step = false;
    614 
    615   /* The execution direction of the last resume we got.  */
    616   exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
    617 
    618   char *finished_object = nullptr;
    619   char *finished_annex = nullptr;
    620   ULONGEST finished_offset = 0;
    621 
    622   /* Should we try the 'ThreadInfo' query packet?
    623 
    624      This variable (NOT available to the user: auto-detect only!)
    625      determines whether GDB will use the new, simpler "ThreadInfo"
    626      query or the older, more complex syntax for thread queries.
    627      This is an auto-detect variable (set to true at each connect,
    628      and set to false when the target fails to recognize it).  */
    629   bool use_threadinfo_query = false;
    630   bool use_threadextra_query = false;
    631 
    632   threadref echo_nextthread {};
    633   threadref nextthread {};
    634   threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
    635 
    636   /* The state of remote notification.  */
    637   struct remote_notif_state *notif_state = nullptr;
    638 
    639   /* The branch trace configuration.  */
    640   struct btrace_config btrace_config {};
    641 
    642   /* The argument to the last "vFile:setfs:" packet we sent, used
    643      to avoid sending repeated unnecessary "vFile:setfs:" packets.
    644      Initialized to -1 to indicate that no "vFile:setfs:" packet
    645      has yet been sent.  */
    646   int fs_pid = -1;
    647 
    648   /* A readahead cache for vFile:pread.  Often, reading a binary
    649      involves a sequence of small reads.  E.g., when parsing an ELF
    650      file.  A readahead cache helps mostly the case of remote
    651      debugging on a connection with higher latency, due to the
    652      request/reply nature of the RSP.  We only cache data for a single
    653      file descriptor at a time.  */
    654   struct readahead_cache readahead_cache;
    655 
    656   /* The list of already fetched and acknowledged stop events.  This
    657      queue is used for notification Stop, and other notifications
    658      don't need queue for their events, because the notification
    659      events of Stop can't be consumed immediately, so that events
    660      should be queued first, and be consumed by remote_wait_{ns,as}
    661      one per time.  Other notifications can consume their events
    662      immediately, so queue is not needed for them.  */
    663   std::vector<stop_reply_up> stop_reply_queue;
    664 
    665   /* FIXME: cagney/1999-09-23: Even though getpkt was called with
    666      ``forever'' still use the normal timeout mechanism.  This is
    667      currently used by the ASYNC code to guarentee that target reads
    668      during the initial connect always time-out.  Once getpkt has been
    669      modified to return a timeout indication and, in turn
    670      remote_wait()/wait_for_inferior() have gained a timeout parameter
    671      this can go away.  */
    672   bool wait_forever_enabled_p = true;
    673 
    674   /* The set of thread options the target reported it supports, via
    675      qSupported.  */
    676   gdb_thread_options supported_thread_options = 0;
    677 
    678 private:
    679   /* Asynchronous signal handle registered as event loop source for
    680      when we have pending events ready to be passed to the core.  */
    681   async_event_handler *m_async_event_handler_token = nullptr;
    682 
    683   /* Mapping of remote protocol data for each gdbarch.  Usually there
    684      is only one entry here, though we may see more with stubs that
    685      support multi-process.  */
    686   std::unordered_map<struct gdbarch *, remote_arch_state>
    687     m_arch_states;
    688 };
    689 
    690 static const target_info remote_target_info = {
    691   "remote",
    692   N_("Remote target using gdb-specific protocol"),
    693   remote_doc
    694 };
    695 
    696 /* Description of a remote packet.  */
    697 
    698 struct packet_description
    699 {
    700   /* Name of the packet used for gdb output.  */
    701   const char *name;
    702 
    703   /* Title of the packet, used by the set/show remote name-packet
    704      commands to identify the individual packages and gdb output.  */
    705   const char *title;
    706 };
    707 
    708 /* Configuration of a remote packet.  */
    709 
    710 struct packet_config
    711 {
    712   /* If auto, GDB auto-detects support for this packet or feature,
    713      either through qSupported, or by trying the packet and looking
    714      at the response.  If true, GDB assumes the target supports this
    715      packet.  If false, the packet is disabled.  Configs that don't
    716      have an associated command always have this set to auto.  */
    717   enum auto_boolean detect;
    718 
    719   /* Does the target support this packet?  */
    720   enum packet_support support;
    721 };
    722 
    723 /* User configurable variables for the number of characters in a
    724    memory read/write packet.  MIN (rsa->remote_packet_size,
    725    rsa->sizeof_g_packet) is the default.  Some targets need smaller
    726    values (fifo overruns, et.al.) and some users need larger values
    727    (speed up transfers).  The variables ``preferred_*'' (the user
    728    request), ``current_*'' (what was actually set) and ``forced_*''
    729    (Positive - a soft limit, negative - a hard limit).  */
    730 
    731 struct memory_packet_config
    732 {
    733   const char *name;
    734   long size;
    735   int fixed_p;
    736 };
    737 
    738 /* These global variables contain the default configuration for every new
    739    remote_feature object.  */
    740 static memory_packet_config memory_read_packet_config =
    741 {
    742   "memory-read-packet-size",
    743 };
    744 static memory_packet_config memory_write_packet_config =
    745 {
    746   "memory-write-packet-size",
    747 };
    748 
    749 /* This global array contains packet descriptions (name and title).  */
    750 static packet_description packets_descriptions[PACKET_MAX];
    751 /* This global array contains the default configuration for every new
    752    per-remote target array.  */
    753 static packet_config remote_protocol_packets[PACKET_MAX];
    754 
    755 /* Description of a remote target's features.  It stores the configuration
    756    and provides functions to determine supported features of the target.  */
    757 
    758 struct remote_features
    759 {
    760   remote_features ()
    761   {
    762     m_memory_read_packet_config = memory_read_packet_config;
    763     m_memory_write_packet_config = memory_write_packet_config;
    764 
    765     std::copy (std::begin (remote_protocol_packets),
    766 	       std::end (remote_protocol_packets),
    767 	       std::begin (m_protocol_packets));
    768   }
    769   ~remote_features () = default;
    770 
    771   DISABLE_COPY_AND_ASSIGN (remote_features);
    772 
    773   /* Returns whether a given packet defined by its enum value is supported.  */
    774   enum packet_support packet_support (int) const;
    775 
    776   /* Returns the packet's corresponding "set remote foo-packet" command
    777      state.  See struct packet_config for more details.  */
    778   enum auto_boolean packet_set_cmd_state (int packet) const
    779   { return m_protocol_packets[packet].detect; }
    780 
    781   /* Returns true if the multi-process extensions are in effect.  */
    782   int remote_multi_process_p () const
    783   { return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE; }
    784 
    785   /* Returns true if fork events are supported.  */
    786   int remote_fork_event_p () const
    787   { return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE; }
    788 
    789   /* Returns true if vfork events are supported.  */
    790   int remote_vfork_event_p () const
    791   { return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE; }
    792 
    793   /* Returns true if exec events are supported.  */
    794   int remote_exec_event_p () const
    795   { return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE; }
    796 
    797   /* Returns true if memory tagging is supported, false otherwise.  */
    798   bool remote_memory_tagging_p () const
    799   { return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE; }
    800 
    801   /* Reset all packets back to "unknown support".  Called when opening a
    802      new connection to a remote target.  */
    803   void reset_all_packet_configs_support ();
    804 
    805 /* Check result value in BUF for packet WHICH_PACKET and update the packet's
    806    support configuration accordingly.  */
    807   packet_result packet_ok (const char *buf, const int which_packet);
    808   packet_result packet_ok (const gdb::char_vector &buf, const int which_packet);
    809 
    810   /* Configuration of a remote target's memory read packet.  */
    811   memory_packet_config m_memory_read_packet_config;
    812   /* Configuration of a remote target's memory write packet.  */
    813   memory_packet_config m_memory_write_packet_config;
    814 
    815   /* The per-remote target array which stores a remote's packet
    816      configurations.  */
    817   packet_config m_protocol_packets[PACKET_MAX];
    818 };
    819 
    820 class remote_target : public process_stratum_target
    821 {
    822 public:
    823   remote_target () = default;
    824   ~remote_target () override;
    825 
    826   const target_info &info () const override
    827   { return remote_target_info; }
    828 
    829   const char *connection_string () override;
    830 
    831   thread_control_capabilities get_thread_control_capabilities () override
    832   { return tc_schedlock; }
    833 
    834   /* Open a remote connection.  */
    835   static void open (const char *, int);
    836 
    837   void close () override;
    838 
    839   void detach (inferior *, int) override;
    840   void disconnect (const char *, int) override;
    841 
    842   void commit_requested_thread_options ();
    843 
    844   void commit_resumed () override;
    845   void resume (ptid_t, int, enum gdb_signal) override;
    846   ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
    847   bool has_pending_events () override;
    848 
    849   void fetch_registers (struct regcache *, int) override;
    850   void store_registers (struct regcache *, int) override;
    851   void prepare_to_store (struct regcache *) override;
    852 
    853   int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
    854 
    855   int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
    856 			 enum remove_bp_reason) override;
    857 
    858 
    859   bool stopped_by_sw_breakpoint () override;
    860   bool supports_stopped_by_sw_breakpoint () override;
    861 
    862   bool stopped_by_hw_breakpoint () override;
    863 
    864   bool supports_stopped_by_hw_breakpoint () override;
    865 
    866   bool stopped_by_watchpoint () override;
    867 
    868   bool stopped_data_address (CORE_ADDR *) override;
    869 
    870   bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
    871 
    872   int can_use_hw_breakpoint (enum bptype, int, int) override;
    873 
    874   int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
    875 
    876   int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
    877 
    878   int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
    879 
    880   int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
    881 			 struct expression *) override;
    882 
    883   int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
    884 			 struct expression *) override;
    885 
    886   void kill () override;
    887 
    888   void load (const char *, int) override;
    889 
    890   void mourn_inferior () override;
    891 
    892   void pass_signals (gdb::array_view<const unsigned char>) override;
    893 
    894   int set_syscall_catchpoint (int, bool, int,
    895 			      gdb::array_view<const int>) override;
    896 
    897   void program_signals (gdb::array_view<const unsigned char>) override;
    898 
    899   bool thread_alive (ptid_t ptid) override;
    900 
    901   const char *thread_name (struct thread_info *) override;
    902 
    903   void update_thread_list () override;
    904 
    905   std::string pid_to_str (ptid_t) override;
    906 
    907   const char *extra_thread_info (struct thread_info *) override;
    908 
    909   ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
    910 
    911   thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
    912 					     int handle_len,
    913 					     inferior *inf) override;
    914 
    915   gdb::array_view<const gdb_byte> thread_info_to_thread_handle (struct thread_info *tp)
    916     override;
    917 
    918   void stop (ptid_t) override;
    919 
    920   void interrupt () override;
    921 
    922   void pass_ctrlc () override;
    923 
    924   enum target_xfer_status xfer_partial (enum target_object object,
    925 					const char *annex,
    926 					gdb_byte *readbuf,
    927 					const gdb_byte *writebuf,
    928 					ULONGEST offset, ULONGEST len,
    929 					ULONGEST *xfered_len) override;
    930 
    931   ULONGEST get_memory_xfer_limit () override;
    932 
    933   void rcmd (const char *command, struct ui_file *output) override;
    934 
    935   const char *pid_to_exec_file (int pid) override;
    936 
    937   void log_command (const char *cmd) override
    938   {
    939     serial_log_command (this, cmd);
    940   }
    941 
    942   CORE_ADDR get_thread_local_address (ptid_t ptid,
    943 				      CORE_ADDR load_module_addr,
    944 				      CORE_ADDR offset) override;
    945 
    946   bool can_execute_reverse () override;
    947 
    948   std::vector<mem_region> memory_map () override;
    949 
    950   void flash_erase (ULONGEST address, LONGEST length) override;
    951 
    952   void flash_done () override;
    953 
    954   const struct target_desc *read_description () override;
    955 
    956   int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
    957 		     const gdb_byte *pattern, ULONGEST pattern_len,
    958 		     CORE_ADDR *found_addrp) override;
    959 
    960   bool can_async_p () override;
    961 
    962   bool is_async_p () override;
    963 
    964   void async (bool) override;
    965 
    966   int async_wait_fd () override;
    967 
    968   void thread_events (int) override;
    969 
    970   bool supports_set_thread_options (gdb_thread_options) override;
    971 
    972   int can_do_single_step () override;
    973 
    974   void terminal_inferior () override;
    975 
    976   void terminal_ours () override;
    977 
    978   bool supports_non_stop () override;
    979 
    980   bool supports_multi_process () override;
    981 
    982   bool supports_disable_randomization () override;
    983 
    984   bool filesystem_is_local () override;
    985 
    986 
    987   int fileio_open (struct inferior *inf, const char *filename,
    988 		   int flags, int mode, int warn_if_slow,
    989 		   fileio_error *target_errno) override;
    990 
    991   int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
    992 		     ULONGEST offset, fileio_error *target_errno) override;
    993 
    994   int fileio_pread (int fd, gdb_byte *read_buf, int len,
    995 		    ULONGEST offset, fileio_error *target_errno) override;
    996 
    997   int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
    998 
    999   int fileio_close (int fd, fileio_error *target_errno) override;
   1000 
   1001   int fileio_unlink (struct inferior *inf,
   1002 		     const char *filename,
   1003 		     fileio_error *target_errno) override;
   1004 
   1005   std::optional<std::string>
   1006     fileio_readlink (struct inferior *inf,
   1007 		     const char *filename,
   1008 		     fileio_error *target_errno) override;
   1009 
   1010   bool supports_enable_disable_tracepoint () override;
   1011 
   1012   bool supports_string_tracing () override;
   1013 
   1014   int remote_supports_cond_tracepoints ();
   1015 
   1016   bool supports_evaluation_of_breakpoint_conditions () override;
   1017 
   1018   int remote_supports_fast_tracepoints ();
   1019 
   1020   int remote_supports_static_tracepoints ();
   1021 
   1022   int remote_supports_install_in_trace ();
   1023 
   1024   bool can_run_breakpoint_commands () override;
   1025 
   1026   void trace_init () override;
   1027 
   1028   void download_tracepoint (struct bp_location *location) override;
   1029 
   1030   bool can_download_tracepoint () override;
   1031 
   1032   void download_trace_state_variable (const trace_state_variable &tsv) override;
   1033 
   1034   void enable_tracepoint (struct bp_location *location) override;
   1035 
   1036   void disable_tracepoint (struct bp_location *location) override;
   1037 
   1038   void trace_set_readonly_regions () override;
   1039 
   1040   void trace_start () override;
   1041 
   1042   int get_trace_status (struct trace_status *ts) override;
   1043 
   1044   void get_tracepoint_status (tracepoint *tp, struct uploaded_tp *utp)
   1045     override;
   1046 
   1047   void trace_stop () override;
   1048 
   1049   int trace_find (enum trace_find_type type, int num,
   1050 		  CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
   1051 
   1052   bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
   1053 
   1054   int save_trace_data (const char *filename) override;
   1055 
   1056   int upload_tracepoints (struct uploaded_tp **utpp) override;
   1057 
   1058   int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
   1059 
   1060   LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
   1061 
   1062   int get_min_fast_tracepoint_insn_len () override;
   1063 
   1064   void set_disconnected_tracing (int val) override;
   1065 
   1066   void set_circular_trace_buffer (int val) override;
   1067 
   1068   void set_trace_buffer_size (LONGEST val) override;
   1069 
   1070   bool set_trace_notes (const char *user, const char *notes,
   1071 			const char *stopnotes) override;
   1072 
   1073   int core_of_thread (ptid_t ptid) override;
   1074 
   1075   int verify_memory (const gdb_byte *data,
   1076 		     CORE_ADDR memaddr, ULONGEST size) override;
   1077 
   1078 
   1079   bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
   1080 
   1081   void set_permissions () override;
   1082 
   1083   bool static_tracepoint_marker_at (CORE_ADDR,
   1084 				    struct static_tracepoint_marker *marker)
   1085     override;
   1086 
   1087   std::vector<static_tracepoint_marker>
   1088     static_tracepoint_markers_by_strid (const char *id) override;
   1089 
   1090   traceframe_info_up traceframe_info () override;
   1091 
   1092   bool use_agent (bool use) override;
   1093   bool can_use_agent () override;
   1094 
   1095   struct btrace_target_info *
   1096     enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
   1097 
   1098   void disable_btrace (struct btrace_target_info *tinfo) override;
   1099 
   1100   void teardown_btrace (struct btrace_target_info *tinfo) override;
   1101 
   1102   enum btrace_error read_btrace (struct btrace_data *data,
   1103 				 struct btrace_target_info *btinfo,
   1104 				 enum btrace_read_type type) override;
   1105 
   1106   const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
   1107   bool augmented_libraries_svr4_read () override;
   1108   void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
   1109   void follow_clone (ptid_t child_ptid) override;
   1110   void follow_exec (inferior *, ptid_t, const char *) override;
   1111   int insert_fork_catchpoint (int) override;
   1112   int remove_fork_catchpoint (int) override;
   1113   int insert_vfork_catchpoint (int) override;
   1114   int remove_vfork_catchpoint (int) override;
   1115   int insert_exec_catchpoint (int) override;
   1116   int remove_exec_catchpoint (int) override;
   1117   enum exec_direction_kind execution_direction () override;
   1118 
   1119   bool supports_memory_tagging () override;
   1120 
   1121   bool fetch_memtags (CORE_ADDR address, size_t len,
   1122 		      gdb::byte_vector &tags, int type) override;
   1123 
   1124   bool store_memtags (CORE_ADDR address, size_t len,
   1125 		      const gdb::byte_vector &tags, int type) override;
   1126 
   1127   bool is_address_tagged (gdbarch *gdbarch, CORE_ADDR address) override;
   1128 
   1129 public: /* Remote specific methods.  */
   1130 
   1131   void remote_download_command_source (int num, ULONGEST addr,
   1132 				       struct command_line *cmds);
   1133 
   1134   void remote_file_put (const char *local_file, const char *remote_file,
   1135 			int from_tty);
   1136   void remote_file_get (const char *remote_file, const char *local_file,
   1137 			int from_tty);
   1138   void remote_file_delete (const char *remote_file, int from_tty);
   1139 
   1140   int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
   1141 			   ULONGEST offset, fileio_error *remote_errno);
   1142   int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
   1143 			    ULONGEST offset, fileio_error *remote_errno);
   1144   int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
   1145 				 ULONGEST offset, fileio_error *remote_errno);
   1146 
   1147   int remote_hostio_send_command (int command_bytes, int which_packet,
   1148 				  fileio_error *remote_errno, const char **attachment,
   1149 				  int *attachment_len);
   1150   int remote_hostio_set_filesystem (struct inferior *inf,
   1151 				    fileio_error *remote_errno);
   1152   /* We should get rid of this and use fileio_open directly.  */
   1153   int remote_hostio_open (struct inferior *inf, const char *filename,
   1154 			  int flags, int mode, int warn_if_slow,
   1155 			  fileio_error *remote_errno);
   1156   int remote_hostio_close (int fd, fileio_error *remote_errno);
   1157 
   1158   int remote_hostio_unlink (inferior *inf, const char *filename,
   1159 			    fileio_error *remote_errno);
   1160 
   1161   struct remote_state *get_remote_state ();
   1162 
   1163   long get_remote_packet_size (void);
   1164   long get_memory_packet_size (struct memory_packet_config *config);
   1165 
   1166   long get_memory_write_packet_size ();
   1167   long get_memory_read_packet_size ();
   1168 
   1169   char *append_pending_thread_resumptions (char *p, char *endp,
   1170 					   ptid_t ptid);
   1171   static void open_1 (const char *name, int from_tty, int extended_p);
   1172   void start_remote (int from_tty, int extended_p);
   1173   void remote_detach_1 (struct inferior *inf, int from_tty);
   1174 
   1175   char *append_resumption (char *p, char *endp,
   1176 			   ptid_t ptid, int step, gdb_signal siggnal);
   1177   int remote_resume_with_vcont (ptid_t scope_ptid, int step,
   1178 				gdb_signal siggnal);
   1179 
   1180   thread_info *add_current_inferior_and_thread (const char *wait_status);
   1181 
   1182   ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
   1183 		  target_wait_flags options);
   1184   ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
   1185 		  target_wait_flags options);
   1186 
   1187   ptid_t process_stop_reply (stop_reply_up stop_reply,
   1188 			     target_waitstatus *status);
   1189 
   1190   ptid_t select_thread_for_ambiguous_stop_reply
   1191     (const struct target_waitstatus &status);
   1192 
   1193   void remote_notice_new_inferior (ptid_t currthread, bool executing);
   1194 
   1195   void print_one_stopped_thread (thread_info *thread);
   1196   void process_initial_stop_replies (int from_tty);
   1197 
   1198   thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
   1199 				  bool silent_p);
   1200 
   1201   void btrace_sync_conf (const btrace_config *conf);
   1202 
   1203   void remote_btrace_maybe_reopen ();
   1204 
   1205   void remove_new_children (threads_listing_context *context);
   1206   void kill_new_fork_children (inferior *inf);
   1207   void discard_pending_stop_replies (struct inferior *inf);
   1208   int stop_reply_queue_length ();
   1209 
   1210   void check_pending_events_prevent_wildcard_vcont
   1211     (bool *may_global_wildcard_vcont);
   1212 
   1213   void discard_pending_stop_replies_in_queue ();
   1214   stop_reply_up remote_notif_remove_queued_reply (ptid_t ptid);
   1215   stop_reply_up queued_stop_reply (ptid_t ptid);
   1216   int peek_stop_reply (ptid_t ptid);
   1217   void remote_parse_stop_reply (const char *buf, stop_reply *event);
   1218 
   1219   void remote_stop_ns (ptid_t ptid);
   1220   void remote_interrupt_as ();
   1221   void remote_interrupt_ns ();
   1222 
   1223   char *remote_get_noisy_reply ();
   1224   int remote_query_attached (int pid);
   1225   inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
   1226 				 int try_open_exec);
   1227 
   1228   ptid_t remote_current_thread (ptid_t oldpid);
   1229   ptid_t get_current_thread (const char *wait_status);
   1230 
   1231   void set_thread (ptid_t ptid, int gen);
   1232   void set_general_thread (ptid_t ptid);
   1233   void set_continue_thread (ptid_t ptid);
   1234   void set_general_process ();
   1235 
   1236   char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
   1237 
   1238   int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
   1239 					  gdb_ext_thread_info *info);
   1240   int remote_get_threadinfo (threadref *threadid, int fieldset,
   1241 			     gdb_ext_thread_info *info);
   1242 
   1243   int parse_threadlist_response (const char *pkt, int result_limit,
   1244 				 threadref *original_echo,
   1245 				 threadref *resultlist,
   1246 				 int *doneflag);
   1247   int remote_get_threadlist (int startflag, threadref *nextthread,
   1248 			     int result_limit, int *done, int *result_count,
   1249 			     threadref *threadlist);
   1250 
   1251   int remote_threadlist_iterator (rmt_thread_action stepfunction,
   1252 				  void *context, int looplimit);
   1253 
   1254   int remote_get_threads_with_ql (threads_listing_context *context);
   1255   int remote_get_threads_with_qxfer (threads_listing_context *context);
   1256   int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
   1257 
   1258   void extended_remote_restart ();
   1259 
   1260   void get_offsets ();
   1261 
   1262   void remote_check_symbols ();
   1263 
   1264   void remote_supported_packet (const struct protocol_feature *feature,
   1265 				enum packet_support support,
   1266 				const char *argument);
   1267 
   1268   void remote_query_supported ();
   1269 
   1270   void remote_packet_size (const protocol_feature *feature,
   1271 			   packet_support support, const char *value);
   1272   void remote_supported_thread_options (const protocol_feature *feature,
   1273 					enum packet_support support,
   1274 					const char *value);
   1275 
   1276   void remote_serial_quit_handler ();
   1277 
   1278   void remote_detach_pid (int pid);
   1279 
   1280   void remote_vcont_probe ();
   1281 
   1282   void remote_resume_with_hc (ptid_t ptid, int step,
   1283 			      gdb_signal siggnal);
   1284 
   1285   void send_interrupt_sequence ();
   1286   void interrupt_query ();
   1287 
   1288   void remote_notif_get_pending_events (const notif_client *nc);
   1289 
   1290   int fetch_register_using_p (struct regcache *regcache,
   1291 			      packet_reg *reg);
   1292   int send_g_packet ();
   1293   void process_g_packet (struct regcache *regcache);
   1294   void fetch_registers_using_g (struct regcache *regcache);
   1295   int store_register_using_P (const struct regcache *regcache,
   1296 			      packet_reg *reg);
   1297   void store_registers_using_G (const struct regcache *regcache);
   1298 
   1299   void set_remote_traceframe ();
   1300 
   1301   void check_binary_download (CORE_ADDR addr);
   1302 
   1303   target_xfer_status remote_write_bytes_aux (const char *header,
   1304 					     CORE_ADDR memaddr,
   1305 					     const gdb_byte *myaddr,
   1306 					     ULONGEST len_units,
   1307 					     int unit_size,
   1308 					     ULONGEST *xfered_len_units,
   1309 					     char packet_format,
   1310 					     int use_length);
   1311 
   1312   target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
   1313 					 const gdb_byte *myaddr, ULONGEST len,
   1314 					 int unit_size, ULONGEST *xfered_len);
   1315 
   1316   target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
   1317 					  ULONGEST len_units,
   1318 					  int unit_size, ULONGEST *xfered_len_units);
   1319 
   1320   target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
   1321 							ULONGEST memaddr,
   1322 							ULONGEST len,
   1323 							int unit_size,
   1324 							ULONGEST *xfered_len);
   1325 
   1326   target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
   1327 					gdb_byte *myaddr, ULONGEST len,
   1328 					int unit_size,
   1329 					ULONGEST *xfered_len);
   1330 
   1331   packet_status remote_send_printf (const char *format, ...)
   1332     ATTRIBUTE_PRINTF (2, 3);
   1333 
   1334   target_xfer_status remote_flash_write (ULONGEST address,
   1335 					 ULONGEST length, ULONGEST *xfered_len,
   1336 					 const gdb_byte *data);
   1337 
   1338   int readchar (int timeout);
   1339 
   1340   void remote_serial_write (const char *str, int len);
   1341   void remote_serial_send_break ();
   1342 
   1343   int putpkt (const char *buf);
   1344   int putpkt_binary (const char *buf, int cnt);
   1345 
   1346   int putpkt (const gdb::char_vector &buf)
   1347   {
   1348     return putpkt (buf.data ());
   1349   }
   1350 
   1351   void skip_frame ();
   1352   long read_frame (gdb::char_vector *buf_p);
   1353   int getpkt (gdb::char_vector *buf, bool forever = false,
   1354 	      bool *is_notif = nullptr);
   1355   int remote_vkill (int pid);
   1356   void remote_kill_k ();
   1357 
   1358   void extended_remote_disable_randomization (int val);
   1359   int extended_remote_run (const std::string &args);
   1360 
   1361   void send_environment_packet (const char *action,
   1362 				const char *packet,
   1363 				const char *value);
   1364 
   1365   void extended_remote_environment_support ();
   1366   void extended_remote_set_inferior_cwd ();
   1367 
   1368   target_xfer_status remote_write_qxfer (const char *object_name,
   1369 					 const char *annex,
   1370 					 const gdb_byte *writebuf,
   1371 					 ULONGEST offset, LONGEST len,
   1372 					 ULONGEST *xfered_len,
   1373 					 const unsigned int which_packet);
   1374 
   1375   target_xfer_status remote_read_qxfer (const char *object_name,
   1376 					const char *annex,
   1377 					gdb_byte *readbuf, ULONGEST offset,
   1378 					LONGEST len,
   1379 					ULONGEST *xfered_len,
   1380 					const unsigned int which_packet);
   1381 
   1382   void push_stop_reply (stop_reply_up new_event);
   1383 
   1384   bool vcont_r_supported ();
   1385 
   1386   remote_features m_features;
   1387 
   1388 private:
   1389 
   1390   bool start_remote_1 (int from_tty, int extended_p);
   1391 
   1392   /* The remote state.  Don't reference this directly.  Use the
   1393      get_remote_state method instead.  */
   1394   remote_state m_remote_state;
   1395 };
   1396 
   1397 static const target_info extended_remote_target_info = {
   1398   "extended-remote",
   1399   N_("Extended remote target using gdb-specific protocol"),
   1400   remote_doc
   1401 };
   1402 
   1403 /* Set up the extended remote target by extending the standard remote
   1404    target and adding to it.  */
   1405 
   1406 class extended_remote_target final : public remote_target
   1407 {
   1408 public:
   1409   const target_info &info () const override
   1410   { return extended_remote_target_info; }
   1411 
   1412   /* Open an extended-remote connection.  */
   1413   static void open (const char *, int);
   1414 
   1415   bool can_create_inferior () override { return true; }
   1416   void create_inferior (const char *, const std::string &,
   1417 			char **, int) override;
   1418 
   1419   void detach (inferior *, int) override;
   1420 
   1421   bool can_attach () override { return true; }
   1422   void attach (const char *, int) override;
   1423 
   1424   void post_attach (int) override;
   1425   bool supports_disable_randomization () override;
   1426 };
   1427 
   1428 struct stop_reply : public notif_event
   1429 {
   1430   /* The identifier of the thread about this event  */
   1431   ptid_t ptid;
   1432 
   1433   /* The remote state this event is associated with.  When the remote
   1434      connection, represented by a remote_state object, is closed,
   1435      all the associated stop_reply events should be released.  */
   1436   struct remote_state *rs;
   1437 
   1438   struct target_waitstatus ws;
   1439 
   1440   /* The architecture associated with the expedited registers.  */
   1441   gdbarch *arch;
   1442 
   1443   /* Expedited registers.  This makes remote debugging a bit more
   1444      efficient for those targets that provide critical registers as
   1445      part of their normal status mechanism (as another roundtrip to
   1446      fetch them is avoided).  */
   1447   std::vector<cached_reg_t> regcache;
   1448 
   1449   enum target_stop_reason stop_reason;
   1450 
   1451   CORE_ADDR watch_data_address;
   1452 
   1453   int core;
   1454 };
   1455 
   1456 /* Return TARGET as a remote_target if it is one, else nullptr.  */
   1457 
   1458 static remote_target *
   1459 as_remote_target (process_stratum_target *target)
   1460 {
   1461   return dynamic_cast<remote_target *> (target);
   1462 }
   1463 
   1464 /* See remote.h.  */
   1465 
   1466 bool
   1467 is_remote_target (process_stratum_target *target)
   1468 {
   1469   return as_remote_target (target) != nullptr;
   1470 }
   1471 
   1472 /* Per-program-space data key.  */
   1473 static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
   1474   remote_pspace_data;
   1475 
   1476 /* The variable registered as the control variable used by the
   1477    remote exec-file commands.  While the remote exec-file setting is
   1478    per-program-space, the set/show machinery uses this as the
   1479    location of the remote exec-file value.  */
   1480 static std::string remote_exec_file_var;
   1481 
   1482 /* The size to align memory write packets, when practical.  The protocol
   1483    does not guarantee any alignment, and gdb will generate short
   1484    writes and unaligned writes, but even as a best-effort attempt this
   1485    can improve bulk transfers.  For instance, if a write is misaligned
   1486    relative to the target's data bus, the stub may need to make an extra
   1487    round trip fetching data from the target.  This doesn't make a
   1488    huge difference, but it's easy to do, so we try to be helpful.
   1489 
   1490    The alignment chosen is arbitrary; usually data bus width is
   1491    important here, not the possibly larger cache line size.  */
   1492 enum { REMOTE_ALIGN_WRITES = 16 };
   1493 
   1494 /* Prototypes for local functions.  */
   1495 
   1496 static int hexnumlen (ULONGEST num);
   1497 
   1498 static int stubhex (int ch);
   1499 
   1500 static int hexnumstr (char *, ULONGEST);
   1501 
   1502 static int hexnumnstr (char *, ULONGEST, int);
   1503 
   1504 static CORE_ADDR remote_address_masked (CORE_ADDR);
   1505 
   1506 static int stub_unpack_int (const char *buff, int fieldlength);
   1507 
   1508 static void set_remote_protocol_packet_cmd (const char *args, int from_tty,
   1509 					    cmd_list_element *c);
   1510 
   1511 static void show_packet_config_cmd (ui_file *file,
   1512 				    const unsigned int which_packet,
   1513 				    remote_target *remote);
   1514 
   1515 static void show_remote_protocol_packet_cmd (struct ui_file *file,
   1516 					     int from_tty,
   1517 					     struct cmd_list_element *c,
   1518 					     const char *value);
   1519 
   1520 static ptid_t read_ptid (const char *buf, const char **obuf);
   1521 
   1522 static bool remote_read_description_p (struct target_ops *target);
   1523 
   1524 static void remote_console_output (const char *msg, ui_file *stream);
   1525 
   1526 static void remote_btrace_reset (remote_state *rs);
   1527 
   1528 static void remote_unpush_and_throw (remote_target *target);
   1529 
   1530 /* For "remote".  */
   1531 
   1532 static struct cmd_list_element *remote_cmdlist;
   1533 
   1534 /* For "set remote" and "show remote".  */
   1535 
   1536 static struct cmd_list_element *remote_set_cmdlist;
   1537 static struct cmd_list_element *remote_show_cmdlist;
   1538 
   1539 /* Controls whether GDB is willing to use range stepping.  */
   1540 
   1541 static bool use_range_stepping = true;
   1542 
   1543 /* From the remote target's point of view, each thread is in one of these three
   1544    states.  */
   1545 enum class resume_state
   1546 {
   1547   /* Not resumed - we haven't been asked to resume this thread.  */
   1548   NOT_RESUMED,
   1549 
   1550   /* We have been asked to resume this thread, but haven't sent a vCont action
   1551      for it yet.  We'll need to consider it next time commit_resume is
   1552      called.  */
   1553   RESUMED_PENDING_VCONT,
   1554 
   1555   /* We have been asked to resume this thread, and we have sent a vCont action
   1556      for it.  */
   1557   RESUMED,
   1558 };
   1559 
   1560 /* Information about a thread's pending vCont-resume.  Used when a thread is in
   1561    the remote_resume_state::RESUMED_PENDING_VCONT state.  remote_target::resume
   1562    stores this information which is then picked up by
   1563    remote_target::commit_resume to know which is the proper action for this
   1564    thread to include in the vCont packet.  */
   1565 struct resumed_pending_vcont_info
   1566 {
   1567   /* True if the last resume call for this thread was a step request, false
   1568      if a continue request.  */
   1569   bool step;
   1570 
   1571   /* The signal specified in the last resume call for this thread.  */
   1572   gdb_signal sig;
   1573 };
   1574 
   1575 /* Private data that we'll store in (struct thread_info)->priv.  */
   1576 struct remote_thread_info : public private_thread_info
   1577 {
   1578   std::string extra;
   1579   std::string name;
   1580   int core = -1;
   1581 
   1582   /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
   1583      sequence of bytes.  */
   1584   gdb::byte_vector thread_handle;
   1585 
   1586   /* Whether the target stopped for a breakpoint/watchpoint.  */
   1587   enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
   1588 
   1589   /* This is set to the data address of the access causing the target
   1590      to stop for a watchpoint.  */
   1591   CORE_ADDR watch_data_address = 0;
   1592 
   1593   /* Get the thread's resume state.  */
   1594   enum resume_state get_resume_state () const
   1595   {
   1596     return m_resume_state;
   1597   }
   1598 
   1599   /* Put the thread in the NOT_RESUMED state.  */
   1600   void set_not_resumed ()
   1601   {
   1602     m_resume_state = resume_state::NOT_RESUMED;
   1603   }
   1604 
   1605   /* Put the thread in the RESUMED_PENDING_VCONT state.  */
   1606   void set_resumed_pending_vcont (bool step, gdb_signal sig)
   1607   {
   1608     m_resume_state = resume_state::RESUMED_PENDING_VCONT;
   1609     m_resumed_pending_vcont_info.step = step;
   1610     m_resumed_pending_vcont_info.sig = sig;
   1611   }
   1612 
   1613   /* Get the information this thread's pending vCont-resumption.
   1614 
   1615      Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
   1616      state.  */
   1617   const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
   1618   {
   1619     gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
   1620 
   1621     return m_resumed_pending_vcont_info;
   1622   }
   1623 
   1624   /* Put the thread in the VCONT_RESUMED state.  */
   1625   void set_resumed ()
   1626   {
   1627     m_resume_state = resume_state::RESUMED;
   1628   }
   1629 
   1630 private:
   1631   /* Resume state for this thread.  This is used to implement vCont action
   1632      coalescing (only when the target operates in non-stop mode).
   1633 
   1634      remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
   1635      which notes that this thread must be considered in the next commit_resume
   1636      call.
   1637 
   1638      remote_target::commit_resume sends a vCont packet with actions for the
   1639      threads in the RESUMED_PENDING_VCONT state and moves them to the
   1640      VCONT_RESUMED state.
   1641 
   1642      When reporting a stop to the core for a thread, that thread is moved back
   1643      to the NOT_RESUMED state.  */
   1644   enum resume_state m_resume_state = resume_state::NOT_RESUMED;
   1645 
   1646   /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state.  */
   1647   struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
   1648 };
   1649 
   1650 remote_state::remote_state ()
   1651   : buf (400)
   1652 {
   1653 }
   1654 
   1655 remote_state::~remote_state ()
   1656 {
   1657   xfree (this->last_pass_packet);
   1658   xfree (this->last_program_signals_packet);
   1659   xfree (this->finished_object);
   1660   xfree (this->finished_annex);
   1661 }
   1662 
   1663 /* Utility: generate error from an incoming stub packet.  */
   1664 static void
   1665 trace_error (char *buf)
   1666 {
   1667   if (*buf++ != 'E')
   1668     return;			/* not an error msg */
   1669   switch (*buf)
   1670     {
   1671     case '1':			/* malformed packet error */
   1672       if (*++buf == '0')	/*   general case: */
   1673 	error (_("remote.c: error in outgoing packet."));
   1674       else
   1675 	error (_("remote.c: error in outgoing packet at field #%ld."),
   1676 	       strtol (buf, NULL, 16));
   1677     default:
   1678       error (_("Target returns error code '%s'."), buf);
   1679     }
   1680 }
   1681 
   1682 /* Utility: wait for reply from stub, while accepting "O" packets.  */
   1683 
   1684 char *
   1685 remote_target::remote_get_noisy_reply ()
   1686 {
   1687   struct remote_state *rs = get_remote_state ();
   1688 
   1689   do				/* Loop on reply from remote stub.  */
   1690     {
   1691       char *buf;
   1692 
   1693       QUIT;			/* Allow user to bail out with ^C.  */
   1694       getpkt (&rs->buf);
   1695       buf = rs->buf.data ();
   1696       if (buf[0] == 'E')
   1697 	trace_error (buf);
   1698       else if (startswith (buf, "qRelocInsn:"))
   1699 	{
   1700 	  ULONGEST ul;
   1701 	  CORE_ADDR from, to, org_to;
   1702 	  const char *p, *pp;
   1703 	  int adjusted_size = 0;
   1704 	  int relocated = 0;
   1705 
   1706 	  p = buf + strlen ("qRelocInsn:");
   1707 	  pp = unpack_varlen_hex (p, &ul);
   1708 	  if (*pp != ';')
   1709 	    error (_("invalid qRelocInsn packet: %s"), buf);
   1710 	  from = ul;
   1711 
   1712 	  p = pp + 1;
   1713 	  unpack_varlen_hex (p, &ul);
   1714 	  to = ul;
   1715 
   1716 	  org_to = to;
   1717 
   1718 	  try
   1719 	    {
   1720 	      gdbarch_relocate_instruction (current_inferior ()->arch (),
   1721 					    &to, from);
   1722 	      relocated = 1;
   1723 	    }
   1724 	  catch (const gdb_exception &ex)
   1725 	    {
   1726 	      if (ex.error == MEMORY_ERROR)
   1727 		{
   1728 		  /* Propagate memory errors silently back to the
   1729 		     target.  The stub may have limited the range of
   1730 		     addresses we can write to, for example.  */
   1731 		}
   1732 	      else
   1733 		{
   1734 		  /* Something unexpectedly bad happened.  Be verbose
   1735 		     so we can tell what, and propagate the error back
   1736 		     to the stub, so it doesn't get stuck waiting for
   1737 		     a response.  */
   1738 		  exception_fprintf (gdb_stderr, ex,
   1739 				     _("warning: relocating instruction: "));
   1740 		}
   1741 	      putpkt ("E01");
   1742 	    }
   1743 
   1744 	  if (relocated)
   1745 	    {
   1746 	      adjusted_size = to - org_to;
   1747 
   1748 	      xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
   1749 	      putpkt (buf);
   1750 	    }
   1751 	}
   1752       else if (buf[0] == 'O' && buf[1] != 'K')
   1753 	{
   1754 	  /* 'O' message from stub */
   1755 	  remote_console_output (buf + 1, gdb_stdtarg);
   1756 	}
   1757       else
   1758 	return buf;		/* Here's the actual reply.  */
   1759     }
   1760   while (1);
   1761 }
   1762 
   1763 struct remote_arch_state *
   1764 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
   1765 {
   1766   remote_arch_state *rsa;
   1767 
   1768   auto it = this->m_arch_states.find (gdbarch);
   1769   if (it == this->m_arch_states.end ())
   1770     {
   1771       auto p = this->m_arch_states.emplace (std::piecewise_construct,
   1772 					    std::forward_as_tuple (gdbarch),
   1773 					    std::forward_as_tuple (gdbarch));
   1774       rsa = &p.first->second;
   1775 
   1776       /* Make sure that the packet buffer is plenty big enough for
   1777 	 this architecture.  */
   1778       if (this->buf.size () < rsa->remote_packet_size)
   1779 	this->buf.resize (2 * rsa->remote_packet_size);
   1780     }
   1781   else
   1782     rsa = &it->second;
   1783 
   1784   return rsa;
   1785 }
   1786 
   1787 /* Fetch the global remote target state.  */
   1788 
   1789 remote_state *
   1790 remote_target::get_remote_state ()
   1791 {
   1792   /* Make sure that the remote architecture state has been
   1793      initialized, because doing so might reallocate rs->buf.  Any
   1794      function which calls getpkt also needs to be mindful of changes
   1795      to rs->buf, but this call limits the number of places which run
   1796      into trouble.  */
   1797   m_remote_state.get_remote_arch_state (current_inferior ()->arch ());
   1798 
   1799   return &m_remote_state;
   1800 }
   1801 
   1802 /* Fetch the remote exec-file from the current program space.  */
   1803 
   1804 static const char *
   1805 get_remote_exec_file (void)
   1806 {
   1807   char *remote_exec_file;
   1808 
   1809   remote_exec_file = remote_pspace_data.get (current_program_space);
   1810   if (remote_exec_file == NULL)
   1811     return "";
   1812 
   1813   return remote_exec_file;
   1814 }
   1815 
   1816 /* Set the remote exec file for PSPACE.  */
   1817 
   1818 static void
   1819 set_pspace_remote_exec_file (struct program_space *pspace,
   1820 			     const char *remote_exec_file)
   1821 {
   1822   char *old_file = remote_pspace_data.get (pspace);
   1823 
   1824   xfree (old_file);
   1825   remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
   1826 }
   1827 
   1828 /* The "set/show remote exec-file" set command hook.  */
   1829 
   1830 static void
   1831 set_remote_exec_file (const char *ignored, int from_tty,
   1832 		      struct cmd_list_element *c)
   1833 {
   1834   set_pspace_remote_exec_file (current_program_space,
   1835 			       remote_exec_file_var.c_str ());
   1836 }
   1837 
   1838 /* The "set/show remote exec-file" show command hook.  */
   1839 
   1840 static void
   1841 show_remote_exec_file (struct ui_file *file, int from_tty,
   1842 		       struct cmd_list_element *cmd, const char *value)
   1843 {
   1844   gdb_printf (file, "%s\n", get_remote_exec_file ());
   1845 }
   1846 
   1847 static int
   1848 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
   1849 {
   1850   int regnum, num_remote_regs, offset;
   1851   struct packet_reg **remote_regs;
   1852 
   1853   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
   1854     {
   1855       struct packet_reg *r = &regs[regnum];
   1856 
   1857       if (register_size (gdbarch, regnum) == 0)
   1858 	/* Do not try to fetch zero-sized (placeholder) registers.  */
   1859 	r->pnum = -1;
   1860       else
   1861 	r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
   1862 
   1863       r->regnum = regnum;
   1864     }
   1865 
   1866   /* Define the g/G packet format as the contents of each register
   1867      with a remote protocol number, in order of ascending protocol
   1868      number.  */
   1869 
   1870   remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
   1871   for (num_remote_regs = 0, regnum = 0;
   1872        regnum < gdbarch_num_regs (gdbarch);
   1873        regnum++)
   1874     if (regs[regnum].pnum != -1)
   1875       remote_regs[num_remote_regs++] = &regs[regnum];
   1876 
   1877   std::sort (remote_regs, remote_regs + num_remote_regs,
   1878 	     [] (const packet_reg *a, const packet_reg *b)
   1879 	      { return a->pnum < b->pnum; });
   1880 
   1881   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
   1882     {
   1883       remote_regs[regnum]->in_g_packet = 1;
   1884       remote_regs[regnum]->offset = offset;
   1885       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
   1886     }
   1887 
   1888   return offset;
   1889 }
   1890 
   1891 /* Given the architecture described by GDBARCH, return the remote
   1892    protocol register's number and the register's offset in the g/G
   1893    packets of GDB register REGNUM, in PNUM and POFFSET respectively.
   1894    If the target does not have a mapping for REGNUM, return false,
   1895    otherwise, return true.  */
   1896 
   1897 int
   1898 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
   1899 				   int *pnum, int *poffset)
   1900 {
   1901   gdb_assert (regnum < gdbarch_num_regs (gdbarch));
   1902 
   1903   std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
   1904 
   1905   map_regcache_remote_table (gdbarch, regs.data ());
   1906 
   1907   *pnum = regs[regnum].pnum;
   1908   *poffset = regs[regnum].offset;
   1909 
   1910   return *pnum != -1;
   1911 }
   1912 
   1913 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
   1914 {
   1915   /* Use the architecture to build a regnum<->pnum table, which will be
   1916      1:1 unless a feature set specifies otherwise.  */
   1917   this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
   1918 
   1919   /* Record the maximum possible size of the g packet - it may turn out
   1920      to be smaller.  */
   1921   this->sizeof_g_packet
   1922     = map_regcache_remote_table (gdbarch, this->regs.get ());
   1923 
   1924   /* Default maximum number of characters in a packet body.  Many
   1925      remote stubs have a hardwired buffer size of 400 bytes
   1926      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
   1927      as the maximum packet-size to ensure that the packet and an extra
   1928      NUL character can always fit in the buffer.  This stops GDB
   1929      trashing stubs that try to squeeze an extra NUL into what is
   1930      already a full buffer (As of 1999-12-04 that was most stubs).  */
   1931   this->remote_packet_size = 400 - 1;
   1932 
   1933   /* This one is filled in when a ``g'' packet is received.  */
   1934   this->actual_register_packet_size = 0;
   1935 
   1936   /* Should rsa->sizeof_g_packet needs more space than the
   1937      default, adjust the size accordingly.  Remember that each byte is
   1938      encoded as two characters.  32 is the overhead for the packet
   1939      header / footer.  NOTE: cagney/1999-10-26: I suspect that 8
   1940      (``$NN:G...#NN'') is a better guess, the below has been padded a
   1941      little.  */
   1942   if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
   1943     this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
   1944 }
   1945 
   1946 /* Get a pointer to the current remote target.  If not connected to a
   1947    remote target, return NULL.  */
   1948 
   1949 static remote_target *
   1950 get_current_remote_target ()
   1951 {
   1952   target_ops *proc_target = current_inferior ()->process_target ();
   1953   return dynamic_cast<remote_target *> (proc_target);
   1954 }
   1955 
   1956 /* Return the current allowed size of a remote packet.  This is
   1957    inferred from the current architecture, and should be used to
   1958    limit the length of outgoing packets.  */
   1959 long
   1960 remote_target::get_remote_packet_size ()
   1961 {
   1962   struct remote_state *rs = get_remote_state ();
   1963   remote_arch_state *rsa
   1964     = rs->get_remote_arch_state (current_inferior ()->arch ());
   1965 
   1966   if (rs->explicit_packet_size)
   1967     return rs->explicit_packet_size;
   1968 
   1969   return rsa->remote_packet_size;
   1970 }
   1971 
   1972 static struct packet_reg *
   1973 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
   1974 			long regnum)
   1975 {
   1976   if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
   1977     return NULL;
   1978   else
   1979     {
   1980       struct packet_reg *r = &rsa->regs[regnum];
   1981 
   1982       gdb_assert (r->regnum == regnum);
   1983       return r;
   1984     }
   1985 }
   1986 
   1987 static struct packet_reg *
   1988 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
   1989 		      LONGEST pnum)
   1990 {
   1991   int i;
   1992 
   1993   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
   1994     {
   1995       struct packet_reg *r = &rsa->regs[i];
   1996 
   1997       if (r->pnum == pnum)
   1998 	return r;
   1999     }
   2000   return NULL;
   2001 }
   2002 
   2003 /* Allow the user to specify what sequence to send to the remote
   2004    when he requests a program interruption: Although ^C is usually
   2005    what remote systems expect (this is the default, here), it is
   2006    sometimes preferable to send a break.  On other systems such
   2007    as the Linux kernel, a break followed by g, which is Magic SysRq g
   2008    is required in order to interrupt the execution.  */
   2009 const char interrupt_sequence_control_c[] = "Ctrl-C";
   2010 const char interrupt_sequence_break[] = "BREAK";
   2011 const char interrupt_sequence_break_g[] = "BREAK-g";
   2012 static const char *const interrupt_sequence_modes[] =
   2013   {
   2014     interrupt_sequence_control_c,
   2015     interrupt_sequence_break,
   2016     interrupt_sequence_break_g,
   2017     NULL
   2018   };
   2019 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
   2020 
   2021 static void
   2022 show_interrupt_sequence (struct ui_file *file, int from_tty,
   2023 			 struct cmd_list_element *c,
   2024 			 const char *value)
   2025 {
   2026   if (interrupt_sequence_mode == interrupt_sequence_control_c)
   2027     gdb_printf (file,
   2028 		_("Send the ASCII ETX character (Ctrl-c) "
   2029 		  "to the remote target to interrupt the "
   2030 		  "execution of the program.\n"));
   2031   else if (interrupt_sequence_mode == interrupt_sequence_break)
   2032     gdb_printf (file,
   2033 		_("send a break signal to the remote target "
   2034 		  "to interrupt the execution of the program.\n"));
   2035   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
   2036     gdb_printf (file,
   2037 		_("Send a break signal and 'g' a.k.a. Magic SysRq g to "
   2038 		  "the remote target to interrupt the execution "
   2039 		  "of Linux kernel.\n"));
   2040   else
   2041     internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
   2042 		    interrupt_sequence_mode);
   2043 }
   2044 
   2045 /* This boolean variable specifies whether interrupt_sequence is sent
   2046    to the remote target when gdb connects to it.
   2047    This is mostly needed when you debug the Linux kernel: The Linux kernel
   2048    expects BREAK g which is Magic SysRq g for connecting gdb.  */
   2049 static bool interrupt_on_connect = false;
   2050 
   2051 /* This variable is used to implement the "set/show remotebreak" commands.
   2052    Since these commands are now deprecated in favor of "set/show remote
   2053    interrupt-sequence", it no longer has any effect on the code.  */
   2054 static bool remote_break;
   2055 
   2056 static void
   2057 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
   2058 {
   2059   if (remote_break)
   2060     interrupt_sequence_mode = interrupt_sequence_break;
   2061   else
   2062     interrupt_sequence_mode = interrupt_sequence_control_c;
   2063 }
   2064 
   2065 static void
   2066 show_remotebreak (struct ui_file *file, int from_tty,
   2067 		  struct cmd_list_element *c,
   2068 		  const char *value)
   2069 {
   2070 }
   2071 
   2072 /* This variable sets the number of bits in an address that are to be
   2073    sent in a memory ("M" or "m") packet.  Normally, after stripping
   2074    leading zeros, the entire address would be sent.  This variable
   2075    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
   2076    initial implementation of remote.c restricted the address sent in
   2077    memory packets to ``host::sizeof long'' bytes - (typically 32
   2078    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
   2079    address was never sent.  Since fixing this bug may cause a break in
   2080    some remote targets this variable is principally provided to
   2081    facilitate backward compatibility.  */
   2082 
   2083 static unsigned int remote_address_size;
   2084 
   2085 
   2086 /* The default max memory-write-packet-size, when the setting is
   2088    "fixed".  The 16k is historical.  (It came from older GDB's using
   2089    alloca for buffers and the knowledge (folklore?) that some hosts
   2090    don't cope very well with large alloca calls.)  */
   2091 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
   2092 
   2093 /* The minimum remote packet size for memory transfers.  Ensures we
   2094    can write at least one byte.  */
   2095 #define MIN_MEMORY_PACKET_SIZE 20
   2096 
   2097 /* Get the memory packet size, assuming it is fixed.  */
   2098 
   2099 static long
   2100 get_fixed_memory_packet_size (struct memory_packet_config *config)
   2101 {
   2102   gdb_assert (config->fixed_p);
   2103 
   2104   if (config->size <= 0)
   2105     return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
   2106   else
   2107     return config->size;
   2108 }
   2109 
   2110 /* Compute the current size of a read/write packet.  Since this makes
   2111    use of ``actual_register_packet_size'' the computation is dynamic.  */
   2112 
   2113 long
   2114 remote_target::get_memory_packet_size (struct memory_packet_config *config)
   2115 {
   2116   struct remote_state *rs = get_remote_state ();
   2117   remote_arch_state *rsa
   2118     = rs->get_remote_arch_state (current_inferior ()->arch ());
   2119 
   2120   long what_they_get;
   2121   if (config->fixed_p)
   2122     what_they_get = get_fixed_memory_packet_size (config);
   2123   else
   2124     {
   2125       what_they_get = get_remote_packet_size ();
   2126       /* Limit the packet to the size specified by the user.  */
   2127       if (config->size > 0
   2128 	  && what_they_get > config->size)
   2129 	what_they_get = config->size;
   2130 
   2131       /* Limit it to the size of the targets ``g'' response unless we have
   2132 	 permission from the stub to use a larger packet size.  */
   2133       if (rs->explicit_packet_size == 0
   2134 	  && rsa->actual_register_packet_size > 0
   2135 	  && what_they_get > rsa->actual_register_packet_size)
   2136 	what_they_get = rsa->actual_register_packet_size;
   2137     }
   2138   if (what_they_get < MIN_MEMORY_PACKET_SIZE)
   2139     what_they_get = MIN_MEMORY_PACKET_SIZE;
   2140 
   2141   /* Make sure there is room in the global buffer for this packet
   2142      (including its trailing NUL byte).  */
   2143   if (rs->buf.size () < what_they_get + 1)
   2144     rs->buf.resize (2 * what_they_get);
   2145 
   2146   return what_they_get;
   2147 }
   2148 
   2149 /* Update the size of a read/write packet.  If they user wants
   2150    something really big then do a sanity check.  */
   2151 
   2152 static void
   2153 set_memory_packet_size (const char *args, struct memory_packet_config *config,
   2154 			bool target_connected)
   2155 {
   2156   int fixed_p = config->fixed_p;
   2157   long size = config->size;
   2158 
   2159   if (args == NULL)
   2160     error (_("Argument required (integer, \"fixed\" or \"limit\")."));
   2161   else if (strcmp (args, "hard") == 0
   2162       || strcmp (args, "fixed") == 0)
   2163     fixed_p = 1;
   2164   else if (strcmp (args, "soft") == 0
   2165 	   || strcmp (args, "limit") == 0)
   2166     fixed_p = 0;
   2167   else
   2168     {
   2169       char *end;
   2170 
   2171       size = strtoul (args, &end, 0);
   2172       if (args == end)
   2173 	error (_("Invalid %s (bad syntax)."), config->name);
   2174 
   2175       /* Instead of explicitly capping the size of a packet to or
   2176 	 disallowing it, the user is allowed to set the size to
   2177 	 something arbitrarily large.  */
   2178     }
   2179 
   2180   /* Extra checks?  */
   2181   if (fixed_p && !config->fixed_p)
   2182     {
   2183       /* So that the query shows the correct value.  */
   2184       long query_size = (size <= 0
   2185 			 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
   2186 			 : size);
   2187 
   2188       if (target_connected
   2189 	  && !query (_("The target may not be able to correctly handle a %s\n"
   2190 		       "of %ld bytes.  Change the packet size? "),
   2191 		     config->name, query_size))
   2192 	error (_("Packet size not changed."));
   2193       else if (!target_connected
   2194 	       && !query (_("Future remote targets may not be able to "
   2195 			    "correctly handle a %s\nof %ld bytes.  Change the "
   2196 			    "packet size for future remote targets? "),
   2197 			  config->name, query_size))
   2198 	error (_("Packet size not changed."));
   2199     }
   2200   /* Update the config.  */
   2201   config->fixed_p = fixed_p;
   2202   config->size = size;
   2203 
   2204   const char *target_type = get_target_type_name (target_connected);
   2205   gdb_printf (_("The %s %s is set to \"%s\".\n"), config->name, target_type,
   2206 	      args);
   2207 
   2208 }
   2209 
   2210 /* Show the memory-read or write-packet size configuration CONFIG of the
   2211    target REMOTE.  If REMOTE is nullptr, the default configuration for future
   2212    remote targets should be passed in CONFIG.  */
   2213 
   2214 static void
   2215 show_memory_packet_size (memory_packet_config *config, remote_target *remote)
   2216 {
   2217   const char *target_type = get_target_type_name (remote != nullptr);
   2218 
   2219   if (config->size == 0)
   2220     gdb_printf (_("The %s %s is 0 (default). "), config->name, target_type);
   2221   else
   2222     gdb_printf (_("The %s %s is %ld. "), config->name, target_type,
   2223 		config->size);
   2224 
   2225   if (config->fixed_p)
   2226     gdb_printf (_("Packets are fixed at %ld bytes.\n"),
   2227 		get_fixed_memory_packet_size (config));
   2228   else
   2229     {
   2230       if (remote != nullptr)
   2231 	gdb_printf (_("Packets are limited to %ld bytes.\n"),
   2232 		    remote->get_memory_packet_size (config));
   2233       else
   2234 	gdb_puts ("The actual limit will be further reduced "
   2235 		  "dependent on the target.\n");
   2236     }
   2237 }
   2238 
   2239 /* Configure the memory-write-packet size of the currently selected target.  If
   2240    no target is available, the default configuration for future remote targets
   2241    is configured.  */
   2242 
   2243 static void
   2244 set_memory_write_packet_size (const char *args, int from_tty)
   2245 {
   2246   remote_target *remote = get_current_remote_target ();
   2247   if (remote != nullptr)
   2248     {
   2249       set_memory_packet_size
   2250 	(args, &remote->m_features.m_memory_write_packet_config, true);
   2251     }
   2252   else
   2253     {
   2254       memory_packet_config* config = &memory_write_packet_config;
   2255       set_memory_packet_size (args, config, false);
   2256     }
   2257 }
   2258 
   2259 /* Display the memory-write-packet size of the currently selected target.  If
   2260    no target is available, the default configuration for future remote targets
   2261    is shown.  */
   2262 
   2263 static void
   2264 show_memory_write_packet_size (const char *args, int from_tty)
   2265 {
   2266   remote_target *remote = get_current_remote_target ();
   2267   if (remote != nullptr)
   2268     show_memory_packet_size (&remote->m_features.m_memory_write_packet_config,
   2269 			     remote);
   2270   else
   2271     show_memory_packet_size (&memory_write_packet_config, nullptr);
   2272 }
   2273 
   2274 /* Show the number of hardware watchpoints that can be used.  */
   2275 
   2276 static void
   2277 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
   2278 				struct cmd_list_element *c,
   2279 				const char *value)
   2280 {
   2281   gdb_printf (file, _("The maximum number of target hardware "
   2282 		      "watchpoints is %s.\n"), value);
   2283 }
   2284 
   2285 /* Show the length limit (in bytes) for hardware watchpoints.  */
   2286 
   2287 static void
   2288 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
   2289 				       struct cmd_list_element *c,
   2290 				       const char *value)
   2291 {
   2292   gdb_printf (file, _("The maximum length (in bytes) of a target "
   2293 		      "hardware watchpoint is %s.\n"), value);
   2294 }
   2295 
   2296 /* Show the number of hardware breakpoints that can be used.  */
   2297 
   2298 static void
   2299 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
   2300 				struct cmd_list_element *c,
   2301 				const char *value)
   2302 {
   2303   gdb_printf (file, _("The maximum number of target hardware "
   2304 		      "breakpoints is %s.\n"), value);
   2305 }
   2306 
   2307 /* Controls the maximum number of characters to display in the debug output
   2308    for each remote packet.  The remaining characters are omitted.  */
   2309 
   2310 static int remote_packet_max_chars = 512;
   2311 
   2312 /* Show the maximum number of characters to display for each remote packet
   2313    when remote debugging is enabled.  */
   2314 
   2315 static void
   2316 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
   2317 			      struct cmd_list_element *c,
   2318 			      const char *value)
   2319 {
   2320   gdb_printf (file, _("Number of remote packet characters to "
   2321 		      "display is %s.\n"), value);
   2322 }
   2323 
   2324 long
   2325 remote_target::get_memory_write_packet_size ()
   2326 {
   2327   return get_memory_packet_size (&m_features.m_memory_write_packet_config);
   2328 }
   2329 
   2330 /* Configure the memory-read-packet size of the currently selected target.  If
   2331    no target is available, the default configuration for future remote targets
   2332    is adapted.  */
   2333 
   2334 static void
   2335 set_memory_read_packet_size (const char *args, int from_tty)
   2336 {
   2337   remote_target *remote = get_current_remote_target ();
   2338   if (remote != nullptr)
   2339     set_memory_packet_size
   2340       (args, &remote->m_features.m_memory_read_packet_config, true);
   2341   else
   2342     {
   2343       memory_packet_config* config = &memory_read_packet_config;
   2344       set_memory_packet_size (args, config, false);
   2345     }
   2346 
   2347 }
   2348 
   2349 /* Display the memory-read-packet size of the currently selected target.  If
   2350    no target is available, the default configuration for future remote targets
   2351    is shown.  */
   2352 
   2353 static void
   2354 show_memory_read_packet_size (const char *args, int from_tty)
   2355 {
   2356   remote_target *remote = get_current_remote_target ();
   2357   if (remote != nullptr)
   2358     show_memory_packet_size (&remote->m_features.m_memory_read_packet_config,
   2359 			     remote);
   2360   else
   2361     show_memory_packet_size (&memory_read_packet_config, nullptr);
   2362 }
   2363 
   2364 long
   2365 remote_target::get_memory_read_packet_size ()
   2366 {
   2367   long size = get_memory_packet_size (&m_features.m_memory_read_packet_config);
   2368 
   2369   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
   2370      extra buffer size argument before the memory read size can be
   2371      increased beyond this.  */
   2372   if (size > get_remote_packet_size ())
   2373     size = get_remote_packet_size ();
   2374   return size;
   2375 }
   2376 
   2377 static enum packet_support packet_config_support (const packet_config *config);
   2378 
   2379 
   2380 static void
   2381 set_remote_protocol_packet_cmd (const char *args, int from_tty,
   2382 				cmd_list_element *c)
   2383 {
   2384   remote_target *remote = get_current_remote_target ();
   2385   gdb_assert (c->var.has_value ());
   2386 
   2387   auto *default_config = static_cast<packet_config *> (c->context ());
   2388   const int packet_idx = std::distance (remote_protocol_packets,
   2389 					default_config);
   2390 
   2391   if (packet_idx >= 0 && packet_idx < PACKET_MAX)
   2392     {
   2393       const char *name = packets_descriptions[packet_idx].name;
   2394       const auto_boolean value = c->var->get<auto_boolean> ();
   2395       const char *support = get_packet_support_name (value);
   2396       const char *target_type = get_target_type_name (remote != nullptr);
   2397 
   2398       if (remote != nullptr)
   2399 	remote->m_features.m_protocol_packets[packet_idx].detect = value;
   2400       else
   2401 	remote_protocol_packets[packet_idx].detect = value;
   2402 
   2403       gdb_printf (_("Support for the '%s' packet %s is set to \"%s\".\n"), name,
   2404 		  target_type, support);
   2405       return;
   2406     }
   2407 
   2408   internal_error (_("Could not find config for %s"), c->name);
   2409 }
   2410 
   2411 static void
   2412 show_packet_config_cmd (ui_file *file, const unsigned int which_packet,
   2413 			remote_target *remote)
   2414 {
   2415   const char *support = "internal-error";
   2416   const char *target_type = get_target_type_name (remote != nullptr);
   2417 
   2418   packet_config *config;
   2419   if (remote != nullptr)
   2420     config = &remote->m_features.m_protocol_packets[which_packet];
   2421   else
   2422     config = &remote_protocol_packets[which_packet];
   2423 
   2424   switch (packet_config_support (config))
   2425     {
   2426     case PACKET_ENABLE:
   2427       support = "enabled";
   2428       break;
   2429     case PACKET_DISABLE:
   2430       support = "disabled";
   2431       break;
   2432     case PACKET_SUPPORT_UNKNOWN:
   2433       support = "unknown";
   2434       break;
   2435     }
   2436   switch (config->detect)
   2437     {
   2438     case AUTO_BOOLEAN_AUTO:
   2439       gdb_printf (file,
   2440 		  _("Support for the '%s' packet %s is \"auto\", "
   2441 		    "currently %s.\n"),
   2442 		  packets_descriptions[which_packet].name, target_type,
   2443 		  support);
   2444       break;
   2445     case AUTO_BOOLEAN_TRUE:
   2446     case AUTO_BOOLEAN_FALSE:
   2447       gdb_printf (file,
   2448 		  _("Support for the '%s' packet %s is \"%s\".\n"),
   2449 		  packets_descriptions[which_packet].name, target_type,
   2450 		  get_packet_support_name (config->detect));
   2451       break;
   2452     }
   2453 }
   2454 
   2455 static void
   2456 add_packet_config_cmd (const unsigned int which_packet, const char *name,
   2457 		       const char *title, int legacy)
   2458 {
   2459   packets_descriptions[which_packet].name = name;
   2460   packets_descriptions[which_packet].title = title;
   2461 
   2462   packet_config *config = &remote_protocol_packets[which_packet];
   2463 
   2464   gdb::unique_xmalloc_ptr<char> set_doc
   2465     = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
   2466 		  name, title);
   2467   gdb::unique_xmalloc_ptr<char> show_doc
   2468     = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
   2469 		  name, title);
   2470   /* set/show TITLE-packet {auto,on,off} */
   2471   gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
   2472   set_show_commands cmds
   2473     = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
   2474 				    &config->detect, set_doc.get (),
   2475 				    show_doc.get (), NULL, /* help_doc */
   2476 				    set_remote_protocol_packet_cmd,
   2477 				    show_remote_protocol_packet_cmd,
   2478 				    &remote_set_cmdlist, &remote_show_cmdlist);
   2479   cmds.show->set_context (config);
   2480   cmds.set->set_context (config);
   2481 
   2482   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
   2483   if (legacy)
   2484     {
   2485       /* It's not clear who should take ownership of the LEGACY_NAME string
   2486 	 created below, so, for now, place the string into a static vector
   2487 	 which ensures the strings is released when GDB exits.  */
   2488       static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
   2489       gdb::unique_xmalloc_ptr<char> legacy_name
   2490 	= xstrprintf ("%s-packet", name);
   2491       add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
   2492 		     &remote_set_cmdlist);
   2493       add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
   2494 		     &remote_show_cmdlist);
   2495       legacy_names.emplace_back (std::move (legacy_name));
   2496     }
   2497 }
   2498 
   2499 /* Check GDBserver's reply packet.  Return packet_result structure
   2500    which contains the packet_status enum and an error message for the
   2501    PACKET_ERROR case.
   2502 
   2503    An error packet can always take the form Exx (where xx is a hex
   2504    code).  When ACCEPT_MSG is true error messages can also take the
   2505    form E.msg (where msg is any arbitrary string).  */
   2506 static packet_result
   2507 packet_check_result (const char *buf, bool accept_msg)
   2508 {
   2509   if (buf[0] != '\0')
   2510     {
   2511       /* The stub recognized the packet request.  Check that the
   2512 	 operation succeeded.  */
   2513       if (buf[0] == 'E'
   2514 	  && isxdigit ((unsigned char)buf[1]) && isxdigit ((unsigned char)buf[2])
   2515 	  && buf[3] == '\0')
   2516 	/* "Enn"  - definitely an error.  */
   2517 	return packet_result::make_numeric_error (buf + 1);
   2518 
   2519       /* Not every request accepts an error in a E.msg form.
   2520 	 Some packets accepts only Enn, in this case E. is not
   2521 	 defined and E. is treated as PACKET_OK.  */
   2522       if (accept_msg)
   2523 	{
   2524 	  /* Always treat "E." as an error.  This will be used for
   2525 	     more verbose error messages, such as E.memtypes.  */
   2526 	  if (buf[0] == 'E' && buf[1] == '.')
   2527 	    {
   2528 	      if (buf[2] != '\0')
   2529 		return packet_result::make_textual_error (buf + 2);
   2530 	      else
   2531 		return packet_result::make_textual_error ("no error provided");
   2532 	    }
   2533 	}
   2534 
   2535       /* The packet may or may not be OK.  Just assume it is.  */
   2536       return packet_result::make_ok ();
   2537     }
   2538   else
   2539   {
   2540     /* The stub does not support the packet.  */
   2541     return packet_result::make_unknown ();
   2542   }
   2543 }
   2544 
   2545 static packet_result
   2546 packet_check_result (const gdb::char_vector &buf, bool accept_msg)
   2547 {
   2548   return packet_check_result (buf.data (), accept_msg);
   2549 }
   2550 
   2551 packet_result
   2552 remote_features::packet_ok (const char *buf, const int which_packet)
   2553 {
   2554   packet_config *config = &m_protocol_packets[which_packet];
   2555   packet_description *descr = &packets_descriptions[which_packet];
   2556 
   2557   if (config->detect != AUTO_BOOLEAN_TRUE
   2558       && config->support == PACKET_DISABLE)
   2559     internal_error (_("packet_ok: attempt to use a disabled packet"));
   2560 
   2561   packet_result result = packet_check_result (buf, true);
   2562   switch (result.status ())
   2563     {
   2564     case PACKET_OK:
   2565     case PACKET_ERROR:
   2566       /* The stub recognized the packet request.  */
   2567       if (config->support == PACKET_SUPPORT_UNKNOWN)
   2568 	{
   2569 	  remote_debug_printf ("Packet %s (%s) is supported",
   2570 			       descr->name, descr->title);
   2571 	  config->support = PACKET_ENABLE;
   2572 	}
   2573       break;
   2574     case PACKET_UNKNOWN:
   2575       /* The stub does not support the packet.  */
   2576       if (config->detect == AUTO_BOOLEAN_AUTO
   2577 	  && config->support == PACKET_ENABLE)
   2578 	{
   2579 	  /* If the stub previously indicated that the packet was
   2580 	     supported then there is a protocol error.  */
   2581 	  error (_("Protocol error: %s (%s) conflicting enabled responses."),
   2582 		 descr->name, descr->title);
   2583 	}
   2584       else if (config->detect == AUTO_BOOLEAN_TRUE)
   2585 	{
   2586 	  /* The user set it wrong.  */
   2587 	  error (_("Enabled packet %s (%s) not recognized by stub"),
   2588 		 descr->name, descr->title);
   2589 	}
   2590 
   2591       remote_debug_printf ("Packet %s (%s) is NOT supported", descr->name,
   2592 			   descr->title);
   2593       config->support = PACKET_DISABLE;
   2594       break;
   2595     }
   2596 
   2597   return result;
   2598 }
   2599 
   2600 packet_result
   2601 remote_features::packet_ok (const gdb::char_vector &buf, const int which_packet)
   2602 {
   2603   return packet_ok (buf.data (), which_packet);
   2604 }
   2605 
   2606 /* Returns whether a given packet or feature is supported.  This takes
   2607    into account the state of the corresponding "set remote foo-packet"
   2608    command, which may be used to bypass auto-detection.  */
   2609 
   2610 static enum packet_support
   2611 packet_config_support (const packet_config *config)
   2612 {
   2613   switch (config->detect)
   2614     {
   2615     case AUTO_BOOLEAN_TRUE:
   2616       return PACKET_ENABLE;
   2617     case AUTO_BOOLEAN_FALSE:
   2618       return PACKET_DISABLE;
   2619     case AUTO_BOOLEAN_AUTO:
   2620       return config->support;
   2621     default:
   2622       gdb_assert_not_reached ("bad switch");
   2623     }
   2624 }
   2625 
   2626 packet_support
   2627 remote_features::packet_support (int packet) const
   2628 {
   2629   const packet_config *config = &m_protocol_packets[packet];
   2630   return packet_config_support (config);
   2631 }
   2632 
   2633 static void
   2634 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
   2635 				 struct cmd_list_element *c,
   2636 				 const char *value)
   2637 {
   2638   remote_target *remote = get_current_remote_target ();
   2639   gdb_assert (c->var.has_value ());
   2640 
   2641   auto *default_config = static_cast<packet_config *> (c->context ());
   2642   const int packet_idx = std::distance (remote_protocol_packets,
   2643 					default_config);
   2644 
   2645   if (packet_idx >= 0 && packet_idx < PACKET_MAX)
   2646     {
   2647        show_packet_config_cmd (file, packet_idx, remote);
   2648        return;
   2649     }
   2650   internal_error (_("Could not find config for %s"), c->name);
   2651 }
   2652 
   2653 /* Should we try one of the 'Z' requests?  */
   2654 
   2655 enum Z_packet_type
   2656 {
   2657   Z_PACKET_SOFTWARE_BP,
   2658   Z_PACKET_HARDWARE_BP,
   2659   Z_PACKET_WRITE_WP,
   2660   Z_PACKET_READ_WP,
   2661   Z_PACKET_ACCESS_WP,
   2662   NR_Z_PACKET_TYPES
   2663 };
   2664 
   2665 /* For compatibility with older distributions.  Provide a ``set remote
   2666    Z-packet ...'' command that updates all the Z packet types.  */
   2667 
   2668 static enum auto_boolean remote_Z_packet_detect;
   2669 
   2670 static void
   2671 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
   2672 				  struct cmd_list_element *c)
   2673 {
   2674   remote_target *remote = get_current_remote_target ();
   2675   int i;
   2676 
   2677   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
   2678     {
   2679       if (remote != nullptr)
   2680 	remote->m_features.m_protocol_packets[PACKET_Z0 + i].detect
   2681 	  = remote_Z_packet_detect;
   2682       else
   2683 	remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
   2684     }
   2685 
   2686   const char *support = get_packet_support_name (remote_Z_packet_detect);
   2687   const char *target_type = get_target_type_name (remote != nullptr);
   2688   gdb_printf (_("Use of Z packets %s is set to \"%s\".\n"), target_type,
   2689 	      support);
   2690 
   2691 }
   2692 
   2693 static void
   2694 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
   2695 				   struct cmd_list_element *c,
   2696 				   const char *value)
   2697 {
   2698   remote_target *remote = get_current_remote_target ();
   2699   int i;
   2700 
   2701   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
   2702     show_packet_config_cmd (file, PACKET_Z0 + i, remote);
   2703 }
   2704 
   2705 /* Insert fork catchpoint target routine.  If fork events are enabled
   2706    then return success, nothing more to do.  */
   2707 
   2708 int
   2709 remote_target::insert_fork_catchpoint (int pid)
   2710 {
   2711   return !m_features.remote_fork_event_p ();
   2712 }
   2713 
   2714 /* Remove fork catchpoint target routine.  Nothing to do, just
   2715    return success.  */
   2716 
   2717 int
   2718 remote_target::remove_fork_catchpoint (int pid)
   2719 {
   2720   return 0;
   2721 }
   2722 
   2723 /* Insert vfork catchpoint target routine.  If vfork events are enabled
   2724    then return success, nothing more to do.  */
   2725 
   2726 int
   2727 remote_target::insert_vfork_catchpoint (int pid)
   2728 {
   2729   return !m_features.remote_vfork_event_p ();
   2730 }
   2731 
   2732 /* Remove vfork catchpoint target routine.  Nothing to do, just
   2733    return success.  */
   2734 
   2735 int
   2736 remote_target::remove_vfork_catchpoint (int pid)
   2737 {
   2738   return 0;
   2739 }
   2740 
   2741 /* Insert exec catchpoint target routine.  If exec events are
   2742    enabled, just return success.  */
   2743 
   2744 int
   2745 remote_target::insert_exec_catchpoint (int pid)
   2746 {
   2747   return !m_features.remote_exec_event_p ();
   2748 }
   2749 
   2750 /* Remove exec catchpoint target routine.  Nothing to do, just
   2751    return success.  */
   2752 
   2753 int
   2754 remote_target::remove_exec_catchpoint (int pid)
   2755 {
   2756   return 0;
   2757 }
   2758 
   2759 
   2760 
   2762 /* Take advantage of the fact that the TID field is not used, to tag
   2763    special ptids with it set to != 0.  */
   2764 static const ptid_t magic_null_ptid (42000, -1, 1);
   2765 static const ptid_t not_sent_ptid (42000, -2, 1);
   2766 static const ptid_t any_thread_ptid (42000, 0, 1);
   2767 
   2768 /* Find out if the stub attached to PID (and hence GDB should offer to
   2769    detach instead of killing it when bailing out).  */
   2770 
   2771 int
   2772 remote_target::remote_query_attached (int pid)
   2773 {
   2774   struct remote_state *rs = get_remote_state ();
   2775   size_t size = get_remote_packet_size ();
   2776 
   2777   if (m_features.packet_support (PACKET_qAttached) == PACKET_DISABLE)
   2778     return 0;
   2779 
   2780   if (m_features.remote_multi_process_p ())
   2781     xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
   2782   else
   2783     xsnprintf (rs->buf.data (), size, "qAttached");
   2784 
   2785   putpkt (rs->buf);
   2786   getpkt (&rs->buf);
   2787 
   2788   packet_result result = m_features.packet_ok (rs->buf, PACKET_qAttached);
   2789   switch (result.status ())
   2790     {
   2791     case PACKET_OK:
   2792       if (strcmp (rs->buf.data (), "1") == 0)
   2793 	return 1;
   2794       break;
   2795     case PACKET_ERROR:
   2796       warning (_("Remote failure reply: %s"), result.err_msg ());
   2797       break;
   2798     case PACKET_UNKNOWN:
   2799       break;
   2800     }
   2801 
   2802   return 0;
   2803 }
   2804 
   2805 /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
   2806    has been invented by GDB, instead of reported by the target.  Since
   2807    we can be connected to a remote system before before knowing about
   2808    any inferior, mark the target with execution when we find the first
   2809    inferior.  If ATTACHED is 1, then we had just attached to this
   2810    inferior.  If it is 0, then we just created this inferior.  If it
   2811    is -1, then try querying the remote stub to find out if it had
   2812    attached to the inferior or not.  If TRY_OPEN_EXEC is true then
   2813    attempt to open this inferior's executable as the main executable
   2814    if no main executable is open already.  */
   2815 
   2816 inferior *
   2817 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
   2818 				    int try_open_exec)
   2819 {
   2820   struct inferior *inf;
   2821 
   2822   /* Check whether this process we're learning about is to be
   2823      considered attached, or if is to be considered to have been
   2824      spawned by the stub.  */
   2825   if (attached == -1)
   2826     attached = remote_query_attached (pid);
   2827 
   2828   if (gdbarch_has_global_solist (current_inferior ()->arch ()))
   2829     {
   2830       /* If the target shares code across all inferiors, then every
   2831 	 attach adds a new inferior.  */
   2832       inf = add_inferior (pid);
   2833 
   2834       /* ... and every inferior is bound to the same program space.
   2835 	 However, each inferior may still have its own address
   2836 	 space.  */
   2837       inf->aspace = maybe_new_address_space ();
   2838       inf->pspace = current_program_space;
   2839     }
   2840   else
   2841     {
   2842       /* In the traditional debugging scenario, there's a 1-1 match
   2843 	 between program/address spaces.  We simply bind the inferior
   2844 	 to the program space's address space.  */
   2845       inf = current_inferior ();
   2846 
   2847       /* However, if the current inferior is already bound to a
   2848 	 process, find some other empty inferior.  */
   2849       if (inf->pid != 0)
   2850 	{
   2851 	  inf = nullptr;
   2852 	  for (inferior *it : all_inferiors ())
   2853 	    if (it->pid == 0)
   2854 	      {
   2855 		inf = it;
   2856 		break;
   2857 	      }
   2858 	}
   2859       if (inf == nullptr)
   2860 	{
   2861 	  /* Since all inferiors were already bound to a process, add
   2862 	     a new inferior.  */
   2863 	  inf = add_inferior_with_spaces ();
   2864 	}
   2865       switch_to_inferior_no_thread (inf);
   2866       inf->push_target (this);
   2867       inferior_appeared (inf, pid);
   2868     }
   2869 
   2870   inf->attach_flag = attached;
   2871   inf->fake_pid_p = fake_pid_p;
   2872 
   2873   /* If no main executable is currently open then attempt to
   2874      open the file that was executed to create this inferior.  */
   2875   if (try_open_exec && get_exec_file (0) == NULL)
   2876     exec_file_locate_attach (pid, 0, 1);
   2877 
   2878   /* Check for exec file mismatch, and let the user solve it.  */
   2879   validate_exec_file (1);
   2880 
   2881   return inf;
   2882 }
   2883 
   2884 static remote_thread_info *get_remote_thread_info (thread_info *thread);
   2885 static remote_thread_info *get_remote_thread_info (remote_target *target,
   2886 						   ptid_t ptid);
   2887 
   2888 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
   2889    according to EXECUTING and RUNNING respectively.  If SILENT_P (or the
   2890    remote_state::starting_up flag) is true then the new thread is added
   2891    silently, otherwise the new thread will be announced to the user.  */
   2892 
   2893 thread_info *
   2894 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
   2895 				  bool silent_p)
   2896 {
   2897   struct remote_state *rs = get_remote_state ();
   2898   struct thread_info *thread;
   2899 
   2900   /* GDB historically didn't pull threads in the initial connection
   2901      setup.  If the remote target doesn't even have a concept of
   2902      threads (e.g., a bare-metal target), even if internally we
   2903      consider that a single-threaded target, mentioning a new thread
   2904      might be confusing to the user.  Be silent then, preserving the
   2905      age old behavior.  */
   2906   if (rs->starting_up || silent_p)
   2907     thread = add_thread_silent (this, ptid);
   2908   else
   2909     thread = add_thread (this, ptid);
   2910 
   2911   if (executing)
   2912     get_remote_thread_info (thread)->set_resumed ();
   2913   set_executing (this, ptid, executing);
   2914   set_running (this, ptid, running);
   2915 
   2916   return thread;
   2917 }
   2918 
   2919 /* Come here when we learn about a thread id from the remote target.
   2920    It may be the first time we hear about such thread, so take the
   2921    opportunity to add it to GDB's thread list.  In case this is the
   2922    first time we're noticing its corresponding inferior, add it to
   2923    GDB's inferior list as well.  EXECUTING indicates whether the
   2924    thread is (internally) executing or stopped.  */
   2925 
   2926 void
   2927 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
   2928 {
   2929   /* In non-stop mode, we assume new found threads are (externally)
   2930      running until proven otherwise with a stop reply.  In all-stop,
   2931      we can only get here if all threads are stopped.  */
   2932   bool running = target_is_non_stop_p ();
   2933 
   2934   /* If this is a new thread, add it to GDB's thread list.
   2935      If we leave it up to WFI to do this, bad things will happen.  */
   2936 
   2937   thread_info *tp = this->find_thread (currthread);
   2938   if (tp != NULL && tp->state == THREAD_EXITED)
   2939     {
   2940       /* We're seeing an event on a thread id we knew had exited.
   2941 	 This has to be a new thread reusing the old id.  Add it.  */
   2942       remote_add_thread (currthread, running, executing, false);
   2943       return;
   2944     }
   2945 
   2946   if (!in_thread_list (this, currthread))
   2947     {
   2948       struct inferior *inf = NULL;
   2949       int pid = currthread.pid ();
   2950 
   2951       if (inferior_ptid.is_pid ()
   2952 	  && pid == inferior_ptid.pid ())
   2953 	{
   2954 	  /* inferior_ptid has no thread member yet.  This can happen
   2955 	     with the vAttach -> remote_wait,"TAAthread:" path if the
   2956 	     stub doesn't support qC.  This is the first stop reported
   2957 	     after an attach, so this is the main thread.  Update the
   2958 	     ptid in the thread list.  */
   2959 	  if (in_thread_list (this, ptid_t (pid)))
   2960 	    thread_change_ptid (this, inferior_ptid, currthread);
   2961 	  else
   2962 	    {
   2963 	      thread_info *thr
   2964 		= remote_add_thread (currthread, running, executing, false);
   2965 	      switch_to_thread (thr);
   2966 	    }
   2967 	  return;
   2968 	}
   2969 
   2970       if (magic_null_ptid == inferior_ptid)
   2971 	{
   2972 	  /* inferior_ptid is not set yet.  This can happen with the
   2973 	     vRun -> remote_wait,"TAAthread:" path if the stub
   2974 	     doesn't support qC.  This is the first stop reported
   2975 	     after an attach, so this is the main thread.  Update the
   2976 	     ptid in the thread list.  */
   2977 	  thread_change_ptid (this, inferior_ptid, currthread);
   2978 	  return;
   2979 	}
   2980 
   2981       /* When connecting to a target remote, or to a target
   2982 	 extended-remote which already was debugging an inferior, we
   2983 	 may not know about it yet.  Add it before adding its child
   2984 	 thread, so notifications are emitted in a sensible order.  */
   2985       if (find_inferior_pid (this, currthread.pid ()) == NULL)
   2986 	{
   2987 	  bool fake_pid_p = !m_features.remote_multi_process_p ();
   2988 
   2989 	  inf = remote_add_inferior (fake_pid_p,
   2990 				     currthread.pid (), -1, 1);
   2991 	}
   2992 
   2993       /* This is really a new thread.  Add it.  */
   2994       thread_info *new_thr
   2995 	= remote_add_thread (currthread, running, executing, false);
   2996 
   2997       /* If we found a new inferior, let the common code do whatever
   2998 	 it needs to with it (e.g., read shared libraries, insert
   2999 	 breakpoints), unless we're just setting up an all-stop
   3000 	 connection.  */
   3001       if (inf != NULL)
   3002 	{
   3003 	  struct remote_state *rs = get_remote_state ();
   3004 
   3005 	  if (!rs->starting_up)
   3006 	    notice_new_inferior (new_thr, executing, 0);
   3007 	}
   3008     }
   3009 }
   3010 
   3011 /* Return THREAD's private thread data, creating it if necessary.  */
   3012 
   3013 static remote_thread_info *
   3014 get_remote_thread_info (thread_info *thread)
   3015 {
   3016   gdb_assert (thread != NULL);
   3017 
   3018   if (thread->priv == NULL)
   3019     thread->priv.reset (new remote_thread_info);
   3020 
   3021   return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
   3022 }
   3023 
   3024 /* Return PTID's private thread data, creating it if necessary.  */
   3025 
   3026 static remote_thread_info *
   3027 get_remote_thread_info (remote_target *target, ptid_t ptid)
   3028 {
   3029   thread_info *thr = target->find_thread (ptid);
   3030   return get_remote_thread_info (thr);
   3031 }
   3032 
   3033 /* Call this function as a result of
   3034    1) A halt indication (T packet) containing a thread id
   3035    2) A direct query of currthread
   3036    3) Successful execution of set thread */
   3037 
   3038 static void
   3039 record_currthread (struct remote_state *rs, ptid_t currthread)
   3040 {
   3041   rs->general_thread = currthread;
   3042 }
   3043 
   3044 /* If 'QPassSignals' is supported, tell the remote stub what signals
   3045    it can simply pass through to the inferior without reporting.  */
   3046 
   3047 void
   3048 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
   3049 {
   3050   if (m_features.packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
   3051     {
   3052       char *pass_packet, *p;
   3053       int count = 0;
   3054       struct remote_state *rs = get_remote_state ();
   3055 
   3056       gdb_assert (pass_signals.size () < 256);
   3057       for (size_t i = 0; i < pass_signals.size (); i++)
   3058 	{
   3059 	  if (pass_signals[i])
   3060 	    count++;
   3061 	}
   3062       pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
   3063       strcpy (pass_packet, "QPassSignals:");
   3064       p = pass_packet + strlen (pass_packet);
   3065       for (size_t i = 0; i < pass_signals.size (); i++)
   3066 	{
   3067 	  if (pass_signals[i])
   3068 	    {
   3069 	      if (i >= 16)
   3070 		*p++ = tohex (i >> 4);
   3071 	      *p++ = tohex (i & 15);
   3072 	      if (count)
   3073 		*p++ = ';';
   3074 	      else
   3075 		break;
   3076 	      count--;
   3077 	    }
   3078 	}
   3079       *p = 0;
   3080       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
   3081 	{
   3082 	  putpkt (pass_packet);
   3083 	  getpkt (&rs->buf);
   3084 	  m_features.packet_ok (rs->buf, PACKET_QPassSignals);
   3085 	  xfree (rs->last_pass_packet);
   3086 	  rs->last_pass_packet = pass_packet;
   3087 	}
   3088       else
   3089 	xfree (pass_packet);
   3090     }
   3091 }
   3092 
   3093 /* If 'QCatchSyscalls' is supported, tell the remote stub
   3094    to report syscalls to GDB.  */
   3095 
   3096 int
   3097 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
   3098 				       gdb::array_view<const int> syscall_counts)
   3099 {
   3100   const char *catch_packet;
   3101   int n_sysno = 0;
   3102 
   3103   if (m_features.packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
   3104     {
   3105       /* Not supported.  */
   3106       return 1;
   3107     }
   3108 
   3109   if (needed && any_count == 0)
   3110     {
   3111       /* Count how many syscalls are to be caught.  */
   3112       for (size_t i = 0; i < syscall_counts.size (); i++)
   3113 	{
   3114 	  if (syscall_counts[i] != 0)
   3115 	    n_sysno++;
   3116 	}
   3117     }
   3118 
   3119   remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
   3120 		       pid, needed, any_count, n_sysno);
   3121 
   3122   std::string built_packet;
   3123   if (needed)
   3124     {
   3125       /* Prepare a packet with the sysno list, assuming max 8+1
   3126 	 characters for a sysno.  If the resulting packet size is too
   3127 	 big, fallback on the non-selective packet.  */
   3128       const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
   3129       built_packet.reserve (maxpktsz);
   3130       built_packet = "QCatchSyscalls:1";
   3131       if (any_count == 0)
   3132 	{
   3133 	  /* Add in each syscall to be caught.  */
   3134 	  for (size_t i = 0; i < syscall_counts.size (); i++)
   3135 	    {
   3136 	      if (syscall_counts[i] != 0)
   3137 		string_appendf (built_packet, ";%zx", i);
   3138 	    }
   3139 	}
   3140       if (built_packet.size () > get_remote_packet_size ())
   3141 	{
   3142 	  /* catch_packet too big.  Fallback to less efficient
   3143 	     non selective mode, with GDB doing the filtering.  */
   3144 	  catch_packet = "QCatchSyscalls:1";
   3145 	}
   3146       else
   3147 	catch_packet = built_packet.c_str ();
   3148     }
   3149   else
   3150     catch_packet = "QCatchSyscalls:0";
   3151 
   3152   struct remote_state *rs = get_remote_state ();
   3153 
   3154   putpkt (catch_packet);
   3155   getpkt (&rs->buf);
   3156   packet_result result = m_features.packet_ok (rs->buf, PACKET_QCatchSyscalls);
   3157   if (result.status () == PACKET_OK)
   3158     return 0;
   3159   else
   3160     return -1;
   3161 }
   3162 
   3163 /* If 'QProgramSignals' is supported, tell the remote stub what
   3164    signals it should pass through to the inferior when detaching.  */
   3165 
   3166 void
   3167 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
   3168 {
   3169   if (m_features.packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
   3170     {
   3171       char *packet, *p;
   3172       int count = 0;
   3173       struct remote_state *rs = get_remote_state ();
   3174 
   3175       gdb_assert (signals.size () < 256);
   3176       for (size_t i = 0; i < signals.size (); i++)
   3177 	{
   3178 	  if (signals[i])
   3179 	    count++;
   3180 	}
   3181       packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
   3182       strcpy (packet, "QProgramSignals:");
   3183       p = packet + strlen (packet);
   3184       for (size_t i = 0; i < signals.size (); i++)
   3185 	{
   3186 	  if (signal_pass_state (i))
   3187 	    {
   3188 	      if (i >= 16)
   3189 		*p++ = tohex (i >> 4);
   3190 	      *p++ = tohex (i & 15);
   3191 	      if (count)
   3192 		*p++ = ';';
   3193 	      else
   3194 		break;
   3195 	      count--;
   3196 	    }
   3197 	}
   3198       *p = 0;
   3199       if (!rs->last_program_signals_packet
   3200 	  || strcmp (rs->last_program_signals_packet, packet) != 0)
   3201 	{
   3202 	  putpkt (packet);
   3203 	  getpkt (&rs->buf);
   3204 	  m_features.packet_ok (rs->buf, PACKET_QProgramSignals);
   3205 	  xfree (rs->last_program_signals_packet);
   3206 	  rs->last_program_signals_packet = packet;
   3207 	}
   3208       else
   3209 	xfree (packet);
   3210     }
   3211 }
   3212 
   3213 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
   3214    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
   3215    thread.  If GEN is set, set the general thread, if not, then set
   3216    the step/continue thread.  */
   3217 void
   3218 remote_target::set_thread (ptid_t ptid, int gen)
   3219 {
   3220   struct remote_state *rs = get_remote_state ();
   3221   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
   3222   char *buf = rs->buf.data ();
   3223   char *endbuf = buf + get_remote_packet_size ();
   3224 
   3225   if (state == ptid)
   3226     return;
   3227 
   3228   *buf++ = 'H';
   3229   *buf++ = gen ? 'g' : 'c';
   3230   if (ptid == magic_null_ptid)
   3231     xsnprintf (buf, endbuf - buf, "0");
   3232   else if (ptid == any_thread_ptid)
   3233     xsnprintf (buf, endbuf - buf, "0");
   3234   else if (ptid == minus_one_ptid)
   3235     xsnprintf (buf, endbuf - buf, "-1");
   3236   else
   3237     write_ptid (buf, endbuf, ptid);
   3238   putpkt (rs->buf);
   3239   getpkt (&rs->buf);
   3240   if (gen)
   3241     rs->general_thread = ptid;
   3242   else
   3243     rs->continue_thread = ptid;
   3244 }
   3245 
   3246 void
   3247 remote_target::set_general_thread (ptid_t ptid)
   3248 {
   3249   set_thread (ptid, 1);
   3250 }
   3251 
   3252 void
   3253 remote_target::set_continue_thread (ptid_t ptid)
   3254 {
   3255   set_thread (ptid, 0);
   3256 }
   3257 
   3258 /* Change the remote current process.  Which thread within the process
   3259    ends up selected isn't important, as long as it is the same process
   3260    as what INFERIOR_PTID points to.
   3261 
   3262    This comes from that fact that there is no explicit notion of
   3263    "selected process" in the protocol.  The selected process for
   3264    general operations is the process the selected general thread
   3265    belongs to.  */
   3266 
   3267 void
   3268 remote_target::set_general_process ()
   3269 {
   3270   /* If the remote can't handle multiple processes, don't bother.  */
   3271   if (!m_features.remote_multi_process_p ())
   3272     return;
   3273 
   3274   remote_state *rs = get_remote_state ();
   3275 
   3276   /* We only need to change the remote current thread if it's pointing
   3277      at some other process.  */
   3278   if (rs->general_thread.pid () != inferior_ptid.pid ())
   3279     set_general_thread (inferior_ptid);
   3280 }
   3281 
   3282 
   3283 /* Return nonzero if this is the main thread that we made up ourselves
   3285    to model non-threaded targets as single-threaded.  */
   3286 
   3287 static int
   3288 remote_thread_always_alive (ptid_t ptid)
   3289 {
   3290   if (ptid == magic_null_ptid)
   3291     /* The main thread is always alive.  */
   3292     return 1;
   3293 
   3294   if (ptid.pid () != 0 && ptid.lwp () == 0)
   3295     /* The main thread is always alive.  This can happen after a
   3296        vAttach, if the remote side doesn't support
   3297        multi-threading.  */
   3298     return 1;
   3299 
   3300   return 0;
   3301 }
   3302 
   3303 /* Return nonzero if the thread PTID is still alive on the remote
   3304    system.  */
   3305 
   3306 bool
   3307 remote_target::thread_alive (ptid_t ptid)
   3308 {
   3309   struct remote_state *rs = get_remote_state ();
   3310   char *p, *endp;
   3311 
   3312   /* Check if this is a thread that we made up ourselves to model
   3313      non-threaded targets as single-threaded.  */
   3314   if (remote_thread_always_alive (ptid))
   3315     return 1;
   3316 
   3317   p = rs->buf.data ();
   3318   endp = p + get_remote_packet_size ();
   3319 
   3320   *p++ = 'T';
   3321   write_ptid (p, endp, ptid);
   3322 
   3323   putpkt (rs->buf);
   3324   getpkt (&rs->buf);
   3325   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
   3326 }
   3327 
   3328 /* Return a pointer to a thread name if we know it and NULL otherwise.
   3329    The thread_info object owns the memory for the name.  */
   3330 
   3331 const char *
   3332 remote_target::thread_name (struct thread_info *info)
   3333 {
   3334   if (info->priv != NULL)
   3335     {
   3336       const std::string &name = get_remote_thread_info (info)->name;
   3337       return !name.empty () ? name.c_str () : NULL;
   3338     }
   3339 
   3340   return NULL;
   3341 }
   3342 
   3343 /* About these extended threadlist and threadinfo packets.  They are
   3344    variable length packets but, the fields within them are often fixed
   3345    length.  They are redundant enough to send over UDP as is the
   3346    remote protocol in general.  There is a matching unit test module
   3347    in libstub.  */
   3348 
   3349 /* WARNING: This threadref data structure comes from the remote O.S.,
   3350    libstub protocol encoding, and remote.c.  It is not particularly
   3351    changeable.  */
   3352 
   3353 /* Right now, the internal structure is int. We want it to be bigger.
   3354    Plan to fix this.  */
   3355 
   3356 typedef int gdb_threadref;	/* Internal GDB thread reference.  */
   3357 
   3358 /* gdb_ext_thread_info is an internal GDB data structure which is
   3359    equivalent to the reply of the remote threadinfo packet.  */
   3360 
   3361 struct gdb_ext_thread_info
   3362   {
   3363     threadref threadid;		/* External form of thread reference.  */
   3364     int active;			/* Has state interesting to GDB?
   3365 				   regs, stack.  */
   3366     char display[256];		/* Brief state display, name,
   3367 				   blocked/suspended.  */
   3368     char shortname[32];		/* To be used to name threads.  */
   3369     char more_display[256];	/* Long info, statistics, queue depth,
   3370 				   whatever.  */
   3371   };
   3372 
   3373 /* The volume of remote transfers can be limited by submitting
   3374    a mask containing bits specifying the desired information.
   3375    Use a union of these values as the 'selection' parameter to
   3376    get_thread_info.  FIXME: Make these TAG names more thread specific.  */
   3377 
   3378 #define TAG_THREADID 1
   3379 #define TAG_EXISTS 2
   3380 #define TAG_DISPLAY 4
   3381 #define TAG_THREADNAME 8
   3382 #define TAG_MOREDISPLAY 16
   3383 
   3384 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
   3385 
   3386 static const char *unpack_nibble (const char *buf, int *val);
   3387 
   3388 static const char *unpack_byte (const char *buf, int *value);
   3389 
   3390 static char *pack_int (char *buf, int value);
   3391 
   3392 static const char *unpack_int (const char *buf, int *value);
   3393 
   3394 static const char *unpack_string (const char *src, char *dest, int length);
   3395 
   3396 static char *pack_threadid (char *pkt, threadref *id);
   3397 
   3398 static const char *unpack_threadid (const char *inbuf, threadref *id);
   3399 
   3400 void int_to_threadref (threadref *id, int value);
   3401 
   3402 static int threadref_to_int (threadref *ref);
   3403 
   3404 static void copy_threadref (threadref *dest, threadref *src);
   3405 
   3406 static int threadmatch (threadref *dest, threadref *src);
   3407 
   3408 static char *pack_threadinfo_request (char *pkt, int mode,
   3409 				      threadref *id);
   3410 
   3411 static char *pack_threadlist_request (char *pkt, int startflag,
   3412 				      int threadcount,
   3413 				      threadref *nextthread);
   3414 
   3415 static int remote_newthread_step (threadref *ref, void *context);
   3416 
   3417 
   3418 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
   3419    buffer we're allowed to write to.  Returns
   3420    BUF+CHARACTERS_WRITTEN.  */
   3421 
   3422 char *
   3423 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
   3424 {
   3425   int pid, tid;
   3426 
   3427   if (m_features.remote_multi_process_p ())
   3428     {
   3429       pid = ptid.pid ();
   3430       if (pid < 0)
   3431 	buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
   3432       else
   3433 	buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
   3434     }
   3435   tid = ptid.lwp ();
   3436   if (tid < 0)
   3437     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
   3438   else
   3439     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
   3440 
   3441   return buf;
   3442 }
   3443 
   3444 /* Extract a PTID from BUF.  If non-null, OBUF is set to one past the
   3445    last parsed char.  Returns null_ptid if no thread id is found, and
   3446    throws an error if the thread id has an invalid format.  */
   3447 
   3448 static ptid_t
   3449 read_ptid (const char *buf, const char **obuf)
   3450 {
   3451   const char *p = buf;
   3452   const char *pp;
   3453   ULONGEST pid = 0, tid = 0;
   3454 
   3455   if (*p == 'p')
   3456     {
   3457       /* Multi-process ptid.  */
   3458       pp = unpack_varlen_hex (p + 1, &pid);
   3459       if (*pp != '.')
   3460 	error (_("invalid remote ptid: %s"), p);
   3461 
   3462       p = pp;
   3463       pp = unpack_varlen_hex (p + 1, &tid);
   3464       if (obuf)
   3465 	*obuf = pp;
   3466       return ptid_t (pid, tid);
   3467     }
   3468 
   3469   /* No multi-process.  Just a tid.  */
   3470   pp = unpack_varlen_hex (p, &tid);
   3471 
   3472   /* Return null_ptid when no thread id is found.  */
   3473   if (p == pp)
   3474     {
   3475       if (obuf)
   3476 	*obuf = pp;
   3477       return null_ptid;
   3478     }
   3479 
   3480   /* Since the stub is not sending a process id, default to what's
   3481      current_inferior, unless it doesn't have a PID yet.  If so,
   3482      then since there's no way to know the pid of the reported
   3483      threads, use the magic number.  */
   3484   inferior *inf = current_inferior ();
   3485   if (inf->pid == 0)
   3486     pid = magic_null_ptid.pid ();
   3487   else
   3488     pid = inf->pid;
   3489 
   3490   if (obuf)
   3491     *obuf = pp;
   3492   return ptid_t (pid, tid);
   3493 }
   3494 
   3495 static int
   3496 stubhex (int ch)
   3497 {
   3498   if (ch >= 'a' && ch <= 'f')
   3499     return ch - 'a' + 10;
   3500   if (ch >= '0' && ch <= '9')
   3501     return ch - '0';
   3502   if (ch >= 'A' && ch <= 'F')
   3503     return ch - 'A' + 10;
   3504   return -1;
   3505 }
   3506 
   3507 static int
   3508 stub_unpack_int (const char *buff, int fieldlength)
   3509 {
   3510   int nibble;
   3511   int retval = 0;
   3512 
   3513   while (fieldlength)
   3514     {
   3515       nibble = stubhex (*buff++);
   3516       retval |= nibble;
   3517       fieldlength--;
   3518       if (fieldlength)
   3519 	retval = retval << 4;
   3520     }
   3521   return retval;
   3522 }
   3523 
   3524 static const char *
   3525 unpack_nibble (const char *buf, int *val)
   3526 {
   3527   *val = fromhex (*buf++);
   3528   return buf;
   3529 }
   3530 
   3531 static const char *
   3532 unpack_byte (const char *buf, int *value)
   3533 {
   3534   *value = stub_unpack_int (buf, 2);
   3535   return buf + 2;
   3536 }
   3537 
   3538 static char *
   3539 pack_int (char *buf, int value)
   3540 {
   3541   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
   3542   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
   3543   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
   3544   buf = pack_hex_byte (buf, (value & 0xff));
   3545   return buf;
   3546 }
   3547 
   3548 static const char *
   3549 unpack_int (const char *buf, int *value)
   3550 {
   3551   *value = stub_unpack_int (buf, 8);
   3552   return buf + 8;
   3553 }
   3554 
   3555 #if 0			/* Currently unused, uncomment when needed.  */
   3556 static char *pack_string (char *pkt, char *string);
   3557 
   3558 static char *
   3559 pack_string (char *pkt, char *string)
   3560 {
   3561   char ch;
   3562   int len;
   3563 
   3564   len = strlen (string);
   3565   if (len > 200)
   3566     len = 200;		/* Bigger than most GDB packets, junk???  */
   3567   pkt = pack_hex_byte (pkt, len);
   3568   while (len-- > 0)
   3569     {
   3570       ch = *string++;
   3571       if ((ch == '\0') || (ch == '#'))
   3572 	ch = '*';		/* Protect encapsulation.  */
   3573       *pkt++ = ch;
   3574     }
   3575   return pkt;
   3576 }
   3577 #endif /* 0 (unused) */
   3578 
   3579 static const char *
   3580 unpack_string (const char *src, char *dest, int length)
   3581 {
   3582   while (length--)
   3583     *dest++ = *src++;
   3584   *dest = '\0';
   3585   return src;
   3586 }
   3587 
   3588 static char *
   3589 pack_threadid (char *pkt, threadref *id)
   3590 {
   3591   char *limit;
   3592   unsigned char *altid;
   3593 
   3594   altid = (unsigned char *) id;
   3595   limit = pkt + BUF_THREAD_ID_SIZE;
   3596   while (pkt < limit)
   3597     pkt = pack_hex_byte (pkt, *altid++);
   3598   return pkt;
   3599 }
   3600 
   3601 
   3602 static const char *
   3603 unpack_threadid (const char *inbuf, threadref *id)
   3604 {
   3605   char *altref;
   3606   const char *limit = inbuf + BUF_THREAD_ID_SIZE;
   3607   int x, y;
   3608 
   3609   altref = (char *) id;
   3610 
   3611   while (inbuf < limit)
   3612     {
   3613       x = stubhex (*inbuf++);
   3614       y = stubhex (*inbuf++);
   3615       *altref++ = (x << 4) | y;
   3616     }
   3617   return inbuf;
   3618 }
   3619 
   3620 /* Externally, threadrefs are 64 bits but internally, they are still
   3621    ints.  This is due to a mismatch of specifications.  We would like
   3622    to use 64bit thread references internally.  This is an adapter
   3623    function.  */
   3624 
   3625 void
   3626 int_to_threadref (threadref *id, int value)
   3627 {
   3628   unsigned char *scan;
   3629 
   3630   scan = (unsigned char *) id;
   3631   {
   3632     int i = 4;
   3633     while (i--)
   3634       *scan++ = 0;
   3635   }
   3636   *scan++ = (value >> 24) & 0xff;
   3637   *scan++ = (value >> 16) & 0xff;
   3638   *scan++ = (value >> 8) & 0xff;
   3639   *scan++ = (value & 0xff);
   3640 }
   3641 
   3642 static int
   3643 threadref_to_int (threadref *ref)
   3644 {
   3645   int i, value = 0;
   3646   unsigned char *scan;
   3647 
   3648   scan = *ref;
   3649   scan += 4;
   3650   i = 4;
   3651   while (i-- > 0)
   3652     value = (value << 8) | ((*scan++) & 0xff);
   3653   return value;
   3654 }
   3655 
   3656 static void
   3657 copy_threadref (threadref *dest, threadref *src)
   3658 {
   3659   int i;
   3660   unsigned char *csrc, *cdest;
   3661 
   3662   csrc = (unsigned char *) src;
   3663   cdest = (unsigned char *) dest;
   3664   i = 8;
   3665   while (i--)
   3666     *cdest++ = *csrc++;
   3667 }
   3668 
   3669 static int
   3670 threadmatch (threadref *dest, threadref *src)
   3671 {
   3672   /* Things are broken right now, so just assume we got a match.  */
   3673 #if 0
   3674   unsigned char *srcp, *destp;
   3675   int i, result;
   3676   srcp = (char *) src;
   3677   destp = (char *) dest;
   3678 
   3679   result = 1;
   3680   while (i-- > 0)
   3681     result &= (*srcp++ == *destp++) ? 1 : 0;
   3682   return result;
   3683 #endif
   3684   return 1;
   3685 }
   3686 
   3687 /*
   3688    threadid:1,        # always request threadid
   3689    context_exists:2,
   3690    display:4,
   3691    unique_name:8,
   3692    more_display:16
   3693  */
   3694 
   3695 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
   3696 
   3697 static char *
   3698 pack_threadinfo_request (char *pkt, int mode, threadref *id)
   3699 {
   3700   *pkt++ = 'q';				/* Info Query */
   3701   *pkt++ = 'P';				/* process or thread info */
   3702   pkt = pack_int (pkt, mode);		/* mode */
   3703   pkt = pack_threadid (pkt, id);	/* threadid */
   3704   *pkt = '\0';				/* terminate */
   3705   return pkt;
   3706 }
   3707 
   3708 /* These values tag the fields in a thread info response packet.  */
   3709 /* Tagging the fields allows us to request specific fields and to
   3710    add more fields as time goes by.  */
   3711 
   3712 #define TAG_THREADID 1		/* Echo the thread identifier.  */
   3713 #define TAG_EXISTS 2		/* Is this process defined enough to
   3714 				   fetch registers and its stack?  */
   3715 #define TAG_DISPLAY 4		/* A short thing maybe to put on a window */
   3716 #define TAG_THREADNAME 8	/* string, maps 1-to-1 with a thread is.  */
   3717 #define TAG_MOREDISPLAY 16	/* Whatever the kernel wants to say about
   3718 				   the process.  */
   3719 
   3720 int
   3721 remote_target::remote_unpack_thread_info_response (const char *pkt,
   3722 						   threadref *expectedref,
   3723 						   gdb_ext_thread_info *info)
   3724 {
   3725   struct remote_state *rs = get_remote_state ();
   3726   int mask, length;
   3727   int tag;
   3728   threadref ref;
   3729   const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit.  */
   3730   int retval = 1;
   3731 
   3732   /* info->threadid = 0; FIXME: implement zero_threadref.  */
   3733   info->active = 0;
   3734   info->display[0] = '\0';
   3735   info->shortname[0] = '\0';
   3736   info->more_display[0] = '\0';
   3737 
   3738   /* Assume the characters indicating the packet type have been
   3739      stripped.  */
   3740   pkt = unpack_int (pkt, &mask);	/* arg mask */
   3741   pkt = unpack_threadid (pkt, &ref);
   3742 
   3743   if (mask == 0)
   3744     warning (_("Incomplete response to threadinfo request."));
   3745   if (!threadmatch (&ref, expectedref))
   3746     {			/* This is an answer to a different request.  */
   3747       warning (_("ERROR RMT Thread info mismatch."));
   3748       return 0;
   3749     }
   3750   copy_threadref (&info->threadid, &ref);
   3751 
   3752   /* Loop on tagged fields , try to bail if something goes wrong.  */
   3753 
   3754   /* Packets are terminated with nulls.  */
   3755   while ((pkt < limit) && mask && *pkt)
   3756     {
   3757       pkt = unpack_int (pkt, &tag);	/* tag */
   3758       pkt = unpack_byte (pkt, &length);	/* length */
   3759       if (!(tag & mask))		/* Tags out of synch with mask.  */
   3760 	{
   3761 	  warning (_("ERROR RMT: threadinfo tag mismatch."));
   3762 	  retval = 0;
   3763 	  break;
   3764 	}
   3765       if (tag == TAG_THREADID)
   3766 	{
   3767 	  if (length != 16)
   3768 	    {
   3769 	      warning (_("ERROR RMT: length of threadid is not 16."));
   3770 	      retval = 0;
   3771 	      break;
   3772 	    }
   3773 	  pkt = unpack_threadid (pkt, &ref);
   3774 	  mask = mask & ~TAG_THREADID;
   3775 	  continue;
   3776 	}
   3777       if (tag == TAG_EXISTS)
   3778 	{
   3779 	  info->active = stub_unpack_int (pkt, length);
   3780 	  pkt += length;
   3781 	  mask = mask & ~(TAG_EXISTS);
   3782 	  if (length > 8)
   3783 	    {
   3784 	      warning (_("ERROR RMT: 'exists' length too long."));
   3785 	      retval = 0;
   3786 	      break;
   3787 	    }
   3788 	  continue;
   3789 	}
   3790       if (tag == TAG_THREADNAME)
   3791 	{
   3792 	  pkt = unpack_string (pkt, &info->shortname[0], length);
   3793 	  mask = mask & ~TAG_THREADNAME;
   3794 	  continue;
   3795 	}
   3796       if (tag == TAG_DISPLAY)
   3797 	{
   3798 	  pkt = unpack_string (pkt, &info->display[0], length);
   3799 	  mask = mask & ~TAG_DISPLAY;
   3800 	  continue;
   3801 	}
   3802       if (tag == TAG_MOREDISPLAY)
   3803 	{
   3804 	  pkt = unpack_string (pkt, &info->more_display[0], length);
   3805 	  mask = mask & ~TAG_MOREDISPLAY;
   3806 	  continue;
   3807 	}
   3808       warning (_("ERROR RMT: unknown thread info tag."));
   3809       break;			/* Not a tag we know about.  */
   3810     }
   3811   return retval;
   3812 }
   3813 
   3814 int
   3815 remote_target::remote_get_threadinfo (threadref *threadid,
   3816 				      int fieldset,
   3817 				      gdb_ext_thread_info *info)
   3818 {
   3819   struct remote_state *rs = get_remote_state ();
   3820   int result;
   3821 
   3822   pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
   3823   putpkt (rs->buf);
   3824   getpkt (&rs->buf);
   3825 
   3826   if (rs->buf[0] == '\0')
   3827     return 0;
   3828 
   3829   result = remote_unpack_thread_info_response (&rs->buf[2],
   3830 					       threadid, info);
   3831   return result;
   3832 }
   3833 
   3834 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
   3835 
   3836 static char *
   3837 pack_threadlist_request (char *pkt, int startflag, int threadcount,
   3838 			 threadref *nextthread)
   3839 {
   3840   *pkt++ = 'q';			/* info query packet */
   3841   *pkt++ = 'L';			/* Process LIST or threadLIST request */
   3842   pkt = pack_nibble (pkt, startflag);		/* initflag 1 bytes */
   3843   pkt = pack_hex_byte (pkt, threadcount);	/* threadcount 2 bytes */
   3844   pkt = pack_threadid (pkt, nextthread);	/* 64 bit thread identifier */
   3845   *pkt = '\0';
   3846   return pkt;
   3847 }
   3848 
   3849 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
   3850 
   3851 int
   3852 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
   3853 					  threadref *original_echo,
   3854 					  threadref *resultlist,
   3855 					  int *doneflag)
   3856 {
   3857   struct remote_state *rs = get_remote_state ();
   3858   int count, resultcount, done;
   3859 
   3860   resultcount = 0;
   3861   /* Assume the 'q' and 'M chars have been stripped.  */
   3862   const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
   3863   /* done parse past here */
   3864   pkt = unpack_byte (pkt, &count);	/* count field */
   3865   pkt = unpack_nibble (pkt, &done);
   3866   /* The first threadid is the argument threadid.  */
   3867   pkt = unpack_threadid (pkt, original_echo);	/* should match query packet */
   3868   while ((count-- > 0) && (pkt < limit))
   3869     {
   3870       pkt = unpack_threadid (pkt, resultlist++);
   3871       if (resultcount++ >= result_limit)
   3872 	break;
   3873     }
   3874   if (doneflag)
   3875     *doneflag = done;
   3876   return resultcount;
   3877 }
   3878 
   3879 /* Fetch the next batch of threads from the remote.  Returns -1 if the
   3880    qL packet is not supported, 0 on error and 1 on success.  */
   3881 
   3882 int
   3883 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
   3884 				      int result_limit, int *done, int *result_count,
   3885 				      threadref *threadlist)
   3886 {
   3887   struct remote_state *rs = get_remote_state ();
   3888   int result = 1;
   3889 
   3890   /* Truncate result limit to be smaller than the packet size.  */
   3891   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
   3892       >= get_remote_packet_size ())
   3893     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
   3894 
   3895   pack_threadlist_request (rs->buf.data (), startflag, result_limit,
   3896 			   nextthread);
   3897   putpkt (rs->buf);
   3898   getpkt (&rs->buf);
   3899   if (rs->buf[0] == '\0')
   3900     {
   3901       /* Packet not supported.  */
   3902       return -1;
   3903     }
   3904 
   3905   *result_count =
   3906     parse_threadlist_response (&rs->buf[2], result_limit,
   3907 			       &rs->echo_nextthread, threadlist, done);
   3908 
   3909   if (!threadmatch (&rs->echo_nextthread, nextthread))
   3910     {
   3911       /* FIXME: This is a good reason to drop the packet.  */
   3912       /* Possibly, there is a duplicate response.  */
   3913       /* Possibilities :
   3914 	 retransmit immediatly - race conditions
   3915 	 retransmit after timeout - yes
   3916 	 exit
   3917 	 wait for packet, then exit
   3918        */
   3919       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
   3920       return 0;			/* I choose simply exiting.  */
   3921     }
   3922   if (*result_count <= 0)
   3923     {
   3924       if (*done != 1)
   3925 	{
   3926 	  warning (_("RMT ERROR : failed to get remote thread list."));
   3927 	  result = 0;
   3928 	}
   3929       return result;		/* break; */
   3930     }
   3931   if (*result_count > result_limit)
   3932     {
   3933       *result_count = 0;
   3934       warning (_("RMT ERROR: threadlist response longer than requested."));
   3935       return 0;
   3936     }
   3937   return result;
   3938 }
   3939 
   3940 /* Fetch the list of remote threads, with the qL packet, and call
   3941    STEPFUNCTION for each thread found.  Stops iterating and returns 1
   3942    if STEPFUNCTION returns true.  Stops iterating and returns 0 if the
   3943    STEPFUNCTION returns false.  If the packet is not supported,
   3944    returns -1.  */
   3945 
   3946 int
   3947 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
   3948 					   void *context, int looplimit)
   3949 {
   3950   struct remote_state *rs = get_remote_state ();
   3951   int done, i, result_count;
   3952   int startflag = 1;
   3953   int result = 1;
   3954   int loopcount = 0;
   3955 
   3956   done = 0;
   3957   while (!done)
   3958     {
   3959       if (loopcount++ > looplimit)
   3960 	{
   3961 	  result = 0;
   3962 	  warning (_("Remote fetch threadlist -infinite loop-."));
   3963 	  break;
   3964 	}
   3965       result = remote_get_threadlist (startflag, &rs->nextthread,
   3966 				      MAXTHREADLISTRESULTS,
   3967 				      &done, &result_count,
   3968 				      rs->resultthreadlist);
   3969       if (result <= 0)
   3970 	break;
   3971       /* Clear for later iterations.  */
   3972       startflag = 0;
   3973       /* Setup to resume next batch of thread references, set nextthread.  */
   3974       if (result_count >= 1)
   3975 	copy_threadref (&rs->nextthread,
   3976 			&rs->resultthreadlist[result_count - 1]);
   3977       i = 0;
   3978       while (result_count--)
   3979 	{
   3980 	  if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
   3981 	    {
   3982 	      result = 0;
   3983 	      break;
   3984 	    }
   3985 	}
   3986     }
   3987   return result;
   3988 }
   3989 
   3990 /* A thread found on the remote target.  */
   3991 
   3992 struct thread_item
   3993 {
   3994   explicit thread_item (ptid_t ptid_)
   3995   : ptid (ptid_)
   3996   {}
   3997 
   3998   thread_item (thread_item &&other) = default;
   3999   thread_item &operator= (thread_item &&other) = default;
   4000 
   4001   DISABLE_COPY_AND_ASSIGN (thread_item);
   4002 
   4003   /* The thread's PTID.  */
   4004   ptid_t ptid;
   4005 
   4006   /* The thread's extra info.  */
   4007   std::string extra;
   4008 
   4009   /* The thread's name.  */
   4010   std::string name;
   4011 
   4012   /* The core the thread was running on.  -1 if not known.  */
   4013   int core = -1;
   4014 
   4015   /* The thread handle associated with the thread.  */
   4016   gdb::byte_vector thread_handle;
   4017 };
   4018 
   4019 /* Context passed around to the various methods listing remote
   4020    threads.  As new threads are found, they're added to the ITEMS
   4021    vector.  */
   4022 
   4023 struct threads_listing_context
   4024 {
   4025   /* Return true if this object contains an entry for a thread with ptid
   4026      PTID.  */
   4027 
   4028   bool contains_thread (ptid_t ptid) const
   4029   {
   4030     auto match_ptid = [&] (const thread_item &item)
   4031       {
   4032 	return item.ptid == ptid;
   4033       };
   4034 
   4035     auto it = std::find_if (this->items.begin (),
   4036 			    this->items.end (),
   4037 			    match_ptid);
   4038 
   4039     return it != this->items.end ();
   4040   }
   4041 
   4042   /* Remove the thread with ptid PTID.  */
   4043 
   4044   void remove_thread (ptid_t ptid)
   4045   {
   4046     auto match_ptid = [&] (const thread_item &item)
   4047       {
   4048 	return item.ptid == ptid;
   4049       };
   4050 
   4051     auto it = std::remove_if (this->items.begin (),
   4052 			      this->items.end (),
   4053 			      match_ptid);
   4054 
   4055     if (it != this->items.end ())
   4056       this->items.erase (it);
   4057   }
   4058 
   4059   /* The threads found on the remote target.  */
   4060   std::vector<thread_item> items;
   4061 };
   4062 
   4063 static int
   4064 remote_newthread_step (threadref *ref, void *data)
   4065 {
   4066   struct threads_listing_context *context
   4067     = (struct threads_listing_context *) data;
   4068   int pid = inferior_ptid.pid ();
   4069   int lwp = threadref_to_int (ref);
   4070   ptid_t ptid (pid, lwp);
   4071 
   4072   context->items.emplace_back (ptid);
   4073 
   4074   return 1;			/* continue iterator */
   4075 }
   4076 
   4077 #define CRAZY_MAX_THREADS 1000
   4078 
   4079 ptid_t
   4080 remote_target::remote_current_thread (ptid_t oldpid)
   4081 {
   4082   struct remote_state *rs = get_remote_state ();
   4083 
   4084   putpkt ("qC");
   4085   getpkt (&rs->buf);
   4086   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
   4087     {
   4088       const char *obuf;
   4089       ptid_t result;
   4090 
   4091       result = read_ptid (&rs->buf[2], &obuf);
   4092       if (*obuf != '\0')
   4093 	remote_debug_printf ("warning: garbage in qC reply");
   4094 
   4095       return result;
   4096     }
   4097   else
   4098     return oldpid;
   4099 }
   4100 
   4101 /* List remote threads using the deprecated qL packet.  */
   4102 
   4103 int
   4104 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
   4105 {
   4106   if (remote_threadlist_iterator (remote_newthread_step, context,
   4107 				  CRAZY_MAX_THREADS) >= 0)
   4108     return 1;
   4109 
   4110   return 0;
   4111 }
   4112 
   4113 #if defined(HAVE_LIBEXPAT)
   4114 
   4115 static void
   4116 start_thread (struct gdb_xml_parser *parser,
   4117 	      const struct gdb_xml_element *element,
   4118 	      void *user_data,
   4119 	      std::vector<gdb_xml_value> &attributes)
   4120 {
   4121   struct threads_listing_context *data
   4122     = (struct threads_listing_context *) user_data;
   4123   struct gdb_xml_value *attr;
   4124 
   4125   char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
   4126   ptid_t ptid = read_ptid (id, NULL);
   4127 
   4128   thread_item &item = data->items.emplace_back (ptid);
   4129 
   4130   attr = xml_find_attribute (attributes, "core");
   4131   if (attr != NULL)
   4132     item.core = *(ULONGEST *) attr->value.get ();
   4133 
   4134   attr = xml_find_attribute (attributes, "name");
   4135   if (attr != NULL)
   4136     item.name = (const char *) attr->value.get ();
   4137 
   4138   attr = xml_find_attribute (attributes, "handle");
   4139   if (attr != NULL)
   4140     item.thread_handle = hex2bin ((const char *) attr->value.get ());
   4141 }
   4142 
   4143 static void
   4144 end_thread (struct gdb_xml_parser *parser,
   4145 	    const struct gdb_xml_element *element,
   4146 	    void *user_data, const char *body_text)
   4147 {
   4148   struct threads_listing_context *data
   4149     = (struct threads_listing_context *) user_data;
   4150 
   4151   if (body_text != NULL && *body_text != '\0')
   4152     data->items.back ().extra = body_text;
   4153 }
   4154 
   4155 const struct gdb_xml_attribute thread_attributes[] = {
   4156   { "id", GDB_XML_AF_NONE, NULL, NULL },
   4157   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
   4158   { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
   4159   { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
   4160   { NULL, GDB_XML_AF_NONE, NULL, NULL }
   4161 };
   4162 
   4163 const struct gdb_xml_element thread_children[] = {
   4164   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
   4165 };
   4166 
   4167 const struct gdb_xml_element threads_children[] = {
   4168   { "thread", thread_attributes, thread_children,
   4169     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
   4170     start_thread, end_thread },
   4171   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
   4172 };
   4173 
   4174 const struct gdb_xml_element threads_elements[] = {
   4175   { "threads", NULL, threads_children,
   4176     GDB_XML_EF_NONE, NULL, NULL },
   4177   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
   4178 };
   4179 
   4180 #endif
   4181 
   4182 /* List remote threads using qXfer:threads:read.  */
   4183 
   4184 int
   4185 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
   4186 {
   4187 #if defined(HAVE_LIBEXPAT)
   4188   if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
   4189     {
   4190       std::optional<gdb::char_vector> xml
   4191 	= target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
   4192 
   4193       if (xml && (*xml)[0] != '\0')
   4194 	{
   4195 	  gdb_xml_parse_quick (_("threads"), "threads.dtd",
   4196 			       threads_elements, xml->data (), context);
   4197 	}
   4198 
   4199       return 1;
   4200     }
   4201 #endif
   4202 
   4203   return 0;
   4204 }
   4205 
   4206 /* List remote threads using qfThreadInfo/qsThreadInfo.  */
   4207 
   4208 int
   4209 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
   4210 {
   4211   struct remote_state *rs = get_remote_state ();
   4212 
   4213   if (rs->use_threadinfo_query)
   4214     {
   4215       const char *bufp;
   4216 
   4217       putpkt ("qfThreadInfo");
   4218       getpkt (&rs->buf);
   4219       bufp = rs->buf.data ();
   4220       if (bufp[0] != '\0')		/* q packet recognized */
   4221 	{
   4222 	  while (*bufp++ == 'm')	/* reply contains one or more TID */
   4223 	    {
   4224 	      do
   4225 		{
   4226 		  ptid_t ptid = read_ptid (bufp, &bufp);
   4227 		  context->items.emplace_back (ptid);
   4228 		}
   4229 	      while (*bufp++ == ',');	/* comma-separated list */
   4230 	      putpkt ("qsThreadInfo");
   4231 	      getpkt (&rs->buf);
   4232 	      bufp = rs->buf.data ();
   4233 	    }
   4234 	  return 1;
   4235 	}
   4236       else
   4237 	{
   4238 	  /* Packet not recognized.  */
   4239 	  rs->use_threadinfo_query = 0;
   4240 	}
   4241     }
   4242 
   4243   return 0;
   4244 }
   4245 
   4246 /* Return true if INF only has one non-exited thread.  */
   4247 
   4248 static bool
   4249 has_single_non_exited_thread (inferior *inf)
   4250 {
   4251   int count = 0;
   4252   for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
   4253     if (++count > 1)
   4254       break;
   4255   return count == 1;
   4256 }
   4257 
   4258 /* Implement the to_update_thread_list function for the remote
   4259    targets.  */
   4260 
   4261 void
   4262 remote_target::update_thread_list ()
   4263 {
   4264   struct threads_listing_context context;
   4265   int got_list = 0;
   4266 
   4267   /* We have a few different mechanisms to fetch the thread list.  Try
   4268      them all, starting with the most preferred one first, falling
   4269      back to older methods.  */
   4270   if (remote_get_threads_with_qxfer (&context)
   4271       || remote_get_threads_with_qthreadinfo (&context)
   4272       || remote_get_threads_with_ql (&context))
   4273     {
   4274       got_list = 1;
   4275 
   4276       if (context.items.empty ()
   4277 	  && remote_thread_always_alive (inferior_ptid))
   4278 	{
   4279 	  /* Some targets don't really support threads, but still
   4280 	     reply an (empty) thread list in response to the thread
   4281 	     listing packets, instead of replying "packet not
   4282 	     supported".  Exit early so we don't delete the main
   4283 	     thread.  */
   4284 	  return;
   4285 	}
   4286 
   4287       /* CONTEXT now holds the current thread list on the remote
   4288 	 target end.  Delete GDB-side threads no longer found on the
   4289 	 target.  */
   4290       for (thread_info *tp : all_threads_safe ())
   4291 	{
   4292 	  if (tp->inf->process_target () != this)
   4293 	    continue;
   4294 
   4295 	  if (!context.contains_thread (tp->ptid))
   4296 	    {
   4297 	      /* Do not remove the thread if it is the last thread in
   4298 		 the inferior.  This situation happens when we have a
   4299 		 pending exit process status to process.  Otherwise we
   4300 		 may end up with a seemingly live inferior (i.e.  pid
   4301 		 != 0) that has no threads.  */
   4302 	      if (has_single_non_exited_thread (tp->inf))
   4303 		continue;
   4304 
   4305 	      /* Do not remove the thread if we've requested to be
   4306 		 notified of its exit.  For example, the thread may be
   4307 		 displaced stepping, infrun will need to handle the
   4308 		 exit event, and displaced stepping info is recorded
   4309 		 in the thread object.  If we deleted the thread now,
   4310 		 we'd lose that info.  */
   4311 	      if ((tp->thread_options () & GDB_THREAD_OPTION_EXIT) != 0)
   4312 		continue;
   4313 
   4314 	      /* Not found.  */
   4315 	      delete_thread (tp);
   4316 	    }
   4317 	}
   4318 
   4319       /* Remove any unreported fork/vfork/clone child threads from
   4320 	 CONTEXT so that we don't interfere with follow
   4321 	 fork/vfork/clone, which is where creation of such threads is
   4322 	 handled.  */
   4323       remove_new_children (&context);
   4324 
   4325       /* And now add threads we don't know about yet to our list.  */
   4326       for (thread_item &item : context.items)
   4327 	{
   4328 	  if (item.ptid != null_ptid)
   4329 	    {
   4330 	      /* In non-stop mode, we assume new found threads are
   4331 		 executing until proven otherwise with a stop reply.
   4332 		 In all-stop, we can only get here if all threads are
   4333 		 stopped.  */
   4334 	      bool executing = target_is_non_stop_p ();
   4335 
   4336 	      remote_notice_new_inferior (item.ptid, executing);
   4337 
   4338 	      thread_info *tp = this->find_thread (item.ptid);
   4339 	      remote_thread_info *info = get_remote_thread_info (tp);
   4340 	      info->core = item.core;
   4341 	      info->extra = std::move (item.extra);
   4342 	      info->name = std::move (item.name);
   4343 	      info->thread_handle = std::move (item.thread_handle);
   4344 	    }
   4345 	}
   4346     }
   4347 
   4348   if (!got_list)
   4349     {
   4350       /* If no thread listing method is supported, then query whether
   4351 	 each known thread is alive, one by one, with the T packet.
   4352 	 If the target doesn't support threads at all, then this is a
   4353 	 no-op.  See remote_thread_alive.  */
   4354       prune_threads ();
   4355     }
   4356 }
   4357 
   4358 /*
   4359  * Collect a descriptive string about the given thread.
   4360  * The target may say anything it wants to about the thread
   4361  * (typically info about its blocked / runnable state, name, etc.).
   4362  * This string will appear in the info threads display.
   4363  *
   4364  * Optional: targets are not required to implement this function.
   4365  */
   4366 
   4367 const char *
   4368 remote_target::extra_thread_info (thread_info *tp)
   4369 {
   4370   struct remote_state *rs = get_remote_state ();
   4371   int set;
   4372   threadref id;
   4373   struct gdb_ext_thread_info threadinfo;
   4374 
   4375   if (rs->remote_desc == 0)		/* paranoia */
   4376     internal_error (_("remote_threads_extra_info"));
   4377 
   4378   if (tp->ptid == magic_null_ptid
   4379       || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
   4380     /* This is the main thread which was added by GDB.  The remote
   4381        server doesn't know about it.  */
   4382     return NULL;
   4383 
   4384   std::string &extra = get_remote_thread_info (tp)->extra;
   4385 
   4386   /* If already have cached info, use it.  */
   4387   if (!extra.empty ())
   4388     return extra.c_str ();
   4389 
   4390   if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
   4391     {
   4392       /* If we're using qXfer:threads:read, then the extra info is
   4393 	 included in the XML.  So if we didn't have anything cached,
   4394 	 it's because there's really no extra info.  */
   4395       return NULL;
   4396     }
   4397 
   4398   if (rs->use_threadextra_query)
   4399     {
   4400       char *b = rs->buf.data ();
   4401       char *endb = b + get_remote_packet_size ();
   4402 
   4403       xsnprintf (b, endb - b, "qThreadExtraInfo,");
   4404       b += strlen (b);
   4405       write_ptid (b, endb, tp->ptid);
   4406 
   4407       putpkt (rs->buf);
   4408       getpkt (&rs->buf);
   4409       if (rs->buf[0] != 0)
   4410 	{
   4411 	  extra.resize (strlen (rs->buf.data ()) / 2);
   4412 	  hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
   4413 	  return extra.c_str ();
   4414 	}
   4415     }
   4416 
   4417   /* If the above query fails, fall back to the old method.  */
   4418   rs->use_threadextra_query = 0;
   4419   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
   4420     | TAG_MOREDISPLAY | TAG_DISPLAY;
   4421   int_to_threadref (&id, tp->ptid.lwp ());
   4422   if (remote_get_threadinfo (&id, set, &threadinfo))
   4423     if (threadinfo.active)
   4424       {
   4425 	if (*threadinfo.shortname)
   4426 	  string_appendf (extra, " Name: %s", threadinfo.shortname);
   4427 	if (*threadinfo.display)
   4428 	  {
   4429 	    if (!extra.empty ())
   4430 	      extra += ',';
   4431 	    string_appendf (extra, " State: %s", threadinfo.display);
   4432 	  }
   4433 	if (*threadinfo.more_display)
   4434 	  {
   4435 	    if (!extra.empty ())
   4436 	      extra += ',';
   4437 	    string_appendf (extra, " Priority: %s", threadinfo.more_display);
   4438 	  }
   4439 	return extra.c_str ();
   4440       }
   4441   return NULL;
   4442 }
   4443 
   4444 
   4446 bool
   4447 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
   4448 					    struct static_tracepoint_marker *marker)
   4449 {
   4450   struct remote_state *rs = get_remote_state ();
   4451   char *p = rs->buf.data ();
   4452 
   4453   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
   4454   p += strlen (p);
   4455   p += hexnumstr (p, addr);
   4456   putpkt (rs->buf);
   4457   getpkt (&rs->buf);
   4458   p = rs->buf.data ();
   4459 
   4460   if (*p == 'E')
   4461     error (_("Remote failure reply: %s"), p);
   4462 
   4463   if (*p++ == 'm')
   4464     {
   4465       parse_static_tracepoint_marker_definition (p, NULL, marker);
   4466       return true;
   4467     }
   4468 
   4469   return false;
   4470 }
   4471 
   4472 std::vector<static_tracepoint_marker>
   4473 remote_target::static_tracepoint_markers_by_strid (const char *strid)
   4474 {
   4475   struct remote_state *rs = get_remote_state ();
   4476   std::vector<static_tracepoint_marker> markers;
   4477   const char *p;
   4478   static_tracepoint_marker marker;
   4479 
   4480   /* Ask for a first packet of static tracepoint marker
   4481      definition.  */
   4482   putpkt ("qTfSTM");
   4483   getpkt (&rs->buf);
   4484   p = rs->buf.data ();
   4485   if (*p == 'E')
   4486     error (_("Remote failure reply: %s"), p);
   4487 
   4488   while (*p++ == 'm')
   4489     {
   4490       do
   4491 	{
   4492 	  parse_static_tracepoint_marker_definition (p, &p, &marker);
   4493 
   4494 	  if (strid == NULL || marker.str_id == strid)
   4495 	    markers.push_back (std::move (marker));
   4496 	}
   4497       while (*p++ == ',');	/* comma-separated list */
   4498       /* Ask for another packet of static tracepoint definition.  */
   4499       putpkt ("qTsSTM");
   4500       getpkt (&rs->buf);
   4501       p = rs->buf.data ();
   4502     }
   4503 
   4504   return markers;
   4505 }
   4506 
   4507 
   4508 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
   4510 
   4511 ptid_t
   4512 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
   4513 {
   4514   return ptid_t (inferior_ptid.pid (), lwp);
   4515 }
   4516 
   4517 
   4519 /* Restart the remote side; this is an extended protocol operation.  */
   4520 
   4521 void
   4522 remote_target::extended_remote_restart ()
   4523 {
   4524   struct remote_state *rs = get_remote_state ();
   4525 
   4526   /* Send the restart command; for reasons I don't understand the
   4527      remote side really expects a number after the "R".  */
   4528   xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
   4529   putpkt (rs->buf);
   4530 
   4531   remote_fileio_reset ();
   4532 }
   4533 
   4534 /* Clean up connection to a remote debugger.  */
   4536 
   4537 void
   4538 remote_target::close ()
   4539 {
   4540   /* Make sure we leave stdin registered in the event loop.  */
   4541   terminal_ours ();
   4542 
   4543   trace_reset_local_state ();
   4544 
   4545   delete this;
   4546 }
   4547 
   4548 remote_target::~remote_target ()
   4549 {
   4550   struct remote_state *rs = get_remote_state ();
   4551 
   4552   /* Check for NULL because we may get here with a partially
   4553      constructed target/connection.  */
   4554   if (rs->remote_desc == nullptr)
   4555     return;
   4556 
   4557   serial_close (rs->remote_desc);
   4558 
   4559   /* We are destroying the remote target, so we should discard
   4560      everything of this target.  */
   4561   discard_pending_stop_replies_in_queue ();
   4562 
   4563   rs->delete_async_event_handler ();
   4564 
   4565   delete rs->notif_state;
   4566 }
   4567 
   4568 /* Query the remote side for the text, data and bss offsets.  */
   4569 
   4570 void
   4571 remote_target::get_offsets ()
   4572 {
   4573   struct remote_state *rs = get_remote_state ();
   4574   char *buf;
   4575   char *ptr;
   4576   int lose, num_segments = 0, do_sections, do_segments;
   4577   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
   4578 
   4579   if (current_program_space->symfile_object_file == NULL)
   4580     return;
   4581 
   4582   putpkt ("qOffsets");
   4583   getpkt (&rs->buf);
   4584   buf = rs->buf.data ();
   4585 
   4586   if (buf[0] == '\000')
   4587     return;			/* Return silently.  Stub doesn't support
   4588 				   this command.  */
   4589   if (buf[0] == 'E')
   4590     {
   4591       warning (_("Remote failure reply: %s"), buf);
   4592       return;
   4593     }
   4594 
   4595   /* Pick up each field in turn.  This used to be done with scanf, but
   4596      scanf will make trouble if CORE_ADDR size doesn't match
   4597      conversion directives correctly.  The following code will work
   4598      with any size of CORE_ADDR.  */
   4599   text_addr = data_addr = bss_addr = 0;
   4600   ptr = buf;
   4601   lose = 0;
   4602 
   4603   if (startswith (ptr, "Text="))
   4604     {
   4605       ptr += 5;
   4606       /* Don't use strtol, could lose on big values.  */
   4607       while (*ptr && *ptr != ';')
   4608 	text_addr = (text_addr << 4) + fromhex (*ptr++);
   4609 
   4610       if (startswith (ptr, ";Data="))
   4611 	{
   4612 	  ptr += 6;
   4613 	  while (*ptr && *ptr != ';')
   4614 	    data_addr = (data_addr << 4) + fromhex (*ptr++);
   4615 	}
   4616       else
   4617 	lose = 1;
   4618 
   4619       if (!lose && startswith (ptr, ";Bss="))
   4620 	{
   4621 	  ptr += 5;
   4622 	  while (*ptr && *ptr != ';')
   4623 	    bss_addr = (bss_addr << 4) + fromhex (*ptr++);
   4624 
   4625 	  if (bss_addr != data_addr)
   4626 	    warning (_("Target reported unsupported offsets: %s"), buf);
   4627 	}
   4628       else
   4629 	lose = 1;
   4630     }
   4631   else if (startswith (ptr, "TextSeg="))
   4632     {
   4633       ptr += 8;
   4634       /* Don't use strtol, could lose on big values.  */
   4635       while (*ptr && *ptr != ';')
   4636 	text_addr = (text_addr << 4) + fromhex (*ptr++);
   4637       num_segments = 1;
   4638 
   4639       if (startswith (ptr, ";DataSeg="))
   4640 	{
   4641 	  ptr += 9;
   4642 	  while (*ptr && *ptr != ';')
   4643 	    data_addr = (data_addr << 4) + fromhex (*ptr++);
   4644 	  num_segments++;
   4645 	}
   4646     }
   4647   else
   4648     lose = 1;
   4649 
   4650   if (lose)
   4651     error (_("Malformed response to offset query, %s"), buf);
   4652   else if (*ptr != '\0')
   4653     warning (_("Target reported unsupported offsets: %s"), buf);
   4654 
   4655   objfile *objf = current_program_space->symfile_object_file;
   4656   section_offsets offs = objf->section_offsets;
   4657 
   4658   symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
   4659   do_segments = (data != NULL);
   4660   do_sections = num_segments == 0;
   4661 
   4662   if (num_segments > 0)
   4663     {
   4664       segments[0] = text_addr;
   4665       segments[1] = data_addr;
   4666     }
   4667   /* If we have two segments, we can still try to relocate everything
   4668      by assuming that the .text and .data offsets apply to the whole
   4669      text and data segments.  Convert the offsets given in the packet
   4670      to base addresses for symfile_map_offsets_to_segments.  */
   4671   else if (data != nullptr && data->segments.size () == 2)
   4672     {
   4673       segments[0] = data->segments[0].base + text_addr;
   4674       segments[1] = data->segments[1].base + data_addr;
   4675       num_segments = 2;
   4676     }
   4677   /* If the object file has only one segment, assume that it is text
   4678      rather than data; main programs with no writable data are rare,
   4679      but programs with no code are useless.  Of course the code might
   4680      have ended up in the data segment... to detect that we would need
   4681      the permissions here.  */
   4682   else if (data && data->segments.size () == 1)
   4683     {
   4684       segments[0] = data->segments[0].base + text_addr;
   4685       num_segments = 1;
   4686     }
   4687   /* There's no way to relocate by segment.  */
   4688   else
   4689     do_segments = 0;
   4690 
   4691   if (do_segments)
   4692     {
   4693       int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
   4694 						 data.get (), offs,
   4695 						 num_segments, segments);
   4696 
   4697       if (ret == 0 && !do_sections)
   4698 	error (_("Can not handle qOffsets TextSeg "
   4699 		 "response with this symbol file"));
   4700 
   4701       if (ret > 0)
   4702 	do_sections = 0;
   4703     }
   4704 
   4705   if (do_sections)
   4706     {
   4707       offs[SECT_OFF_TEXT (objf)] = text_addr;
   4708 
   4709       /* This is a temporary kludge to force data and bss to use the
   4710 	 same offsets because that's what nlmconv does now.  The real
   4711 	 solution requires changes to the stub and remote.c that I
   4712 	 don't have time to do right now.  */
   4713 
   4714       offs[SECT_OFF_DATA (objf)] = data_addr;
   4715       offs[SECT_OFF_BSS (objf)] = data_addr;
   4716     }
   4717 
   4718   objfile_relocate (objf, offs);
   4719 }
   4720 
   4721 /* Send interrupt_sequence to remote target.  */
   4722 
   4723 void
   4724 remote_target::send_interrupt_sequence ()
   4725 {
   4726   if (interrupt_sequence_mode == interrupt_sequence_control_c)
   4727     remote_serial_write ("\x03", 1);
   4728   else if (interrupt_sequence_mode == interrupt_sequence_break)
   4729     remote_serial_send_break ();
   4730   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
   4731     {
   4732       remote_serial_send_break ();
   4733       remote_serial_write ("g", 1);
   4734     }
   4735   else
   4736     internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
   4737 		    interrupt_sequence_mode);
   4738 }
   4739 
   4740 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
   4741    and extract the PTID.  Returns NULL_PTID if not found.  */
   4742 
   4743 static ptid_t
   4744 stop_reply_extract_thread (const char *stop_reply)
   4745 {
   4746   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
   4747     {
   4748       const char *p;
   4749 
   4750       /* Txx r:val ; r:val (...)  */
   4751       p = &stop_reply[3];
   4752 
   4753       /* Look for "register" named "thread".  */
   4754       while (*p != '\0')
   4755 	{
   4756 	  const char *p1;
   4757 
   4758 	  p1 = strchr (p, ':');
   4759 	  if (p1 == NULL)
   4760 	    return null_ptid;
   4761 
   4762 	  if (strncmp (p, "thread", p1 - p) == 0)
   4763 	    return read_ptid (++p1, &p);
   4764 
   4765 	  p1 = strchr (p, ';');
   4766 	  if (p1 == NULL)
   4767 	    return null_ptid;
   4768 	  p1++;
   4769 
   4770 	  p = p1;
   4771 	}
   4772     }
   4773 
   4774   return null_ptid;
   4775 }
   4776 
   4777 /* Determine the remote side's current thread.  If we have a stop
   4778    reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
   4779    "thread" register we can extract the current thread from.  If not,
   4780    ask the remote which is the current thread with qC.  The former
   4781    method avoids a roundtrip.  */
   4782 
   4783 ptid_t
   4784 remote_target::get_current_thread (const char *wait_status)
   4785 {
   4786   ptid_t ptid = null_ptid;
   4787 
   4788   /* Note we don't use remote_parse_stop_reply as that makes use of
   4789      the target architecture, which we haven't yet fully determined at
   4790      this point.  */
   4791   if (wait_status != NULL)
   4792     ptid = stop_reply_extract_thread (wait_status);
   4793   if (ptid == null_ptid)
   4794     ptid = remote_current_thread (inferior_ptid);
   4795 
   4796   return ptid;
   4797 }
   4798 
   4799 /* Query the remote target for which is the current thread/process,
   4800    add it to our tables, and update INFERIOR_PTID.  The caller is
   4801    responsible for setting the state such that the remote end is ready
   4802    to return the current thread.
   4803 
   4804    This function is called after handling the '?' or 'vRun' packets,
   4805    whose response is a stop reply from which we can also try
   4806    extracting the thread.  If the target doesn't support the explicit
   4807    qC query, we infer the current thread from that stop reply, passed
   4808    in in WAIT_STATUS, which may be NULL.
   4809 
   4810    The function returns pointer to the main thread of the inferior. */
   4811 
   4812 thread_info *
   4813 remote_target::add_current_inferior_and_thread (const char *wait_status)
   4814 {
   4815   bool fake_pid_p = false;
   4816 
   4817   switch_to_no_thread ();
   4818 
   4819   /* Now, if we have thread information, update the current thread's
   4820      ptid.  */
   4821   ptid_t curr_ptid = get_current_thread (wait_status);
   4822 
   4823   if (curr_ptid != null_ptid)
   4824     {
   4825       if (!m_features.remote_multi_process_p ())
   4826 	fake_pid_p = true;
   4827     }
   4828   else
   4829     {
   4830       /* Without this, some commands which require an active target
   4831 	 (such as kill) won't work.  This variable serves (at least)
   4832 	 double duty as both the pid of the target process (if it has
   4833 	 such), and as a flag indicating that a target is active.  */
   4834       curr_ptid = magic_null_ptid;
   4835       fake_pid_p = true;
   4836     }
   4837 
   4838   remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
   4839 
   4840   /* Add the main thread and switch to it.  Don't try reading
   4841      registers yet, since we haven't fetched the target description
   4842      yet.  */
   4843   thread_info *tp = add_thread_silent (this, curr_ptid);
   4844   switch_to_thread_no_regs (tp);
   4845 
   4846   return tp;
   4847 }
   4848 
   4849 /* Print info about a thread that was found already stopped on
   4850    connection.  */
   4851 
   4852 void
   4853 remote_target::print_one_stopped_thread (thread_info *thread)
   4854 {
   4855   target_waitstatus ws;
   4856 
   4857   /* If there is a pending waitstatus, use it.  If there isn't it's because
   4858      the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
   4859      and process_initial_stop_replies decided it wasn't interesting to save
   4860      and report to the core.  */
   4861   if (thread->has_pending_waitstatus ())
   4862     {
   4863       ws = thread->pending_waitstatus ();
   4864       thread->clear_pending_waitstatus ();
   4865     }
   4866   else
   4867     {
   4868       ws.set_stopped (GDB_SIGNAL_0);
   4869     }
   4870 
   4871   switch_to_thread (thread);
   4872   thread->set_stop_pc (get_frame_pc (get_current_frame ()));
   4873   set_current_sal_from_frame (get_current_frame ());
   4874 
   4875   /* For "info program".  */
   4876   set_last_target_status (this, thread->ptid, ws);
   4877 
   4878   if (ws.kind () == TARGET_WAITKIND_STOPPED)
   4879     {
   4880       enum gdb_signal sig = ws.sig ();
   4881 
   4882       if (signal_print_state (sig))
   4883 	notify_signal_received (sig);
   4884     }
   4885 
   4886   notify_normal_stop (nullptr, 1);
   4887 }
   4888 
   4889 /* Process all initial stop replies the remote side sent in response
   4890    to the ? packet.  These indicate threads that were already stopped
   4891    on initial connection.  We mark these threads as stopped and print
   4892    their current frame before giving the user the prompt.  */
   4893 
   4894 void
   4895 remote_target::process_initial_stop_replies (int from_tty)
   4896 {
   4897   int pending_stop_replies = stop_reply_queue_length ();
   4898   struct thread_info *selected = NULL;
   4899   struct thread_info *lowest_stopped = NULL;
   4900   struct thread_info *first = NULL;
   4901 
   4902   /* This is only used when the target is non-stop.  */
   4903   gdb_assert (target_is_non_stop_p ());
   4904 
   4905   /* Consume the initial pending events.  */
   4906   while (pending_stop_replies-- > 0)
   4907     {
   4908       ptid_t waiton_ptid = minus_one_ptid;
   4909       ptid_t event_ptid;
   4910       struct target_waitstatus ws;
   4911       int ignore_event = 0;
   4912 
   4913       event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
   4914       if (remote_debug)
   4915 	print_target_wait_results (waiton_ptid, event_ptid, ws);
   4916 
   4917       switch (ws.kind ())
   4918 	{
   4919 	case TARGET_WAITKIND_IGNORE:
   4920 	case TARGET_WAITKIND_NO_RESUMED:
   4921 	case TARGET_WAITKIND_SIGNALLED:
   4922 	case TARGET_WAITKIND_EXITED:
   4923 	  /* We shouldn't see these, but if we do, just ignore.  */
   4924 	  remote_debug_printf ("event ignored");
   4925 	  ignore_event = 1;
   4926 	  break;
   4927 
   4928 	default:
   4929 	  break;
   4930 	}
   4931 
   4932       if (ignore_event)
   4933 	continue;
   4934 
   4935       thread_info *evthread = this->find_thread (event_ptid);
   4936 
   4937       if (ws.kind () == TARGET_WAITKIND_STOPPED)
   4938 	{
   4939 	  enum gdb_signal sig = ws.sig ();
   4940 
   4941 	  /* Stubs traditionally report SIGTRAP as initial signal,
   4942 	     instead of signal 0.  Suppress it.  */
   4943 	  if (sig == GDB_SIGNAL_TRAP)
   4944 	    sig = GDB_SIGNAL_0;
   4945 	  evthread->set_stop_signal (sig);
   4946 	  ws.set_stopped (sig);
   4947 	}
   4948 
   4949       if (ws.kind () != TARGET_WAITKIND_STOPPED
   4950 	  || ws.sig () != GDB_SIGNAL_0)
   4951 	evthread->set_pending_waitstatus (ws);
   4952 
   4953       set_executing (this, event_ptid, false);
   4954       set_running (this, event_ptid, false);
   4955       get_remote_thread_info (evthread)->set_not_resumed ();
   4956     }
   4957 
   4958   /* "Notice" the new inferiors before anything related to
   4959      registers/memory.  */
   4960   for (inferior *inf : all_non_exited_inferiors (this))
   4961     {
   4962       inf->needs_setup = true;
   4963 
   4964       if (non_stop)
   4965 	{
   4966 	  thread_info *thread = any_live_thread_of_inferior (inf);
   4967 	  notice_new_inferior (thread, thread->state == THREAD_RUNNING,
   4968 			       from_tty);
   4969 	}
   4970     }
   4971 
   4972   /* If all-stop on top of non-stop, pause all threads.  Note this
   4973      records the threads' stop pc, so must be done after "noticing"
   4974      the inferiors.  */
   4975   if (!non_stop)
   4976     {
   4977       {
   4978 	/* At this point, the remote target is not async.  It needs to be for
   4979 	   the poll in stop_all_threads to consider events from it, so enable
   4980 	   it temporarily.  */
   4981 	gdb_assert (!this->is_async_p ());
   4982 	SCOPE_EXIT { target_async (false); };
   4983 	target_async (true);
   4984 	stop_all_threads ("remote connect in all-stop");
   4985       }
   4986 
   4987       /* If all threads of an inferior were already stopped, we
   4988 	 haven't setup the inferior yet.  */
   4989       for (inferior *inf : all_non_exited_inferiors (this))
   4990 	{
   4991 	  if (inf->needs_setup)
   4992 	    {
   4993 	      thread_info *thread = any_live_thread_of_inferior (inf);
   4994 	      switch_to_thread_no_regs (thread);
   4995 	      setup_inferior (0);
   4996 	    }
   4997 	}
   4998     }
   4999 
   5000   /* Now go over all threads that are stopped, and print their current
   5001      frame.  If all-stop, then if there's a signalled thread, pick
   5002      that as current.  */
   5003   for (thread_info *thread : all_non_exited_threads (this))
   5004     {
   5005       if (first == NULL)
   5006 	first = thread;
   5007 
   5008       if (!non_stop)
   5009 	thread->set_running (false);
   5010       else if (thread->state != THREAD_STOPPED)
   5011 	continue;
   5012 
   5013       if (selected == nullptr && thread->has_pending_waitstatus ())
   5014 	selected = thread;
   5015 
   5016       if (lowest_stopped == NULL
   5017 	  || thread->inf->num < lowest_stopped->inf->num
   5018 	  || thread->per_inf_num < lowest_stopped->per_inf_num)
   5019 	lowest_stopped = thread;
   5020 
   5021       if (non_stop)
   5022 	print_one_stopped_thread (thread);
   5023     }
   5024 
   5025   /* In all-stop, we only print the status of one thread, and leave
   5026      others with their status pending.  */
   5027   if (!non_stop)
   5028     {
   5029       thread_info *thread = selected;
   5030       if (thread == NULL)
   5031 	thread = lowest_stopped;
   5032       if (thread == NULL)
   5033 	thread = first;
   5034 
   5035       print_one_stopped_thread (thread);
   5036     }
   5037 }
   5038 
   5039 /* Mark a remote_target as starting (by setting the starting_up flag within
   5040    its remote_state) for the lifetime of this object.  The reference count
   5041    on the remote target is temporarily incremented, to prevent the target
   5042    being deleted under our feet.  */
   5043 
   5044 struct scoped_mark_target_starting
   5045 {
   5046   /* Constructor, TARGET is the target to be marked as starting, its
   5047      reference count will be incremented.  */
   5048   scoped_mark_target_starting (remote_target *target)
   5049     : m_remote_target (remote_target_ref::new_reference (target)),
   5050       m_restore_starting_up (set_starting_up_flag (target))
   5051   { /* Nothing.  */ }
   5052 
   5053 private:
   5054 
   5055   /* Helper function, set the starting_up flag on TARGET and return an
   5056      object which, when it goes out of scope, will restore the previous
   5057      value of the starting_up flag.  */
   5058   static scoped_restore_tmpl<bool>
   5059   set_starting_up_flag (remote_target *target)
   5060   {
   5061     remote_state *rs = target->get_remote_state ();
   5062     gdb_assert (!rs->starting_up);
   5063     return make_scoped_restore (&rs->starting_up, true);
   5064   }
   5065 
   5066   /* A gdb::ref_ptr pointer to a remote_target.  */
   5067   using remote_target_ref = gdb::ref_ptr<remote_target, target_ops_ref_policy>;
   5068 
   5069   /* A reference to the target on which we are operating.  */
   5070   remote_target_ref m_remote_target;
   5071 
   5072   /* An object which restores the previous value of the starting_up flag
   5073      when it goes out of scope.  */
   5074   scoped_restore_tmpl<bool> m_restore_starting_up;
   5075 };
   5076 
   5077 /* Transfer ownership of the stop_reply owned by EVENT to a
   5078    stop_reply_up object.  */
   5079 
   5080 static stop_reply_up
   5081 as_stop_reply_up (notif_event_up event)
   5082 {
   5083   auto *stop_reply = static_cast<struct stop_reply *> (event.release ());
   5084   return stop_reply_up (stop_reply);
   5085 }
   5086 
   5087 /* Helper for remote_target::start_remote, start the remote connection and
   5088    sync state.  Return true if everything goes OK, otherwise, return false.
   5089    This function exists so that the scoped_restore created within it will
   5090    expire before we return to remote_target::start_remote.  */
   5091 
   5092 bool
   5093 remote_target::start_remote_1 (int from_tty, int extended_p)
   5094 {
   5095   REMOTE_SCOPED_DEBUG_ENTER_EXIT;
   5096 
   5097   struct remote_state *rs = get_remote_state ();
   5098 
   5099   /* Signal other parts that we're going through the initial setup,
   5100      and so things may not be stable yet.  E.g., we don't try to
   5101      install tracepoints until we've relocated symbols.  Also, a
   5102      Ctrl-C before we're connected and synced up can't interrupt the
   5103      target.  Instead, it offers to drop the (potentially wedged)
   5104      connection.  */
   5105   scoped_mark_target_starting target_is_starting (this);
   5106 
   5107   QUIT;
   5108 
   5109   if (interrupt_on_connect)
   5110     send_interrupt_sequence ();
   5111 
   5112   /* Ack any packet which the remote side has already sent.  */
   5113   remote_serial_write ("+", 1);
   5114 
   5115   /* The first packet we send to the target is the optional "supported
   5116      packets" request.  If the target can answer this, it will tell us
   5117      which later probes to skip.  */
   5118   remote_query_supported ();
   5119 
   5120   /* Check vCont support and set the remote state's vCont_action_support
   5121      attribute.  */
   5122   remote_vcont_probe ();
   5123 
   5124   /* If the stub wants to get a QAllow, compose one and send it.  */
   5125   if (m_features.packet_support (PACKET_QAllow) != PACKET_DISABLE)
   5126     set_permissions ();
   5127 
   5128   /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
   5129      unknown 'v' packet with string "OK".  "OK" gets interpreted by GDB
   5130      as a reply to known packet.  For packet "vFile:setfs:" it is an
   5131      invalid reply and GDB would return error in
   5132      remote_hostio_set_filesystem, making remote files access impossible.
   5133      Disable "vFile:setfs:" in such case.  Do not disable other 'v' packets as
   5134      other "vFile" packets get correctly detected even on gdbserver < 7.7.  */
   5135   {
   5136     const char v_mustreplyempty[] = "vMustReplyEmpty";
   5137 
   5138     putpkt (v_mustreplyempty);
   5139     getpkt (&rs->buf);
   5140     if (strcmp (rs->buf.data (), "OK") == 0)
   5141       {
   5142 	m_features.m_protocol_packets[PACKET_vFile_setfs].support
   5143 	  = PACKET_DISABLE;
   5144       }
   5145     else if (strcmp (rs->buf.data (), "") != 0)
   5146       error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
   5147 	     rs->buf.data ());
   5148   }
   5149 
   5150   /* Next, we possibly activate noack mode.
   5151 
   5152      If the QStartNoAckMode packet configuration is set to AUTO,
   5153      enable noack mode if the stub reported a wish for it with
   5154      qSupported.
   5155 
   5156      If set to TRUE, then enable noack mode even if the stub didn't
   5157      report it in qSupported.  If the stub doesn't reply OK, the
   5158      session ends with an error.
   5159 
   5160      If FALSE, then don't activate noack mode, regardless of what the
   5161      stub claimed should be the default with qSupported.  */
   5162 
   5163   if (m_features.packet_support (PACKET_QStartNoAckMode) != PACKET_DISABLE)
   5164     {
   5165       putpkt ("QStartNoAckMode");
   5166       getpkt (&rs->buf);
   5167       if ((m_features.packet_ok (rs->buf, PACKET_QStartNoAckMode)).status ()
   5168 	  == PACKET_OK)
   5169 	rs->noack_mode = 1;
   5170     }
   5171 
   5172   if (extended_p)
   5173     {
   5174       /* Tell the remote that we are using the extended protocol.  */
   5175       putpkt ("!");
   5176       getpkt (&rs->buf);
   5177     }
   5178 
   5179   /* Let the target know which signals it is allowed to pass down to
   5180      the program.  */
   5181   update_signals_program_target ();
   5182 
   5183   /* Next, if the target can specify a description, read it.  We do
   5184      this before anything involving memory or registers.  */
   5185   target_find_description ();
   5186 
   5187   /* Next, now that we know something about the target, update the
   5188      address spaces in the program spaces.  */
   5189   update_address_spaces ();
   5190 
   5191   /* On OSs where the list of libraries is global to all
   5192      processes, we fetch them early.  */
   5193   if (gdbarch_has_global_solist (current_inferior ()->arch ()))
   5194     solib_add (NULL, from_tty, auto_solib_add);
   5195 
   5196   if (target_is_non_stop_p ())
   5197     {
   5198       if (m_features.packet_support (PACKET_QNonStop) != PACKET_ENABLE)
   5199 	error (_("Non-stop mode requested, but remote "
   5200 		 "does not support non-stop"));
   5201 
   5202       putpkt ("QNonStop:1");
   5203       getpkt (&rs->buf);
   5204 
   5205       if (strcmp (rs->buf.data (), "OK") != 0)
   5206 	error (_("Remote refused setting non-stop mode with: %s"),
   5207 	       rs->buf.data ());
   5208 
   5209       /* Find about threads and processes the stub is already
   5210 	 controlling.  We default to adding them in the running state.
   5211 	 The '?' query below will then tell us about which threads are
   5212 	 stopped.  */
   5213       this->update_thread_list ();
   5214     }
   5215   else if (m_features.packet_support (PACKET_QNonStop) == PACKET_ENABLE)
   5216     {
   5217       /* Don't assume that the stub can operate in all-stop mode.
   5218 	 Request it explicitly.  */
   5219       putpkt ("QNonStop:0");
   5220       getpkt (&rs->buf);
   5221 
   5222       if (strcmp (rs->buf.data (), "OK") != 0)
   5223 	error (_("Remote refused setting all-stop mode with: %s"),
   5224 	       rs->buf.data ());
   5225     }
   5226 
   5227   /* Upload TSVs regardless of whether the target is running or not.  The
   5228      remote stub, such as GDBserver, may have some predefined or builtin
   5229      TSVs, even if the target is not running.  */
   5230   if (get_trace_status (current_trace_status ()) != -1)
   5231     {
   5232       struct uploaded_tsv *uploaded_tsvs = NULL;
   5233 
   5234       upload_trace_state_variables (&uploaded_tsvs);
   5235       merge_uploaded_trace_state_variables (&uploaded_tsvs);
   5236     }
   5237 
   5238   /* Check whether the target is running now.  */
   5239   putpkt ("?");
   5240   getpkt (&rs->buf);
   5241 
   5242   if (!target_is_non_stop_p ())
   5243     {
   5244       char *wait_status = NULL;
   5245 
   5246       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
   5247 	{
   5248 	  if (!extended_p)
   5249 	    error (_("The target is not running (try extended-remote?)"));
   5250 	  return false;
   5251 	}
   5252       else
   5253 	{
   5254 	  /* Save the reply for later.  */
   5255 	  wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
   5256 	  strcpy (wait_status, rs->buf.data ());
   5257 	}
   5258 
   5259       /* Fetch thread list.  */
   5260       target_update_thread_list ();
   5261 
   5262       /* Let the stub know that we want it to return the thread.  */
   5263       set_continue_thread (minus_one_ptid);
   5264 
   5265       if (thread_count (this) == 0)
   5266 	{
   5267 	  /* Target has no concept of threads at all.  GDB treats
   5268 	     non-threaded target as single-threaded; add a main
   5269 	     thread.  */
   5270 	  thread_info *tp = add_current_inferior_and_thread (wait_status);
   5271 	  get_remote_thread_info (tp)->set_resumed ();
   5272 	}
   5273       else
   5274 	{
   5275 	  /* We have thread information; select the thread the target
   5276 	     says should be current.  If we're reconnecting to a
   5277 	     multi-threaded program, this will ideally be the thread
   5278 	     that last reported an event before GDB disconnected.  */
   5279 	  ptid_t curr_thread = get_current_thread (wait_status);
   5280 	  if (curr_thread == null_ptid)
   5281 	    {
   5282 	      /* Odd... The target was able to list threads, but not
   5283 		 tell us which thread was current (no "thread"
   5284 		 register in T stop reply?).  Just pick the first
   5285 		 thread in the thread list then.  */
   5286 
   5287 	      remote_debug_printf ("warning: couldn't determine remote "
   5288 				   "current thread; picking first in list.");
   5289 
   5290 	      for (thread_info *tp : all_non_exited_threads (this,
   5291 							     minus_one_ptid))
   5292 		{
   5293 		  switch_to_thread (tp);
   5294 		  break;
   5295 		}
   5296 	    }
   5297 	  else
   5298 	    switch_to_thread (this->find_thread (curr_thread));
   5299 
   5300 	  get_remote_thread_info (inferior_thread ())->set_resumed ();
   5301 	}
   5302 
   5303       /* init_wait_for_inferior should be called before get_offsets in order
   5304 	 to manage `inserted' flag in bp loc in a correct state.
   5305 	 breakpoint_init_inferior, called from init_wait_for_inferior, set
   5306 	 `inserted' flag to 0, while before breakpoint_re_set, called from
   5307 	 start_remote, set `inserted' flag to 1.  In the initialization of
   5308 	 inferior, breakpoint_init_inferior should be called first, and then
   5309 	 breakpoint_re_set can be called.  If this order is broken, state of
   5310 	 `inserted' flag is wrong, and cause some problems on breakpoint
   5311 	 manipulation.  */
   5312       init_wait_for_inferior ();
   5313 
   5314       get_offsets ();		/* Get text, data & bss offsets.  */
   5315 
   5316       /* If we could not find a description using qXfer, and we know
   5317 	 how to do it some other way, try again.  This is not
   5318 	 supported for non-stop; it could be, but it is tricky if
   5319 	 there are no stopped threads when we connect.  */
   5320       if (remote_read_description_p (this)
   5321 	  && gdbarch_target_desc (current_inferior ()->arch ()) == NULL)
   5322 	{
   5323 	  target_clear_description ();
   5324 	  target_find_description ();
   5325 	}
   5326 
   5327       /* Use the previously fetched status.  */
   5328       gdb_assert (wait_status != NULL);
   5329       notif_event_up reply
   5330 	= remote_notif_parse (this, &notif_client_stop, wait_status);
   5331       push_stop_reply (as_stop_reply_up (std::move (reply)));
   5332 
   5333       ::start_remote (from_tty); /* Initialize gdb process mechanisms.  */
   5334     }
   5335   else
   5336     {
   5337       /* Clear WFI global state.  Do this before finding about new
   5338 	 threads and inferiors, and setting the current inferior.
   5339 	 Otherwise we would clear the proceed status of the current
   5340 	 inferior when we want its stop_soon state to be preserved
   5341 	 (see notice_new_inferior).  */
   5342       init_wait_for_inferior ();
   5343 
   5344       /* In non-stop, we will either get an "OK", meaning that there
   5345 	 are no stopped threads at this time; or, a regular stop
   5346 	 reply.  In the latter case, there may be more than one thread
   5347 	 stopped --- we pull them all out using the vStopped
   5348 	 mechanism.  */
   5349       if (strcmp (rs->buf.data (), "OK") != 0)
   5350 	{
   5351 	  const notif_client *notif = &notif_client_stop;
   5352 
   5353 	  /* remote_notif_get_pending_replies acks this one, and gets
   5354 	     the rest out.  */
   5355 	  rs->notif_state->pending_event[notif_client_stop.id]
   5356 	    = remote_notif_parse (this, notif, rs->buf.data ());
   5357 	  remote_notif_get_pending_events (notif);
   5358 	}
   5359 
   5360       if (thread_count (this) == 0)
   5361 	{
   5362 	  if (!extended_p)
   5363 	    error (_("The target is not running (try extended-remote?)"));
   5364 	  return false;
   5365 	}
   5366 
   5367       /* Report all signals during attach/startup.  */
   5368       pass_signals ({});
   5369 
   5370       /* If there are already stopped threads, mark them stopped and
   5371 	 report their stops before giving the prompt to the user.  */
   5372       process_initial_stop_replies (from_tty);
   5373 
   5374       if (target_can_async_p ())
   5375 	target_async (true);
   5376     }
   5377 
   5378   /* Give the target a chance to look up symbols.  */
   5379   for (inferior *inf : all_inferiors (this))
   5380     {
   5381       /* The inferiors that exist at this point were created from what
   5382 	 was found already running on the remote side, so we know they
   5383 	 have execution.  */
   5384       gdb_assert (this->has_execution (inf));
   5385 
   5386       /* No use without a symbol-file.  */
   5387       if (inf->pspace->symfile_object_file == nullptr)
   5388 	continue;
   5389 
   5390       /* Need to switch to a specific thread, because remote_check_symbols
   5391 	 uses INFERIOR_PTID to set the general thread.  */
   5392       scoped_restore_current_thread restore_thread;
   5393       thread_info *thread = any_thread_of_inferior (inf);
   5394       switch_to_thread (thread);
   5395       this->remote_check_symbols ();
   5396     }
   5397 
   5398   /* Possibly the target has been engaged in a trace run started
   5399      previously; find out where things are at.  */
   5400   if (get_trace_status (current_trace_status ()) != -1)
   5401     {
   5402       struct uploaded_tp *uploaded_tps = NULL;
   5403 
   5404       if (current_trace_status ()->running)
   5405 	gdb_printf (_("Trace is already running on the target.\n"));
   5406 
   5407       upload_tracepoints (&uploaded_tps);
   5408 
   5409       merge_uploaded_tracepoints (&uploaded_tps);
   5410     }
   5411 
   5412   /* Possibly the target has been engaged in a btrace record started
   5413      previously; find out where things are at.  */
   5414   remote_btrace_maybe_reopen ();
   5415 
   5416   return true;
   5417 }
   5418 
   5419 /* Start the remote connection and sync state.  */
   5420 
   5421 void
   5422 remote_target::start_remote (int from_tty, int extended_p)
   5423 {
   5424   if (start_remote_1 (from_tty, extended_p)
   5425       && breakpoints_should_be_inserted_now ())
   5426     insert_breakpoints ();
   5427 }
   5428 
   5429 const char *
   5430 remote_target::connection_string ()
   5431 {
   5432   remote_state *rs = get_remote_state ();
   5433 
   5434   if (rs->remote_desc->name != NULL)
   5435     return rs->remote_desc->name;
   5436   else
   5437     return NULL;
   5438 }
   5439 
   5440 /* Open a connection to a remote debugger.
   5441    NAME is the filename used for communication.  */
   5442 
   5443 void
   5444 remote_target::open (const char *name, int from_tty)
   5445 {
   5446   open_1 (name, from_tty, 0);
   5447 }
   5448 
   5449 /* Open a connection to a remote debugger using the extended
   5450    remote gdb protocol.  NAME is the filename used for communication.  */
   5451 
   5452 void
   5453 extended_remote_target::open (const char *name, int from_tty)
   5454 {
   5455   open_1 (name, from_tty, 1 /*extended_p */);
   5456 }
   5457 
   5458 void
   5459 remote_features::reset_all_packet_configs_support ()
   5460 {
   5461   int i;
   5462 
   5463   for (i = 0; i < PACKET_MAX; i++)
   5464     m_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
   5465 }
   5466 
   5467 /* Initialize all packet configs.  */
   5468 
   5469 static void
   5470 init_all_packet_configs (void)
   5471 {
   5472   int i;
   5473 
   5474   for (i = 0; i < PACKET_MAX; i++)
   5475     {
   5476       remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
   5477       remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
   5478     }
   5479 }
   5480 
   5481 /* Symbol look-up.  */
   5482 
   5483 void
   5484 remote_target::remote_check_symbols ()
   5485 {
   5486   char *tmp;
   5487   int end;
   5488 
   5489   /* It doesn't make sense to send a qSymbol packet for an inferior that
   5490      doesn't have execution, because the remote side doesn't know about
   5491      inferiors without execution.  */
   5492   gdb_assert (target_has_execution ());
   5493 
   5494   if (m_features.packet_support (PACKET_qSymbol) == PACKET_DISABLE)
   5495     return;
   5496 
   5497   /* Make sure the remote is pointing at the right process.  Note
   5498      there's no way to select "no process".  */
   5499   set_general_process ();
   5500 
   5501   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
   5502      because we need both at the same time.  */
   5503   gdb::char_vector msg (get_remote_packet_size ());
   5504   gdb::char_vector reply (get_remote_packet_size ());
   5505 
   5506   /* Invite target to request symbol lookups.  */
   5507 
   5508   putpkt ("qSymbol::");
   5509   getpkt (&reply);
   5510   m_features.packet_ok (reply, PACKET_qSymbol);
   5511 
   5512   while (startswith (reply.data (), "qSymbol:"))
   5513     {
   5514       struct bound_minimal_symbol sym;
   5515 
   5516       tmp = &reply[8];
   5517       end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
   5518 		     strlen (tmp) / 2);
   5519       msg[end] = '\0';
   5520       sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
   5521       if (sym.minsym == NULL)
   5522 	xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
   5523 		   &reply[8]);
   5524       else
   5525 	{
   5526 	  int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
   5527 	  CORE_ADDR sym_addr = sym.value_address ();
   5528 
   5529 	  /* If this is a function address, return the start of code
   5530 	     instead of any data function descriptor.  */
   5531 	  sym_addr = gdbarch_convert_from_func_ptr_addr
   5532 	    (current_inferior ()->arch (), sym_addr,
   5533 	     current_inferior ()->top_target ());
   5534 
   5535 	  xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
   5536 		     phex_nz (sym_addr, addr_size), &reply[8]);
   5537 	}
   5538 
   5539       putpkt (msg.data ());
   5540       getpkt (&reply);
   5541     }
   5542 }
   5543 
   5544 static struct serial *
   5545 remote_serial_open (const char *name)
   5546 {
   5547   static int udp_warning = 0;
   5548 
   5549   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
   5550      of in ser-tcp.c, because it is the remote protocol assuming that the
   5551      serial connection is reliable and not the serial connection promising
   5552      to be.  */
   5553   if (!udp_warning && startswith (name, "udp:"))
   5554     {
   5555       warning (_("The remote protocol may be unreliable over UDP.\n"
   5556 		 "Some events may be lost, rendering further debugging "
   5557 		 "impossible."));
   5558       udp_warning = 1;
   5559     }
   5560 
   5561   return serial_open (name);
   5562 }
   5563 
   5564 /* Inform the target of our permission settings.  The permission flags
   5565    work without this, but if the target knows the settings, it can do
   5566    a couple things.  First, it can add its own check, to catch cases
   5567    that somehow manage to get by the permissions checks in target
   5568    methods.  Second, if the target is wired to disallow particular
   5569    settings (for instance, a system in the field that is not set up to
   5570    be able to stop at a breakpoint), it can object to any unavailable
   5571    permissions.  */
   5572 
   5573 void
   5574 remote_target::set_permissions ()
   5575 {
   5576   struct remote_state *rs = get_remote_state ();
   5577 
   5578   xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
   5579 	     "WriteReg:%x;WriteMem:%x;"
   5580 	     "InsertBreak:%x;InsertTrace:%x;"
   5581 	     "InsertFastTrace:%x;Stop:%x",
   5582 	     may_write_registers, may_write_memory,
   5583 	     may_insert_breakpoints, may_insert_tracepoints,
   5584 	     may_insert_fast_tracepoints, may_stop);
   5585   putpkt (rs->buf);
   5586   getpkt (&rs->buf);
   5587 
   5588   /* If the target didn't like the packet, warn the user.  Do not try
   5589      to undo the user's settings, that would just be maddening.  */
   5590   if (strcmp (rs->buf.data (), "OK") != 0)
   5591     warning (_("Remote refused setting permissions with: %s"),
   5592 	     rs->buf.data ());
   5593 }
   5594 
   5595 /* This type describes each known response to the qSupported
   5596    packet.  */
   5597 struct protocol_feature
   5598 {
   5599   /* The name of this protocol feature.  */
   5600   const char *name;
   5601 
   5602   /* The default for this protocol feature.  */
   5603   enum packet_support default_support;
   5604 
   5605   /* The function to call when this feature is reported, or after
   5606      qSupported processing if the feature is not supported.
   5607      The first argument points to this structure.  The second
   5608      argument indicates whether the packet requested support be
   5609      enabled, disabled, or probed (or the default, if this function
   5610      is being called at the end of processing and this feature was
   5611      not reported).  The third argument may be NULL; if not NULL, it
   5612      is a NUL-terminated string taken from the packet following
   5613      this feature's name and an equals sign.  */
   5614   void (*func) (remote_target *remote, const struct protocol_feature *,
   5615 		enum packet_support, const char *);
   5616 
   5617   /* The corresponding packet for this feature.  Only used if
   5618      FUNC is remote_supported_packet.  */
   5619   int packet;
   5620 };
   5621 
   5622 static void
   5623 remote_supported_packet (remote_target *remote,
   5624 			 const struct protocol_feature *feature,
   5625 			 enum packet_support support,
   5626 			 const char *argument)
   5627 {
   5628   if (argument)
   5629     {
   5630       warning (_("Remote qSupported response supplied an unexpected value for"
   5631 		 " \"%s\"."), feature->name);
   5632       return;
   5633     }
   5634 
   5635   remote->m_features.m_protocol_packets[feature->packet].support = support;
   5636 }
   5637 
   5638 void
   5639 remote_target::remote_packet_size (const protocol_feature *feature,
   5640 				   enum packet_support support,
   5641 				   const char *value)
   5642 {
   5643   struct remote_state *rs = get_remote_state ();
   5644 
   5645   int packet_size;
   5646   char *value_end;
   5647 
   5648   if (support != PACKET_ENABLE)
   5649     return;
   5650 
   5651   if (value == NULL || *value == '\0')
   5652     {
   5653       warning (_("Remote target reported \"%s\" without a size."),
   5654 	       feature->name);
   5655       return;
   5656     }
   5657 
   5658   errno = 0;
   5659   packet_size = strtol (value, &value_end, 16);
   5660   if (errno != 0 || *value_end != '\0' || packet_size < 0)
   5661     {
   5662       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
   5663 	       feature->name, value);
   5664       return;
   5665     }
   5666 
   5667   /* Record the new maximum packet size.  */
   5668   rs->explicit_packet_size = packet_size;
   5669 }
   5670 
   5671 static void
   5672 remote_packet_size (remote_target *remote, const protocol_feature *feature,
   5673 		    enum packet_support support, const char *value)
   5674 {
   5675   remote->remote_packet_size (feature, support, value);
   5676 }
   5677 
   5678 void
   5679 remote_target::remote_supported_thread_options (const protocol_feature *feature,
   5680 						enum packet_support support,
   5681 						const char *value)
   5682 {
   5683   struct remote_state *rs = get_remote_state ();
   5684 
   5685   m_features.m_protocol_packets[feature->packet].support = support;
   5686 
   5687   if (support != PACKET_ENABLE)
   5688     return;
   5689 
   5690   if (value == nullptr || *value == '\0')
   5691     {
   5692       warning (_("Remote target reported \"%s\" without supported options."),
   5693 	       feature->name);
   5694       return;
   5695     }
   5696 
   5697   ULONGEST options = 0;
   5698   const char *p = unpack_varlen_hex (value, &options);
   5699 
   5700   if (*p != '\0')
   5701     {
   5702       warning (_("Remote target reported \"%s\" with "
   5703 		 "bad thread options: \"%s\"."),
   5704 	       feature->name, value);
   5705       return;
   5706     }
   5707 
   5708   /* Record the set of supported options.  */
   5709   rs->supported_thread_options = (gdb_thread_option) options;
   5710 }
   5711 
   5712 static void
   5713 remote_supported_thread_options (remote_target *remote,
   5714 				 const protocol_feature *feature,
   5715 				 enum packet_support support,
   5716 				 const char *value)
   5717 {
   5718   remote->remote_supported_thread_options (feature, support, value);
   5719 }
   5720 
   5721 static const struct protocol_feature remote_protocol_features[] = {
   5722   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
   5723   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
   5724     PACKET_qXfer_auxv },
   5725   { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
   5726     PACKET_qXfer_exec_file },
   5727   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
   5728     PACKET_qXfer_features },
   5729   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
   5730     PACKET_qXfer_libraries },
   5731   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
   5732     PACKET_qXfer_libraries_svr4 },
   5733   { "augmented-libraries-svr4-read", PACKET_DISABLE,
   5734     remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
   5735   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
   5736     PACKET_qXfer_memory_map },
   5737   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
   5738     PACKET_qXfer_osdata },
   5739   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
   5740     PACKET_qXfer_threads },
   5741   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
   5742     PACKET_qXfer_traceframe_info },
   5743   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
   5744     PACKET_QPassSignals },
   5745   { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
   5746     PACKET_QCatchSyscalls },
   5747   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
   5748     PACKET_QProgramSignals },
   5749   { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
   5750     PACKET_QSetWorkingDir },
   5751   { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
   5752     PACKET_QStartupWithShell },
   5753   { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
   5754     PACKET_QEnvironmentHexEncoded },
   5755   { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
   5756     PACKET_QEnvironmentReset },
   5757   { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
   5758     PACKET_QEnvironmentUnset },
   5759   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
   5760     PACKET_QStartNoAckMode },
   5761   { "multiprocess", PACKET_DISABLE, remote_supported_packet,
   5762     PACKET_multiprocess_feature },
   5763   { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
   5764   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
   5765     PACKET_qXfer_siginfo_read },
   5766   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
   5767     PACKET_qXfer_siginfo_write },
   5768   { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
   5769     PACKET_ConditionalTracepoints },
   5770   { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
   5771     PACKET_ConditionalBreakpoints },
   5772   { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
   5773     PACKET_BreakpointCommands },
   5774   { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
   5775     PACKET_FastTracepoints },
   5776   { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
   5777     PACKET_StaticTracepoints },
   5778   {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
   5779    PACKET_InstallInTrace},
   5780   { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
   5781     PACKET_DisconnectedTracing_feature },
   5782   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
   5783     PACKET_bc },
   5784   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
   5785     PACKET_bs },
   5786   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
   5787     PACKET_TracepointSource },
   5788   { "QAllow", PACKET_DISABLE, remote_supported_packet,
   5789     PACKET_QAllow },
   5790   { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
   5791     PACKET_EnableDisableTracepoints_feature },
   5792   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
   5793     PACKET_qXfer_fdpic },
   5794   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
   5795     PACKET_qXfer_uib },
   5796   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
   5797     PACKET_QDisableRandomization },
   5798   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
   5799   { "QTBuffer:size", PACKET_DISABLE,
   5800     remote_supported_packet, PACKET_QTBuffer_size},
   5801   { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
   5802   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
   5803   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
   5804   { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
   5805   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
   5806     PACKET_qXfer_btrace },
   5807   { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
   5808     PACKET_qXfer_btrace_conf },
   5809   { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
   5810     PACKET_Qbtrace_conf_bts_size },
   5811   { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
   5812   { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
   5813   { "fork-events", PACKET_DISABLE, remote_supported_packet,
   5814     PACKET_fork_event_feature },
   5815   { "vfork-events", PACKET_DISABLE, remote_supported_packet,
   5816     PACKET_vfork_event_feature },
   5817   { "exec-events", PACKET_DISABLE, remote_supported_packet,
   5818     PACKET_exec_event_feature },
   5819   { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
   5820     PACKET_Qbtrace_conf_pt_size },
   5821   { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
   5822   { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
   5823   { "QThreadOptions", PACKET_DISABLE, remote_supported_thread_options,
   5824     PACKET_QThreadOptions },
   5825   { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
   5826   { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
   5827     PACKET_memory_tagging_feature },
   5828 };
   5829 
   5830 static char *remote_support_xml;
   5831 
   5832 /* Register string appended to "xmlRegisters=" in qSupported query.  */
   5833 
   5834 void
   5835 register_remote_support_xml (const char *xml)
   5836 {
   5837 #if defined(HAVE_LIBEXPAT)
   5838   if (remote_support_xml == NULL)
   5839     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
   5840   else
   5841     {
   5842       char *copy = xstrdup (remote_support_xml + 13);
   5843       char *saveptr;
   5844       char *p = strtok_r (copy, ",", &saveptr);
   5845 
   5846       do
   5847 	{
   5848 	  if (strcmp (p, xml) == 0)
   5849 	    {
   5850 	      /* already there */
   5851 	      xfree (copy);
   5852 	      return;
   5853 	    }
   5854 	}
   5855       while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
   5856       xfree (copy);
   5857 
   5858       remote_support_xml = reconcat (remote_support_xml,
   5859 				     remote_support_xml, ",", xml,
   5860 				     (char *) NULL);
   5861     }
   5862 #endif
   5863 }
   5864 
   5865 static void
   5866 remote_query_supported_append (std::string *msg, const char *append)
   5867 {
   5868   if (!msg->empty ())
   5869     msg->append (";");
   5870   msg->append (append);
   5871 }
   5872 
   5873 void
   5874 remote_target::remote_query_supported ()
   5875 {
   5876   struct remote_state *rs = get_remote_state ();
   5877   char *next;
   5878   int i;
   5879   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
   5880 
   5881   /* The packet support flags are handled differently for this packet
   5882      than for most others.  We treat an error, a disabled packet, and
   5883      an empty response identically: any features which must be reported
   5884      to be used will be automatically disabled.  An empty buffer
   5885      accomplishes this, since that is also the representation for a list
   5886      containing no features.  */
   5887 
   5888   rs->buf[0] = 0;
   5889   if (m_features.packet_support (PACKET_qSupported) != PACKET_DISABLE)
   5890     {
   5891       std::string q;
   5892 
   5893       if (m_features.packet_set_cmd_state (PACKET_multiprocess_feature)
   5894 	  != AUTO_BOOLEAN_FALSE)
   5895 	remote_query_supported_append (&q, "multiprocess+");
   5896 
   5897       if (m_features.packet_set_cmd_state (PACKET_swbreak_feature)
   5898 	  != AUTO_BOOLEAN_FALSE)
   5899 	remote_query_supported_append (&q, "swbreak+");
   5900 
   5901       if (m_features.packet_set_cmd_state (PACKET_hwbreak_feature)
   5902 	  != AUTO_BOOLEAN_FALSE)
   5903 	remote_query_supported_append (&q, "hwbreak+");
   5904 
   5905       remote_query_supported_append (&q, "qRelocInsn+");
   5906 
   5907       if (m_features.packet_set_cmd_state (PACKET_fork_event_feature)
   5908 	  != AUTO_BOOLEAN_FALSE)
   5909 	remote_query_supported_append (&q, "fork-events+");
   5910 
   5911       if (m_features.packet_set_cmd_state (PACKET_vfork_event_feature)
   5912 	  != AUTO_BOOLEAN_FALSE)
   5913 	remote_query_supported_append (&q, "vfork-events+");
   5914 
   5915       if (m_features.packet_set_cmd_state (PACKET_exec_event_feature)
   5916 	  != AUTO_BOOLEAN_FALSE)
   5917 	remote_query_supported_append (&q, "exec-events+");
   5918 
   5919       if (m_features.packet_set_cmd_state (PACKET_vContSupported)
   5920 	  != AUTO_BOOLEAN_FALSE)
   5921 	remote_query_supported_append (&q, "vContSupported+");
   5922 
   5923       if (m_features.packet_set_cmd_state (PACKET_QThreadEvents)
   5924 	  != AUTO_BOOLEAN_FALSE)
   5925 	remote_query_supported_append (&q, "QThreadEvents+");
   5926 
   5927       if (m_features.packet_set_cmd_state (PACKET_QThreadOptions)
   5928 	  != AUTO_BOOLEAN_FALSE)
   5929 	remote_query_supported_append (&q, "QThreadOptions+");
   5930 
   5931       if (m_features.packet_set_cmd_state (PACKET_no_resumed)
   5932 	  != AUTO_BOOLEAN_FALSE)
   5933 	remote_query_supported_append (&q, "no-resumed+");
   5934 
   5935       if (m_features.packet_set_cmd_state (PACKET_memory_tagging_feature)
   5936 	  != AUTO_BOOLEAN_FALSE)
   5937 	remote_query_supported_append (&q, "memory-tagging+");
   5938 
   5939       /* Keep this one last to work around a gdbserver <= 7.10 bug in
   5940 	 the qSupported:xmlRegisters=i386 handling.  */
   5941       if (remote_support_xml != NULL
   5942 	  && (m_features.packet_support (PACKET_qXfer_features)
   5943 	      != PACKET_DISABLE))
   5944 	remote_query_supported_append (&q, remote_support_xml);
   5945 
   5946       q = "qSupported:" + q;
   5947       putpkt (q.c_str ());
   5948 
   5949       getpkt (&rs->buf);
   5950 
   5951       /* If an error occurred, warn, but do not return - just reset the
   5952 	 buffer to empty and go on to disable features.  */
   5953       packet_result result = m_features.packet_ok (rs->buf, PACKET_qSupported);
   5954       if (result.status () == PACKET_ERROR)
   5955 	{
   5956 	  warning (_("Remote failure reply: %s"), result.err_msg ());
   5957 	  rs->buf[0] = 0;
   5958 	}
   5959     }
   5960 
   5961   memset (seen, 0, sizeof (seen));
   5962 
   5963   next = rs->buf.data ();
   5964   while (*next)
   5965     {
   5966       enum packet_support is_supported;
   5967       char *p, *end, *name_end, *value;
   5968 
   5969       /* First separate out this item from the rest of the packet.  If
   5970 	 there's another item after this, we overwrite the separator
   5971 	 (terminated strings are much easier to work with).  */
   5972       p = next;
   5973       end = strchr (p, ';');
   5974       if (end == NULL)
   5975 	{
   5976 	  end = p + strlen (p);
   5977 	  next = end;
   5978 	}
   5979       else
   5980 	{
   5981 	  *end = '\0';
   5982 	  next = end + 1;
   5983 
   5984 	  if (end == p)
   5985 	    {
   5986 	      warning (_("empty item in \"qSupported\" response"));
   5987 	      continue;
   5988 	    }
   5989 	}
   5990 
   5991       name_end = strchr (p, '=');
   5992       if (name_end)
   5993 	{
   5994 	  /* This is a name=value entry.  */
   5995 	  is_supported = PACKET_ENABLE;
   5996 	  value = name_end + 1;
   5997 	  *name_end = '\0';
   5998 	}
   5999       else
   6000 	{
   6001 	  value = NULL;
   6002 	  switch (end[-1])
   6003 	    {
   6004 	    case '+':
   6005 	      is_supported = PACKET_ENABLE;
   6006 	      break;
   6007 
   6008 	    case '-':
   6009 	      is_supported = PACKET_DISABLE;
   6010 	      break;
   6011 
   6012 	    case '?':
   6013 	      is_supported = PACKET_SUPPORT_UNKNOWN;
   6014 	      break;
   6015 
   6016 	    default:
   6017 	      warning (_("unrecognized item \"%s\" "
   6018 			 "in \"qSupported\" response"), p);
   6019 	      continue;
   6020 	    }
   6021 	  end[-1] = '\0';
   6022 	}
   6023 
   6024       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
   6025 	if (strcmp (remote_protocol_features[i].name, p) == 0)
   6026 	  {
   6027 	    const struct protocol_feature *feature;
   6028 
   6029 	    seen[i] = 1;
   6030 	    feature = &remote_protocol_features[i];
   6031 	    feature->func (this, feature, is_supported, value);
   6032 	    break;
   6033 	  }
   6034     }
   6035 
   6036   /* If we increased the packet size, make sure to increase the global
   6037      buffer size also.  We delay this until after parsing the entire
   6038      qSupported packet, because this is the same buffer we were
   6039      parsing.  */
   6040   if (rs->buf.size () < rs->explicit_packet_size)
   6041     rs->buf.resize (rs->explicit_packet_size);
   6042 
   6043   /* Handle the defaults for unmentioned features.  */
   6044   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
   6045     if (!seen[i])
   6046       {
   6047 	const struct protocol_feature *feature;
   6048 
   6049 	feature = &remote_protocol_features[i];
   6050 	feature->func (this, feature, feature->default_support, NULL);
   6051       }
   6052 }
   6053 
   6054 /* Serial QUIT handler for the remote serial descriptor.
   6055 
   6056    Defers handling a Ctrl-C until we're done with the current
   6057    command/response packet sequence, unless:
   6058 
   6059    - We're setting up the connection.  Don't send a remote interrupt
   6060      request, as we're not fully synced yet.  Quit immediately
   6061      instead.
   6062 
   6063    - The target has been resumed in the foreground
   6064      (target_terminal::is_ours is false) with a synchronous resume
   6065      packet, and we're blocked waiting for the stop reply, thus a
   6066      Ctrl-C should be immediately sent to the target.
   6067 
   6068    - We get a second Ctrl-C while still within the same serial read or
   6069      write.  In that case the serial is seemingly wedged --- offer to
   6070      quit/disconnect.
   6071 
   6072    - We see a second Ctrl-C without target response, after having
   6073      previously interrupted the target.  In that case the target/stub
   6074      is probably wedged --- offer to quit/disconnect.
   6075 */
   6076 
   6077 void
   6078 remote_target::remote_serial_quit_handler ()
   6079 {
   6080   struct remote_state *rs = get_remote_state ();
   6081 
   6082   if (check_quit_flag ())
   6083     {
   6084       /* If we're starting up, we're not fully synced yet.  Quit
   6085 	 immediately.  */
   6086       if (rs->starting_up)
   6087 	quit ();
   6088       else if (rs->got_ctrlc_during_io)
   6089 	{
   6090 	  if (query (_("The target is not responding to GDB commands.\n"
   6091 		       "Stop debugging it? ")))
   6092 	    remote_unpush_and_throw (this);
   6093 	}
   6094       /* If ^C has already been sent once, offer to disconnect.  */
   6095       else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
   6096 	interrupt_query ();
   6097       /* All-stop protocol, and blocked waiting for stop reply.  Send
   6098 	 an interrupt request.  */
   6099       else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
   6100 	target_interrupt ();
   6101       else
   6102 	rs->got_ctrlc_during_io = 1;
   6103     }
   6104 }
   6105 
   6106 /* The remote_target that is current while the quit handler is
   6107    overridden with remote_serial_quit_handler.  */
   6108 static remote_target *curr_quit_handler_target;
   6109 
   6110 static void
   6111 remote_serial_quit_handler ()
   6112 {
   6113   curr_quit_handler_target->remote_serial_quit_handler ();
   6114 }
   6115 
   6116 /* Remove the remote target from the target stack of each inferior
   6117    that is using it.  Upper targets depend on it so remove them
   6118    first.  */
   6119 
   6120 static void
   6121 remote_unpush_target (remote_target *target)
   6122 {
   6123   /* We have to unpush the target from all inferiors, even those that
   6124      aren't running.  */
   6125   scoped_restore_current_inferior restore_current_inferior;
   6126 
   6127   for (inferior *inf : all_inferiors (target))
   6128     {
   6129       switch_to_inferior_no_thread (inf);
   6130       inf->pop_all_targets_at_and_above (process_stratum);
   6131       generic_mourn_inferior ();
   6132     }
   6133 
   6134   /* Don't rely on target_close doing this when the target is popped
   6135      from the last remote inferior above, because something may be
   6136      holding a reference to the target higher up on the stack, meaning
   6137      target_close won't be called yet.  We lost the connection to the
   6138      target, so clear these now, otherwise we may later throw
   6139      TARGET_CLOSE_ERROR while trying to tell the remote target to
   6140      close the file.  */
   6141   fileio_handles_invalidate_target (target);
   6142 }
   6143 
   6144 static void
   6145 remote_unpush_and_throw (remote_target *target)
   6146 {
   6147   remote_unpush_target (target);
   6148   throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
   6149 }
   6150 
   6151 void
   6152 remote_target::open_1 (const char *name, int from_tty, int extended_p)
   6153 {
   6154   remote_target *curr_remote = get_current_remote_target ();
   6155 
   6156   if (name == 0)
   6157     error (_("To open a remote debug connection, you need to specify what\n"
   6158 	   "serial device is attached to the remote system\n"
   6159 	   "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
   6160 
   6161   /* If we're connected to a running target, target_preopen will kill it.
   6162      Ask this question first, before target_preopen has a chance to kill
   6163      anything.  */
   6164   if (curr_remote != NULL && !target_has_execution ())
   6165     {
   6166       if (from_tty
   6167 	  && !query (_("Already connected to a remote target.  Disconnect? ")))
   6168 	error (_("Still connected."));
   6169     }
   6170 
   6171   /* Here the possibly existing remote target gets unpushed.  */
   6172   target_preopen (from_tty);
   6173 
   6174   remote_fileio_reset ();
   6175   reopen_exec_file ();
   6176   reread_symbols (from_tty);
   6177 
   6178   remote_target *remote
   6179     = (extended_p ? new extended_remote_target () : new remote_target ());
   6180   target_ops_up target_holder (remote);
   6181 
   6182   remote_state *rs = remote->get_remote_state ();
   6183 
   6184   /* See FIXME above.  */
   6185   if (!target_async_permitted)
   6186     rs->wait_forever_enabled_p = true;
   6187 
   6188   rs->remote_desc = remote_serial_open (name);
   6189 
   6190   if (baud_rate != -1)
   6191     {
   6192       try
   6193 	{
   6194 	  serial_setbaudrate (rs->remote_desc, baud_rate);
   6195 	}
   6196       catch (const gdb_exception_error &)
   6197 	{
   6198 	  /* The requested speed could not be set.  Error out to
   6199 	     top level after closing remote_desc.  Take care to
   6200 	     set remote_desc to NULL to avoid closing remote_desc
   6201 	     more than once.  */
   6202 	  serial_close (rs->remote_desc);
   6203 	  rs->remote_desc = NULL;
   6204 	  throw;
   6205 	}
   6206     }
   6207 
   6208   serial_setparity (rs->remote_desc, serial_parity);
   6209   serial_raw (rs->remote_desc);
   6210 
   6211   /* If there is something sitting in the buffer we might take it as a
   6212      response to a command, which would be bad.  */
   6213   serial_flush_input (rs->remote_desc);
   6214 
   6215   if (from_tty)
   6216     {
   6217       gdb_puts ("Remote debugging using ");
   6218       gdb_puts (name);
   6219       gdb_puts ("\n");
   6220     }
   6221 
   6222   /* Switch to using the remote target now.  */
   6223   current_inferior ()->push_target (std::move (target_holder));
   6224 
   6225   /* Register extra event sources in the event loop.  */
   6226   rs->create_async_event_handler ();
   6227 
   6228   rs->notif_state = remote_notif_state_allocate (remote);
   6229 
   6230   /* Reset the target state; these things will be queried either by
   6231      remote_query_supported or as they are needed.  */
   6232   remote->m_features.reset_all_packet_configs_support ();
   6233   rs->explicit_packet_size = 0;
   6234   rs->noack_mode = 0;
   6235   rs->extended = extended_p;
   6236   rs->waiting_for_stop_reply = 0;
   6237   rs->ctrlc_pending_p = 0;
   6238   rs->got_ctrlc_during_io = 0;
   6239 
   6240   rs->general_thread = not_sent_ptid;
   6241   rs->continue_thread = not_sent_ptid;
   6242   rs->remote_traceframe_number = -1;
   6243 
   6244   rs->last_resume_exec_dir = EXEC_FORWARD;
   6245 
   6246   /* Probe for ability to use "ThreadInfo" query, as required.  */
   6247   rs->use_threadinfo_query = 1;
   6248   rs->use_threadextra_query = 1;
   6249 
   6250   rs->readahead_cache.invalidate ();
   6251 
   6252   if (target_async_permitted)
   6253     {
   6254       /* FIXME: cagney/1999-09-23: During the initial connection it is
   6255 	 assumed that the target is already ready and able to respond to
   6256 	 requests.  Unfortunately remote_start_remote() eventually calls
   6257 	 wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
   6258 	 around this.  Eventually a mechanism that allows
   6259 	 wait_for_inferior() to expect/get timeouts will be
   6260 	 implemented.  */
   6261       rs->wait_forever_enabled_p = false;
   6262     }
   6263 
   6264   /* First delete any symbols previously loaded from shared libraries.  */
   6265   no_shared_libraries (NULL, 0);
   6266 
   6267   /* Start the remote connection.  If error() or QUIT, discard this
   6268      target (we'd otherwise be in an inconsistent state) and then
   6269      propogate the error on up the exception chain.  This ensures that
   6270      the caller doesn't stumble along blindly assuming that the
   6271      function succeeded.  The CLI doesn't have this problem but other
   6272      UI's, such as MI do.
   6273 
   6274      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
   6275      this function should return an error indication letting the
   6276      caller restore the previous state.  Unfortunately the command
   6277      ``target remote'' is directly wired to this function making that
   6278      impossible.  On a positive note, the CLI side of this problem has
   6279      been fixed - the function set_cmd_context() makes it possible for
   6280      all the ``target ....'' commands to share a common callback
   6281      function.  See cli-dump.c.  */
   6282   {
   6283 
   6284     try
   6285       {
   6286 	remote->start_remote (from_tty, extended_p);
   6287       }
   6288     catch (const gdb_exception &ex)
   6289       {
   6290 	/* Pop the partially set up target - unless something else did
   6291 	   already before throwing the exception.  */
   6292 	if (ex.error != TARGET_CLOSE_ERROR)
   6293 	  remote_unpush_target (remote);
   6294 	throw;
   6295       }
   6296   }
   6297 
   6298   remote_btrace_reset (rs);
   6299 
   6300   if (target_async_permitted)
   6301     rs->wait_forever_enabled_p = true;
   6302 }
   6303 
   6304 /* Determine if WS represents a fork status.  */
   6305 
   6306 static bool
   6307 is_fork_status (target_waitkind kind)
   6308 {
   6309   return (kind == TARGET_WAITKIND_FORKED
   6310 	  || kind == TARGET_WAITKIND_VFORKED);
   6311 }
   6312 
   6313 /* Return a reference to the field where a pending child status, if
   6314    there's one, is recorded.  If there's no child event pending, the
   6315    returned waitstatus has TARGET_WAITKIND_IGNORE kind.  */
   6316 
   6317 static const target_waitstatus &
   6318 thread_pending_status (struct thread_info *thread)
   6319 {
   6320   return (thread->has_pending_waitstatus ()
   6321 	  ? thread->pending_waitstatus ()
   6322 	  : thread->pending_follow);
   6323 }
   6324 
   6325 /* Return THREAD's pending status if it is a pending fork/vfork (but
   6326    not clone) parent, else return nullptr.  */
   6327 
   6328 static const target_waitstatus *
   6329 thread_pending_fork_status (struct thread_info *thread)
   6330 {
   6331   const target_waitstatus &ws = thread_pending_status (thread);
   6332 
   6333   if (!is_fork_status (ws.kind ()))
   6334     return nullptr;
   6335 
   6336   return &ws;
   6337 }
   6338 
   6339 /* Return THREAD's pending status if is is a pending fork/vfork/clone
   6340    event, else return nullptr.  */
   6341 
   6342 static const target_waitstatus *
   6343 thread_pending_child_status (thread_info *thread)
   6344 {
   6345   const target_waitstatus &ws = thread_pending_status (thread);
   6346 
   6347   if (!is_new_child_status (ws.kind ()))
   6348     return nullptr;
   6349 
   6350   return &ws;
   6351 }
   6352 
   6353 /* Detach the specified process.  */
   6354 
   6355 void
   6356 remote_target::remote_detach_pid (int pid)
   6357 {
   6358   struct remote_state *rs = get_remote_state ();
   6359 
   6360   /* This should not be necessary, but the handling for D;PID in
   6361      GDBserver versions prior to 8.2 incorrectly assumes that the
   6362      selected process points to the same process we're detaching,
   6363      leading to misbehavior (and possibly GDBserver crashing) when it
   6364      does not.  Since it's easy and cheap, work around it by forcing
   6365      GDBserver to select GDB's current process.  */
   6366   set_general_process ();
   6367 
   6368   if (m_features.remote_multi_process_p ())
   6369     xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
   6370   else
   6371     strcpy (rs->buf.data (), "D");
   6372 
   6373   putpkt (rs->buf);
   6374   getpkt (&rs->buf);
   6375 
   6376   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
   6377     ;
   6378   else if (rs->buf[0] == '\0')
   6379     error (_("Remote doesn't know how to detach"));
   6380   else
   6381     {
   6382       /* It is possible that we have an unprocessed exit event for this
   6383 	 pid.  If this is the case then we can ignore the failure to detach
   6384 	 and just pretend that the detach worked, as far as the user is
   6385 	 concerned, the process exited immediately after the detach.  */
   6386       bool process_has_already_exited = false;
   6387       remote_notif_get_pending_events (&notif_client_stop);
   6388       for (stop_reply_up &reply : rs->stop_reply_queue)
   6389 	{
   6390 	  if (reply->ptid.pid () != pid)
   6391 	    continue;
   6392 
   6393 	  enum target_waitkind kind = reply->ws.kind ();
   6394 	  if (kind == TARGET_WAITKIND_EXITED
   6395 	      || kind == TARGET_WAITKIND_SIGNALLED)
   6396 	    {
   6397 	      process_has_already_exited = true;
   6398 	      remote_debug_printf
   6399 		("detach failed, but process already exited");
   6400 	      break;
   6401 	    }
   6402 	}
   6403 
   6404       if (!process_has_already_exited)
   6405 	error (_("can't detach process: %s"), (char *) rs->buf.data ());
   6406     }
   6407 }
   6408 
   6409 /* This detaches a program to which we previously attached, using
   6410    inferior_ptid to identify the process.  After this is done, GDB
   6411    can be used to debug some other program.  We better not have left
   6412    any breakpoints in the target program or it'll die when it hits
   6413    one.  */
   6414 
   6415 void
   6416 remote_target::remote_detach_1 (inferior *inf, int from_tty)
   6417 {
   6418   int pid = inferior_ptid.pid ();
   6419   struct remote_state *rs = get_remote_state ();
   6420   int is_fork_parent;
   6421 
   6422   if (!target_has_execution ())
   6423     error (_("No process to detach from."));
   6424 
   6425   target_announce_detach (from_tty);
   6426 
   6427   if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
   6428     {
   6429       /* If we're in breakpoints-always-inserted mode, or the inferior
   6430 	 is running, we have to remove breakpoints before detaching.
   6431 	 We don't do this in common code instead because not all
   6432 	 targets support removing breakpoints while the target is
   6433 	 running.  The remote target / gdbserver does, though.  */
   6434       remove_breakpoints_inf (current_inferior ());
   6435     }
   6436 
   6437   /* Tell the remote target to detach.  */
   6438   remote_detach_pid (pid);
   6439 
   6440   /* Exit only if this is the only active inferior.  */
   6441   if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
   6442     gdb_puts (_("Ending remote debugging.\n"));
   6443 
   6444   /* See if any thread of the inferior we are detaching has a pending fork
   6445      status.  In that case, we must detach from the child resulting from
   6446      that fork.  */
   6447   for (thread_info *thread : inf->non_exited_threads ())
   6448     {
   6449       const target_waitstatus *ws = thread_pending_fork_status (thread);
   6450 
   6451       if (ws == nullptr)
   6452 	continue;
   6453 
   6454       remote_detach_pid (ws->child_ptid ().pid ());
   6455     }
   6456 
   6457   /* Check also for any pending fork events in the stop reply queue.  */
   6458   remote_notif_get_pending_events (&notif_client_stop);
   6459   for (stop_reply_up &reply : rs->stop_reply_queue)
   6460     {
   6461       if (reply->ptid.pid () != pid)
   6462 	continue;
   6463 
   6464       if (!is_fork_status (reply->ws.kind ()))
   6465 	continue;
   6466 
   6467       remote_detach_pid (reply->ws.child_ptid ().pid ());
   6468     }
   6469 
   6470   thread_info *tp = this->find_thread (inferior_ptid);
   6471 
   6472   /* Check to see if we are detaching a fork parent.  Note that if we
   6473      are detaching a fork child, tp == NULL.  */
   6474   is_fork_parent = (tp != NULL
   6475 		    && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
   6476 
   6477   /* If doing detach-on-fork, we don't mourn, because that will delete
   6478      breakpoints that should be available for the followed inferior.  */
   6479   if (!is_fork_parent)
   6480     {
   6481       /* Save the pid as a string before mourning, since that will
   6482 	 unpush the remote target, and we need the string after.  */
   6483       std::string infpid = target_pid_to_str (ptid_t (pid));
   6484 
   6485       target_mourn_inferior (inferior_ptid);
   6486       if (print_inferior_events)
   6487 	gdb_printf (_("[Inferior %d (%s) detached]\n"),
   6488 		    inf->num, infpid.c_str ());
   6489     }
   6490   else
   6491     {
   6492       switch_to_no_thread ();
   6493       detach_inferior (current_inferior ());
   6494     }
   6495 }
   6496 
   6497 void
   6498 remote_target::detach (inferior *inf, int from_tty)
   6499 {
   6500   remote_detach_1 (inf, from_tty);
   6501 }
   6502 
   6503 void
   6504 extended_remote_target::detach (inferior *inf, int from_tty)
   6505 {
   6506   remote_detach_1 (inf, from_tty);
   6507 }
   6508 
   6509 /* Target follow-fork function for remote targets.  On entry, and
   6510    at return, the current inferior is the fork parent.
   6511 
   6512    Note that although this is currently only used for extended-remote,
   6513    it is named remote_follow_fork in anticipation of using it for the
   6514    remote target as well.  */
   6515 
   6516 void
   6517 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
   6518 			    target_waitkind fork_kind, bool follow_child,
   6519 			    bool detach_fork)
   6520 {
   6521   process_stratum_target::follow_fork (child_inf, child_ptid,
   6522 				       fork_kind, follow_child, detach_fork);
   6523 
   6524   if ((fork_kind == TARGET_WAITKIND_FORKED
   6525        && m_features.remote_fork_event_p ())
   6526       || (fork_kind == TARGET_WAITKIND_VFORKED
   6527 	  && m_features.remote_vfork_event_p ()))
   6528     {
   6529       /* When following the parent and detaching the child, we detach
   6530 	 the child here.  For the case of following the child and
   6531 	 detaching the parent, the detach is done in the target-
   6532 	 independent follow fork code in infrun.c.  We can't use
   6533 	 target_detach when detaching an unfollowed child because
   6534 	 the client side doesn't know anything about the child.  */
   6535       if (detach_fork && !follow_child)
   6536 	{
   6537 	  /* Detach the fork child.  */
   6538 	  remote_detach_pid (child_ptid.pid ());
   6539 	}
   6540     }
   6541 }
   6542 
   6543 void
   6544 remote_target::follow_clone (ptid_t child_ptid)
   6545 {
   6546   remote_add_thread (child_ptid, false, false, false);
   6547 }
   6548 
   6549 /* Target follow-exec function for remote targets.  Save EXECD_PATHNAME
   6550    in the program space of the new inferior.  */
   6551 
   6552 void
   6553 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
   6554 			    const char *execd_pathname)
   6555 {
   6556   process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
   6557 
   6558   /* We know that this is a target file name, so if it has the "target:"
   6559      prefix we strip it off before saving it in the program space.  */
   6560   if (is_target_filename (execd_pathname))
   6561     execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
   6562 
   6563   set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
   6564 }
   6565 
   6566 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
   6567 
   6568 void
   6569 remote_target::disconnect (const char *args, int from_tty)
   6570 {
   6571   if (args)
   6572     error (_("Argument given to \"disconnect\" when remotely debugging."));
   6573 
   6574   /* Make sure we unpush even the extended remote targets.  Calling
   6575      target_mourn_inferior won't unpush, and
   6576      remote_target::mourn_inferior won't unpush if there is more than
   6577      one inferior left.  */
   6578   remote_unpush_target (this);
   6579 
   6580   if (from_tty)
   6581     gdb_puts ("Ending remote debugging.\n");
   6582 }
   6583 
   6584 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
   6585    be chatty about it.  */
   6586 
   6587 void
   6588 extended_remote_target::attach (const char *args, int from_tty)
   6589 {
   6590   struct remote_state *rs = get_remote_state ();
   6591   int pid;
   6592   char *wait_status = NULL;
   6593 
   6594   pid = parse_pid_to_attach (args);
   6595 
   6596   /* Remote PID can be freely equal to getpid, do not check it here the same
   6597      way as in other targets.  */
   6598 
   6599   if (m_features.packet_support (PACKET_vAttach) == PACKET_DISABLE)
   6600     error (_("This target does not support attaching to a process"));
   6601 
   6602   target_announce_attach (from_tty, pid);
   6603 
   6604   xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
   6605   putpkt (rs->buf);
   6606   getpkt (&rs->buf);
   6607 
   6608   packet_result result = m_features.packet_ok (rs->buf, PACKET_vAttach);
   6609   switch (result.status ())
   6610     {
   6611     case PACKET_OK:
   6612       if (!target_is_non_stop_p ())
   6613 	{
   6614 	  /* Save the reply for later.  */
   6615 	  wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
   6616 	  strcpy (wait_status, rs->buf.data ());
   6617 	}
   6618       else if (strcmp (rs->buf.data (), "OK") != 0)
   6619 	error (_("Attaching to %s failed with: %s"),
   6620 	       target_pid_to_str (ptid_t (pid)).c_str (),
   6621 	       rs->buf.data ());
   6622       break;
   6623     case PACKET_UNKNOWN:
   6624       error (_("This target does not support attaching to a process"));
   6625     case PACKET_ERROR:
   6626       error (_("Attaching to %s failed: %s"),
   6627 	     target_pid_to_str (ptid_t (pid)).c_str (), result.err_msg ());
   6628     }
   6629 
   6630   switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
   6631 
   6632   inferior_ptid = ptid_t (pid);
   6633 
   6634   if (target_is_non_stop_p ())
   6635     {
   6636       /* Get list of threads.  */
   6637       update_thread_list ();
   6638 
   6639       thread_info *thread = first_thread_of_inferior (current_inferior ());
   6640       if (thread != nullptr)
   6641 	switch_to_thread (thread);
   6642 
   6643       /* Invalidate our notion of the remote current thread.  */
   6644       record_currthread (rs, minus_one_ptid);
   6645     }
   6646   else
   6647     {
   6648       /* Now, if we have thread information, update the main thread's
   6649 	 ptid.  */
   6650       ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
   6651 
   6652       /* Add the main thread to the thread list.  We add the thread
   6653 	 silently in this case (the final true parameter).  */
   6654       thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
   6655 
   6656       switch_to_thread (thr);
   6657     }
   6658 
   6659   /* Next, if the target can specify a description, read it.  We do
   6660      this before anything involving memory or registers.  */
   6661   target_find_description ();
   6662 
   6663   if (!target_is_non_stop_p ())
   6664     {
   6665       /* Use the previously fetched status.  */
   6666       gdb_assert (wait_status != NULL);
   6667 
   6668       notif_event_up reply
   6669 	= remote_notif_parse (this, &notif_client_stop, wait_status);
   6670       push_stop_reply (as_stop_reply_up (std::move (reply)));
   6671     }
   6672   else
   6673     {
   6674       gdb_assert (wait_status == NULL);
   6675 
   6676       gdb_assert (target_can_async_p ());
   6677     }
   6678 }
   6679 
   6680 /* Implementation of the to_post_attach method.  */
   6681 
   6682 void
   6683 extended_remote_target::post_attach (int pid)
   6684 {
   6685   /* Get text, data & bss offsets.  */
   6686   get_offsets ();
   6687 
   6688   /* In certain cases GDB might not have had the chance to start
   6689      symbol lookup up until now.  This could happen if the debugged
   6690      binary is not using shared libraries, the vsyscall page is not
   6691      present (on Linux) and the binary itself hadn't changed since the
   6692      debugging process was started.  */
   6693   if (current_program_space->symfile_object_file != NULL)
   6694     remote_check_symbols();
   6695 }
   6696 
   6697 
   6698 /* Check for the availability of vCont.  This function should also check
   6700    the response.  */
   6701 
   6702 void
   6703 remote_target::remote_vcont_probe ()
   6704 {
   6705   remote_state *rs = get_remote_state ();
   6706   char *buf;
   6707 
   6708   strcpy (rs->buf.data (), "vCont?");
   6709   putpkt (rs->buf);
   6710   getpkt (&rs->buf);
   6711   buf = rs->buf.data ();
   6712 
   6713   /* Make sure that the features we assume are supported.  */
   6714   if (startswith (buf, "vCont"))
   6715     {
   6716       char *p = &buf[5];
   6717       int support_c, support_C;
   6718 
   6719       rs->supports_vCont.s = 0;
   6720       rs->supports_vCont.S = 0;
   6721       support_c = 0;
   6722       support_C = 0;
   6723       rs->supports_vCont.t = 0;
   6724       rs->supports_vCont.r = 0;
   6725       while (p && *p == ';')
   6726 	{
   6727 	  p++;
   6728 	  if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
   6729 	    rs->supports_vCont.s = 1;
   6730 	  else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
   6731 	    rs->supports_vCont.S = 1;
   6732 	  else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
   6733 	    support_c = 1;
   6734 	  else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
   6735 	    support_C = 1;
   6736 	  else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
   6737 	    rs->supports_vCont.t = 1;
   6738 	  else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
   6739 	    rs->supports_vCont.r = 1;
   6740 
   6741 	  p = strchr (p, ';');
   6742 	}
   6743 
   6744       /* If c, and C are not all supported, we can't use vCont.  Clearing
   6745 	 BUF will make packet_ok disable the packet.  */
   6746       if (!support_c || !support_C)
   6747 	buf[0] = 0;
   6748     }
   6749 
   6750   m_features.packet_ok (rs->buf, PACKET_vCont);
   6751 }
   6752 
   6753 /* Helper function for building "vCont" resumptions.  Write a
   6754    resumption to P.  ENDP points to one-passed-the-end of the buffer
   6755    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
   6756    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
   6757    resumed thread should be single-stepped and/or signalled.  If PTID
   6758    equals minus_one_ptid, then all threads are resumed; if PTID
   6759    represents a process, then all threads of the process are
   6760    resumed.  */
   6761 
   6762 char *
   6763 remote_target::append_resumption (char *p, char *endp,
   6764 				  ptid_t ptid, int step, gdb_signal siggnal)
   6765 {
   6766   struct remote_state *rs = get_remote_state ();
   6767 
   6768   if (step && siggnal != GDB_SIGNAL_0)
   6769     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
   6770   else if (step
   6771 	   /* GDB is willing to range step.  */
   6772 	   && use_range_stepping
   6773 	   /* Target supports range stepping.  */
   6774 	   && rs->supports_vCont.r
   6775 	   /* We don't currently support range stepping multiple
   6776 	      threads with a wildcard (though the protocol allows it,
   6777 	      so stubs shouldn't make an active effort to forbid
   6778 	      it).  */
   6779 	   && !(m_features.remote_multi_process_p () && ptid.is_pid ()))
   6780     {
   6781       struct thread_info *tp;
   6782 
   6783       if (ptid == minus_one_ptid)
   6784 	{
   6785 	  /* If we don't know about the target thread's tid, then
   6786 	     we're resuming magic_null_ptid (see caller).  */
   6787 	  tp = this->find_thread (magic_null_ptid);
   6788 	}
   6789       else
   6790 	tp = this->find_thread (ptid);
   6791       gdb_assert (tp != NULL);
   6792 
   6793       if (tp->control.may_range_step)
   6794 	{
   6795 	  int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
   6796 
   6797 	  p += xsnprintf (p, endp - p, ";r%s,%s",
   6798 			  phex_nz (tp->control.step_range_start,
   6799 				   addr_size),
   6800 			  phex_nz (tp->control.step_range_end,
   6801 				   addr_size));
   6802 	}
   6803       else
   6804 	p += xsnprintf (p, endp - p, ";s");
   6805     }
   6806   else if (step)
   6807     p += xsnprintf (p, endp - p, ";s");
   6808   else if (siggnal != GDB_SIGNAL_0)
   6809     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
   6810   else
   6811     p += xsnprintf (p, endp - p, ";c");
   6812 
   6813   if (m_features.remote_multi_process_p () && ptid.is_pid ())
   6814     {
   6815       ptid_t nptid;
   6816 
   6817       /* All (-1) threads of process.  */
   6818       nptid = ptid_t (ptid.pid (), -1);
   6819 
   6820       p += xsnprintf (p, endp - p, ":");
   6821       p = write_ptid (p, endp, nptid);
   6822     }
   6823   else if (ptid != minus_one_ptid)
   6824     {
   6825       p += xsnprintf (p, endp - p, ":");
   6826       p = write_ptid (p, endp, ptid);
   6827     }
   6828 
   6829   return p;
   6830 }
   6831 
   6832 /* Clear the thread's private info on resume.  */
   6833 
   6834 static void
   6835 resume_clear_thread_private_info (struct thread_info *thread)
   6836 {
   6837   if (thread->priv != NULL)
   6838     {
   6839       remote_thread_info *priv = get_remote_thread_info (thread);
   6840 
   6841       priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
   6842       priv->watch_data_address = 0;
   6843     }
   6844 }
   6845 
   6846 /* Append a vCont continue-with-signal action for threads that have a
   6847    non-zero stop signal.  */
   6848 
   6849 char *
   6850 remote_target::append_pending_thread_resumptions (char *p, char *endp,
   6851 						  ptid_t ptid)
   6852 {
   6853   for (thread_info *thread : all_non_exited_threads (this, ptid))
   6854     if (inferior_ptid != thread->ptid
   6855 	&& thread->stop_signal () != GDB_SIGNAL_0)
   6856       {
   6857 	p = append_resumption (p, endp, thread->ptid,
   6858 			       0, thread->stop_signal ());
   6859 	thread->set_stop_signal (GDB_SIGNAL_0);
   6860 	resume_clear_thread_private_info (thread);
   6861       }
   6862 
   6863   return p;
   6864 }
   6865 
   6866 /* Set the target running, using the packets that use Hc
   6867    (c/s/C/S).  */
   6868 
   6869 void
   6870 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
   6871 				      gdb_signal siggnal)
   6872 {
   6873   struct remote_state *rs = get_remote_state ();
   6874   char *buf;
   6875 
   6876   rs->last_sent_signal = siggnal;
   6877   rs->last_sent_step = step;
   6878 
   6879   /* The c/s/C/S resume packets use Hc, so set the continue
   6880      thread.  */
   6881   if (ptid == minus_one_ptid)
   6882     set_continue_thread (any_thread_ptid);
   6883   else
   6884     set_continue_thread (ptid);
   6885 
   6886   for (thread_info *thread : all_non_exited_threads (this))
   6887     resume_clear_thread_private_info (thread);
   6888 
   6889   buf = rs->buf.data ();
   6890   if (::execution_direction == EXEC_REVERSE)
   6891     {
   6892       /* We don't pass signals to the target in reverse exec mode.  */
   6893       if (info_verbose && siggnal != GDB_SIGNAL_0)
   6894 	warning (_(" - Can't pass signal %d to target in reverse: ignored."),
   6895 		 siggnal);
   6896 
   6897       if (step && m_features.packet_support (PACKET_bs) == PACKET_DISABLE)
   6898 	error (_("Remote reverse-step not supported."));
   6899       if (!step && m_features.packet_support (PACKET_bc) == PACKET_DISABLE)
   6900 	error (_("Remote reverse-continue not supported."));
   6901 
   6902       strcpy (buf, step ? "bs" : "bc");
   6903     }
   6904   else if (siggnal != GDB_SIGNAL_0)
   6905     {
   6906       buf[0] = step ? 'S' : 'C';
   6907       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
   6908       buf[2] = tohex (((int) siggnal) & 0xf);
   6909       buf[3] = '\0';
   6910     }
   6911   else
   6912     strcpy (buf, step ? "s" : "c");
   6913 
   6914   putpkt (buf);
   6915 }
   6916 
   6917 /* Resume the remote inferior by using a "vCont" packet.  SCOPE_PTID,
   6918    STEP, and SIGGNAL have the same meaning as in target_resume.  This
   6919    function returns non-zero iff it resumes the inferior.
   6920 
   6921    This function issues a strict subset of all possible vCont commands
   6922    at the moment.  */
   6923 
   6924 int
   6925 remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
   6926 					 enum gdb_signal siggnal)
   6927 {
   6928   struct remote_state *rs = get_remote_state ();
   6929   char *p;
   6930   char *endp;
   6931 
   6932   /* No reverse execution actions defined for vCont.  */
   6933   if (::execution_direction == EXEC_REVERSE)
   6934     return 0;
   6935 
   6936   if (m_features.packet_support (PACKET_vCont) == PACKET_DISABLE)
   6937     return 0;
   6938 
   6939   p = rs->buf.data ();
   6940   endp = p + get_remote_packet_size ();
   6941 
   6942   /* If we could generate a wider range of packets, we'd have to worry
   6943      about overflowing BUF.  Should there be a generic
   6944      "multi-part-packet" packet?  */
   6945 
   6946   p += xsnprintf (p, endp - p, "vCont");
   6947 
   6948   if (scope_ptid == magic_null_ptid)
   6949     {
   6950       /* MAGIC_NULL_PTID means that we don't have any active threads,
   6951 	 so we don't have any TID numbers the inferior will
   6952 	 understand.  Make sure to only send forms that do not specify
   6953 	 a TID.  */
   6954       append_resumption (p, endp, minus_one_ptid, step, siggnal);
   6955     }
   6956   else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
   6957     {
   6958       /* Resume all threads (of all processes, or of a single
   6959 	 process), with preference for INFERIOR_PTID.  This assumes
   6960 	 inferior_ptid belongs to the set of all threads we are about
   6961 	 to resume.  */
   6962       if (step || siggnal != GDB_SIGNAL_0)
   6963 	{
   6964 	  /* Step inferior_ptid, with or without signal.  */
   6965 	  p = append_resumption (p, endp, inferior_ptid, step, siggnal);
   6966 	}
   6967 
   6968       /* Also pass down any pending signaled resumption for other
   6969 	 threads not the current.  */
   6970       p = append_pending_thread_resumptions (p, endp, scope_ptid);
   6971 
   6972       /* And continue others without a signal.  */
   6973       append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
   6974     }
   6975   else
   6976     {
   6977       /* Scheduler locking; resume only SCOPE_PTID.  */
   6978       append_resumption (p, endp, scope_ptid, step, siggnal);
   6979     }
   6980 
   6981   gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
   6982   putpkt (rs->buf);
   6983 
   6984   if (target_is_non_stop_p ())
   6985     {
   6986       /* In non-stop, the stub replies to vCont with "OK".  The stop
   6987 	 reply will be reported asynchronously by means of a `%Stop'
   6988 	 notification.  */
   6989       getpkt (&rs->buf);
   6990       if (strcmp (rs->buf.data (), "OK") != 0)
   6991 	error (_("Unexpected vCont reply in non-stop mode: %s"),
   6992 	       rs->buf.data ());
   6993     }
   6994 
   6995   return 1;
   6996 }
   6997 
   6998 /* Tell the remote machine to resume.  */
   6999 
   7000 void
   7001 remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
   7002 {
   7003   struct remote_state *rs = get_remote_state ();
   7004 
   7005   /* When connected in non-stop mode, the core resumes threads
   7006      individually.  Resuming remote threads directly in target_resume
   7007      would thus result in sending one packet per thread.  Instead, to
   7008      minimize roundtrip latency, here we just store the resume
   7009      request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
   7010      resumption will be done in remote_target::commit_resume, where we'll be
   7011      able to do vCont action coalescing.  */
   7012   if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
   7013     {
   7014       remote_thread_info *remote_thr
   7015 	= get_remote_thread_info (inferior_thread ());
   7016 
   7017       /* We don't expect the core to ask to resume an already resumed (from
   7018 	 its point of view) thread.  */
   7019       gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
   7020 
   7021       remote_thr->set_resumed_pending_vcont (step, siggnal);
   7022 
   7023       /* There's actually nothing that says that the core can't
   7024 	 request a wildcard resume in non-stop mode, though.  It's
   7025 	 just that we know it doesn't currently, so we don't bother
   7026 	 with it.  */
   7027       gdb_assert (scope_ptid == inferior_ptid);
   7028       return;
   7029     }
   7030 
   7031   commit_requested_thread_options ();
   7032 
   7033   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
   7034      (explained in remote-notif.c:handle_notification) so
   7035      remote_notif_process is not called.  We need find a place where
   7036      it is safe to start a 'vNotif' sequence.  It is good to do it
   7037      before resuming inferior, because inferior was stopped and no RSP
   7038      traffic at that moment.  */
   7039   if (!target_is_non_stop_p ())
   7040     remote_notif_process (rs->notif_state, &notif_client_stop);
   7041 
   7042   rs->last_resume_exec_dir = ::execution_direction;
   7043 
   7044   /* Prefer vCont, and fallback to s/c/S/C, which use Hc.  */
   7045   if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
   7046     remote_resume_with_hc (scope_ptid, step, siggnal);
   7047 
   7048   /* Update resumed state tracked by the remote target.  */
   7049   for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
   7050     get_remote_thread_info (tp)->set_resumed ();
   7051 
   7052   /* We've just told the target to resume.  The remote server will
   7053      wait for the inferior to stop, and then send a stop reply.  In
   7054      the mean time, we can't start another command/query ourselves
   7055      because the stub wouldn't be ready to process it.  This applies
   7056      only to the base all-stop protocol, however.  In non-stop (which
   7057      only supports vCont), the stub replies with an "OK", and is
   7058      immediate able to process further serial input.  */
   7059   if (!target_is_non_stop_p ())
   7060     rs->waiting_for_stop_reply = 1;
   7061 }
   7062 
   7063 /* Private per-inferior info for target remote processes.  */
   7064 
   7065 struct remote_inferior : public private_inferior
   7066 {
   7067   /* Whether we can send a wildcard vCont for this process.  */
   7068   bool may_wildcard_vcont = true;
   7069 };
   7070 
   7071 /* Get the remote private inferior data associated to INF.  */
   7072 
   7073 static remote_inferior *
   7074 get_remote_inferior (inferior *inf)
   7075 {
   7076   if (inf->priv == NULL)
   7077     inf->priv.reset (new remote_inferior);
   7078 
   7079   return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
   7080 }
   7081 
   7082 /* Class used to track the construction of a vCont packet in the
   7083    outgoing packet buffer.  This is used to send multiple vCont
   7084    packets if we have more actions than would fit a single packet.  */
   7085 
   7086 class vcont_builder
   7087 {
   7088 public:
   7089   explicit vcont_builder (remote_target *remote)
   7090     : m_remote (remote)
   7091   {
   7092     restart ();
   7093   }
   7094 
   7095   void flush ();
   7096   void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
   7097 
   7098 private:
   7099   void restart ();
   7100 
   7101   /* The remote target.  */
   7102   remote_target *m_remote;
   7103 
   7104   /* Pointer to the first action.  P points here if no action has been
   7105      appended yet.  */
   7106   char *m_first_action;
   7107 
   7108   /* Where the next action will be appended.  */
   7109   char *m_p;
   7110 
   7111   /* The end of the buffer.  Must never write past this.  */
   7112   char *m_endp;
   7113 };
   7114 
   7115 /* Prepare the outgoing buffer for a new vCont packet.  */
   7116 
   7117 void
   7118 vcont_builder::restart ()
   7119 {
   7120   struct remote_state *rs = m_remote->get_remote_state ();
   7121 
   7122   m_p = rs->buf.data ();
   7123   m_endp = m_p + m_remote->get_remote_packet_size ();
   7124   m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
   7125   m_first_action = m_p;
   7126 }
   7127 
   7128 /* If the vCont packet being built has any action, send it to the
   7129    remote end.  */
   7130 
   7131 void
   7132 vcont_builder::flush ()
   7133 {
   7134   struct remote_state *rs;
   7135 
   7136   if (m_p == m_first_action)
   7137     return;
   7138 
   7139   rs = m_remote->get_remote_state ();
   7140   m_remote->putpkt (rs->buf);
   7141   m_remote->getpkt (&rs->buf);
   7142   if (strcmp (rs->buf.data (), "OK") != 0)
   7143     error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
   7144 }
   7145 
   7146 /* The largest action is range-stepping, with its two addresses.  This
   7147    is more than sufficient.  If a new, bigger action is created, it'll
   7148    quickly trigger a failed assertion in append_resumption (and we'll
   7149    just bump this).  */
   7150 #define MAX_ACTION_SIZE 200
   7151 
   7152 /* Append a new vCont action in the outgoing packet being built.  If
   7153    the action doesn't fit the packet along with previous actions, push
   7154    what we've got so far to the remote end and start over a new vCont
   7155    packet (with the new action).  */
   7156 
   7157 void
   7158 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
   7159 {
   7160   char buf[MAX_ACTION_SIZE + 1];
   7161 
   7162   char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
   7163 					    ptid, step, siggnal);
   7164 
   7165   /* Check whether this new action would fit in the vCont packet along
   7166      with previous actions.  If not, send what we've got so far and
   7167      start a new vCont packet.  */
   7168   size_t rsize = endp - buf;
   7169   if (rsize > m_endp - m_p)
   7170     {
   7171       flush ();
   7172       restart ();
   7173 
   7174       /* Should now fit.  */
   7175       gdb_assert (rsize <= m_endp - m_p);
   7176     }
   7177 
   7178   memcpy (m_p, buf, rsize);
   7179   m_p += rsize;
   7180   *m_p = '\0';
   7181 }
   7182 
   7183 /* to_commit_resume implementation.  */
   7184 
   7185 void
   7186 remote_target::commit_resumed ()
   7187 {
   7188   /* If connected in all-stop mode, we'd send the remote resume
   7189      request directly from remote_resume.  Likewise if
   7190      reverse-debugging, as there are no defined vCont actions for
   7191      reverse execution.  */
   7192   if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
   7193     return;
   7194 
   7195   commit_requested_thread_options ();
   7196 
   7197   /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
   7198      instead of resuming all threads of each process individually.
   7199      However, if any thread of a process must remain halted, we can't
   7200      send wildcard resumes and must send one action per thread.
   7201 
   7202      Care must be taken to not resume threads/processes the server
   7203      side already told us are stopped, but the core doesn't know about
   7204      yet, because the events are still in the vStopped notification
   7205      queue.  For example:
   7206 
   7207        #1 => vCont s:p1.1;c
   7208        #2 <= OK
   7209        #3 <= %Stopped T05 p1.1
   7210        #4 => vStopped
   7211        #5 <= T05 p1.2
   7212        #6 => vStopped
   7213        #7 <= OK
   7214        #8 (infrun handles the stop for p1.1 and continues stepping)
   7215        #9 => vCont s:p1.1;c
   7216 
   7217      The last vCont above would resume thread p1.2 by mistake, because
   7218      the server has no idea that the event for p1.2 had not been
   7219      handled yet.
   7220 
   7221      The server side must similarly ignore resume actions for the
   7222      thread that has a pending %Stopped notification (and any other
   7223      threads with events pending), until GDB acks the notification
   7224      with vStopped.  Otherwise, e.g., the following case is
   7225      mishandled:
   7226 
   7227        #1 => g  (or any other packet)
   7228        #2 <= [registers]
   7229        #3 <= %Stopped T05 p1.2
   7230        #4 => vCont s:p1.1;c
   7231        #5 <= OK
   7232 
   7233      Above, the server must not resume thread p1.2.  GDB can't know
   7234      that p1.2 stopped until it acks the %Stopped notification, and
   7235      since from GDB's perspective all threads should be running, it
   7236      sends a "c" action.
   7237 
   7238      Finally, special care must also be given to handling fork/vfork
   7239      events.  A (v)fork event actually tells us that two processes
   7240      stopped -- the parent and the child.  Until we follow the fork,
   7241      we must not resume the child.  Therefore, if we have a pending
   7242      fork follow, we must not send a global wildcard resume action
   7243      (vCont;c).  We can still send process-wide wildcards though.  */
   7244 
   7245   /* Start by assuming a global wildcard (vCont;c) is possible.  */
   7246   bool may_global_wildcard_vcont = true;
   7247 
   7248   /* And assume every process is individually wildcard-able too.  */
   7249   for (inferior *inf : all_non_exited_inferiors (this))
   7250     {
   7251       remote_inferior *priv = get_remote_inferior (inf);
   7252 
   7253       priv->may_wildcard_vcont = true;
   7254     }
   7255 
   7256   /* Check for any pending events (not reported or processed yet) and
   7257      disable process and global wildcard resumes appropriately.  */
   7258   check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
   7259 
   7260   bool any_pending_vcont_resume = false;
   7261 
   7262   for (thread_info *tp : all_non_exited_threads (this))
   7263     {
   7264       remote_thread_info *priv = get_remote_thread_info (tp);
   7265 
   7266       /* If a thread of a process is not meant to be resumed, then we
   7267 	 can't wildcard that process.  */
   7268       if (priv->get_resume_state () == resume_state::NOT_RESUMED)
   7269 	{
   7270 	  get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
   7271 
   7272 	  /* And if we can't wildcard a process, we can't wildcard
   7273 	     everything either.  */
   7274 	  may_global_wildcard_vcont = false;
   7275 	  continue;
   7276 	}
   7277 
   7278       if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
   7279 	any_pending_vcont_resume = true;
   7280 
   7281       /* If a thread is the parent of an unfollowed fork/vfork/clone,
   7282 	 then we can't do a global wildcard, as that would resume the
   7283 	 pending child.  */
   7284       if (thread_pending_child_status (tp) != nullptr)
   7285 	may_global_wildcard_vcont = false;
   7286     }
   7287 
   7288   /* We didn't have any resumed thread pending a vCont resume, so nothing to
   7289      do.  */
   7290   if (!any_pending_vcont_resume)
   7291     return;
   7292 
   7293   /* Now let's build the vCont packet(s).  Actions must be appended
   7294      from narrower to wider scopes (thread -> process -> global).  If
   7295      we end up with too many actions for a single packet vcont_builder
   7296      flushes the current vCont packet to the remote side and starts a
   7297      new one.  */
   7298   struct vcont_builder vcont_builder (this);
   7299 
   7300   /* Threads first.  */
   7301   for (thread_info *tp : all_non_exited_threads (this))
   7302     {
   7303       remote_thread_info *remote_thr = get_remote_thread_info (tp);
   7304 
   7305       /* If the thread was previously vCont-resumed, no need to send a specific
   7306 	 action for it.  If we didn't receive a resume request for it, don't
   7307 	 send an action for it either.  */
   7308       if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
   7309 	continue;
   7310 
   7311       gdb_assert (!thread_is_in_step_over_chain (tp));
   7312 
   7313       /* We should never be commit-resuming a thread that has a stop reply.
   7314 	 Otherwise, we would end up reporting a stop event for a thread while
   7315 	 it is running on the remote target.  */
   7316       remote_state *rs = get_remote_state ();
   7317       for (const auto &stop_reply : rs->stop_reply_queue)
   7318 	gdb_assert (stop_reply->ptid != tp->ptid);
   7319 
   7320       const resumed_pending_vcont_info &info
   7321 	= remote_thr->resumed_pending_vcont_info ();
   7322 
   7323       /* Check if we need to send a specific action for this thread.  If not,
   7324 	 it will be included in a wildcard resume instead.  */
   7325       if (info.step || info.sig != GDB_SIGNAL_0
   7326 	  || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
   7327 	vcont_builder.push_action (tp->ptid, info.step, info.sig);
   7328 
   7329       remote_thr->set_resumed ();
   7330     }
   7331 
   7332   /* Now check whether we can send any process-wide wildcard.  This is
   7333      to avoid sending a global wildcard in the case nothing is
   7334      supposed to be resumed.  */
   7335   bool any_process_wildcard = false;
   7336 
   7337   for (inferior *inf : all_non_exited_inferiors (this))
   7338     {
   7339       if (get_remote_inferior (inf)->may_wildcard_vcont)
   7340 	{
   7341 	  any_process_wildcard = true;
   7342 	  break;
   7343 	}
   7344     }
   7345 
   7346   if (any_process_wildcard)
   7347     {
   7348       /* If all processes are wildcard-able, then send a single "c"
   7349 	 action, otherwise, send an "all (-1) threads of process"
   7350 	 continue action for each running process, if any.  */
   7351       if (may_global_wildcard_vcont)
   7352 	{
   7353 	  vcont_builder.push_action (minus_one_ptid,
   7354 				     false, GDB_SIGNAL_0);
   7355 	}
   7356       else
   7357 	{
   7358 	  for (inferior *inf : all_non_exited_inferiors (this))
   7359 	    {
   7360 	      if (get_remote_inferior (inf)->may_wildcard_vcont)
   7361 		{
   7362 		  vcont_builder.push_action (ptid_t (inf->pid),
   7363 					     false, GDB_SIGNAL_0);
   7364 		}
   7365 	    }
   7366 	}
   7367     }
   7368 
   7369   vcont_builder.flush ();
   7370 }
   7371 
   7372 /* Implementation of target_has_pending_events.  */
   7373 
   7374 bool
   7375 remote_target::has_pending_events ()
   7376 {
   7377   if (target_can_async_p ())
   7378     {
   7379       remote_state *rs = get_remote_state ();
   7380 
   7381       if (rs->async_event_handler_marked ())
   7382 	return true;
   7383 
   7384       /* Note that BUFCNT can be negative, indicating sticky
   7385 	 error.  */
   7386       if (rs->remote_desc->bufcnt != 0)
   7387 	return true;
   7388     }
   7389   return false;
   7390 }
   7391 
   7392 
   7393 
   7395 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
   7396    thread, all threads of a remote process, or all threads of all
   7397    processes.  */
   7398 
   7399 void
   7400 remote_target::remote_stop_ns (ptid_t ptid)
   7401 {
   7402   struct remote_state *rs = get_remote_state ();
   7403   char *p = rs->buf.data ();
   7404   char *endp = p + get_remote_packet_size ();
   7405 
   7406   /* If any thread that needs to stop was resumed but pending a vCont
   7407      resume, generate a phony stop_reply.  However, first check
   7408      whether the thread wasn't resumed with a signal.  Generating a
   7409      phony stop in that case would result in losing the signal.  */
   7410   bool needs_commit = false;
   7411   for (thread_info *tp : all_non_exited_threads (this, ptid))
   7412     {
   7413       remote_thread_info *remote_thr = get_remote_thread_info (tp);
   7414 
   7415       if (remote_thr->get_resume_state ()
   7416 	  == resume_state::RESUMED_PENDING_VCONT)
   7417 	{
   7418 	  const resumed_pending_vcont_info &info
   7419 	    = remote_thr->resumed_pending_vcont_info ();
   7420 	  if (info.sig != GDB_SIGNAL_0)
   7421 	    {
   7422 	      /* This signal must be forwarded to the inferior.  We
   7423 		 could commit-resume just this thread, but its simpler
   7424 		 to just commit-resume everything.  */
   7425 	      needs_commit = true;
   7426 	      break;
   7427 	    }
   7428 	}
   7429     }
   7430 
   7431   if (needs_commit)
   7432     commit_resumed ();
   7433   else
   7434     for (thread_info *tp : all_non_exited_threads (this, ptid))
   7435       {
   7436 	remote_thread_info *remote_thr = get_remote_thread_info (tp);
   7437 
   7438 	if (remote_thr->get_resume_state ()
   7439 	    == resume_state::RESUMED_PENDING_VCONT)
   7440 	  {
   7441 	    remote_debug_printf ("Enqueueing phony stop reply for thread pending "
   7442 				 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
   7443 				 tp->ptid.lwp (),
   7444 				 pulongest (tp->ptid.tid ()));
   7445 
   7446 	    /* Check that the thread wasn't resumed with a signal.
   7447 	       Generating a phony stop would result in losing the
   7448 	       signal.  */
   7449 	    const resumed_pending_vcont_info &info
   7450 	      = remote_thr->resumed_pending_vcont_info ();
   7451 	    gdb_assert (info.sig == GDB_SIGNAL_0);
   7452 
   7453 	    stop_reply_up sr = std::make_unique<stop_reply> ();
   7454 	    sr->ptid = tp->ptid;
   7455 	    sr->rs = rs;
   7456 	    sr->ws.set_stopped (GDB_SIGNAL_0);
   7457 	    sr->arch = tp->inf->arch ();
   7458 	    sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
   7459 	    sr->watch_data_address = 0;
   7460 	    sr->core = 0;
   7461 	    this->push_stop_reply (std::move (sr));
   7462 
   7463 	    /* Pretend that this thread was actually resumed on the
   7464 	       remote target, then stopped.  If we leave it in the
   7465 	       RESUMED_PENDING_VCONT state and the commit_resumed
   7466 	       method is called while the stop reply is still in the
   7467 	       queue, we'll end up reporting a stop event to the core
   7468 	       for that thread while it is running on the remote
   7469 	       target... that would be bad.  */
   7470 	    remote_thr->set_resumed ();
   7471 	  }
   7472       }
   7473 
   7474   if (!rs->supports_vCont.t)
   7475     error (_("Remote server does not support stopping threads"));
   7476 
   7477   if (ptid == minus_one_ptid
   7478       || (!m_features.remote_multi_process_p () && ptid.is_pid ()))
   7479     p += xsnprintf (p, endp - p, "vCont;t");
   7480   else
   7481     {
   7482       ptid_t nptid;
   7483 
   7484       p += xsnprintf (p, endp - p, "vCont;t:");
   7485 
   7486       if (ptid.is_pid ())
   7487 	  /* All (-1) threads of process.  */
   7488 	nptid = ptid_t (ptid.pid (), -1);
   7489       else
   7490 	{
   7491 	  /* Small optimization: if we already have a stop reply for
   7492 	     this thread, no use in telling the stub we want this
   7493 	     stopped.  */
   7494 	  if (peek_stop_reply (ptid))
   7495 	    return;
   7496 
   7497 	  nptid = ptid;
   7498 	}
   7499 
   7500       write_ptid (p, endp, nptid);
   7501     }
   7502 
   7503   /* In non-stop, we get an immediate OK reply.  The stop reply will
   7504      come in asynchronously by notification.  */
   7505   putpkt (rs->buf);
   7506   getpkt (&rs->buf);
   7507   if (strcmp (rs->buf.data (), "OK") != 0)
   7508     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
   7509 	   rs->buf.data ());
   7510 }
   7511 
   7512 /* All-stop version of target_interrupt.  Sends a break or a ^C to
   7513    interrupt the remote target.  It is undefined which thread of which
   7514    process reports the interrupt.  */
   7515 
   7516 void
   7517 remote_target::remote_interrupt_as ()
   7518 {
   7519   struct remote_state *rs = get_remote_state ();
   7520 
   7521   rs->ctrlc_pending_p = 1;
   7522 
   7523   /* If the inferior is stopped already, but the core didn't know
   7524      about it yet, just ignore the request.  The pending stop events
   7525      will be collected in remote_wait.  */
   7526   if (stop_reply_queue_length () > 0)
   7527     return;
   7528 
   7529   /* Send interrupt_sequence to remote target.  */
   7530   send_interrupt_sequence ();
   7531 }
   7532 
   7533 /* Non-stop version of target_interrupt.  Uses `vCtrlC' to interrupt
   7534    the remote target.  It is undefined which thread of which process
   7535    reports the interrupt.  Throws an error if the packet is not
   7536    supported by the server.  */
   7537 
   7538 void
   7539 remote_target::remote_interrupt_ns ()
   7540 {
   7541   struct remote_state *rs = get_remote_state ();
   7542   char *p = rs->buf.data ();
   7543   char *endp = p + get_remote_packet_size ();
   7544 
   7545   xsnprintf (p, endp - p, "vCtrlC");
   7546 
   7547   /* In non-stop, we get an immediate OK reply.  The stop reply will
   7548      come in asynchronously by notification.  */
   7549   putpkt (rs->buf);
   7550   getpkt (&rs->buf);
   7551 
   7552   packet_result result = m_features.packet_ok (rs->buf, PACKET_vCtrlC);
   7553   switch (result.status ())
   7554     {
   7555     case PACKET_OK:
   7556       break;
   7557     case PACKET_UNKNOWN:
   7558       error (_("No support for interrupting the remote target."));
   7559     case PACKET_ERROR:
   7560       error (_("Interrupting target failed: %s"), result.err_msg ());
   7561     }
   7562 }
   7563 
   7564 /* Implement the to_stop function for the remote targets.  */
   7565 
   7566 void
   7567 remote_target::stop (ptid_t ptid)
   7568 {
   7569   REMOTE_SCOPED_DEBUG_ENTER_EXIT;
   7570 
   7571   if (target_is_non_stop_p ())
   7572     remote_stop_ns (ptid);
   7573   else
   7574     {
   7575       /* We don't currently have a way to transparently pause the
   7576 	 remote target in all-stop mode.  Interrupt it instead.  */
   7577       remote_interrupt_as ();
   7578     }
   7579 }
   7580 
   7581 /* Implement the to_interrupt function for the remote targets.  */
   7582 
   7583 void
   7584 remote_target::interrupt ()
   7585 {
   7586   REMOTE_SCOPED_DEBUG_ENTER_EXIT;
   7587 
   7588   if (target_is_non_stop_p ())
   7589     remote_interrupt_ns ();
   7590   else
   7591     remote_interrupt_as ();
   7592 }
   7593 
   7594 /* Implement the to_pass_ctrlc function for the remote targets.  */
   7595 
   7596 void
   7597 remote_target::pass_ctrlc ()
   7598 {
   7599   REMOTE_SCOPED_DEBUG_ENTER_EXIT;
   7600 
   7601   struct remote_state *rs = get_remote_state ();
   7602 
   7603   /* If we're starting up, we're not fully synced yet.  Quit
   7604      immediately.  */
   7605   if (rs->starting_up)
   7606     quit ();
   7607   /* If ^C has already been sent once, offer to disconnect.  */
   7608   else if (rs->ctrlc_pending_p)
   7609     interrupt_query ();
   7610   else
   7611     target_interrupt ();
   7612 }
   7613 
   7614 /* Ask the user what to do when an interrupt is received.  */
   7615 
   7616 void
   7617 remote_target::interrupt_query ()
   7618 {
   7619   struct remote_state *rs = get_remote_state ();
   7620 
   7621   if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
   7622     {
   7623       if (query (_("The target is not responding to interrupt requests.\n"
   7624 		   "Stop debugging it? ")))
   7625 	{
   7626 	  remote_unpush_target (this);
   7627 	  throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
   7628 	}
   7629     }
   7630   else
   7631     {
   7632       if (query (_("Interrupted while waiting for the program.\n"
   7633 		   "Give up waiting? ")))
   7634 	quit ();
   7635     }
   7636 }
   7637 
   7638 /* Enable/disable target terminal ownership.  Most targets can use
   7639    terminal groups to control terminal ownership.  Remote targets are
   7640    different in that explicit transfer of ownership to/from GDB/target
   7641    is required.  */
   7642 
   7643 void
   7644 remote_target::terminal_inferior ()
   7645 {
   7646   /* NOTE: At this point we could also register our selves as the
   7647      recipient of all input.  Any characters typed could then be
   7648      passed on down to the target.  */
   7649 }
   7650 
   7651 void
   7652 remote_target::terminal_ours ()
   7653 {
   7654 }
   7655 
   7656 static void
   7657 remote_console_output (const char *msg, ui_file *stream)
   7658 {
   7659   const char *p;
   7660 
   7661   for (p = msg; p[0] && p[1]; p += 2)
   7662     {
   7663       char tb[2];
   7664       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
   7665 
   7666       tb[0] = c;
   7667       tb[1] = 0;
   7668       stream->puts (tb);
   7669     }
   7670   stream->flush ();
   7671 }
   7672 
   7673 /* Return the length of the stop reply queue.  */
   7674 
   7675 int
   7676 remote_target::stop_reply_queue_length ()
   7677 {
   7678   remote_state *rs = get_remote_state ();
   7679   return rs->stop_reply_queue.size ();
   7680 }
   7681 
   7682 static void
   7683 remote_notif_stop_parse (remote_target *remote,
   7684 			 const notif_client *self, const char *buf,
   7685 			 struct notif_event *event)
   7686 {
   7687   remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
   7688 }
   7689 
   7690 static void
   7691 remote_notif_stop_ack (remote_target *remote,
   7692 		       const notif_client *self, const char *buf,
   7693 		       notif_event_up event)
   7694 {
   7695   stop_reply_up stop_reply = as_stop_reply_up (std::move (event));
   7696 
   7697   /* acknowledge */
   7698   putpkt (remote, self->ack_command);
   7699 
   7700   /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
   7701      the notification.  It was left in the queue because we need to
   7702      acknowledge it and pull the rest of the notifications out.  */
   7703   if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
   7704     remote->push_stop_reply (std::move (stop_reply));
   7705 }
   7706 
   7707 static int
   7708 remote_notif_stop_can_get_pending_events (remote_target *remote,
   7709 					  const notif_client *self)
   7710 {
   7711   /* We can't get pending events in remote_notif_process for
   7712      notification stop, and we have to do this in remote_wait_ns
   7713      instead.  If we fetch all queued events from stub, remote stub
   7714      may exit and we have no chance to process them back in
   7715      remote_wait_ns.  */
   7716   remote_state *rs = remote->get_remote_state ();
   7717   rs->mark_async_event_handler ();
   7718   return 0;
   7719 }
   7720 
   7721 static notif_event_up
   7722 remote_notif_stop_alloc_reply ()
   7723 {
   7724   return notif_event_up (new struct stop_reply ());
   7725 }
   7726 
   7727 /* A client of notification Stop.  */
   7728 
   7729 const notif_client notif_client_stop =
   7730 {
   7731   "Stop",
   7732   "vStopped",
   7733   remote_notif_stop_parse,
   7734   remote_notif_stop_ack,
   7735   remote_notif_stop_can_get_pending_events,
   7736   remote_notif_stop_alloc_reply,
   7737   REMOTE_NOTIF_STOP,
   7738 };
   7739 
   7740 /* If CONTEXT contains any fork/vfork/clone child threads that have
   7741    not been reported yet, remove them from the CONTEXT list.  If such
   7742    a thread exists it is because we are stopped at a fork/vfork/clone
   7743    catchpoint and have not yet called follow_fork/follow_clone, which
   7744    will set up the host-side data structures for the new child.  */
   7745 
   7746 void
   7747 remote_target::remove_new_children (threads_listing_context *context)
   7748 {
   7749   const notif_client *notif = &notif_client_stop;
   7750 
   7751   /* For any threads stopped at a (v)fork/clone event, remove the
   7752      corresponding child threads from the CONTEXT list.  */
   7753   for (thread_info *thread : all_non_exited_threads (this))
   7754     {
   7755       const target_waitstatus *ws = thread_pending_child_status (thread);
   7756 
   7757       if (ws == nullptr)
   7758 	continue;
   7759 
   7760       context->remove_thread (ws->child_ptid ());
   7761     }
   7762 
   7763   /* Check for any pending (v)fork/clone events (not reported or
   7764      processed yet) in process PID and remove those child threads from
   7765      the CONTEXT list as well.  */
   7766   remote_notif_get_pending_events (notif);
   7767   for (auto &event : get_remote_state ()->stop_reply_queue)
   7768     if (is_new_child_status (event->ws.kind ()))
   7769       context->remove_thread (event->ws.child_ptid ());
   7770     else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
   7771       context->remove_thread (event->ptid);
   7772 }
   7773 
   7774 /* Check whether any event pending in the vStopped queue would prevent a
   7775    global or process wildcard vCont action.  Set *may_global_wildcard to
   7776    false if we can't do a global wildcard (vCont;c), and clear the event
   7777    inferior's may_wildcard_vcont flag if we can't do a process-wide
   7778    wildcard resume (vCont;c:pPID.-1).  */
   7779 
   7780 void
   7781 remote_target::check_pending_events_prevent_wildcard_vcont
   7782   (bool *may_global_wildcard)
   7783 {
   7784   const notif_client *notif = &notif_client_stop;
   7785 
   7786   remote_notif_get_pending_events (notif);
   7787   for (auto &event : get_remote_state ()->stop_reply_queue)
   7788     {
   7789       if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
   7790 	  || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
   7791 	continue;
   7792 
   7793       if (event->ws.kind () == TARGET_WAITKIND_FORKED
   7794 	  || event->ws.kind () == TARGET_WAITKIND_VFORKED)
   7795 	*may_global_wildcard = false;
   7796 
   7797       /* This may be the first time we heard about this process.
   7798 	 Regardless, we must not do a global wildcard resume, otherwise
   7799 	 we'd resume this process too.  */
   7800       *may_global_wildcard = false;
   7801       if (event->ptid != null_ptid)
   7802 	{
   7803 	  inferior *inf = find_inferior_ptid (this, event->ptid);
   7804 	  if (inf != NULL)
   7805 	    get_remote_inferior (inf)->may_wildcard_vcont = false;
   7806 	}
   7807     }
   7808 }
   7809 
   7810 /* Discard all pending stop replies of inferior INF.  */
   7811 
   7812 void
   7813 remote_target::discard_pending_stop_replies (struct inferior *inf)
   7814 {
   7815   struct remote_state *rs = get_remote_state ();
   7816   struct remote_notif_state *rns = rs->notif_state;
   7817 
   7818   /* This function can be notified when an inferior exists.  When the
   7819      target is not remote, the notification state is NULL.  */
   7820   if (rs->remote_desc == NULL)
   7821     return;
   7822 
   7823   struct notif_event *notif_event
   7824     = rns->pending_event[notif_client_stop.id].get ();
   7825   auto *reply = static_cast<stop_reply *> (notif_event);
   7826 
   7827   /* Discard the in-flight notification.  */
   7828   if (reply != NULL && reply->ptid.pid () == inf->pid)
   7829     {
   7830       /* Leave the notification pending, since the server expects that
   7831 	 we acknowledge it with vStopped.  But clear its contents, so
   7832 	 that later on when we acknowledge it, we also discard it.  */
   7833       remote_debug_printf
   7834 	("discarding in-flight notification: ptid: %s, ws: %s\n",
   7835 	 reply->ptid.to_string().c_str(),
   7836 	 reply->ws.to_string ().c_str ());
   7837       reply->ws.set_ignore ();
   7838     }
   7839 
   7840   /* Discard the stop replies we have already pulled with
   7841      vStopped.  */
   7842   auto iter = std::remove_if (rs->stop_reply_queue.begin (),
   7843 			      rs->stop_reply_queue.end (),
   7844 			      [=] (const stop_reply_up &event)
   7845 			      {
   7846 				return event->ptid.pid () == inf->pid;
   7847 			      });
   7848   for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
   7849     remote_debug_printf
   7850       ("discarding queued stop reply: ptid: %s, ws: %s\n",
   7851        (*it)->ptid.to_string().c_str(),
   7852        (*it)->ws.to_string ().c_str ());
   7853   rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
   7854 }
   7855 
   7856 /* Discard the stop replies for RS in stop_reply_queue.  */
   7857 
   7858 void
   7859 remote_target::discard_pending_stop_replies_in_queue ()
   7860 {
   7861   remote_state *rs = get_remote_state ();
   7862 
   7863   /* Discard the stop replies we have already pulled with
   7864      vStopped.  */
   7865   auto iter = std::remove_if (rs->stop_reply_queue.begin (),
   7866 			      rs->stop_reply_queue.end (),
   7867 			      [=] (const stop_reply_up &event)
   7868 			      {
   7869 				return event->rs == rs;
   7870 			      });
   7871   rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
   7872 }
   7873 
   7874 /* Remove the first reply in 'stop_reply_queue' which matches
   7875    PTID.  */
   7876 
   7877 stop_reply_up
   7878 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
   7879 {
   7880   remote_state *rs = get_remote_state ();
   7881 
   7882   auto iter = std::find_if (rs->stop_reply_queue.begin (),
   7883 			    rs->stop_reply_queue.end (),
   7884 			    [=] (const stop_reply_up &event)
   7885 			    {
   7886 			      return event->ptid.matches (ptid);
   7887 			    });
   7888   stop_reply_up result;
   7889   if (iter != rs->stop_reply_queue.end ())
   7890     {
   7891       result = std::move (*iter);
   7892       rs->stop_reply_queue.erase (iter);
   7893     }
   7894 
   7895   if (notif_debug)
   7896     gdb_printf (gdb_stdlog,
   7897 		"notif: discard queued event: 'Stop' in %s\n",
   7898 		ptid.to_string ().c_str ());
   7899 
   7900   return result;
   7901 }
   7902 
   7903 /* Look for a queued stop reply belonging to PTID.  If one is found,
   7904    remove it from the queue, and return it.  Returns NULL if none is
   7905    found.  If there are still queued events left to process, tell the
   7906    event loop to get back to target_wait soon.  */
   7907 
   7908 stop_reply_up
   7909 remote_target::queued_stop_reply (ptid_t ptid)
   7910 {
   7911   remote_state *rs = get_remote_state ();
   7912   stop_reply_up r = remote_notif_remove_queued_reply (ptid);
   7913 
   7914   if (!rs->stop_reply_queue.empty () && target_can_async_p ())
   7915     {
   7916       /* There's still at least an event left.  */
   7917       rs->mark_async_event_handler ();
   7918     }
   7919 
   7920   return r;
   7921 }
   7922 
   7923 /* Push a fully parsed stop reply in the stop reply queue.  Since we
   7924    know that we now have at least one queued event left to pass to the
   7925    core side, tell the event loop to get back to target_wait soon.  */
   7926 
   7927 void
   7928 remote_target::push_stop_reply (stop_reply_up new_event)
   7929 {
   7930   remote_state *rs = get_remote_state ();
   7931   rs->stop_reply_queue.push_back (std::move (new_event));
   7932 
   7933   if (notif_debug)
   7934     gdb_printf (gdb_stdlog,
   7935 		"notif: push 'Stop' %s to queue %d\n",
   7936 		new_event->ptid.to_string ().c_str (),
   7937 		int (rs->stop_reply_queue.size ()));
   7938 
   7939   /* Mark the pending event queue only if async mode is currently enabled.
   7940      If async mode is not currently enabled, then, if it later becomes
   7941      enabled, and there are events in this queue, we will mark the event
   7942      token at that point, see remote_target::async.  */
   7943   if (target_is_async_p ())
   7944     rs->mark_async_event_handler ();
   7945 }
   7946 
   7947 /* Returns true if we have a stop reply for PTID.  */
   7948 
   7949 int
   7950 remote_target::peek_stop_reply (ptid_t ptid)
   7951 {
   7952   remote_state *rs = get_remote_state ();
   7953   for (auto &event : rs->stop_reply_queue)
   7954     if (ptid == event->ptid
   7955 	&& event->ws.kind () == TARGET_WAITKIND_STOPPED)
   7956       return 1;
   7957   return 0;
   7958 }
   7959 
   7960 /* Helper for remote_parse_stop_reply.  Return nonzero if the substring
   7961    starting with P and ending with PEND matches PREFIX.  */
   7962 
   7963 static int
   7964 strprefix (const char *p, const char *pend, const char *prefix)
   7965 {
   7966   for ( ; p < pend; p++, prefix++)
   7967     if (*p != *prefix)
   7968       return 0;
   7969   return *prefix == '\0';
   7970 }
   7971 
   7972 /* Parse the stop reply in BUF.  Either the function succeeds, and the
   7973    result is stored in EVENT, or throws an error.  */
   7974 
   7975 void
   7976 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
   7977 {
   7978   remote_arch_state *rsa = NULL;
   7979   ULONGEST addr;
   7980   const char *p;
   7981   int skipregs = 0;
   7982 
   7983   event->ptid = null_ptid;
   7984   event->rs = get_remote_state ();
   7985   event->ws.set_ignore ();
   7986   event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
   7987   event->regcache.clear ();
   7988   event->core = -1;
   7989 
   7990   switch (buf[0])
   7991     {
   7992     case 'T':		/* Status with PC, SP, FP, ...	*/
   7993       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
   7994       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
   7995 	    ss = signal number
   7996 	    n... = register number
   7997 	    r... = register contents
   7998       */
   7999 
   8000       p = &buf[3];	/* after Txx */
   8001       while (*p)
   8002 	{
   8003 	  const char *p1;
   8004 	  int fieldsize;
   8005 
   8006 	  p1 = strchr (p, ':');
   8007 	  if (p1 == NULL)
   8008 	    error (_("Malformed packet(a) (missing colon): %s\n\
   8009 Packet: '%s'\n"),
   8010 		   p, buf);
   8011 	  if (p == p1)
   8012 	    error (_("Malformed packet(a) (missing register number): %s\n\
   8013 Packet: '%s'\n"),
   8014 		   p, buf);
   8015 
   8016 	  /* Some "registers" are actually extended stop information.
   8017 	     Note if you're adding a new entry here: GDB 7.9 and
   8018 	     earlier assume that all register "numbers" that start
   8019 	     with an hex digit are real register numbers.  Make sure
   8020 	     the server only sends such a packet if it knows the
   8021 	     client understands it.  */
   8022 
   8023 	  if (strprefix (p, p1, "thread"))
   8024 	    event->ptid = read_ptid (++p1, &p);
   8025 	  else if (strprefix (p, p1, "syscall_entry"))
   8026 	    {
   8027 	      ULONGEST sysno;
   8028 
   8029 	      p = unpack_varlen_hex (++p1, &sysno);
   8030 	      event->ws.set_syscall_entry ((int) sysno);
   8031 	    }
   8032 	  else if (strprefix (p, p1, "syscall_return"))
   8033 	    {
   8034 	      ULONGEST sysno;
   8035 
   8036 	      p = unpack_varlen_hex (++p1, &sysno);
   8037 	      event->ws.set_syscall_return ((int) sysno);
   8038 	    }
   8039 	  else if (strprefix (p, p1, "watch")
   8040 		   || strprefix (p, p1, "rwatch")
   8041 		   || strprefix (p, p1, "awatch"))
   8042 	    {
   8043 	      event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
   8044 	      p = unpack_varlen_hex (++p1, &addr);
   8045 	      event->watch_data_address = (CORE_ADDR) addr;
   8046 	    }
   8047 	  else if (strprefix (p, p1, "swbreak"))
   8048 	    {
   8049 	      event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
   8050 
   8051 	      /* Make sure the stub doesn't forget to indicate support
   8052 		 with qSupported.  */
   8053 	      if (m_features.packet_support (PACKET_swbreak_feature)
   8054 		  != PACKET_ENABLE)
   8055 		error (_("Unexpected swbreak stop reason"));
   8056 
   8057 	      /* The value part is documented as "must be empty",
   8058 		 though we ignore it, in case we ever decide to make
   8059 		 use of it in a backward compatible way.  */
   8060 	      p = strchrnul (p1 + 1, ';');
   8061 	    }
   8062 	  else if (strprefix (p, p1, "hwbreak"))
   8063 	    {
   8064 	      event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
   8065 
   8066 	      /* Make sure the stub doesn't forget to indicate support
   8067 		 with qSupported.  */
   8068 	      if (m_features.packet_support (PACKET_hwbreak_feature)
   8069 		  != PACKET_ENABLE)
   8070 		error (_("Unexpected hwbreak stop reason"));
   8071 
   8072 	      /* See above.  */
   8073 	      p = strchrnul (p1 + 1, ';');
   8074 	    }
   8075 	  else if (strprefix (p, p1, "library"))
   8076 	    {
   8077 	      event->ws.set_loaded ();
   8078 	      p = strchrnul (p1 + 1, ';');
   8079 	    }
   8080 	  else if (strprefix (p, p1, "replaylog"))
   8081 	    {
   8082 	      event->ws.set_no_history ();
   8083 	      /* p1 will indicate "begin" or "end", but it makes
   8084 		 no difference for now, so ignore it.  */
   8085 	      p = strchrnul (p1 + 1, ';');
   8086 	    }
   8087 	  else if (strprefix (p, p1, "core"))
   8088 	    {
   8089 	      ULONGEST c;
   8090 
   8091 	      p = unpack_varlen_hex (++p1, &c);
   8092 	      event->core = c;
   8093 	    }
   8094 	  else if (strprefix (p, p1, "fork"))
   8095 	    event->ws.set_forked (read_ptid (++p1, &p));
   8096 	  else if (strprefix (p, p1, "vfork"))
   8097 	    event->ws.set_vforked (read_ptid (++p1, &p));
   8098 	  else if (strprefix (p, p1, "clone"))
   8099 	    event->ws.set_thread_cloned (read_ptid (++p1, &p));
   8100 	  else if (strprefix (p, p1, "vforkdone"))
   8101 	    {
   8102 	      event->ws.set_vfork_done ();
   8103 	      p = strchrnul (p1 + 1, ';');
   8104 	    }
   8105 	  else if (strprefix (p, p1, "exec"))
   8106 	    {
   8107 	      ULONGEST ignored;
   8108 	      int pathlen;
   8109 
   8110 	      /* Determine the length of the execd pathname.  */
   8111 	      p = unpack_varlen_hex (++p1, &ignored);
   8112 	      pathlen = (p - p1) / 2;
   8113 
   8114 	      /* Save the pathname for event reporting and for
   8115 		 the next run command.  */
   8116 	      gdb::unique_xmalloc_ptr<char> pathname
   8117 		((char *) xmalloc (pathlen + 1));
   8118 	      hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
   8119 	      pathname.get ()[pathlen] = '\0';
   8120 
   8121 	      /* This is freed during event handling.  */
   8122 	      event->ws.set_execd (std::move (pathname));
   8123 
   8124 	      /* Skip the registers included in this packet, since
   8125 		 they may be for an architecture different from the
   8126 		 one used by the original program.  */
   8127 	      skipregs = 1;
   8128 	    }
   8129 	  else if (strprefix (p, p1, "create"))
   8130 	    {
   8131 	      event->ws.set_thread_created ();
   8132 	      p = strchrnul (p1 + 1, ';');
   8133 	    }
   8134 	  else
   8135 	    {
   8136 	      ULONGEST pnum;
   8137 	      const char *p_temp;
   8138 
   8139 	      if (skipregs)
   8140 		{
   8141 		  p = strchrnul (p1 + 1, ';');
   8142 		  p++;
   8143 		  continue;
   8144 		}
   8145 
   8146 	      /* Maybe a real ``P'' register number.  */
   8147 	      p_temp = unpack_varlen_hex (p, &pnum);
   8148 	      /* If the first invalid character is the colon, we got a
   8149 		 register number.  Otherwise, it's an unknown stop
   8150 		 reason.  */
   8151 	      if (p_temp == p1)
   8152 		{
   8153 		  /* If we haven't parsed the event's thread yet, find
   8154 		     it now, in order to find the architecture of the
   8155 		     reported expedited registers.  */
   8156 		  if (event->ptid == null_ptid)
   8157 		    {
   8158 		      /* If there is no thread-id information then leave
   8159 			 the event->ptid as null_ptid.  Later in
   8160 			 process_stop_reply we will pick a suitable
   8161 			 thread.  */
   8162 		      const char *thr = strstr (p1 + 1, ";thread:");
   8163 		      if (thr != NULL)
   8164 			event->ptid = read_ptid (thr + strlen (";thread:"),
   8165 						 NULL);
   8166 		    }
   8167 
   8168 		  if (rsa == NULL)
   8169 		    {
   8170 		      inferior *inf
   8171 			= (event->ptid == null_ptid
   8172 			   ? NULL
   8173 			   : find_inferior_ptid (this, event->ptid));
   8174 		      /* If this is the first time we learn anything
   8175 			 about this process, skip the registers
   8176 			 included in this packet, since we don't yet
   8177 			 know which architecture to use to parse them.
   8178 			 We'll determine the architecture later when
   8179 			 we process the stop reply and retrieve the
   8180 			 target description, via
   8181 			 remote_notice_new_inferior ->
   8182 			 post_create_inferior.  */
   8183 		      if (inf == NULL)
   8184 			{
   8185 			  p = strchrnul (p1 + 1, ';');
   8186 			  p++;
   8187 			  continue;
   8188 			}
   8189 
   8190 		      event->arch = inf->arch ();
   8191 		      rsa = event->rs->get_remote_arch_state (event->arch);
   8192 		    }
   8193 
   8194 		  packet_reg *reg
   8195 		    = packet_reg_from_pnum (event->arch, rsa, pnum);
   8196 		  cached_reg_t cached_reg;
   8197 
   8198 		  if (reg == NULL)
   8199 		    error (_("Remote sent bad register number %s: %s\n\
   8200 Packet: '%s'\n"),
   8201 			   hex_string (pnum), p, buf);
   8202 
   8203 		  cached_reg.num = reg->regnum;
   8204 		  cached_reg.data.reset ((gdb_byte *)
   8205 					 xmalloc (register_size (event->arch,
   8206 								 reg->regnum)));
   8207 
   8208 		  p = p1 + 1;
   8209 		  fieldsize = hex2bin (p, cached_reg.data.get (),
   8210 				       register_size (event->arch, reg->regnum));
   8211 		  p += 2 * fieldsize;
   8212 		  if (fieldsize < register_size (event->arch, reg->regnum))
   8213 		    warning (_("Remote reply is too short: %s"), buf);
   8214 
   8215 		  event->regcache.push_back (std::move (cached_reg));
   8216 		}
   8217 	      else
   8218 		{
   8219 		  /* Not a number.  Silently skip unknown optional
   8220 		     info.  */
   8221 		  p = strchrnul (p1 + 1, ';');
   8222 		}
   8223 	    }
   8224 
   8225 	  if (*p != ';')
   8226 	    error (_("Remote register badly formatted: %s\nhere: %s"),
   8227 		   buf, p);
   8228 	  ++p;
   8229 	}
   8230 
   8231       if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
   8232 	break;
   8233 
   8234       [[fallthrough]];
   8235     case 'S':		/* Old style status, just signal only.  */
   8236       {
   8237 	int sig;
   8238 
   8239 	sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
   8240 	if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
   8241 	  event->ws.set_stopped ((enum gdb_signal) sig);
   8242 	else
   8243 	  event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
   8244       }
   8245       break;
   8246     case 'w':		/* Thread exited.  */
   8247       {
   8248 	ULONGEST value;
   8249 
   8250 	p = unpack_varlen_hex (&buf[1], &value);
   8251 	event->ws.set_thread_exited (value);
   8252 	if (*p != ';')
   8253 	  error (_("stop reply packet badly formatted: %s"), buf);
   8254 	event->ptid = read_ptid (++p, NULL);
   8255 	break;
   8256       }
   8257     case 'W':		/* Target exited.  */
   8258     case 'X':
   8259       {
   8260 	ULONGEST value;
   8261 
   8262 	/* GDB used to accept only 2 hex chars here.  Stubs should
   8263 	   only send more if they detect GDB supports multi-process
   8264 	   support.  */
   8265 	p = unpack_varlen_hex (&buf[1], &value);
   8266 
   8267 	if (buf[0] == 'W')
   8268 	  {
   8269 	    /* The remote process exited.  */
   8270 	    event->ws.set_exited (value);
   8271 	  }
   8272 	else
   8273 	  {
   8274 	    /* The remote process exited with a signal.  */
   8275 	    if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
   8276 	      event->ws.set_signalled ((enum gdb_signal) value);
   8277 	    else
   8278 	      event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
   8279 	  }
   8280 
   8281 	/* If no process is specified, return null_ptid, and let the
   8282 	   caller figure out the right process to use.  */
   8283 	int pid = 0;
   8284 	if (*p == '\0')
   8285 	  ;
   8286 	else if (*p == ';')
   8287 	  {
   8288 	    p++;
   8289 
   8290 	    if (*p == '\0')
   8291 	      ;
   8292 	    else if (startswith (p, "process:"))
   8293 	      {
   8294 		ULONGEST upid;
   8295 
   8296 		p += sizeof ("process:") - 1;
   8297 		unpack_varlen_hex (p, &upid);
   8298 		pid = upid;
   8299 	      }
   8300 	    else
   8301 	      error (_("unknown stop reply packet: %s"), buf);
   8302 	  }
   8303 	else
   8304 	  error (_("unknown stop reply packet: %s"), buf);
   8305 	event->ptid = ptid_t (pid);
   8306       }
   8307       break;
   8308     case 'N':
   8309       event->ws.set_no_resumed ();
   8310       event->ptid = minus_one_ptid;
   8311       break;
   8312     }
   8313 }
   8314 
   8315 /* When the stub wants to tell GDB about a new notification reply, it
   8316    sends a notification (%Stop, for example).  Those can come it at
   8317    any time, hence, we have to make sure that any pending
   8318    putpkt/getpkt sequence we're making is finished, before querying
   8319    the stub for more events with the corresponding ack command
   8320    (vStopped, for example).  E.g., if we started a vStopped sequence
   8321    immediately upon receiving the notification, something like this
   8322    could happen:
   8323 
   8324     1.1) --> Hg 1
   8325     1.2) <-- OK
   8326     1.3) --> g
   8327     1.4) <-- %Stop
   8328     1.5) --> vStopped
   8329     1.6) <-- (registers reply to step #1.3)
   8330 
   8331    Obviously, the reply in step #1.6 would be unexpected to a vStopped
   8332    query.
   8333 
   8334    To solve this, whenever we parse a %Stop notification successfully,
   8335    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
   8336    doing whatever we were doing:
   8337 
   8338     2.1) --> Hg 1
   8339     2.2) <-- OK
   8340     2.3) --> g
   8341     2.4) <-- %Stop
   8342       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
   8343     2.5) <-- (registers reply to step #2.3)
   8344 
   8345    Eventually after step #2.5, we return to the event loop, which
   8346    notices there's an event on the
   8347    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
   8348    associated callback --- the function below.  At this point, we're
   8349    always safe to start a vStopped sequence. :
   8350 
   8351     2.6) --> vStopped
   8352     2.7) <-- T05 thread:2
   8353     2.8) --> vStopped
   8354     2.9) --> OK
   8355 */
   8356 
   8357 void
   8358 remote_target::remote_notif_get_pending_events (const notif_client *nc)
   8359 {
   8360   struct remote_state *rs = get_remote_state ();
   8361 
   8362   if (rs->notif_state->pending_event[nc->id] != NULL)
   8363     {
   8364       if (notif_debug)
   8365 	gdb_printf (gdb_stdlog,
   8366 		    "notif: process: '%s' ack pending event\n",
   8367 		    nc->name);
   8368 
   8369       /* acknowledge */
   8370       nc->ack (this, nc, rs->buf.data (),
   8371 	       std::move (rs->notif_state->pending_event[nc->id]));
   8372 
   8373       while (1)
   8374 	{
   8375 	  getpkt (&rs->buf);
   8376 	  if (strcmp (rs->buf.data (), "OK") == 0)
   8377 	    break;
   8378 	  else
   8379 	    remote_notif_ack (this, nc, rs->buf.data ());
   8380 	}
   8381     }
   8382   else
   8383     {
   8384       if (notif_debug)
   8385 	gdb_printf (gdb_stdlog,
   8386 		    "notif: process: '%s' no pending reply\n",
   8387 		    nc->name);
   8388     }
   8389 }
   8390 
   8391 /* Wrapper around remote_target::remote_notif_get_pending_events to
   8392    avoid having to export the whole remote_target class.  */
   8393 
   8394 void
   8395 remote_notif_get_pending_events (remote_target *remote, const notif_client *nc)
   8396 {
   8397   remote->remote_notif_get_pending_events (nc);
   8398 }
   8399 
   8400 /* Called from process_stop_reply when the stop packet we are responding
   8401    to didn't include a process-id or thread-id.  STATUS is the stop event
   8402    we are responding to.
   8403 
   8404    It is the task of this function to select a suitable thread (or process)
   8405    and return its ptid, this is the thread (or process) we will assume the
   8406    stop event came from.
   8407 
   8408    In some cases there isn't really any choice about which thread (or
   8409    process) is selected, a basic remote with a single process containing a
   8410    single thread might choose not to send any process-id or thread-id in
   8411    its stop packets, this function will select and return the one and only
   8412    thread.
   8413 
   8414    However, if a target supports multiple threads (or processes) and still
   8415    doesn't include a thread-id (or process-id) in its stop packet then
   8416    first, this is a badly behaving target, and second, we're going to have
   8417    to select a thread (or process) at random and use that.  This function
   8418    will print a warning to the user if it detects that there is the
   8419    possibility that GDB is guessing which thread (or process) to
   8420    report.
   8421 
   8422    Note that this is called before GDB fetches the updated thread list from the
   8423    target.  So it's possible for the stop reply to be ambiguous and for GDB to
   8424    not realize it.  For example, if there's initially one thread, the target
   8425    spawns a second thread, and then sends a stop reply without an id that
   8426    concerns the first thread.  GDB will assume the stop reply is about the
   8427    first thread - the only thread it knows about - without printing a warning.
   8428    Anyway, if the remote meant for the stop reply to be about the second thread,
   8429    then it would be really broken, because GDB doesn't know about that thread
   8430    yet.  */
   8431 
   8432 ptid_t
   8433 remote_target::select_thread_for_ambiguous_stop_reply
   8434   (const target_waitstatus &status)
   8435 {
   8436   REMOTE_SCOPED_DEBUG_ENTER_EXIT;
   8437 
   8438   /* Some stop events apply to all threads in an inferior, while others
   8439      only apply to a single thread.  */
   8440   bool process_wide_stop
   8441     = (status.kind () == TARGET_WAITKIND_EXITED
   8442        || status.kind () == TARGET_WAITKIND_SIGNALLED);
   8443 
   8444   remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
   8445 
   8446   thread_info *first_resumed_thread = nullptr;
   8447   bool ambiguous = false;
   8448 
   8449   /* Consider all non-exited threads of the target, find the first resumed
   8450      one.  */
   8451   for (thread_info *thr : all_non_exited_threads (this))
   8452     {
   8453       remote_thread_info *remote_thr = get_remote_thread_info (thr);
   8454 
   8455       if (remote_thr->get_resume_state () != resume_state::RESUMED)
   8456 	continue;
   8457 
   8458       if (first_resumed_thread == nullptr)
   8459 	first_resumed_thread = thr;
   8460       else if (!process_wide_stop
   8461 	       || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
   8462 	ambiguous = true;
   8463     }
   8464 
   8465   gdb_assert (first_resumed_thread != nullptr);
   8466 
   8467   remote_debug_printf ("first resumed thread is %s",
   8468 		       pid_to_str (first_resumed_thread->ptid).c_str ());
   8469   remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
   8470 
   8471   /* Warn if the remote target is sending ambiguous stop replies.  */
   8472   if (ambiguous)
   8473     {
   8474       static bool warned = false;
   8475 
   8476       if (!warned)
   8477 	{
   8478 	  /* If you are seeing this warning then the remote target has
   8479 	     stopped without specifying a thread-id, but the target
   8480 	     does have multiple threads (or inferiors), and so GDB is
   8481 	     having to guess which thread stopped.
   8482 
   8483 	     Examples of what might cause this are the target sending
   8484 	     and 'S' stop packet, or a 'T' stop packet and not
   8485 	     including a thread-id.
   8486 
   8487 	     Additionally, the target might send a 'W' or 'X packet
   8488 	     without including a process-id, when the target has
   8489 	     multiple running inferiors.  */
   8490 	  if (process_wide_stop)
   8491 	    warning (_("multi-inferior target stopped without "
   8492 		       "sending a process-id, using first "
   8493 		       "non-exited inferior"));
   8494 	  else
   8495 	    warning (_("multi-threaded target stopped without "
   8496 		       "sending a thread-id, using first "
   8497 		       "non-exited thread"));
   8498 	  warned = true;
   8499 	}
   8500     }
   8501 
   8502   /* If this is a stop for all threads then don't use a particular threads
   8503      ptid, instead create a new ptid where only the pid field is set.  */
   8504   if (process_wide_stop)
   8505     return ptid_t (first_resumed_thread->ptid.pid ());
   8506   else
   8507     return first_resumed_thread->ptid;
   8508 }
   8509 
   8510 /* Called when it is decided that STOP_REPLY holds the info of the
   8511    event that is to be returned to the core.  This function always
   8512    destroys STOP_REPLY.  */
   8513 
   8514 ptid_t
   8515 remote_target::process_stop_reply (stop_reply_up stop_reply,
   8516 				   struct target_waitstatus *status)
   8517 {
   8518   *status = stop_reply->ws;
   8519   ptid_t ptid = stop_reply->ptid;
   8520 
   8521   /* If no thread/process was reported by the stub then select a suitable
   8522      thread/process.  */
   8523   if (ptid == null_ptid)
   8524     ptid = select_thread_for_ambiguous_stop_reply (*status);
   8525   gdb_assert (ptid != null_ptid);
   8526 
   8527   if (status->kind () != TARGET_WAITKIND_EXITED
   8528       && status->kind () != TARGET_WAITKIND_SIGNALLED
   8529       && status->kind () != TARGET_WAITKIND_NO_RESUMED)
   8530     {
   8531       remote_notice_new_inferior (ptid, false);
   8532 
   8533       /* Expedited registers.  */
   8534       if (!stop_reply->regcache.empty ())
   8535 	{
   8536 	  /* 'w' stop replies don't cary expedited registers (which
   8537 	     wouldn't make any sense for a thread that is gone
   8538 	     already).  */
   8539 	  gdb_assert (status->kind () != TARGET_WAITKIND_THREAD_EXITED);
   8540 
   8541 	  regcache *regcache
   8542 	    = get_thread_arch_regcache (find_inferior_ptid (this, ptid), ptid,
   8543 					stop_reply->arch);
   8544 
   8545 	  for (cached_reg_t &reg : stop_reply->regcache)
   8546 	    regcache->raw_supply (reg.num, reg.data.get ());
   8547 	}
   8548 
   8549       remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
   8550       remote_thr->core = stop_reply->core;
   8551       remote_thr->stop_reason = stop_reply->stop_reason;
   8552       remote_thr->watch_data_address = stop_reply->watch_data_address;
   8553 
   8554       if (target_is_non_stop_p ())
   8555 	{
   8556 	  /* If the target works in non-stop mode, a stop-reply indicates that
   8557 	     only this thread stopped.  */
   8558 	  remote_thr->set_not_resumed ();
   8559 	}
   8560       else
   8561 	{
   8562 	  /* If the target works in all-stop mode, a stop-reply indicates that
   8563 	     all the target's threads stopped.  */
   8564 	  for (thread_info *tp : all_non_exited_threads (this))
   8565 	    get_remote_thread_info (tp)->set_not_resumed ();
   8566 	}
   8567     }
   8568 
   8569   return ptid;
   8570 }
   8571 
   8572 /* The non-stop mode version of target_wait.  */
   8573 
   8574 ptid_t
   8575 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
   8576 			target_wait_flags options)
   8577 {
   8578   struct remote_state *rs = get_remote_state ();
   8579   int ret;
   8580   bool is_notif = false;
   8581 
   8582   /* If in non-stop mode, get out of getpkt even if a
   8583      notification is received.	*/
   8584 
   8585   ret = getpkt (&rs->buf, false /* forever */, &is_notif);
   8586   while (1)
   8587     {
   8588       if (ret != -1 && !is_notif)
   8589 	switch (rs->buf[0])
   8590 	  {
   8591 	  case 'E':		/* Error of some sort.	*/
   8592 	    /* We're out of sync with the target now.  Did it continue
   8593 	       or not?  We can't tell which thread it was in non-stop,
   8594 	       so just ignore this.  */
   8595 	    warning (_("Remote failure reply: %s"), rs->buf.data ());
   8596 	    break;
   8597 	  case 'O':		/* Console output.  */
   8598 	    remote_console_output (&rs->buf[1], gdb_stdtarg);
   8599 	    break;
   8600 	  default:
   8601 	    warning (_("Invalid remote reply: %s"), rs->buf.data ());
   8602 	    break;
   8603 	  }
   8604 
   8605       /* Acknowledge a pending stop reply that may have arrived in the
   8606 	 mean time.  */
   8607       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
   8608 	remote_notif_get_pending_events (&notif_client_stop);
   8609 
   8610       /* If indeed we noticed a stop reply, we're done.  */
   8611       stop_reply_up stop_reply = queued_stop_reply (ptid);
   8612       if (stop_reply != NULL)
   8613 	return process_stop_reply (std::move (stop_reply), status);
   8614 
   8615       /* Still no event.  If we're just polling for an event, then
   8616 	 return to the event loop.  */
   8617       if (options & TARGET_WNOHANG)
   8618 	{
   8619 	  status->set_ignore ();
   8620 	  return minus_one_ptid;
   8621 	}
   8622 
   8623       /* Otherwise do a blocking wait.  */
   8624       ret = getpkt (&rs->buf, true /* forever */, &is_notif);
   8625     }
   8626 }
   8627 
   8628 /* Return the first resumed thread.  */
   8629 
   8630 static ptid_t
   8631 first_remote_resumed_thread (remote_target *target)
   8632 {
   8633   for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
   8634     if (tp->resumed ())
   8635       return tp->ptid;
   8636   return null_ptid;
   8637 }
   8638 
   8639 /* Wait until the remote machine stops, then return, storing status in
   8640    STATUS just as `wait' would.  */
   8641 
   8642 ptid_t
   8643 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
   8644 			target_wait_flags options)
   8645 {
   8646   struct remote_state *rs = get_remote_state ();
   8647   ptid_t event_ptid = null_ptid;
   8648   char *buf;
   8649   stop_reply_up stop_reply;
   8650 
   8651  again:
   8652 
   8653   status->set_ignore ();
   8654 
   8655   stop_reply = queued_stop_reply (ptid);
   8656   if (stop_reply != NULL)
   8657     {
   8658       /* None of the paths that push a stop reply onto the queue should
   8659 	 have set the waiting_for_stop_reply flag.  */
   8660       gdb_assert (!rs->waiting_for_stop_reply);
   8661       event_ptid = process_stop_reply (std::move (stop_reply), status);
   8662     }
   8663   else
   8664     {
   8665       bool forever = ((options & TARGET_WNOHANG) == 0
   8666 		      && rs->wait_forever_enabled_p);
   8667 
   8668       if (!rs->waiting_for_stop_reply)
   8669 	{
   8670 	  status->set_no_resumed ();
   8671 	  return minus_one_ptid;
   8672 	}
   8673 
   8674       /* FIXME: cagney/1999-09-27: If we're in async mode we should
   8675 	 _never_ wait for ever -> test on target_is_async_p().
   8676 	 However, before we do that we need to ensure that the caller
   8677 	 knows how to take the target into/out of async mode.  */
   8678       bool is_notif;
   8679       int ret = getpkt (&rs->buf, forever, &is_notif);
   8680 
   8681       /* GDB gets a notification.  Return to core as this event is
   8682 	 not interesting.  */
   8683       if (ret != -1 && is_notif)
   8684 	return minus_one_ptid;
   8685 
   8686       if (ret == -1 && (options & TARGET_WNOHANG) != 0)
   8687 	return minus_one_ptid;
   8688 
   8689       buf = rs->buf.data ();
   8690 
   8691       /* Assume that the target has acknowledged Ctrl-C unless we receive
   8692 	 an 'F' or 'O' packet.  */
   8693       if (buf[0] != 'F' && buf[0] != 'O')
   8694 	rs->ctrlc_pending_p = 0;
   8695 
   8696       switch (buf[0])
   8697 	{
   8698 	case 'E':		/* Error of some sort.	*/
   8699 	  /* We're out of sync with the target now.  Did it continue or
   8700 	     not?  Not is more likely, so report a stop.  */
   8701 	  rs->waiting_for_stop_reply = 0;
   8702 
   8703 	  warning (_("Remote failure reply: %s"), buf);
   8704 	  status->set_stopped (GDB_SIGNAL_0);
   8705 	  break;
   8706 	case 'F':		/* File-I/O request.  */
   8707 	  /* GDB may access the inferior memory while handling the File-I/O
   8708 	     request, but we don't want GDB accessing memory while waiting
   8709 	     for a stop reply.  See the comments in putpkt_binary.  Set
   8710 	     waiting_for_stop_reply to 0 temporarily.  */
   8711 	  rs->waiting_for_stop_reply = 0;
   8712 	  remote_fileio_request (this, buf, rs->ctrlc_pending_p);
   8713 	  rs->ctrlc_pending_p = 0;
   8714 	  /* GDB handled the File-I/O request, and the target is running
   8715 	     again.  Keep waiting for events.  */
   8716 	  rs->waiting_for_stop_reply = 1;
   8717 	  break;
   8718 	case 'N': case 'T': case 'S': case 'X': case 'W': case 'w':
   8719 	  {
   8720 	    /* There is a stop reply to handle.  */
   8721 	    rs->waiting_for_stop_reply = 0;
   8722 
   8723 	    stop_reply
   8724 	      = as_stop_reply_up (remote_notif_parse (this,
   8725 						      &notif_client_stop,
   8726 						      rs->buf.data ()));
   8727 
   8728 	    event_ptid = process_stop_reply (std::move (stop_reply), status);
   8729 	    break;
   8730 	  }
   8731 	case 'O':		/* Console output.  */
   8732 	  remote_console_output (buf + 1, gdb_stdtarg);
   8733 	  break;
   8734 	case '\0':
   8735 	  if (rs->last_sent_signal != GDB_SIGNAL_0)
   8736 	    {
   8737 	      /* Zero length reply means that we tried 'S' or 'C' and the
   8738 		 remote system doesn't support it.  */
   8739 	      target_terminal::ours_for_output ();
   8740 	      gdb_printf
   8741 		("Can't send signals to this remote system.  %s not sent.\n",
   8742 		 gdb_signal_to_name (rs->last_sent_signal));
   8743 	      rs->last_sent_signal = GDB_SIGNAL_0;
   8744 	      target_terminal::inferior ();
   8745 
   8746 	      strcpy (buf, rs->last_sent_step ? "s" : "c");
   8747 	      putpkt (buf);
   8748 	      break;
   8749 	    }
   8750 	  [[fallthrough]];
   8751 	default:
   8752 	  warning (_("Invalid remote reply: %s"), buf);
   8753 	  break;
   8754 	}
   8755     }
   8756 
   8757   if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
   8758     return minus_one_ptid;
   8759   else if (status->kind () == TARGET_WAITKIND_IGNORE)
   8760     {
   8761       /* Nothing interesting happened.  If we're doing a non-blocking
   8762 	 poll, we're done.  Otherwise, go back to waiting.  */
   8763       if (options & TARGET_WNOHANG)
   8764 	return minus_one_ptid;
   8765       else
   8766 	goto again;
   8767     }
   8768   else if (status->kind () != TARGET_WAITKIND_EXITED
   8769 	   && status->kind () != TARGET_WAITKIND_SIGNALLED)
   8770     {
   8771       if (event_ptid != null_ptid)
   8772 	record_currthread (rs, event_ptid);
   8773       else
   8774 	event_ptid = first_remote_resumed_thread (this);
   8775     }
   8776   else
   8777     {
   8778       /* A process exit.  Invalidate our notion of current thread.  */
   8779       record_currthread (rs, minus_one_ptid);
   8780       /* It's possible that the packet did not include a pid.  */
   8781       if (event_ptid == null_ptid)
   8782 	event_ptid = first_remote_resumed_thread (this);
   8783       /* EVENT_PTID could still be NULL_PTID.  Double-check.  */
   8784       if (event_ptid == null_ptid)
   8785 	event_ptid = magic_null_ptid;
   8786     }
   8787 
   8788   return event_ptid;
   8789 }
   8790 
   8791 /* Wait until the remote machine stops, then return, storing status in
   8792    STATUS just as `wait' would.  */
   8793 
   8794 ptid_t
   8795 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
   8796 		     target_wait_flags options)
   8797 {
   8798   REMOTE_SCOPED_DEBUG_ENTER_EXIT;
   8799 
   8800   remote_state *rs = get_remote_state ();
   8801 
   8802   /* Start by clearing the flag that asks for our wait method to be called,
   8803      we'll mark it again at the end if needed.  If the target is not in
   8804      async mode then the async token should not be marked.  */
   8805   if (target_is_async_p ())
   8806     rs->clear_async_event_handler ();
   8807   else
   8808     gdb_assert (!rs->async_event_handler_marked ());
   8809 
   8810   ptid_t event_ptid;
   8811 
   8812   if (target_is_non_stop_p ())
   8813     event_ptid = wait_ns (ptid, status, options);
   8814   else
   8815     event_ptid = wait_as (ptid, status, options);
   8816 
   8817   if (target_is_async_p ())
   8818     {
   8819       /* If there are events left in the queue, or unacknowledged
   8820 	 notifications, then tell the event loop to call us again.  */
   8821       if (!rs->stop_reply_queue.empty ()
   8822 	  || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
   8823 	rs->mark_async_event_handler ();
   8824     }
   8825 
   8826   return event_ptid;
   8827 }
   8828 
   8829 /* Fetch a single register using a 'p' packet.  */
   8830 
   8831 int
   8832 remote_target::fetch_register_using_p (struct regcache *regcache,
   8833 				       packet_reg *reg)
   8834 {
   8835   struct gdbarch *gdbarch = regcache->arch ();
   8836   struct remote_state *rs = get_remote_state ();
   8837   char *buf, *p;
   8838   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
   8839   int i;
   8840 
   8841   if (m_features.packet_support (PACKET_p) == PACKET_DISABLE)
   8842     return 0;
   8843 
   8844   if (reg->pnum == -1)
   8845     return 0;
   8846 
   8847   p = rs->buf.data ();
   8848   *p++ = 'p';
   8849   p += hexnumstr (p, reg->pnum);
   8850   *p++ = '\0';
   8851   putpkt (rs->buf);
   8852   getpkt (&rs->buf);
   8853 
   8854   buf = rs->buf.data ();
   8855 
   8856   packet_result result = m_features.packet_ok (rs->buf, PACKET_p);
   8857   switch (result.status ())
   8858     {
   8859     case PACKET_OK:
   8860       break;
   8861     case PACKET_UNKNOWN:
   8862       return 0;
   8863     case PACKET_ERROR:
   8864       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
   8865 	     gdbarch_register_name (regcache->arch (), reg->regnum),
   8866 	     result.err_msg ());
   8867     }
   8868 
   8869   /* If this register is unfetchable, tell the regcache.  */
   8870   if (buf[0] == 'x')
   8871     {
   8872       regcache->raw_supply (reg->regnum, NULL);
   8873       return 1;
   8874     }
   8875 
   8876   /* Otherwise, parse and supply the value.  */
   8877   p = buf;
   8878   i = 0;
   8879   while (p[0] != 0)
   8880     {
   8881       if (p[1] == 0)
   8882 	error (_("fetch_register_using_p: early buf termination"));
   8883 
   8884       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
   8885       p += 2;
   8886     }
   8887   regcache->raw_supply (reg->regnum, regp);
   8888   return 1;
   8889 }
   8890 
   8891 /* Fetch the registers included in the target's 'g' packet.  */
   8892 
   8893 int
   8894 remote_target::send_g_packet ()
   8895 {
   8896   struct remote_state *rs = get_remote_state ();
   8897   int buf_len;
   8898 
   8899   xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
   8900   putpkt (rs->buf);
   8901   getpkt (&rs->buf);
   8902   packet_result result = packet_check_result (rs->buf, true);
   8903   if (result.status () == PACKET_ERROR)
   8904     error (_("Could not read registers; remote failure reply '%s'"),
   8905 	   result.err_msg ());
   8906 
   8907   /* We can get out of synch in various cases.  If the first character
   8908      in the buffer is not a hex character, assume that has happened
   8909      and try to fetch another packet to read.  */
   8910   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
   8911 	 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
   8912 	 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
   8913 	 && rs->buf[0] != 'x')	/* New: unavailable register value.  */
   8914     {
   8915       remote_debug_printf ("Bad register packet; fetching a new packet");
   8916       getpkt (&rs->buf);
   8917     }
   8918 
   8919   buf_len = strlen (rs->buf.data ());
   8920 
   8921   /* Sanity check the received packet.  */
   8922   if (buf_len % 2 != 0)
   8923     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
   8924 
   8925   return buf_len / 2;
   8926 }
   8927 
   8928 void
   8929 remote_target::process_g_packet (struct regcache *regcache)
   8930 {
   8931   struct gdbarch *gdbarch = regcache->arch ();
   8932   struct remote_state *rs = get_remote_state ();
   8933   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
   8934   int i, buf_len;
   8935   char *p;
   8936   char *regs;
   8937 
   8938   buf_len = strlen (rs->buf.data ());
   8939 
   8940   /* Further sanity checks, with knowledge of the architecture.  */
   8941   if (buf_len > 2 * rsa->sizeof_g_packet)
   8942     error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
   8943 	     "bytes): %s"),
   8944 	   rsa->sizeof_g_packet, buf_len / 2,
   8945 	   rs->buf.data ());
   8946 
   8947   /* Save the size of the packet sent to us by the target.  It is used
   8948      as a heuristic when determining the max size of packets that the
   8949      target can safely receive.  */
   8950   if (rsa->actual_register_packet_size == 0)
   8951     rsa->actual_register_packet_size = buf_len;
   8952 
   8953   /* If this is smaller than we guessed the 'g' packet would be,
   8954      update our records.  A 'g' reply that doesn't include a register's
   8955      value implies either that the register is not available, or that
   8956      the 'p' packet must be used.  */
   8957   if (buf_len < 2 * rsa->sizeof_g_packet)
   8958     {
   8959       long sizeof_g_packet = buf_len / 2;
   8960 
   8961       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
   8962 	{
   8963 	  long offset = rsa->regs[i].offset;
   8964 	  long reg_size = register_size (gdbarch, i);
   8965 
   8966 	  if (rsa->regs[i].pnum == -1)
   8967 	    continue;
   8968 
   8969 	  if (offset >= sizeof_g_packet)
   8970 	    rsa->regs[i].in_g_packet = 0;
   8971 	  else if (offset + reg_size > sizeof_g_packet)
   8972 	    error (_("Truncated register %d in remote 'g' packet"), i);
   8973 	  else
   8974 	    rsa->regs[i].in_g_packet = 1;
   8975 	}
   8976 
   8977       /* Looks valid enough, we can assume this is the correct length
   8978 	 for a 'g' packet.  It's important not to adjust
   8979 	 rsa->sizeof_g_packet if we have truncated registers otherwise
   8980 	 this "if" won't be run the next time the method is called
   8981 	 with a packet of the same size and one of the internal errors
   8982 	 below will trigger instead.  */
   8983       rsa->sizeof_g_packet = sizeof_g_packet;
   8984     }
   8985 
   8986   regs = (char *) alloca (rsa->sizeof_g_packet);
   8987 
   8988   /* Unimplemented registers read as all bits zero.  */
   8989   memset (regs, 0, rsa->sizeof_g_packet);
   8990 
   8991   /* Reply describes registers byte by byte, each byte encoded as two
   8992      hex characters.  Suck them all up, then supply them to the
   8993      register cacheing/storage mechanism.  */
   8994 
   8995   p = rs->buf.data ();
   8996   for (i = 0; i < rsa->sizeof_g_packet; i++)
   8997     {
   8998       if (p[0] == 0 || p[1] == 0)
   8999 	/* This shouldn't happen - we adjusted sizeof_g_packet above.  */
   9000 	internal_error (_("unexpected end of 'g' packet reply"));
   9001 
   9002       if (p[0] == 'x' && p[1] == 'x')
   9003 	regs[i] = 0;		/* 'x' */
   9004       else
   9005 	regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
   9006       p += 2;
   9007     }
   9008 
   9009   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
   9010     {
   9011       struct packet_reg *r = &rsa->regs[i];
   9012       long reg_size = register_size (gdbarch, i);
   9013 
   9014       if (r->in_g_packet)
   9015 	{
   9016 	  if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
   9017 	    /* This shouldn't happen - we adjusted in_g_packet above.  */
   9018 	    internal_error (_("unexpected end of 'g' packet reply"));
   9019 	  else if (rs->buf[r->offset * 2] == 'x')
   9020 	    {
   9021 	      gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
   9022 	      /* The register isn't available, mark it as such (at
   9023 		 the same time setting the value to zero).  */
   9024 	      regcache->raw_supply (r->regnum, NULL);
   9025 	    }
   9026 	  else
   9027 	    regcache->raw_supply (r->regnum, regs + r->offset);
   9028 	}
   9029     }
   9030 }
   9031 
   9032 void
   9033 remote_target::fetch_registers_using_g (struct regcache *regcache)
   9034 {
   9035   send_g_packet ();
   9036   process_g_packet (regcache);
   9037 }
   9038 
   9039 /* Make the remote selected traceframe match GDB's selected
   9040    traceframe.  */
   9041 
   9042 void
   9043 remote_target::set_remote_traceframe ()
   9044 {
   9045   int newnum;
   9046   struct remote_state *rs = get_remote_state ();
   9047 
   9048   if (rs->remote_traceframe_number == get_traceframe_number ())
   9049     return;
   9050 
   9051   /* Avoid recursion, remote_trace_find calls us again.  */
   9052   rs->remote_traceframe_number = get_traceframe_number ();
   9053 
   9054   newnum = target_trace_find (tfind_number,
   9055 			      get_traceframe_number (), 0, 0, NULL);
   9056 
   9057   /* Should not happen.  If it does, all bets are off.  */
   9058   if (newnum != get_traceframe_number ())
   9059     warning (_("could not set remote traceframe"));
   9060 }
   9061 
   9062 void
   9063 remote_target::fetch_registers (struct regcache *regcache, int regnum)
   9064 {
   9065   struct gdbarch *gdbarch = regcache->arch ();
   9066   struct remote_state *rs = get_remote_state ();
   9067   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
   9068   int i;
   9069 
   9070   set_remote_traceframe ();
   9071   set_general_thread (regcache->ptid ());
   9072 
   9073   if (regnum >= 0)
   9074     {
   9075       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
   9076 
   9077       gdb_assert (reg != NULL);
   9078 
   9079       /* If this register might be in the 'g' packet, try that first -
   9080 	 we are likely to read more than one register.  If this is the
   9081 	 first 'g' packet, we might be overly optimistic about its
   9082 	 contents, so fall back to 'p'.  */
   9083       if (reg->in_g_packet)
   9084 	{
   9085 	  fetch_registers_using_g (regcache);
   9086 	  if (reg->in_g_packet)
   9087 	    return;
   9088 	}
   9089 
   9090       if (fetch_register_using_p (regcache, reg))
   9091 	return;
   9092 
   9093       /* This register is not available.  */
   9094       regcache->raw_supply (reg->regnum, NULL);
   9095 
   9096       return;
   9097     }
   9098 
   9099   fetch_registers_using_g (regcache);
   9100 
   9101   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
   9102     if (!rsa->regs[i].in_g_packet)
   9103       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
   9104 	{
   9105 	  /* This register is not available.  */
   9106 	  regcache->raw_supply (i, NULL);
   9107 	}
   9108 }
   9109 
   9110 /* Prepare to store registers.  Since we may send them all (using a
   9111    'G' request), we have to read out the ones we don't want to change
   9112    first.  */
   9113 
   9114 void
   9115 remote_target::prepare_to_store (struct regcache *regcache)
   9116 {
   9117   struct remote_state *rs = get_remote_state ();
   9118   remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
   9119   int i;
   9120 
   9121   /* Make sure the entire registers array is valid.  */
   9122   switch (m_features.packet_support (PACKET_P))
   9123     {
   9124     case PACKET_DISABLE:
   9125     case PACKET_SUPPORT_UNKNOWN:
   9126       /* Make sure all the necessary registers are cached.  */
   9127       for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
   9128 	if (rsa->regs[i].in_g_packet)
   9129 	  regcache->raw_update (rsa->regs[i].regnum);
   9130       break;
   9131     case PACKET_ENABLE:
   9132       break;
   9133     }
   9134 }
   9135 
   9136 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
   9137    packet was not recognized.  */
   9138 
   9139 int
   9140 remote_target::store_register_using_P (const struct regcache *regcache,
   9141 				       packet_reg *reg)
   9142 {
   9143   struct gdbarch *gdbarch = regcache->arch ();
   9144   struct remote_state *rs = get_remote_state ();
   9145   /* Try storing a single register.  */
   9146   char *buf = rs->buf.data ();
   9147   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
   9148   char *p;
   9149 
   9150   if (m_features.packet_support (PACKET_P) == PACKET_DISABLE)
   9151     return 0;
   9152 
   9153   if (reg->pnum == -1)
   9154     return 0;
   9155 
   9156   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
   9157   p = buf + strlen (buf);
   9158   regcache->raw_collect (reg->regnum, regp);
   9159   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
   9160   putpkt (rs->buf);
   9161   getpkt (&rs->buf);
   9162 
   9163   packet_result result = m_features.packet_ok (rs->buf, PACKET_P);
   9164   switch (result.status ())
   9165     {
   9166     case PACKET_OK:
   9167       return 1;
   9168     case PACKET_ERROR:
   9169       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
   9170 	     gdbarch_register_name (gdbarch, reg->regnum), result.err_msg ());
   9171     case PACKET_UNKNOWN:
   9172       return 0;
   9173     default:
   9174       internal_error (_("Bad result from packet_ok"));
   9175     }
   9176 }
   9177 
   9178 /* Store register REGNUM, or all registers if REGNUM == -1, from the
   9179    contents of the register cache buffer.  FIXME: ignores errors.  */
   9180 
   9181 void
   9182 remote_target::store_registers_using_G (const struct regcache *regcache)
   9183 {
   9184   struct remote_state *rs = get_remote_state ();
   9185   remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
   9186   gdb_byte *regs;
   9187   char *p;
   9188 
   9189   /* Extract all the registers in the regcache copying them into a
   9190      local buffer.  */
   9191   {
   9192     int i;
   9193 
   9194     regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
   9195     memset (regs, 0, rsa->sizeof_g_packet);
   9196     for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
   9197       {
   9198 	struct packet_reg *r = &rsa->regs[i];
   9199 
   9200 	if (r->in_g_packet)
   9201 	  regcache->raw_collect (r->regnum, regs + r->offset);
   9202       }
   9203   }
   9204 
   9205   /* Command describes registers byte by byte,
   9206      each byte encoded as two hex characters.  */
   9207   p = rs->buf.data ();
   9208   *p++ = 'G';
   9209   bin2hex (regs, p, rsa->sizeof_g_packet);
   9210   putpkt (rs->buf);
   9211   getpkt (&rs->buf);
   9212   packet_result pkt_status = packet_check_result (rs->buf, true);
   9213   if (pkt_status.status () == PACKET_ERROR)
   9214     error (_("Could not write registers; remote failure reply '%s'"),
   9215 	   pkt_status.err_msg ());
   9216 }
   9217 
   9218 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
   9219    of the register cache buffer.  FIXME: ignores errors.  */
   9220 
   9221 void
   9222 remote_target::store_registers (struct regcache *regcache, int regnum)
   9223 {
   9224   struct gdbarch *gdbarch = regcache->arch ();
   9225   struct remote_state *rs = get_remote_state ();
   9226   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
   9227   int i;
   9228 
   9229   set_remote_traceframe ();
   9230   set_general_thread (regcache->ptid ());
   9231 
   9232   if (regnum >= 0)
   9233     {
   9234       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
   9235 
   9236       gdb_assert (reg != NULL);
   9237 
   9238       /* Always prefer to store registers using the 'P' packet if
   9239 	 possible; we often change only a small number of registers.
   9240 	 Sometimes we change a larger number; we'd need help from a
   9241 	 higher layer to know to use 'G'.  */
   9242       if (store_register_using_P (regcache, reg))
   9243 	return;
   9244 
   9245       /* For now, don't complain if we have no way to write the
   9246 	 register.  GDB loses track of unavailable registers too
   9247 	 easily.  Some day, this may be an error.  We don't have
   9248 	 any way to read the register, either...  */
   9249       if (!reg->in_g_packet)
   9250 	return;
   9251 
   9252       store_registers_using_G (regcache);
   9253       return;
   9254     }
   9255 
   9256   store_registers_using_G (regcache);
   9257 
   9258   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
   9259     if (!rsa->regs[i].in_g_packet)
   9260       if (!store_register_using_P (regcache, &rsa->regs[i]))
   9261 	/* See above for why we do not issue an error here.  */
   9262 	continue;
   9263 }
   9264 
   9265 
   9267 /* Return the number of hex digits in num.  */
   9268 
   9269 static int
   9270 hexnumlen (ULONGEST num)
   9271 {
   9272   int i;
   9273 
   9274   for (i = 0; num != 0; i++)
   9275     num >>= 4;
   9276 
   9277   return std::max (i, 1);
   9278 }
   9279 
   9280 /* Set BUF to the minimum number of hex digits representing NUM.  */
   9281 
   9282 static int
   9283 hexnumstr (char *buf, ULONGEST num)
   9284 {
   9285   int len = hexnumlen (num);
   9286 
   9287   return hexnumnstr (buf, num, len);
   9288 }
   9289 
   9290 
   9291 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
   9292 
   9293 static int
   9294 hexnumnstr (char *buf, ULONGEST num, int width)
   9295 {
   9296   int i;
   9297 
   9298   buf[width] = '\0';
   9299 
   9300   for (i = width - 1; i >= 0; i--)
   9301     {
   9302       buf[i] = "0123456789abcdef"[(num & 0xf)];
   9303       num >>= 4;
   9304     }
   9305 
   9306   return width;
   9307 }
   9308 
   9309 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
   9310 
   9311 static CORE_ADDR
   9312 remote_address_masked (CORE_ADDR addr)
   9313 {
   9314   unsigned int address_size = remote_address_size;
   9315 
   9316   /* If "remoteaddresssize" was not set, default to target address size.  */
   9317   if (!address_size)
   9318     address_size = gdbarch_addr_bit (current_inferior ()->arch ());
   9319 
   9320   if (address_size > 0
   9321       && address_size < (sizeof (ULONGEST) * 8))
   9322     {
   9323       /* Only create a mask when that mask can safely be constructed
   9324 	 in a ULONGEST variable.  */
   9325       ULONGEST mask = 1;
   9326 
   9327       mask = (mask << address_size) - 1;
   9328       addr &= mask;
   9329     }
   9330   return addr;
   9331 }
   9332 
   9333 /* Determine whether the remote target supports binary downloading.
   9334    This is accomplished by sending a no-op memory write of zero length
   9335    to the target at the specified address. It does not suffice to send
   9336    the whole packet, since many stubs strip the eighth bit and
   9337    subsequently compute a wrong checksum, which causes real havoc with
   9338    remote_write_bytes.
   9339 
   9340    NOTE: This can still lose if the serial line is not eight-bit
   9341    clean.  In cases like this, the user should clear "remote
   9342    X-packet".  */
   9343 
   9344 void
   9345 remote_target::check_binary_download (CORE_ADDR addr)
   9346 {
   9347   struct remote_state *rs = get_remote_state ();
   9348 
   9349   switch (m_features.packet_support (PACKET_X))
   9350     {
   9351     case PACKET_DISABLE:
   9352       break;
   9353     case PACKET_ENABLE:
   9354       break;
   9355     case PACKET_SUPPORT_UNKNOWN:
   9356       {
   9357 	char *p;
   9358 
   9359 	p = rs->buf.data ();
   9360 	*p++ = 'X';
   9361 	p += hexnumstr (p, (ULONGEST) addr);
   9362 	*p++ = ',';
   9363 	p += hexnumstr (p, (ULONGEST) 0);
   9364 	*p++ = ':';
   9365 	*p = '\0';
   9366 
   9367 	putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
   9368 	getpkt (&rs->buf);
   9369 
   9370 	if (rs->buf[0] == '\0')
   9371 	  {
   9372 	    remote_debug_printf ("binary downloading NOT supported by target");
   9373 	    m_features.m_protocol_packets[PACKET_X].support = PACKET_DISABLE;
   9374 	  }
   9375 	else
   9376 	  {
   9377 	    remote_debug_printf ("binary downloading supported by target");
   9378 	    m_features.m_protocol_packets[PACKET_X].support = PACKET_ENABLE;
   9379 	  }
   9380 	break;
   9381       }
   9382     }
   9383 }
   9384 
   9385 /* Helper function to resize the payload in order to try to get a good
   9386    alignment.  We try to write an amount of data such that the next write will
   9387    start on an address aligned on REMOTE_ALIGN_WRITES.  */
   9388 
   9389 static int
   9390 align_for_efficient_write (int todo, CORE_ADDR memaddr)
   9391 {
   9392   return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
   9393 }
   9394 
   9395 /* Write memory data directly to the remote machine.
   9396    This does not inform the data cache; the data cache uses this.
   9397    HEADER is the starting part of the packet.
   9398    MEMADDR is the address in the remote memory space.
   9399    MYADDR is the address of the buffer in our space.
   9400    LEN_UNITS is the number of addressable units to write.
   9401    UNIT_SIZE is the length in bytes of an addressable unit.
   9402    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
   9403    should send data as binary ('X'), or hex-encoded ('M').
   9404 
   9405    The function creates packet of the form
   9406        <HEADER><ADDRESS>,<LENGTH>:<DATA>
   9407 
   9408    where encoding of <DATA> is terminated by PACKET_FORMAT.
   9409 
   9410    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
   9411    are omitted.
   9412 
   9413    Return the transferred status, error or OK (an
   9414    'enum target_xfer_status' value).  Save the number of addressable units
   9415    transferred in *XFERED_LEN_UNITS.  Only transfer a single packet.
   9416 
   9417    On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
   9418    exchange between gdb and the stub could look like (?? in place of the
   9419    checksum):
   9420 
   9421    -> $m1000,4#??
   9422    <- aaaabbbbccccdddd
   9423 
   9424    -> $M1000,3:eeeeffffeeee#??
   9425    <- OK
   9426 
   9427    -> $m1000,4#??
   9428    <- eeeeffffeeeedddd  */
   9429 
   9430 target_xfer_status
   9431 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
   9432 				       const gdb_byte *myaddr,
   9433 				       ULONGEST len_units,
   9434 				       int unit_size,
   9435 				       ULONGEST *xfered_len_units,
   9436 				       char packet_format, int use_length)
   9437 {
   9438   struct remote_state *rs = get_remote_state ();
   9439   char *p;
   9440   char *plen = NULL;
   9441   int plenlen = 0;
   9442   int todo_units;
   9443   int units_written;
   9444   int payload_capacity_bytes;
   9445   int payload_length_bytes;
   9446 
   9447   if (packet_format != 'X' && packet_format != 'M')
   9448     internal_error (_("remote_write_bytes_aux: bad packet format"));
   9449 
   9450   if (len_units == 0)
   9451     return TARGET_XFER_EOF;
   9452 
   9453   payload_capacity_bytes = get_memory_write_packet_size ();
   9454 
   9455   /* The packet buffer will be large enough for the payload;
   9456      get_memory_packet_size ensures this.  */
   9457   rs->buf[0] = '\0';
   9458 
   9459   /* Compute the size of the actual payload by subtracting out the
   9460      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
   9461 
   9462   payload_capacity_bytes -= strlen ("$,:#NN");
   9463   if (!use_length)
   9464     /* The comma won't be used.  */
   9465     payload_capacity_bytes += 1;
   9466   payload_capacity_bytes -= strlen (header);
   9467   payload_capacity_bytes -= hexnumlen (memaddr);
   9468 
   9469   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
   9470 
   9471   strcat (rs->buf.data (), header);
   9472   p = rs->buf.data () + strlen (header);
   9473 
   9474   /* Compute a best guess of the number of bytes actually transfered.  */
   9475   if (packet_format == 'X')
   9476     {
   9477       /* Best guess at number of bytes that will fit.  */
   9478       todo_units = std::min (len_units,
   9479 			     (ULONGEST) payload_capacity_bytes / unit_size);
   9480       if (use_length)
   9481 	payload_capacity_bytes -= hexnumlen (todo_units);
   9482       todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
   9483     }
   9484   else
   9485     {
   9486       /* Number of bytes that will fit.  */
   9487       todo_units
   9488 	= std::min (len_units,
   9489 		    (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
   9490       if (use_length)
   9491 	payload_capacity_bytes -= hexnumlen (todo_units);
   9492       todo_units = std::min (todo_units,
   9493 			     (payload_capacity_bytes / unit_size) / 2);
   9494     }
   9495 
   9496   if (todo_units <= 0)
   9497     internal_error (_("minimum packet size too small to write data"));
   9498 
   9499   /* If we already need another packet, then try to align the end
   9500      of this packet to a useful boundary.  */
   9501   if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
   9502     todo_units = align_for_efficient_write (todo_units, memaddr);
   9503 
   9504   /* Append "<memaddr>".  */
   9505   memaddr = remote_address_masked (memaddr);
   9506   p += hexnumstr (p, (ULONGEST) memaddr);
   9507 
   9508   if (use_length)
   9509     {
   9510       /* Append ",".  */
   9511       *p++ = ',';
   9512 
   9513       /* Append the length and retain its location and size.  It may need to be
   9514 	 adjusted once the packet body has been created.  */
   9515       plen = p;
   9516       plenlen = hexnumstr (p, (ULONGEST) todo_units);
   9517       p += plenlen;
   9518     }
   9519 
   9520   /* Append ":".  */
   9521   *p++ = ':';
   9522   *p = '\0';
   9523 
   9524   /* Append the packet body.  */
   9525   if (packet_format == 'X')
   9526     {
   9527       /* Binary mode.  Send target system values byte by byte, in
   9528 	 increasing byte addresses.  Only escape certain critical
   9529 	 characters.  */
   9530       payload_length_bytes =
   9531 	  remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
   9532 				&units_written, payload_capacity_bytes);
   9533 
   9534       /* If not all TODO units fit, then we'll need another packet.  Make
   9535 	 a second try to keep the end of the packet aligned.  Don't do
   9536 	 this if the packet is tiny.  */
   9537       if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
   9538 	{
   9539 	  int new_todo_units;
   9540 
   9541 	  new_todo_units = align_for_efficient_write (units_written, memaddr);
   9542 
   9543 	  if (new_todo_units != units_written)
   9544 	    payload_length_bytes =
   9545 		remote_escape_output (myaddr, new_todo_units, unit_size,
   9546 				      (gdb_byte *) p, &units_written,
   9547 				      payload_capacity_bytes);
   9548 	}
   9549 
   9550       p += payload_length_bytes;
   9551       if (use_length && units_written < todo_units)
   9552 	{
   9553 	  /* Escape chars have filled up the buffer prematurely,
   9554 	     and we have actually sent fewer units than planned.
   9555 	     Fix-up the length field of the packet.  Use the same
   9556 	     number of characters as before.  */
   9557 	  plen += hexnumnstr (plen, (ULONGEST) units_written,
   9558 			      plenlen);
   9559 	  *plen = ':';  /* overwrite \0 from hexnumnstr() */
   9560 	}
   9561     }
   9562   else
   9563     {
   9564       /* Normal mode: Send target system values byte by byte, in
   9565 	 increasing byte addresses.  Each byte is encoded as a two hex
   9566 	 value.  */
   9567       p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
   9568       units_written = todo_units;
   9569     }
   9570 
   9571   putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
   9572   getpkt (&rs->buf);
   9573 
   9574   if (rs->buf[0] == 'E')
   9575     return TARGET_XFER_E_IO;
   9576 
   9577   /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
   9578      send fewer units than we'd planned.  */
   9579   *xfered_len_units = (ULONGEST) units_written;
   9580   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
   9581 }
   9582 
   9583 /* Write memory data directly to the remote machine.
   9584    This does not inform the data cache; the data cache uses this.
   9585    MEMADDR is the address in the remote memory space.
   9586    MYADDR is the address of the buffer in our space.
   9587    LEN is the number of bytes.
   9588 
   9589    Return the transferred status, error or OK (an
   9590    'enum target_xfer_status' value).  Save the number of bytes
   9591    transferred in *XFERED_LEN.  Only transfer a single packet.  */
   9592 
   9593 target_xfer_status
   9594 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
   9595 				   ULONGEST len, int unit_size,
   9596 				   ULONGEST *xfered_len)
   9597 {
   9598   const char *packet_format = NULL;
   9599 
   9600   /* Check whether the target supports binary download.  */
   9601   check_binary_download (memaddr);
   9602 
   9603   switch (m_features.packet_support (PACKET_X))
   9604     {
   9605     case PACKET_ENABLE:
   9606       packet_format = "X";
   9607       break;
   9608     case PACKET_DISABLE:
   9609       packet_format = "M";
   9610       break;
   9611     case PACKET_SUPPORT_UNKNOWN:
   9612       internal_error (_("remote_write_bytes: bad internal state"));
   9613     default:
   9614       internal_error (_("bad switch"));
   9615     }
   9616 
   9617   return remote_write_bytes_aux (packet_format,
   9618 				 memaddr, myaddr, len, unit_size, xfered_len,
   9619 				 packet_format[0], 1);
   9620 }
   9621 
   9622 /* Read memory data directly from the remote machine.
   9623    This does not use the data cache; the data cache uses this.
   9624    MEMADDR is the address in the remote memory space.
   9625    MYADDR is the address of the buffer in our space.
   9626    LEN_UNITS is the number of addressable memory units to read..
   9627    UNIT_SIZE is the length in bytes of an addressable unit.
   9628 
   9629    Return the transferred status, error or OK (an
   9630    'enum target_xfer_status' value).  Save the number of bytes
   9631    transferred in *XFERED_LEN_UNITS.
   9632 
   9633    See the comment of remote_write_bytes_aux for an example of
   9634    memory read/write exchange between gdb and the stub.  */
   9635 
   9636 target_xfer_status
   9637 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
   9638 				    ULONGEST len_units,
   9639 				    int unit_size, ULONGEST *xfered_len_units)
   9640 {
   9641   struct remote_state *rs = get_remote_state ();
   9642   int buf_size_bytes;		/* Max size of packet output buffer.  */
   9643   char *p;
   9644   int todo_units;
   9645   int decoded_bytes;
   9646 
   9647   buf_size_bytes = get_memory_read_packet_size ();
   9648   /* The packet buffer will be large enough for the payload;
   9649      get_memory_packet_size ensures this.  */
   9650 
   9651   /* Number of units that will fit.  */
   9652   todo_units = std::min (len_units,
   9653 			 (ULONGEST) (buf_size_bytes / unit_size) / 2);
   9654 
   9655   /* Construct "m"<memaddr>","<len>".  */
   9656   memaddr = remote_address_masked (memaddr);
   9657   p = rs->buf.data ();
   9658   *p++ = 'm';
   9659   p += hexnumstr (p, (ULONGEST) memaddr);
   9660   *p++ = ',';
   9661   p += hexnumstr (p, (ULONGEST) todo_units);
   9662   *p = '\0';
   9663   putpkt (rs->buf);
   9664   getpkt (&rs->buf);
   9665   packet_result result = packet_check_result (rs->buf, false);
   9666   if (result.status () == PACKET_ERROR)
   9667     return TARGET_XFER_E_IO;
   9668   /* Reply describes memory byte by byte, each byte encoded as two hex
   9669      characters.  */
   9670   p = rs->buf.data ();
   9671   decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
   9672   /* Return what we have.  Let higher layers handle partial reads.  */
   9673   *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
   9674   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
   9675 }
   9676 
   9677 /* Using the set of read-only target sections of remote, read live
   9678    read-only memory.
   9679 
   9680    For interface/parameters/return description see target.h,
   9681    to_xfer_partial.  */
   9682 
   9683 target_xfer_status
   9684 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
   9685 						  ULONGEST memaddr,
   9686 						  ULONGEST len,
   9687 						  int unit_size,
   9688 						  ULONGEST *xfered_len)
   9689 {
   9690   const struct target_section *secp;
   9691 
   9692   secp = target_section_by_addr (this, memaddr);
   9693   if (secp != NULL
   9694       && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
   9695     {
   9696       ULONGEST memend = memaddr + len;
   9697 
   9698       const std::vector<target_section> *table
   9699 	= target_get_section_table (this);
   9700       for (const target_section &p : *table)
   9701 	{
   9702 	  if (memaddr >= p.addr)
   9703 	    {
   9704 	      if (memend <= p.endaddr)
   9705 		{
   9706 		  /* Entire transfer is within this section.  */
   9707 		  return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
   9708 					      xfered_len);
   9709 		}
   9710 	      else if (memaddr >= p.endaddr)
   9711 		{
   9712 		  /* This section ends before the transfer starts.  */
   9713 		  continue;
   9714 		}
   9715 	      else
   9716 		{
   9717 		  /* This section overlaps the transfer.  Just do half.  */
   9718 		  len = p.endaddr - memaddr;
   9719 		  return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
   9720 					      xfered_len);
   9721 		}
   9722 	    }
   9723 	}
   9724     }
   9725 
   9726   return TARGET_XFER_EOF;
   9727 }
   9728 
   9729 /* Similar to remote_read_bytes_1, but it reads from the remote stub
   9730    first if the requested memory is unavailable in traceframe.
   9731    Otherwise, fall back to remote_read_bytes_1.  */
   9732 
   9733 target_xfer_status
   9734 remote_target::remote_read_bytes (CORE_ADDR memaddr,
   9735 				  gdb_byte *myaddr, ULONGEST len, int unit_size,
   9736 				  ULONGEST *xfered_len)
   9737 {
   9738   if (len == 0)
   9739     return TARGET_XFER_EOF;
   9740 
   9741   if (get_traceframe_number () != -1)
   9742     {
   9743       std::vector<mem_range> available;
   9744 
   9745       /* If we fail to get the set of available memory, then the
   9746 	 target does not support querying traceframe info, and so we
   9747 	 attempt reading from the traceframe anyway (assuming the
   9748 	 target implements the old QTro packet then).  */
   9749       if (traceframe_available_memory (&available, memaddr, len))
   9750 	{
   9751 	  if (available.empty () || available[0].start != memaddr)
   9752 	    {
   9753 	      enum target_xfer_status res;
   9754 
   9755 	      /* Don't read into the traceframe's available
   9756 		 memory.  */
   9757 	      if (!available.empty ())
   9758 		{
   9759 		  LONGEST oldlen = len;
   9760 
   9761 		  len = available[0].start - memaddr;
   9762 		  gdb_assert (len <= oldlen);
   9763 		}
   9764 
   9765 	      /* This goes through the topmost target again.  */
   9766 	      res = remote_xfer_live_readonly_partial (myaddr, memaddr,
   9767 						       len, unit_size, xfered_len);
   9768 	      if (res == TARGET_XFER_OK)
   9769 		return TARGET_XFER_OK;
   9770 	      else
   9771 		{
   9772 		  /* No use trying further, we know some memory starting
   9773 		     at MEMADDR isn't available.  */
   9774 		  *xfered_len = len;
   9775 		  return (*xfered_len != 0) ?
   9776 		    TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
   9777 		}
   9778 	    }
   9779 
   9780 	  /* Don't try to read more than how much is available, in
   9781 	     case the target implements the deprecated QTro packet to
   9782 	     cater for older GDBs (the target's knowledge of read-only
   9783 	     sections may be outdated by now).  */
   9784 	  len = available[0].length;
   9785 	}
   9786     }
   9787 
   9788   return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
   9789 }
   9790 
   9791 
   9792 
   9794 /* Sends a packet with content determined by the printf format string
   9795    FORMAT and the remaining arguments, then gets the reply.  Returns
   9796    whether the packet was a success, a failure, or unknown.  */
   9797 
   9798 packet_status
   9799 remote_target::remote_send_printf (const char *format, ...)
   9800 {
   9801   struct remote_state *rs = get_remote_state ();
   9802   int max_size = get_remote_packet_size ();
   9803   va_list ap;
   9804 
   9805   va_start (ap, format);
   9806 
   9807   rs->buf[0] = '\0';
   9808   int size = vsnprintf (rs->buf.data (), max_size, format, ap);
   9809 
   9810   va_end (ap);
   9811 
   9812   if (size >= max_size)
   9813     internal_error (_("Too long remote packet."));
   9814 
   9815   if (putpkt (rs->buf) < 0)
   9816     error (_("Communication problem with target."));
   9817 
   9818   rs->buf[0] = '\0';
   9819   getpkt (&rs->buf);
   9820 
   9821   return packet_check_result (rs->buf, true).status ();
   9822 }
   9823 
   9824 /* Flash writing can take quite some time.  We'll set
   9825    effectively infinite timeout for flash operations.
   9826    In future, we'll need to decide on a better approach.  */
   9827 static const int remote_flash_timeout = 1000;
   9828 
   9829 void
   9830 remote_target::flash_erase (ULONGEST address, LONGEST length)
   9831 {
   9832   int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
   9833   enum packet_status ret;
   9834   scoped_restore restore_timeout
   9835     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
   9836 
   9837   ret = remote_send_printf ("vFlashErase:%s,%s",
   9838 			    phex (address, addr_size),
   9839 			    phex (length, 4));
   9840   switch (ret)
   9841     {
   9842     case PACKET_UNKNOWN:
   9843       error (_("Remote target does not support flash erase"));
   9844     case PACKET_ERROR:
   9845       error (_("Error erasing flash with vFlashErase packet"));
   9846     default:
   9847       break;
   9848     }
   9849 }
   9850 
   9851 target_xfer_status
   9852 remote_target::remote_flash_write (ULONGEST address,
   9853 				   ULONGEST length, ULONGEST *xfered_len,
   9854 				   const gdb_byte *data)
   9855 {
   9856   scoped_restore restore_timeout
   9857     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
   9858   return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
   9859 				 xfered_len,'X', 0);
   9860 }
   9861 
   9862 void
   9863 remote_target::flash_done ()
   9864 {
   9865   int ret;
   9866 
   9867   scoped_restore restore_timeout
   9868     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
   9869 
   9870   ret = remote_send_printf ("vFlashDone");
   9871 
   9872   switch (ret)
   9873     {
   9874     case PACKET_UNKNOWN:
   9875       error (_("Remote target does not support vFlashDone"));
   9876     case PACKET_ERROR:
   9877       error (_("Error finishing flash operation"));
   9878     default:
   9879       break;
   9880     }
   9881 }
   9882 
   9883 
   9884 /* Stuff for dealing with the packets which are part of this protocol.
   9886    See comment at top of file for details.  */
   9887 
   9888 /* Read a single character from the remote end.  The current quit
   9889    handler is overridden to avoid quitting in the middle of packet
   9890    sequence, as that would break communication with the remote server.
   9891    See remote_serial_quit_handler for more detail.  */
   9892 
   9893 int
   9894 remote_target::readchar (int timeout)
   9895 {
   9896   int ch;
   9897   struct remote_state *rs = get_remote_state ();
   9898 
   9899   try
   9900     {
   9901       scoped_restore restore_quit_target
   9902 	= make_scoped_restore (&curr_quit_handler_target, this);
   9903       scoped_restore restore_quit
   9904 	= make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
   9905 
   9906       rs->got_ctrlc_during_io = 0;
   9907 
   9908       ch = serial_readchar (rs->remote_desc, timeout);
   9909 
   9910       if (rs->got_ctrlc_during_io)
   9911 	set_quit_flag ();
   9912     }
   9913   catch (const gdb_exception_error &ex)
   9914     {
   9915       remote_unpush_target (this);
   9916       throw_error (TARGET_CLOSE_ERROR,
   9917 		   _("Remote communication error.  "
   9918 		     "Target disconnected: %s"),
   9919 		   ex.what ());
   9920     }
   9921 
   9922   if (ch >= 0)
   9923     return ch;
   9924 
   9925   if (ch == SERIAL_EOF)
   9926     {
   9927       remote_unpush_target (this);
   9928       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
   9929     }
   9930 
   9931   return ch;
   9932 }
   9933 
   9934 /* Wrapper for serial_write that closes the target and throws if
   9935    writing fails.  The current quit handler is overridden to avoid
   9936    quitting in the middle of packet sequence, as that would break
   9937    communication with the remote server.  See
   9938    remote_serial_quit_handler for more detail.  */
   9939 
   9940 void
   9941 remote_target::remote_serial_write (const char *str, int len)
   9942 {
   9943   struct remote_state *rs = get_remote_state ();
   9944 
   9945   scoped_restore restore_quit_target
   9946     = make_scoped_restore (&curr_quit_handler_target, this);
   9947   scoped_restore restore_quit
   9948     = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
   9949 
   9950   rs->got_ctrlc_during_io = 0;
   9951 
   9952   try
   9953     {
   9954       serial_write (rs->remote_desc, str, len);
   9955     }
   9956   catch (const gdb_exception_error &ex)
   9957     {
   9958       remote_unpush_target (this);
   9959       throw_error (TARGET_CLOSE_ERROR,
   9960 		   _("Remote communication error.  "
   9961 		     "Target disconnected: %s"),
   9962 		   ex.what ());
   9963     }
   9964 
   9965   if (rs->got_ctrlc_during_io)
   9966     set_quit_flag ();
   9967 }
   9968 
   9969 void
   9970 remote_target::remote_serial_send_break ()
   9971 {
   9972   struct remote_state *rs = get_remote_state ();
   9973 
   9974   try
   9975     {
   9976       serial_send_break (rs->remote_desc);
   9977     }
   9978   catch (const gdb_exception_error &ex)
   9979     {
   9980       remote_unpush_target (this);
   9981       throw_error (TARGET_CLOSE_ERROR,
   9982 		   _("Remote communication error.  "
   9983 		     "Target disconnected: %s"),
   9984 		   ex.what ());
   9985     }
   9986 }
   9987 
   9988 /* Return a string representing an escaped version of BUF, of len N.
   9989    E.g. \n is converted to \\n, \t to \\t, etc.  */
   9990 
   9991 static std::string
   9992 escape_buffer (const char *buf, int n)
   9993 {
   9994   string_file stb;
   9995 
   9996   stb.putstrn (buf, n, '\\');
   9997   return stb.release ();
   9998 }
   9999 
   10000 int
   10001 remote_target::putpkt (const char *buf)
   10002 {
   10003   return putpkt_binary (buf, strlen (buf));
   10004 }
   10005 
   10006 /* Wrapper around remote_target::putpkt to avoid exporting
   10007    remote_target.  */
   10008 
   10009 int
   10010 putpkt (remote_target *remote, const char *buf)
   10011 {
   10012   return remote->putpkt (buf);
   10013 }
   10014 
   10015 /* Send a packet to the remote machine, with error checking.  The data
   10016    of the packet is in BUF.  The string in BUF can be at most
   10017    get_remote_packet_size () - 5 to account for the $, # and checksum,
   10018    and for a possible /0 if we are debugging (remote_debug) and want
   10019    to print the sent packet as a string.  */
   10020 
   10021 int
   10022 remote_target::putpkt_binary (const char *buf, int cnt)
   10023 {
   10024   struct remote_state *rs = get_remote_state ();
   10025   int i;
   10026   unsigned char csum = 0;
   10027   gdb::def_vector<char> data (cnt + 6);
   10028   char *buf2 = data.data ();
   10029 
   10030   int ch;
   10031   int tcount = 0;
   10032   char *p;
   10033 
   10034   /* Catch cases like trying to read memory or listing threads while
   10035      we're waiting for a stop reply.  The remote server wouldn't be
   10036      ready to handle this request, so we'd hang and timeout.  We don't
   10037      have to worry about this in synchronous mode, because in that
   10038      case it's not possible to issue a command while the target is
   10039      running.  This is not a problem in non-stop mode, because in that
   10040      case, the stub is always ready to process serial input.  */
   10041   if (!target_is_non_stop_p ()
   10042       && target_is_async_p ()
   10043       && rs->waiting_for_stop_reply)
   10044     {
   10045       error (_("Cannot execute this command while the target is running.\n"
   10046 	       "Use the \"interrupt\" command to stop the target\n"
   10047 	       "and then try again."));
   10048     }
   10049 
   10050   /* Copy the packet into buffer BUF2, encapsulating it
   10051      and giving it a checksum.  */
   10052 
   10053   p = buf2;
   10054   *p++ = '$';
   10055 
   10056   for (i = 0; i < cnt; i++)
   10057     {
   10058       csum += buf[i];
   10059       *p++ = buf[i];
   10060     }
   10061   *p++ = '#';
   10062   *p++ = tohex ((csum >> 4) & 0xf);
   10063   *p++ = tohex (csum & 0xf);
   10064 
   10065   /* Send it over and over until we get a positive ack.  */
   10066 
   10067   while (1)
   10068     {
   10069       if (remote_debug)
   10070 	{
   10071 	  *p = '\0';
   10072 
   10073 	  int len = (int) (p - buf2);
   10074 	  int max_chars;
   10075 
   10076 	  if (remote_packet_max_chars < 0)
   10077 	    max_chars = len;
   10078 	  else
   10079 	    max_chars = remote_packet_max_chars;
   10080 
   10081 	  std::string str
   10082 	    = escape_buffer (buf2, std::min (len, max_chars));
   10083 
   10084 	  if (len > max_chars)
   10085 	    remote_debug_printf_nofunc
   10086 	      ("Sending packet: %s [%d bytes omitted]", str.c_str (),
   10087 	       len - max_chars);
   10088 	  else
   10089 	    remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
   10090 	}
   10091       remote_serial_write (buf2, p - buf2);
   10092 
   10093       /* If this is a no acks version of the remote protocol, send the
   10094 	 packet and move on.  */
   10095       if (rs->noack_mode)
   10096 	break;
   10097 
   10098       /* Read until either a timeout occurs (-2) or '+' is read.
   10099 	 Handle any notification that arrives in the mean time.  */
   10100       while (1)
   10101 	{
   10102 	  ch = readchar (remote_timeout);
   10103 
   10104 	  switch (ch)
   10105 	    {
   10106 	    case '+':
   10107 	      remote_debug_printf_nofunc ("Received Ack");
   10108 	      return 1;
   10109 	    case '-':
   10110 	      remote_debug_printf_nofunc ("Received Nak");
   10111 	      [[fallthrough]];
   10112 	    case SERIAL_TIMEOUT:
   10113 	      tcount++;
   10114 	      if (tcount > 3)
   10115 		return 0;
   10116 	      break;		/* Retransmit buffer.  */
   10117 	    case '$':
   10118 	      {
   10119 		remote_debug_printf ("Packet instead of Ack, ignoring it");
   10120 		/* It's probably an old response sent because an ACK
   10121 		   was lost.  Gobble up the packet and ack it so it
   10122 		   doesn't get retransmitted when we resend this
   10123 		   packet.  */
   10124 		skip_frame ();
   10125 		remote_serial_write ("+", 1);
   10126 		continue;	/* Now, go look for +.  */
   10127 	      }
   10128 
   10129 	    case '%':
   10130 	      {
   10131 		int val;
   10132 
   10133 		/* If we got a notification, handle it, and go back to looking
   10134 		   for an ack.  */
   10135 		/* We've found the start of a notification.  Now
   10136 		   collect the data.  */
   10137 		val = read_frame (&rs->buf);
   10138 		if (val >= 0)
   10139 		  {
   10140 		    remote_debug_printf_nofunc
   10141 		      ("  Notification received: %s",
   10142 		       escape_buffer (rs->buf.data (), val).c_str ());
   10143 
   10144 		    handle_notification (rs->notif_state, rs->buf.data ());
   10145 		    /* We're in sync now, rewait for the ack.  */
   10146 		    tcount = 0;
   10147 		  }
   10148 		else
   10149 		  remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
   10150 					      rs->buf.data ());
   10151 		continue;
   10152 	      }
   10153 	    default:
   10154 	      remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
   10155 					  rs->buf.data ());
   10156 	      continue;
   10157 	    }
   10158 	  break;		/* Here to retransmit.  */
   10159 	}
   10160 
   10161 #if 0
   10162       /* This is wrong.  If doing a long backtrace, the user should be
   10163 	 able to get out next time we call QUIT, without anything as
   10164 	 violent as interrupt_query.  If we want to provide a way out of
   10165 	 here without getting to the next QUIT, it should be based on
   10166 	 hitting ^C twice as in remote_wait.  */
   10167       if (quit_flag)
   10168 	{
   10169 	  quit_flag = 0;
   10170 	  interrupt_query ();
   10171 	}
   10172 #endif
   10173     }
   10174 
   10175   return 0;
   10176 }
   10177 
   10178 /* Come here after finding the start of a frame when we expected an
   10179    ack.  Do our best to discard the rest of this packet.  */
   10180 
   10181 void
   10182 remote_target::skip_frame ()
   10183 {
   10184   int c;
   10185 
   10186   while (1)
   10187     {
   10188       c = readchar (remote_timeout);
   10189       switch (c)
   10190 	{
   10191 	case SERIAL_TIMEOUT:
   10192 	  /* Nothing we can do.  */
   10193 	  return;
   10194 	case '#':
   10195 	  /* Discard the two bytes of checksum and stop.  */
   10196 	  c = readchar (remote_timeout);
   10197 	  if (c >= 0)
   10198 	    c = readchar (remote_timeout);
   10199 
   10200 	  return;
   10201 	case '*':		/* Run length encoding.  */
   10202 	  /* Discard the repeat count.  */
   10203 	  c = readchar (remote_timeout);
   10204 	  if (c < 0)
   10205 	    return;
   10206 	  break;
   10207 	default:
   10208 	  /* A regular character.  */
   10209 	  break;
   10210 	}
   10211     }
   10212 }
   10213 
   10214 /* Come here after finding the start of the frame.  Collect the rest
   10215    into *BUF, verifying the checksum, length, and handling run-length
   10216    compression.  NUL terminate the buffer.  If there is not enough room,
   10217    expand *BUF.
   10218 
   10219    Returns -1 on error, number of characters in buffer (ignoring the
   10220    trailing NULL) on success. (could be extended to return one of the
   10221    SERIAL status indications).  */
   10222 
   10223 long
   10224 remote_target::read_frame (gdb::char_vector *buf_p)
   10225 {
   10226   unsigned char csum;
   10227   long bc;
   10228   int c;
   10229   char *buf = buf_p->data ();
   10230   struct remote_state *rs = get_remote_state ();
   10231 
   10232   csum = 0;
   10233   bc = 0;
   10234 
   10235   while (1)
   10236     {
   10237       c = readchar (remote_timeout);
   10238       switch (c)
   10239 	{
   10240 	case SERIAL_TIMEOUT:
   10241 	  remote_debug_printf ("Timeout in mid-packet, retrying");
   10242 	  return -1;
   10243 
   10244 	case '$':
   10245 	  remote_debug_printf ("Saw new packet start in middle of old one");
   10246 	  return -1;		/* Start a new packet, count retries.  */
   10247 
   10248 	case '#':
   10249 	  {
   10250 	    unsigned char pktcsum;
   10251 	    int check_0 = 0;
   10252 	    int check_1 = 0;
   10253 
   10254 	    buf[bc] = '\0';
   10255 
   10256 	    check_0 = readchar (remote_timeout);
   10257 	    if (check_0 >= 0)
   10258 	      check_1 = readchar (remote_timeout);
   10259 
   10260 	    if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
   10261 	      {
   10262 		remote_debug_printf ("Timeout in checksum, retrying");
   10263 		return -1;
   10264 	      }
   10265 	    else if (check_0 < 0 || check_1 < 0)
   10266 	      {
   10267 		remote_debug_printf ("Communication error in checksum");
   10268 		return -1;
   10269 	      }
   10270 
   10271 	    /* Don't recompute the checksum; with no ack packets we
   10272 	       don't have any way to indicate a packet retransmission
   10273 	       is necessary.  */
   10274 	    if (rs->noack_mode)
   10275 	      return bc;
   10276 
   10277 	    pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
   10278 	    if (csum == pktcsum)
   10279 	      return bc;
   10280 
   10281 	    remote_debug_printf
   10282 	      ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
   10283 	       pktcsum, csum, escape_buffer (buf, bc).c_str ());
   10284 
   10285 	    /* Number of characters in buffer ignoring trailing
   10286 	       NULL.  */
   10287 	    return -1;
   10288 	  }
   10289 	case '*':		/* Run length encoding.  */
   10290 	  {
   10291 	    int repeat;
   10292 
   10293 	    csum += c;
   10294 	    c = readchar (remote_timeout);
   10295 	    csum += c;
   10296 	    repeat = c - ' ' + 3;	/* Compute repeat count.  */
   10297 
   10298 	    /* The character before ``*'' is repeated.  */
   10299 
   10300 	    if (repeat > 0 && repeat <= 255 && bc > 0)
   10301 	      {
   10302 		if (bc + repeat - 1 >= buf_p->size () - 1)
   10303 		  {
   10304 		    /* Make some more room in the buffer.  */
   10305 		    buf_p->resize (buf_p->size () + repeat);
   10306 		    buf = buf_p->data ();
   10307 		  }
   10308 
   10309 		memset (&buf[bc], buf[bc - 1], repeat);
   10310 		bc += repeat;
   10311 		continue;
   10312 	      }
   10313 
   10314 	    buf[bc] = '\0';
   10315 	    gdb_printf (_("Invalid run length encoding: %s\n"), buf);
   10316 	    return -1;
   10317 	  }
   10318 	default:
   10319 	  if (bc >= buf_p->size () - 1)
   10320 	    {
   10321 	      /* Make some more room in the buffer.  */
   10322 	      buf_p->resize (buf_p->size () * 2);
   10323 	      buf = buf_p->data ();
   10324 	    }
   10325 
   10326 	  buf[bc++] = c;
   10327 	  csum += c;
   10328 	  continue;
   10329 	}
   10330     }
   10331 }
   10332 
   10333 /* Set this to the maximum number of seconds to wait instead of waiting forever
   10334    in target_wait().  If this timer times out, then it generates an error and
   10335    the command is aborted.  This replaces most of the need for timeouts in the
   10336    GDB test suite, and makes it possible to distinguish between a hung target
   10337    and one with slow communications.  */
   10338 
   10339 static int watchdog = 0;
   10340 static void
   10341 show_watchdog (struct ui_file *file, int from_tty,
   10342 	       struct cmd_list_element *c, const char *value)
   10343 {
   10344   gdb_printf (file, _("Watchdog timer is %s.\n"), value);
   10345 }
   10346 
   10347 /* Read a packet from the remote machine, with error checking, and
   10348    store it in *BUF.  Resize *BUF if necessary to hold the result.  If
   10349    FOREVER, wait forever rather than timing out; this is used (in
   10350    synchronous mode) to wait for a target that is is executing user
   10351    code to stop.  If FOREVER == false, this function is allowed to time
   10352    out gracefully and return an indication of this to the caller.
   10353    Otherwise return the number of bytes read.  If IS_NOTIF is not
   10354    NULL, then consider receiving a notification enough reason to
   10355    return to the caller.  In this case, *IS_NOTIF is an output boolean
   10356    that indicates whether *BUF holds a notification or not (a regular
   10357    packet).  */
   10358 
   10359 int
   10360 remote_target::getpkt (gdb::char_vector *buf, bool forever, bool *is_notif)
   10361 {
   10362   struct remote_state *rs = get_remote_state ();
   10363   int c;
   10364   int tries;
   10365   int timeout;
   10366   int val = -1;
   10367 
   10368   strcpy (buf->data (), "timeout");
   10369 
   10370   if (forever)
   10371     timeout = watchdog > 0 ? watchdog : -1;
   10372   else if (is_notif != nullptr)
   10373     timeout = 0; /* There should already be a char in the buffer.  If
   10374 		    not, bail out.  */
   10375   else
   10376     timeout = remote_timeout;
   10377 
   10378 #define MAX_TRIES 3
   10379 
   10380   /* Process any number of notifications, and then return when
   10381      we get a packet.  */
   10382   for (;;)
   10383     {
   10384       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
   10385 	 times.  */
   10386       for (tries = 1; tries <= MAX_TRIES; tries++)
   10387 	{
   10388 	  /* This can loop forever if the remote side sends us
   10389 	     characters continuously, but if it pauses, we'll get
   10390 	     SERIAL_TIMEOUT from readchar because of timeout.  Then
   10391 	     we'll count that as a retry.
   10392 
   10393 	     Note that even when forever is set, we will only wait
   10394 	     forever prior to the start of a packet.  After that, we
   10395 	     expect characters to arrive at a brisk pace.  They should
   10396 	     show up within remote_timeout intervals.  */
   10397 	  do
   10398 	    c = readchar (timeout);
   10399 	  while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
   10400 
   10401 	  if (c == SERIAL_TIMEOUT)
   10402 	    {
   10403 	      if (is_notif != nullptr)
   10404 		return -1; /* Don't complain, it's normal to not get
   10405 			      anything in this case.  */
   10406 
   10407 	      if (forever)	/* Watchdog went off?  Kill the target.  */
   10408 		{
   10409 		  remote_unpush_target (this);
   10410 		  throw_error (TARGET_CLOSE_ERROR,
   10411 			       _("Watchdog timeout has expired.  "
   10412 				 "Target detached."));
   10413 		}
   10414 
   10415 	      remote_debug_printf ("Timed out.");
   10416 	    }
   10417 	  else
   10418 	    {
   10419 	      /* We've found the start of a packet or notification.
   10420 		 Now collect the data.  */
   10421 	      val = read_frame (buf);
   10422 	      if (val >= 0)
   10423 		break;
   10424 	    }
   10425 
   10426 	  remote_serial_write ("-", 1);
   10427 	}
   10428 
   10429       if (tries > MAX_TRIES)
   10430 	{
   10431 	  /* We have tried hard enough, and just can't receive the
   10432 	     packet/notification.  Give up.  */
   10433 	  gdb_printf (_("Ignoring packet error, continuing...\n"));
   10434 
   10435 	  /* Skip the ack char if we're in no-ack mode.  */
   10436 	  if (!rs->noack_mode)
   10437 	    remote_serial_write ("+", 1);
   10438 	  return -1;
   10439 	}
   10440 
   10441       /* If we got an ordinary packet, return that to our caller.  */
   10442       if (c == '$')
   10443 	{
   10444 	  if (remote_debug)
   10445 	    {
   10446 	      int max_chars;
   10447 
   10448 	      if (remote_packet_max_chars < 0)
   10449 		max_chars = val;
   10450 	      else
   10451 		max_chars = remote_packet_max_chars;
   10452 
   10453 	      std::string str
   10454 		= escape_buffer (buf->data (),
   10455 				 std::min (val, max_chars));
   10456 
   10457 	      if (val > max_chars)
   10458 		remote_debug_printf_nofunc
   10459 		  ("Packet received: %s [%d bytes omitted]", str.c_str (),
   10460 		   val - max_chars);
   10461 	      else
   10462 		remote_debug_printf_nofunc ("Packet received: %s",
   10463 					    str.c_str ());
   10464 	    }
   10465 
   10466 	  /* Skip the ack char if we're in no-ack mode.  */
   10467 	  if (!rs->noack_mode)
   10468 	    remote_serial_write ("+", 1);
   10469 	  if (is_notif != NULL)
   10470 	    *is_notif = false;
   10471 	  return val;
   10472 	}
   10473 
   10474        /* If we got a notification, handle it, and go back to looking
   10475 	 for a packet.  */
   10476       else
   10477 	{
   10478 	  gdb_assert (c == '%');
   10479 
   10480 	  remote_debug_printf_nofunc
   10481 	    ("  Notification received: %s",
   10482 	     escape_buffer (buf->data (), val).c_str ());
   10483 
   10484 	  if (is_notif != NULL)
   10485 	    *is_notif = true;
   10486 
   10487 	  handle_notification (rs->notif_state, buf->data ());
   10488 
   10489 	  /* Notifications require no acknowledgement.  */
   10490 
   10491 	  if (is_notif != nullptr)
   10492 	    return val;
   10493 	}
   10494     }
   10495 }
   10496 
   10497 /* Kill any new fork children of inferior INF that haven't been
   10498    processed by follow_fork.  */
   10499 
   10500 void
   10501 remote_target::kill_new_fork_children (inferior *inf)
   10502 {
   10503   remote_state *rs = get_remote_state ();
   10504   const notif_client *notif = &notif_client_stop;
   10505 
   10506   /* Kill the fork child threads of any threads in inferior INF that are stopped
   10507      at a fork event.  */
   10508   for (thread_info *thread : inf->non_exited_threads ())
   10509     {
   10510       const target_waitstatus *ws = thread_pending_fork_status (thread);
   10511 
   10512       if (ws == nullptr)
   10513 	continue;
   10514 
   10515       int child_pid = ws->child_ptid ().pid ();
   10516       int res = remote_vkill (child_pid);
   10517 
   10518       if (res != 0)
   10519 	error (_("Can't kill fork child process %d"), child_pid);
   10520     }
   10521 
   10522   /* Check for any pending fork events (not reported or processed yet)
   10523      in inferior INF and kill those fork child threads as well.  */
   10524   remote_notif_get_pending_events (notif);
   10525   for (auto &event : rs->stop_reply_queue)
   10526     {
   10527       if (event->ptid.pid () != inf->pid)
   10528 	continue;
   10529 
   10530       if (!is_fork_status (event->ws.kind ()))
   10531 	continue;
   10532 
   10533       int child_pid = event->ws.child_ptid ().pid ();
   10534       int res = remote_vkill (child_pid);
   10535 
   10536       if (res != 0)
   10537 	error (_("Can't kill fork child process %d"), child_pid);
   10538     }
   10539 }
   10540 
   10541 
   10542 /* Target hook to kill the current inferior.  */
   10544 
   10545 void
   10546 remote_target::kill ()
   10547 {
   10548   int res = -1;
   10549   inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
   10550 
   10551   gdb_assert (inf != nullptr);
   10552 
   10553   if (m_features.packet_support (PACKET_vKill) != PACKET_DISABLE)
   10554     {
   10555       /* If we're stopped while forking and we haven't followed yet,
   10556 	 kill the child task.  We need to do this before killing the
   10557 	 parent task because if this is a vfork then the parent will
   10558 	 be sleeping.  */
   10559       kill_new_fork_children (inf);
   10560 
   10561       res = remote_vkill (inf->pid);
   10562       if (res == 0)
   10563 	{
   10564 	  target_mourn_inferior (inferior_ptid);
   10565 	  return;
   10566 	}
   10567     }
   10568 
   10569   /* If we are in 'target remote' mode and we are killing the only
   10570      inferior, then we will tell gdbserver to exit and unpush the
   10571      target.  */
   10572   if (res == -1 && !m_features.remote_multi_process_p ()
   10573       && number_of_live_inferiors (this) == 1)
   10574     {
   10575       remote_kill_k ();
   10576 
   10577       /* We've killed the remote end, we get to mourn it.  If we are
   10578 	 not in extended mode, mourning the inferior also unpushes
   10579 	 remote_ops from the target stack, which closes the remote
   10580 	 connection.  */
   10581       target_mourn_inferior (inferior_ptid);
   10582 
   10583       return;
   10584     }
   10585 
   10586   error (_("Can't kill process"));
   10587 }
   10588 
   10589 /* Send a kill request to the target using the 'vKill' packet.  */
   10590 
   10591 int
   10592 remote_target::remote_vkill (int pid)
   10593 {
   10594   if (m_features.packet_support (PACKET_vKill) == PACKET_DISABLE)
   10595     return -1;
   10596 
   10597   remote_state *rs = get_remote_state ();
   10598 
   10599   /* Tell the remote target to detach.  */
   10600   xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
   10601   putpkt (rs->buf);
   10602   getpkt (&rs->buf);
   10603 
   10604   switch ((m_features.packet_ok (rs->buf, PACKET_vKill)).status ())
   10605     {
   10606     case PACKET_OK:
   10607       return 0;
   10608     case PACKET_ERROR:
   10609       return 1;
   10610     case PACKET_UNKNOWN:
   10611       return -1;
   10612     default:
   10613       internal_error (_("Bad result from packet_ok"));
   10614     }
   10615 }
   10616 
   10617 /* Send a kill request to the target using the 'k' packet.  */
   10618 
   10619 void
   10620 remote_target::remote_kill_k ()
   10621 {
   10622   /* Catch errors so the user can quit from gdb even when we
   10623      aren't on speaking terms with the remote system.  */
   10624   try
   10625     {
   10626       putpkt ("k");
   10627     }
   10628   catch (const gdb_exception_error &ex)
   10629     {
   10630       if (ex.error == TARGET_CLOSE_ERROR)
   10631 	{
   10632 	  /* If we got an (EOF) error that caused the target
   10633 	     to go away, then we're done, that's what we wanted.
   10634 	     "k" is susceptible to cause a premature EOF, given
   10635 	     that the remote server isn't actually required to
   10636 	     reply to "k", and it can happen that it doesn't
   10637 	     even get to reply ACK to the "k".  */
   10638 	  return;
   10639 	}
   10640 
   10641       /* Otherwise, something went wrong.  We didn't actually kill
   10642 	 the target.  Just propagate the exception, and let the
   10643 	 user or higher layers decide what to do.  */
   10644       throw;
   10645     }
   10646 }
   10647 
   10648 void
   10649 remote_target::mourn_inferior ()
   10650 {
   10651   struct remote_state *rs = get_remote_state ();
   10652 
   10653   /* We're no longer interested in notification events of an inferior
   10654      that exited or was killed/detached.  */
   10655   discard_pending_stop_replies (current_inferior ());
   10656 
   10657   /* In 'target remote' mode with one inferior, we close the connection.  */
   10658   if (!rs->extended && number_of_live_inferiors (this) <= 1)
   10659     {
   10660       remote_unpush_target (this);
   10661       return;
   10662     }
   10663 
   10664   /* In case we got here due to an error, but we're going to stay
   10665      connected.  */
   10666   rs->waiting_for_stop_reply = 0;
   10667 
   10668   /* If the current general thread belonged to the process we just
   10669      detached from or has exited, the remote side current general
   10670      thread becomes undefined.  Considering a case like this:
   10671 
   10672      - We just got here due to a detach.
   10673      - The process that we're detaching from happens to immediately
   10674        report a global breakpoint being hit in non-stop mode, in the
   10675        same thread we had selected before.
   10676      - GDB attaches to this process again.
   10677      - This event happens to be the next event we handle.
   10678 
   10679      GDB would consider that the current general thread didn't need to
   10680      be set on the stub side (with Hg), since for all it knew,
   10681      GENERAL_THREAD hadn't changed.
   10682 
   10683      Notice that although in all-stop mode, the remote server always
   10684      sets the current thread to the thread reporting the stop event,
   10685      that doesn't happen in non-stop mode; in non-stop, the stub *must
   10686      not* change the current thread when reporting a breakpoint hit,
   10687      due to the decoupling of event reporting and event handling.
   10688 
   10689      To keep things simple, we always invalidate our notion of the
   10690      current thread.  */
   10691   record_currthread (rs, minus_one_ptid);
   10692 
   10693   /* Call common code to mark the inferior as not running.  */
   10694   generic_mourn_inferior ();
   10695 }
   10696 
   10697 bool
   10698 extended_remote_target::supports_disable_randomization ()
   10699 {
   10700   return (m_features.packet_support (PACKET_QDisableRandomization)
   10701 	  == PACKET_ENABLE);
   10702 }
   10703 
   10704 void
   10705 remote_target::extended_remote_disable_randomization (int val)
   10706 {
   10707   struct remote_state *rs = get_remote_state ();
   10708   char *reply;
   10709 
   10710   xsnprintf (rs->buf.data (), get_remote_packet_size (),
   10711 	     "QDisableRandomization:%x", val);
   10712   putpkt (rs->buf);
   10713   reply = remote_get_noisy_reply ();
   10714   if (*reply == '\0')
   10715     error (_("Target does not support QDisableRandomization."));
   10716   if (strcmp (reply, "OK") != 0)
   10717     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
   10718 }
   10719 
   10720 int
   10721 remote_target::extended_remote_run (const std::string &args)
   10722 {
   10723   struct remote_state *rs = get_remote_state ();
   10724   int len;
   10725   const char *remote_exec_file = get_remote_exec_file ();
   10726 
   10727   /* If the user has disabled vRun support, or we have detected that
   10728      support is not available, do not try it.  */
   10729   if (m_features.packet_support (PACKET_vRun) == PACKET_DISABLE)
   10730     return -1;
   10731 
   10732   strcpy (rs->buf.data (), "vRun;");
   10733   len = strlen (rs->buf.data ());
   10734 
   10735   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
   10736     error (_("Remote file name too long for run packet"));
   10737   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
   10738 		      strlen (remote_exec_file));
   10739 
   10740   if (!args.empty ())
   10741     {
   10742       int i;
   10743 
   10744       gdb_argv argv (args.c_str ());
   10745       for (i = 0; argv[i] != NULL; i++)
   10746 	{
   10747 	  if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
   10748 	    error (_("Argument list too long for run packet"));
   10749 	  rs->buf[len++] = ';';
   10750 	  len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
   10751 			      strlen (argv[i]));
   10752 	}
   10753     }
   10754 
   10755   rs->buf[len++] = '\0';
   10756 
   10757   putpkt (rs->buf);
   10758   getpkt (&rs->buf);
   10759 
   10760   packet_result result = m_features.packet_ok (rs->buf, PACKET_vRun);
   10761   switch (result.status ())
   10762     {
   10763     case PACKET_OK:
   10764       /* We have a wait response.  All is well.  */
   10765       return 0;
   10766     case PACKET_UNKNOWN:
   10767       return -1;
   10768     case PACKET_ERROR:
   10769       /* If we have a textual error message, print just that.  This
   10770 	 makes remote debugging output the same as native output, when
   10771 	 possible.  */
   10772       if (result.textual_err_msg ())
   10773 	error (("%s"), result.err_msg ());
   10774       if (remote_exec_file[0] == '\0')
   10775 	error (_("Running the default executable on the remote target failed; "
   10776 		 "try \"set remote exec-file\"?"));
   10777       else
   10778 	error (_("Running \"%s\" on the remote target failed"),
   10779 	       remote_exec_file);
   10780     default:
   10781       gdb_assert_not_reached ("bad switch");
   10782     }
   10783 }
   10784 
   10785 /* Helper function to send set/unset environment packets.  ACTION is
   10786    either "set" or "unset".  PACKET is either "QEnvironmentHexEncoded"
   10787    or "QEnvironmentUnsetVariable".  VALUE is the variable to be
   10788    sent.  */
   10789 
   10790 void
   10791 remote_target::send_environment_packet (const char *action,
   10792 					const char *packet,
   10793 					const char *value)
   10794 {
   10795   remote_state *rs = get_remote_state ();
   10796 
   10797   /* Convert the environment variable to an hex string, which
   10798      is the best format to be transmitted over the wire.  */
   10799   std::string encoded_value = bin2hex ((const gdb_byte *) value,
   10800 					 strlen (value));
   10801 
   10802   xsnprintf (rs->buf.data (), get_remote_packet_size (),
   10803 	     "%s:%s", packet, encoded_value.c_str ());
   10804 
   10805   putpkt (rs->buf);
   10806   getpkt (&rs->buf);
   10807   if (strcmp (rs->buf.data (), "OK") != 0)
   10808     warning (_("Unable to %s environment variable '%s' on remote."),
   10809 	     action, value);
   10810 }
   10811 
   10812 /* Helper function to handle the QEnvironment* packets.  */
   10813 
   10814 void
   10815 remote_target::extended_remote_environment_support ()
   10816 {
   10817   remote_state *rs = get_remote_state ();
   10818 
   10819   if (m_features.packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
   10820     {
   10821       putpkt ("QEnvironmentReset");
   10822       getpkt (&rs->buf);
   10823       if (strcmp (rs->buf.data (), "OK") != 0)
   10824 	warning (_("Unable to reset environment on remote."));
   10825     }
   10826 
   10827   gdb_environ *e = &current_inferior ()->environment;
   10828 
   10829   if (m_features.packet_support (PACKET_QEnvironmentHexEncoded)
   10830       != PACKET_DISABLE)
   10831     {
   10832       for (const std::string &el : e->user_set_env ())
   10833 	send_environment_packet ("set", "QEnvironmentHexEncoded",
   10834 				 el.c_str ());
   10835     }
   10836 
   10837 
   10838   if (m_features.packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
   10839     for (const std::string &el : e->user_unset_env ())
   10840       send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
   10841 }
   10842 
   10843 /* Helper function to set the current working directory for the
   10844    inferior in the remote target.  */
   10845 
   10846 void
   10847 remote_target::extended_remote_set_inferior_cwd ()
   10848 {
   10849   if (m_features.packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
   10850     {
   10851       const std::string &inferior_cwd = current_inferior ()->cwd ();
   10852       remote_state *rs = get_remote_state ();
   10853 
   10854       if (!inferior_cwd.empty ())
   10855 	{
   10856 	  std::string hexpath
   10857 	    = bin2hex ((const gdb_byte *) inferior_cwd.data (),
   10858 		       inferior_cwd.size ());
   10859 
   10860 	  xsnprintf (rs->buf.data (), get_remote_packet_size (),
   10861 		     "QSetWorkingDir:%s", hexpath.c_str ());
   10862 	}
   10863       else
   10864 	{
   10865 	  /* An empty inferior_cwd means that the user wants us to
   10866 	     reset the remote server's inferior's cwd.  */
   10867 	  xsnprintf (rs->buf.data (), get_remote_packet_size (),
   10868 		     "QSetWorkingDir:");
   10869 	}
   10870 
   10871       putpkt (rs->buf);
   10872       getpkt (&rs->buf);
   10873       packet_result result = m_features.packet_ok (rs->buf, PACKET_QSetWorkingDir);
   10874       if (result.status () == PACKET_ERROR)
   10875 	error (_("\
   10876 Remote replied unexpectedly while setting the inferior's working\n\
   10877 directory: %s"),
   10878 	       result.err_msg ());
   10879       if (result.status () == PACKET_UNKNOWN)
   10880 	error (_("Remote target failed to process setting the inferior's working directory"));
   10881 
   10882     }
   10883 }
   10884 
   10885 /* In the extended protocol we want to be able to do things like
   10886    "run" and have them basically work as expected.  So we need
   10887    a special create_inferior function.  We support changing the
   10888    executable file and the command line arguments, but not the
   10889    environment.  */
   10890 
   10891 void
   10892 extended_remote_target::create_inferior (const char *exec_file,
   10893 					 const std::string &args,
   10894 					 char **env, int from_tty)
   10895 {
   10896   int run_worked;
   10897   char *stop_reply;
   10898   struct remote_state *rs = get_remote_state ();
   10899   const char *remote_exec_file = get_remote_exec_file ();
   10900 
   10901   /* If running asynchronously, register the target file descriptor
   10902      with the event loop.  */
   10903   if (target_can_async_p ())
   10904     target_async (true);
   10905 
   10906   /* Disable address space randomization if requested (and supported).  */
   10907   if (supports_disable_randomization ())
   10908     extended_remote_disable_randomization (disable_randomization);
   10909 
   10910   /* If startup-with-shell is on, we inform gdbserver to start the
   10911      remote inferior using a shell.  */
   10912   if (m_features.packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
   10913     {
   10914       xsnprintf (rs->buf.data (), get_remote_packet_size (),
   10915 		 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
   10916       putpkt (rs->buf);
   10917       getpkt (&rs->buf);
   10918       if (strcmp (rs->buf.data (), "OK") != 0)
   10919 	error (_("\
   10920 Remote replied unexpectedly while setting startup-with-shell: %s"),
   10921 	       rs->buf.data ());
   10922     }
   10923 
   10924   extended_remote_environment_support ();
   10925 
   10926   extended_remote_set_inferior_cwd ();
   10927 
   10928   /* Now restart the remote server.  */
   10929   run_worked = extended_remote_run (args) != -1;
   10930   if (!run_worked)
   10931     {
   10932       /* vRun was not supported.  Fail if we need it to do what the
   10933 	 user requested.  */
   10934       if (remote_exec_file[0])
   10935 	error (_("Remote target does not support \"set remote exec-file\""));
   10936       if (!args.empty ())
   10937 	error (_("Remote target does not support \"set args\" or run ARGS"));
   10938 
   10939       /* Fall back to "R".  */
   10940       extended_remote_restart ();
   10941     }
   10942 
   10943   /* vRun's success return is a stop reply.  */
   10944   stop_reply = run_worked ? rs->buf.data () : NULL;
   10945   add_current_inferior_and_thread (stop_reply);
   10946 
   10947   /* Get updated offsets, if the stub uses qOffsets.  */
   10948   get_offsets ();
   10949 }
   10950 
   10951 
   10953 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
   10954    the list of conditions (in agent expression bytecode format), if any, the
   10955    target needs to evaluate.  The output is placed into the packet buffer
   10956    started from BUF and ended at BUF_END.  */
   10957 
   10958 static int
   10959 remote_add_target_side_condition (struct gdbarch *gdbarch,
   10960 				  struct bp_target_info *bp_tgt, char *buf,
   10961 				  char *buf_end)
   10962 {
   10963   if (bp_tgt->conditions.empty ())
   10964     return 0;
   10965 
   10966   buf += strlen (buf);
   10967   xsnprintf (buf, buf_end - buf, "%s", ";");
   10968   buf++;
   10969 
   10970   /* Send conditions to the target.  */
   10971   for (agent_expr *aexpr : bp_tgt->conditions)
   10972     {
   10973       xsnprintf (buf, buf_end - buf, "X%x,", (int) aexpr->buf.size ());
   10974       buf += strlen (buf);
   10975       for (int i = 0; i < aexpr->buf.size (); ++i)
   10976 	buf = pack_hex_byte (buf, aexpr->buf[i]);
   10977       *buf = '\0';
   10978     }
   10979   return 0;
   10980 }
   10981 
   10982 static void
   10983 remote_add_target_side_commands (struct gdbarch *gdbarch,
   10984 				 struct bp_target_info *bp_tgt, char *buf)
   10985 {
   10986   if (bp_tgt->tcommands.empty ())
   10987     return;
   10988 
   10989   buf += strlen (buf);
   10990 
   10991   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
   10992   buf += strlen (buf);
   10993 
   10994   /* Concatenate all the agent expressions that are commands into the
   10995      cmds parameter.  */
   10996   for (agent_expr *aexpr : bp_tgt->tcommands)
   10997     {
   10998       sprintf (buf, "X%x,", (int) aexpr->buf.size ());
   10999       buf += strlen (buf);
   11000       for (int i = 0; i < aexpr->buf.size (); ++i)
   11001 	buf = pack_hex_byte (buf, aexpr->buf[i]);
   11002       *buf = '\0';
   11003     }
   11004 }
   11005 
   11006 /* Insert a breakpoint.  On targets that have software breakpoint
   11007    support, we ask the remote target to do the work; on targets
   11008    which don't, we insert a traditional memory breakpoint.  */
   11009 
   11010 int
   11011 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
   11012 				  struct bp_target_info *bp_tgt)
   11013 {
   11014   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
   11015      If it succeeds, then set the support to PACKET_ENABLE.  If it
   11016      fails, and the user has explicitly requested the Z support then
   11017      report an error, otherwise, mark it disabled and go on.  */
   11018 
   11019   if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
   11020     {
   11021       CORE_ADDR addr = bp_tgt->reqstd_address;
   11022       struct remote_state *rs;
   11023       char *p, *endbuf;
   11024 
   11025       /* Make sure the remote is pointing at the right process, if
   11026 	 necessary.  */
   11027       if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
   11028 	set_general_process ();
   11029 
   11030       rs = get_remote_state ();
   11031       p = rs->buf.data ();
   11032       endbuf = p + get_remote_packet_size ();
   11033 
   11034       *(p++) = 'Z';
   11035       *(p++) = '0';
   11036       *(p++) = ',';
   11037       addr = (ULONGEST) remote_address_masked (addr);
   11038       p += hexnumstr (p, addr);
   11039       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
   11040 
   11041       if (supports_evaluation_of_breakpoint_conditions ())
   11042 	remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
   11043 
   11044       if (can_run_breakpoint_commands ())
   11045 	remote_add_target_side_commands (gdbarch, bp_tgt, p);
   11046 
   11047       putpkt (rs->buf);
   11048       getpkt (&rs->buf);
   11049 
   11050       switch ((m_features.packet_ok (rs->buf, PACKET_Z0)).status ())
   11051 	{
   11052 	case PACKET_ERROR:
   11053 	  return -1;
   11054 	case PACKET_OK:
   11055 	  return 0;
   11056 	case PACKET_UNKNOWN:
   11057 	  break;
   11058 	}
   11059     }
   11060 
   11061   /* If this breakpoint has target-side commands but this stub doesn't
   11062      support Z0 packets, throw error.  */
   11063   if (!bp_tgt->tcommands.empty ())
   11064     throw_error (NOT_SUPPORTED_ERROR, _("\
   11065 Target doesn't support breakpoints that have target side commands."));
   11066 
   11067   return memory_insert_breakpoint (this, gdbarch, bp_tgt);
   11068 }
   11069 
   11070 int
   11071 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
   11072 				  struct bp_target_info *bp_tgt,
   11073 				  enum remove_bp_reason reason)
   11074 {
   11075   CORE_ADDR addr = bp_tgt->placed_address;
   11076   struct remote_state *rs = get_remote_state ();
   11077 
   11078   if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
   11079     {
   11080       char *p = rs->buf.data ();
   11081       char *endbuf = p + get_remote_packet_size ();
   11082 
   11083       /* Make sure the remote is pointing at the right process, if
   11084 	 necessary.  */
   11085       if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
   11086 	set_general_process ();
   11087 
   11088       *(p++) = 'z';
   11089       *(p++) = '0';
   11090       *(p++) = ',';
   11091 
   11092       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
   11093       p += hexnumstr (p, addr);
   11094       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
   11095 
   11096       putpkt (rs->buf);
   11097       getpkt (&rs->buf);
   11098 
   11099       return (rs->buf[0] == 'E');
   11100     }
   11101 
   11102   return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
   11103 }
   11104 
   11105 static enum Z_packet_type
   11106 watchpoint_to_Z_packet (int type)
   11107 {
   11108   switch (type)
   11109     {
   11110     case hw_write:
   11111       return Z_PACKET_WRITE_WP;
   11112       break;
   11113     case hw_read:
   11114       return Z_PACKET_READ_WP;
   11115       break;
   11116     case hw_access:
   11117       return Z_PACKET_ACCESS_WP;
   11118       break;
   11119     default:
   11120       internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
   11121     }
   11122 }
   11123 
   11124 int
   11125 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
   11126 				  enum target_hw_bp_type type, struct expression *cond)
   11127 {
   11128   struct remote_state *rs = get_remote_state ();
   11129   char *endbuf = rs->buf.data () + get_remote_packet_size ();
   11130   char *p;
   11131   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
   11132 
   11133   if (m_features.packet_support ((to_underlying (PACKET_Z0)
   11134 				  + to_underlying (packet))) == PACKET_DISABLE)
   11135     return 1;
   11136 
   11137   /* Make sure the remote is pointing at the right process, if
   11138      necessary.  */
   11139   if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
   11140     set_general_process ();
   11141 
   11142   xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
   11143   p = strchr (rs->buf.data (), '\0');
   11144   addr = remote_address_masked (addr);
   11145   p += hexnumstr (p, (ULONGEST) addr);
   11146   xsnprintf (p, endbuf - p, ",%x", len);
   11147 
   11148   putpkt (rs->buf);
   11149   getpkt (&rs->buf);
   11150 
   11151   switch ((m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
   11152 					  + to_underlying (packet)))).status ())
   11153     {
   11154     case PACKET_ERROR:
   11155       return -1;
   11156     case PACKET_UNKNOWN:
   11157       return 1;
   11158     case PACKET_OK:
   11159       return 0;
   11160     }
   11161   internal_error (_("remote_insert_watchpoint: reached end of function"));
   11162 }
   11163 
   11164 bool
   11165 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
   11166 					     CORE_ADDR start, int length)
   11167 {
   11168   CORE_ADDR diff = remote_address_masked (addr - start);
   11169 
   11170   return diff < length;
   11171 }
   11172 
   11173 
   11174 int
   11175 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
   11176 				  enum target_hw_bp_type type, struct expression *cond)
   11177 {
   11178   struct remote_state *rs = get_remote_state ();
   11179   char *endbuf = rs->buf.data () + get_remote_packet_size ();
   11180   char *p;
   11181   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
   11182 
   11183   if (m_features.packet_support ((to_underlying (PACKET_Z0)
   11184 				  + to_underlying (packet))) == PACKET_DISABLE)
   11185     return -1;
   11186 
   11187   /* Make sure the remote is pointing at the right process, if
   11188      necessary.  */
   11189   if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
   11190     set_general_process ();
   11191 
   11192   xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
   11193   p = strchr (rs->buf.data (), '\0');
   11194   addr = remote_address_masked (addr);
   11195   p += hexnumstr (p, (ULONGEST) addr);
   11196   xsnprintf (p, endbuf - p, ",%x", len);
   11197   putpkt (rs->buf);
   11198   getpkt (&rs->buf);
   11199 
   11200   switch ((m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
   11201 					  + to_underlying (packet)))).status ())
   11202     {
   11203     case PACKET_ERROR:
   11204     case PACKET_UNKNOWN:
   11205       return -1;
   11206     case PACKET_OK:
   11207       return 0;
   11208     }
   11209   internal_error (_("remote_remove_watchpoint: reached end of function"));
   11210 }
   11211 
   11212 
   11213 static int remote_hw_watchpoint_limit = -1;
   11214 static int remote_hw_watchpoint_length_limit = -1;
   11215 static int remote_hw_breakpoint_limit = -1;
   11216 
   11217 int
   11218 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
   11219 {
   11220   if (remote_hw_watchpoint_length_limit == 0)
   11221     return 0;
   11222   else if (remote_hw_watchpoint_length_limit < 0)
   11223     return 1;
   11224   else if (len <= remote_hw_watchpoint_length_limit)
   11225     return 1;
   11226   else
   11227     return 0;
   11228 }
   11229 
   11230 int
   11231 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
   11232 {
   11233   if (type == bp_hardware_breakpoint)
   11234     {
   11235       if (remote_hw_breakpoint_limit == 0)
   11236 	return 0;
   11237       else if (remote_hw_breakpoint_limit < 0)
   11238 	return 1;
   11239       else if (cnt <= remote_hw_breakpoint_limit)
   11240 	return 1;
   11241     }
   11242   else
   11243     {
   11244       if (remote_hw_watchpoint_limit == 0)
   11245 	return 0;
   11246       else if (remote_hw_watchpoint_limit < 0)
   11247 	return 1;
   11248       else if (ot)
   11249 	return -1;
   11250       else if (cnt <= remote_hw_watchpoint_limit)
   11251 	return 1;
   11252     }
   11253   return -1;
   11254 }
   11255 
   11256 /* The to_stopped_by_sw_breakpoint method of target remote.  */
   11257 
   11258 bool
   11259 remote_target::stopped_by_sw_breakpoint ()
   11260 {
   11261   struct thread_info *thread = inferior_thread ();
   11262 
   11263   return (thread->priv != NULL
   11264 	  && (get_remote_thread_info (thread)->stop_reason
   11265 	      == TARGET_STOPPED_BY_SW_BREAKPOINT));
   11266 }
   11267 
   11268 /* The to_supports_stopped_by_sw_breakpoint method of target
   11269    remote.  */
   11270 
   11271 bool
   11272 remote_target::supports_stopped_by_sw_breakpoint ()
   11273 {
   11274   return (m_features.packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
   11275 }
   11276 
   11277 /* The to_stopped_by_hw_breakpoint method of target remote.  */
   11278 
   11279 bool
   11280 remote_target::stopped_by_hw_breakpoint ()
   11281 {
   11282   struct thread_info *thread = inferior_thread ();
   11283 
   11284   return (thread->priv != NULL
   11285 	  && (get_remote_thread_info (thread)->stop_reason
   11286 	      == TARGET_STOPPED_BY_HW_BREAKPOINT));
   11287 }
   11288 
   11289 /* The to_supports_stopped_by_hw_breakpoint method of target
   11290    remote.  */
   11291 
   11292 bool
   11293 remote_target::supports_stopped_by_hw_breakpoint ()
   11294 {
   11295   return (m_features.packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
   11296 }
   11297 
   11298 bool
   11299 remote_target::stopped_by_watchpoint ()
   11300 {
   11301   struct thread_info *thread = inferior_thread ();
   11302 
   11303   return (thread->priv != NULL
   11304 	  && (get_remote_thread_info (thread)->stop_reason
   11305 	      == TARGET_STOPPED_BY_WATCHPOINT));
   11306 }
   11307 
   11308 bool
   11309 remote_target::stopped_data_address (CORE_ADDR *addr_p)
   11310 {
   11311   struct thread_info *thread = inferior_thread ();
   11312 
   11313   if (thread->priv != NULL
   11314       && (get_remote_thread_info (thread)->stop_reason
   11315 	  == TARGET_STOPPED_BY_WATCHPOINT))
   11316     {
   11317       *addr_p = get_remote_thread_info (thread)->watch_data_address;
   11318       return true;
   11319     }
   11320 
   11321   return false;
   11322 }
   11323 
   11324 
   11325 int
   11326 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
   11327 				     struct bp_target_info *bp_tgt)
   11328 {
   11329   CORE_ADDR addr = bp_tgt->reqstd_address;
   11330   struct remote_state *rs;
   11331   char *p, *endbuf;
   11332 
   11333   if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
   11334     return -1;
   11335 
   11336   /* Make sure the remote is pointing at the right process, if
   11337      necessary.  */
   11338   if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
   11339     set_general_process ();
   11340 
   11341   rs = get_remote_state ();
   11342   p = rs->buf.data ();
   11343   endbuf = p + get_remote_packet_size ();
   11344 
   11345   *(p++) = 'Z';
   11346   *(p++) = '1';
   11347   *(p++) = ',';
   11348 
   11349   addr = remote_address_masked (addr);
   11350   p += hexnumstr (p, (ULONGEST) addr);
   11351   xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
   11352 
   11353   if (supports_evaluation_of_breakpoint_conditions ())
   11354     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
   11355 
   11356   if (can_run_breakpoint_commands ())
   11357     remote_add_target_side_commands (gdbarch, bp_tgt, p);
   11358 
   11359   putpkt (rs->buf);
   11360   getpkt (&rs->buf);
   11361 
   11362   packet_result result = m_features.packet_ok (rs->buf, PACKET_Z1);
   11363   switch (result.status ())
   11364     {
   11365     case PACKET_ERROR:
   11366       error (_("Remote failure reply: %s"), result.err_msg ());
   11367     case PACKET_UNKNOWN:
   11368       return -1;
   11369     case PACKET_OK:
   11370       return 0;
   11371     }
   11372   internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
   11373 }
   11374 
   11375 
   11376 int
   11377 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
   11378 				     struct bp_target_info *bp_tgt)
   11379 {
   11380   CORE_ADDR addr;
   11381   struct remote_state *rs = get_remote_state ();
   11382   char *p = rs->buf.data ();
   11383   char *endbuf = p + get_remote_packet_size ();
   11384 
   11385   if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
   11386     return -1;
   11387 
   11388   /* Make sure the remote is pointing at the right process, if
   11389      necessary.  */
   11390   if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
   11391     set_general_process ();
   11392 
   11393   *(p++) = 'z';
   11394   *(p++) = '1';
   11395   *(p++) = ',';
   11396 
   11397   addr = remote_address_masked (bp_tgt->placed_address);
   11398   p += hexnumstr (p, (ULONGEST) addr);
   11399   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->kind);
   11400 
   11401   putpkt (rs->buf);
   11402   getpkt (&rs->buf);
   11403 
   11404   switch ((m_features.packet_ok (rs->buf, PACKET_Z1)).status ())
   11405     {
   11406     case PACKET_ERROR:
   11407     case PACKET_UNKNOWN:
   11408       return -1;
   11409     case PACKET_OK:
   11410       return 0;
   11411     }
   11412   internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
   11413 }
   11414 
   11415 /* Verify memory using the "qCRC:" request.  */
   11416 
   11417 int
   11418 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
   11419 {
   11420   struct remote_state *rs = get_remote_state ();
   11421   unsigned long host_crc, target_crc;
   11422   char *tmp;
   11423 
   11424   /* It doesn't make sense to use qCRC if the remote target is
   11425      connected but not running.  */
   11426   if (target_has_execution ()
   11427       && m_features.packet_support (PACKET_qCRC) != PACKET_DISABLE)
   11428     {
   11429       enum packet_status status;
   11430 
   11431       /* Make sure the remote is pointing at the right process.  */
   11432       set_general_process ();
   11433 
   11434       /* FIXME: assumes lma can fit into long.  */
   11435       xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
   11436 		 (long) lma, (long) size);
   11437       putpkt (rs->buf);
   11438 
   11439       /* Be clever; compute the host_crc before waiting for target
   11440 	 reply.  */
   11441       host_crc = xcrc32 (data, size, 0xffffffff);
   11442 
   11443       getpkt (&rs->buf);
   11444 
   11445       status = (m_features.packet_ok (rs->buf, PACKET_qCRC)).status ();
   11446       if (status == PACKET_ERROR)
   11447 	return -1;
   11448       else if (status == PACKET_OK)
   11449 	{
   11450 	  for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
   11451 	    target_crc = target_crc * 16 + fromhex (*tmp);
   11452 
   11453 	  return (host_crc == target_crc);
   11454 	}
   11455     }
   11456 
   11457   return simple_verify_memory (this, data, lma, size);
   11458 }
   11459 
   11460 /* compare-sections command
   11461 
   11462    With no arguments, compares each loadable section in the exec bfd
   11463    with the same memory range on the target, and reports mismatches.
   11464    Useful for verifying the image on the target against the exec file.  */
   11465 
   11466 static void
   11467 compare_sections_command (const char *args, int from_tty)
   11468 {
   11469   asection *s;
   11470   const char *sectname;
   11471   bfd_size_type size;
   11472   bfd_vma lma;
   11473   int matched = 0;
   11474   int mismatched = 0;
   11475   int res;
   11476   int read_only = 0;
   11477 
   11478   if (!current_program_space->exec_bfd ())
   11479     error (_("command cannot be used without an exec file"));
   11480 
   11481   if (args != NULL && strcmp (args, "-r") == 0)
   11482     {
   11483       read_only = 1;
   11484       args = NULL;
   11485     }
   11486 
   11487   for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
   11488     {
   11489       if (!(s->flags & SEC_LOAD))
   11490 	continue;		/* Skip non-loadable section.  */
   11491 
   11492       if (read_only && (s->flags & SEC_READONLY) == 0)
   11493 	continue;		/* Skip writeable sections */
   11494 
   11495       size = bfd_section_size (s);
   11496       if (size == 0)
   11497 	continue;		/* Skip zero-length section.  */
   11498 
   11499       sectname = bfd_section_name (s);
   11500       if (args && strcmp (args, sectname) != 0)
   11501 	continue;		/* Not the section selected by user.  */
   11502 
   11503       matched = 1;		/* Do this section.  */
   11504       lma = s->lma;
   11505 
   11506       gdb::byte_vector sectdata (size);
   11507       bfd_get_section_contents (current_program_space->exec_bfd (), s,
   11508 				sectdata.data (), 0, size);
   11509 
   11510       res = target_verify_memory (sectdata.data (), lma, size);
   11511 
   11512       if (res == -1)
   11513 	error (_("target memory fault, section %s, range %s -- %s"), sectname,
   11514 	       paddress (current_inferior ()->arch (), lma),
   11515 	       paddress (current_inferior ()->arch (), lma + size));
   11516 
   11517       gdb_printf ("Section %s, range %s -- %s: ", sectname,
   11518 		  paddress (current_inferior ()->arch (), lma),
   11519 		  paddress (current_inferior ()->arch (), lma + size));
   11520       if (res)
   11521 	gdb_printf ("matched.\n");
   11522       else
   11523 	{
   11524 	  gdb_printf ("MIS-MATCHED!\n");
   11525 	  mismatched++;
   11526 	}
   11527     }
   11528   if (mismatched > 0)
   11529     warning (_("One or more sections of the target image does "
   11530 	       "not match the loaded file"));
   11531   if (args && !matched)
   11532     gdb_printf (_("No loaded section named '%s'.\n"), args);
   11533 }
   11534 
   11535 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
   11536    into remote target.  The number of bytes written to the remote
   11537    target is returned, or -1 for error.  */
   11538 
   11539 target_xfer_status
   11540 remote_target::remote_write_qxfer (const char *object_name,
   11541 				   const char *annex, const gdb_byte *writebuf,
   11542 				   ULONGEST offset, LONGEST len,
   11543 				   ULONGEST *xfered_len,
   11544 				   const unsigned int which_packet)
   11545 {
   11546   int i, buf_len;
   11547   ULONGEST n;
   11548   struct remote_state *rs = get_remote_state ();
   11549   int max_size = get_memory_write_packet_size ();
   11550 
   11551   if (m_features.packet_support (which_packet) == PACKET_DISABLE)
   11552     return TARGET_XFER_E_IO;
   11553 
   11554   /* Insert header.  */
   11555   i = snprintf (rs->buf.data (), max_size,
   11556 		"qXfer:%s:write:%s:%s:",
   11557 		object_name, annex ? annex : "",
   11558 		phex_nz (offset, sizeof offset));
   11559   max_size -= (i + 1);
   11560 
   11561   /* Escape as much data as fits into rs->buf.  */
   11562   buf_len = remote_escape_output
   11563     (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
   11564 
   11565   if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
   11566       || getpkt (&rs->buf) < 0
   11567       || (m_features.packet_ok (rs->buf, which_packet)).status () != PACKET_OK)
   11568     return TARGET_XFER_E_IO;
   11569 
   11570   unpack_varlen_hex (rs->buf.data (), &n);
   11571 
   11572   *xfered_len = n;
   11573   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
   11574 }
   11575 
   11576 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
   11577    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
   11578    number of bytes read is returned, or 0 for EOF, or -1 for error.
   11579    The number of bytes read may be less than LEN without indicating an
   11580    EOF.  PACKET is checked and updated to indicate whether the remote
   11581    target supports this object.  */
   11582 
   11583 target_xfer_status
   11584 remote_target::remote_read_qxfer (const char *object_name,
   11585 				  const char *annex,
   11586 				  gdb_byte *readbuf, ULONGEST offset,
   11587 				  LONGEST len,
   11588 				  ULONGEST *xfered_len,
   11589 				  const unsigned int which_packet)
   11590 {
   11591   struct remote_state *rs = get_remote_state ();
   11592   LONGEST i, n, packet_len;
   11593 
   11594   if (m_features.packet_support (which_packet) == PACKET_DISABLE)
   11595     return TARGET_XFER_E_IO;
   11596 
   11597   /* Check whether we've cached an end-of-object packet that matches
   11598      this request.  */
   11599   if (rs->finished_object)
   11600     {
   11601       if (strcmp (object_name, rs->finished_object) == 0
   11602 	  && strcmp (annex ? annex : "", rs->finished_annex) == 0
   11603 	  && offset == rs->finished_offset)
   11604 	return TARGET_XFER_EOF;
   11605 
   11606 
   11607       /* Otherwise, we're now reading something different.  Discard
   11608 	 the cache.  */
   11609       xfree (rs->finished_object);
   11610       xfree (rs->finished_annex);
   11611       rs->finished_object = NULL;
   11612       rs->finished_annex = NULL;
   11613     }
   11614 
   11615   /* Request only enough to fit in a single packet.  The actual data
   11616      may not, since we don't know how much of it will need to be escaped;
   11617      the target is free to respond with slightly less data.  We subtract
   11618      five to account for the response type and the protocol frame.  */
   11619   n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
   11620   snprintf (rs->buf.data (), get_remote_packet_size () - 4,
   11621 	    "qXfer:%s:read:%s:%s,%s",
   11622 	    object_name, annex ? annex : "",
   11623 	    phex_nz (offset, sizeof offset),
   11624 	    phex_nz (n, sizeof n));
   11625   i = putpkt (rs->buf);
   11626   if (i < 0)
   11627     return TARGET_XFER_E_IO;
   11628 
   11629   rs->buf[0] = '\0';
   11630   packet_len = getpkt (&rs->buf);
   11631   if (packet_len < 0
   11632       || m_features.packet_ok (rs->buf, which_packet).status () != PACKET_OK)
   11633     return TARGET_XFER_E_IO;
   11634 
   11635   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
   11636     error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
   11637 
   11638   /* 'm' means there is (or at least might be) more data after this
   11639      batch.  That does not make sense unless there's at least one byte
   11640      of data in this reply.  */
   11641   if (rs->buf[0] == 'm' && packet_len == 1)
   11642     error (_("Remote qXfer reply contained no data."));
   11643 
   11644   /* Got some data.  */
   11645   i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
   11646 			     packet_len - 1, readbuf, n);
   11647 
   11648   /* 'l' is an EOF marker, possibly including a final block of data,
   11649      or possibly empty.  If we have the final block of a non-empty
   11650      object, record this fact to bypass a subsequent partial read.  */
   11651   if (rs->buf[0] == 'l' && offset + i > 0)
   11652     {
   11653       rs->finished_object = xstrdup (object_name);
   11654       rs->finished_annex = xstrdup (annex ? annex : "");
   11655       rs->finished_offset = offset + i;
   11656     }
   11657 
   11658   if (i == 0)
   11659     return TARGET_XFER_EOF;
   11660   else
   11661     {
   11662       *xfered_len = i;
   11663       return TARGET_XFER_OK;
   11664     }
   11665 }
   11666 
   11667 enum target_xfer_status
   11668 remote_target::xfer_partial (enum target_object object,
   11669 			     const char *annex, gdb_byte *readbuf,
   11670 			     const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
   11671 			     ULONGEST *xfered_len)
   11672 {
   11673   struct remote_state *rs;
   11674   int i;
   11675   char *p2;
   11676   char query_type;
   11677   int unit_size
   11678     = gdbarch_addressable_memory_unit_size (current_inferior ()->arch ());
   11679 
   11680   set_remote_traceframe ();
   11681   set_general_thread (inferior_ptid);
   11682 
   11683   rs = get_remote_state ();
   11684 
   11685   /* Handle memory using the standard memory routines.  */
   11686   if (object == TARGET_OBJECT_MEMORY)
   11687     {
   11688       /* If the remote target is connected but not running, we should
   11689 	 pass this request down to a lower stratum (e.g. the executable
   11690 	 file).  */
   11691       if (!target_has_execution ())
   11692 	return TARGET_XFER_EOF;
   11693 
   11694       if (writebuf != NULL)
   11695 	return remote_write_bytes (offset, writebuf, len, unit_size,
   11696 				   xfered_len);
   11697       else
   11698 	return remote_read_bytes (offset, readbuf, len, unit_size,
   11699 				  xfered_len);
   11700     }
   11701 
   11702   /* Handle extra signal info using qxfer packets.  */
   11703   if (object == TARGET_OBJECT_SIGNAL_INFO)
   11704     {
   11705       if (readbuf)
   11706 	return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
   11707 				  xfered_len, PACKET_qXfer_siginfo_read);
   11708       else
   11709 	return remote_write_qxfer ("siginfo", annex, writebuf, offset, len,
   11710 				   xfered_len, PACKET_qXfer_siginfo_write);
   11711     }
   11712 
   11713   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
   11714     {
   11715       if (readbuf)
   11716 	return remote_read_qxfer ("statictrace", annex,
   11717 				  readbuf, offset, len, xfered_len,
   11718 				  PACKET_qXfer_statictrace_read);
   11719       else
   11720 	return TARGET_XFER_E_IO;
   11721     }
   11722 
   11723   /* Only handle flash writes.  */
   11724   if (writebuf != NULL)
   11725     {
   11726       switch (object)
   11727 	{
   11728 	case TARGET_OBJECT_FLASH:
   11729 	  return remote_flash_write (offset, len, xfered_len,
   11730 				     writebuf);
   11731 
   11732 	default:
   11733 	  return TARGET_XFER_E_IO;
   11734 	}
   11735     }
   11736 
   11737   /* Map pre-existing objects onto letters.  DO NOT do this for new
   11738      objects!!!  Instead specify new query packets.  */
   11739   switch (object)
   11740     {
   11741     case TARGET_OBJECT_AVR:
   11742       query_type = 'R';
   11743       break;
   11744 
   11745     case TARGET_OBJECT_AUXV:
   11746       gdb_assert (annex == NULL);
   11747       return remote_read_qxfer
   11748 	("auxv", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_auxv);
   11749 
   11750     case TARGET_OBJECT_AVAILABLE_FEATURES:
   11751       return remote_read_qxfer
   11752 	("features", annex, readbuf, offset, len, xfered_len,
   11753 	 PACKET_qXfer_features);
   11754 
   11755     case TARGET_OBJECT_LIBRARIES:
   11756       return remote_read_qxfer
   11757 	("libraries", annex, readbuf, offset, len, xfered_len,
   11758 	 PACKET_qXfer_libraries);
   11759 
   11760     case TARGET_OBJECT_LIBRARIES_SVR4:
   11761       return remote_read_qxfer
   11762 	("libraries-svr4", annex, readbuf, offset, len, xfered_len,
   11763 	 PACKET_qXfer_libraries_svr4);
   11764 
   11765     case TARGET_OBJECT_MEMORY_MAP:
   11766       gdb_assert (annex == NULL);
   11767       return remote_read_qxfer
   11768 	("memory-map", annex, readbuf, offset, len, xfered_len,
   11769 	 PACKET_qXfer_memory_map);
   11770 
   11771     case TARGET_OBJECT_OSDATA:
   11772       /* Should only get here if we're connected.  */
   11773       gdb_assert (rs->remote_desc);
   11774       return remote_read_qxfer
   11775 	("osdata", annex, readbuf, offset, len, xfered_len,
   11776 	 PACKET_qXfer_osdata);
   11777 
   11778     case TARGET_OBJECT_THREADS:
   11779       gdb_assert (annex == NULL);
   11780       return remote_read_qxfer
   11781 	("threads", annex, readbuf, offset, len, xfered_len,
   11782 	 PACKET_qXfer_threads);
   11783 
   11784     case TARGET_OBJECT_TRACEFRAME_INFO:
   11785       gdb_assert (annex == NULL);
   11786       return remote_read_qxfer
   11787 	("traceframe-info", annex, readbuf, offset, len, xfered_len,
   11788 	 PACKET_qXfer_traceframe_info);
   11789 
   11790     case TARGET_OBJECT_FDPIC:
   11791       return remote_read_qxfer
   11792 	("fdpic", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_fdpic);
   11793 
   11794     case TARGET_OBJECT_OPENVMS_UIB:
   11795       return remote_read_qxfer
   11796 	("uib", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_uib);
   11797 
   11798     case TARGET_OBJECT_BTRACE:
   11799       return remote_read_qxfer
   11800 	("btrace", annex, readbuf, offset, len, xfered_len,
   11801 	 PACKET_qXfer_btrace);
   11802 
   11803     case TARGET_OBJECT_BTRACE_CONF:
   11804       return remote_read_qxfer
   11805 	("btrace-conf", annex, readbuf, offset, len, xfered_len,
   11806 	 PACKET_qXfer_btrace_conf);
   11807 
   11808     case TARGET_OBJECT_EXEC_FILE:
   11809       return remote_read_qxfer
   11810 	("exec-file", annex, readbuf, offset, len, xfered_len,
   11811 	 PACKET_qXfer_exec_file);
   11812 
   11813     default:
   11814       return TARGET_XFER_E_IO;
   11815     }
   11816 
   11817   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
   11818      large enough let the caller deal with it.  */
   11819   if (len < get_remote_packet_size ())
   11820     return TARGET_XFER_E_IO;
   11821   len = get_remote_packet_size ();
   11822 
   11823   /* Except for querying the minimum buffer size, target must be open.  */
   11824   if (!rs->remote_desc)
   11825     error (_("remote query is only available after target open"));
   11826 
   11827   gdb_assert (annex != NULL);
   11828   gdb_assert (readbuf != NULL);
   11829 
   11830   p2 = rs->buf.data ();
   11831   *p2++ = 'q';
   11832   *p2++ = query_type;
   11833 
   11834   /* We used one buffer char for the remote protocol q command and
   11835      another for the query type.  As the remote protocol encapsulation
   11836      uses 4 chars plus one extra in case we are debugging
   11837      (remote_debug), we have PBUFZIZ - 7 left to pack the query
   11838      string.  */
   11839   i = 0;
   11840   while (annex[i] && (i < (get_remote_packet_size () - 8)))
   11841     {
   11842       /* Bad caller may have sent forbidden characters.  */
   11843       gdb_assert (isprint ((unsigned char)annex[i]) && annex[i] != '$' && annex[i] != '#');
   11844       *p2++ = annex[i];
   11845       i++;
   11846     }
   11847   *p2 = '\0';
   11848   gdb_assert (annex[i] == '\0');
   11849 
   11850   i = putpkt (rs->buf);
   11851   if (i < 0)
   11852     return TARGET_XFER_E_IO;
   11853 
   11854   getpkt (&rs->buf);
   11855   strcpy ((char *) readbuf, rs->buf.data ());
   11856 
   11857   *xfered_len = strlen ((char *) readbuf);
   11858   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
   11859 }
   11860 
   11861 /* Implementation of to_get_memory_xfer_limit.  */
   11862 
   11863 ULONGEST
   11864 remote_target::get_memory_xfer_limit ()
   11865 {
   11866   return get_memory_write_packet_size ();
   11867 }
   11868 
   11869 int
   11870 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
   11871 			      const gdb_byte *pattern, ULONGEST pattern_len,
   11872 			      CORE_ADDR *found_addrp)
   11873 {
   11874   int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
   11875   struct remote_state *rs = get_remote_state ();
   11876   int max_size = get_memory_write_packet_size ();
   11877 
   11878   /* Number of packet bytes used to encode the pattern;
   11879      this could be more than PATTERN_LEN due to escape characters.  */
   11880   int escaped_pattern_len;
   11881   /* Amount of pattern that was encodable in the packet.  */
   11882   int used_pattern_len;
   11883   int i;
   11884   int found;
   11885   ULONGEST found_addr;
   11886 
   11887   auto read_memory = [this] (CORE_ADDR addr, gdb_byte *result, size_t len)
   11888     {
   11889       return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
   11890 	      == len);
   11891     };
   11892 
   11893   /* Don't go to the target if we don't have to.  This is done before
   11894      checking packet_support to avoid the possibility that a success for this
   11895      edge case means the facility works in general.  */
   11896   if (pattern_len > search_space_len)
   11897     return 0;
   11898   if (pattern_len == 0)
   11899     {
   11900       *found_addrp = start_addr;
   11901       return 1;
   11902     }
   11903 
   11904   /* If we already know the packet isn't supported, fall back to the simple
   11905      way of searching memory.  */
   11906 
   11907   if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
   11908     {
   11909       /* Target doesn't provided special support, fall back and use the
   11910 	 standard support (copy memory and do the search here).  */
   11911       return simple_search_memory (read_memory, start_addr, search_space_len,
   11912 				   pattern, pattern_len, found_addrp);
   11913     }
   11914 
   11915   /* Make sure the remote is pointing at the right process.  */
   11916   set_general_process ();
   11917 
   11918   /* Insert header.  */
   11919   i = snprintf (rs->buf.data (), max_size,
   11920 		"qSearch:memory:%s;%s;",
   11921 		phex_nz (start_addr, addr_size),
   11922 		phex_nz (search_space_len, sizeof (search_space_len)));
   11923   max_size -= (i + 1);
   11924 
   11925   /* Escape as much data as fits into rs->buf.  */
   11926   escaped_pattern_len =
   11927     remote_escape_output (pattern, pattern_len, 1,
   11928 			  (gdb_byte *) rs->buf.data () + i,
   11929 			  &used_pattern_len, max_size);
   11930 
   11931   /* Bail if the pattern is too large.  */
   11932   if (used_pattern_len != pattern_len)
   11933     error (_("Pattern is too large to transmit to remote target."));
   11934 
   11935   if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
   11936       || getpkt (&rs->buf) < 0
   11937       || m_features.packet_ok (rs->buf, PACKET_qSearch_memory).status ()
   11938       != PACKET_OK)
   11939     {
   11940       /* The request may not have worked because the command is not
   11941 	 supported.  If so, fall back to the simple way.  */
   11942       if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
   11943 	{
   11944 	  return simple_search_memory (read_memory, start_addr, search_space_len,
   11945 				       pattern, pattern_len, found_addrp);
   11946 	}
   11947       return -1;
   11948     }
   11949 
   11950   if (rs->buf[0] == '0')
   11951     found = 0;
   11952   else if (rs->buf[0] == '1')
   11953     {
   11954       found = 1;
   11955       if (rs->buf[1] != ',')
   11956 	error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
   11957       unpack_varlen_hex (&rs->buf[2], &found_addr);
   11958       *found_addrp = found_addr;
   11959     }
   11960   else
   11961     error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
   11962 
   11963   return found;
   11964 }
   11965 
   11966 void
   11967 remote_target::rcmd (const char *command, struct ui_file *outbuf)
   11968 {
   11969   struct remote_state *rs = get_remote_state ();
   11970   char *p = rs->buf.data ();
   11971 
   11972   if (!rs->remote_desc)
   11973     error (_("remote rcmd is only available after target open"));
   11974 
   11975   /* Send a NULL command across as an empty command.  */
   11976   if (command == NULL)
   11977     command = "";
   11978 
   11979   /* The query prefix.  */
   11980   strcpy (rs->buf.data (), "qRcmd,");
   11981   p = strchr (rs->buf.data (), '\0');
   11982 
   11983   if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
   11984       > get_remote_packet_size ())
   11985     error (_("\"monitor\" command ``%s'' is too long."), command);
   11986 
   11987   /* Encode the actual command.  */
   11988   bin2hex ((const gdb_byte *) command, p, strlen (command));
   11989 
   11990   if (putpkt (rs->buf) < 0)
   11991     error (_("Communication problem with target."));
   11992 
   11993   /* get/display the response */
   11994   while (1)
   11995     {
   11996       char *buf;
   11997 
   11998       /* XXX - see also remote_get_noisy_reply().  */
   11999       QUIT;			/* Allow user to bail out with ^C.  */
   12000       rs->buf[0] = '\0';
   12001       if (getpkt (&rs->buf) == -1)
   12002 	{
   12003 	  /* Timeout.  Continue to (try to) read responses.
   12004 	     This is better than stopping with an error, assuming the stub
   12005 	     is still executing the (long) monitor command.
   12006 	     If needed, the user can interrupt gdb using C-c, obtaining
   12007 	     an effect similar to stop on timeout.  */
   12008 	  continue;
   12009 	}
   12010       buf = rs->buf.data ();
   12011       if (buf[0] == 'O' && buf[1] != 'K')
   12012 	{
   12013 	  /* 'O' message from stub.  */
   12014 	  remote_console_output (buf + 1, outbuf);
   12015 	  continue;
   12016 	}
   12017       packet_result result = packet_check_result (buf, false);
   12018       switch (result.status ())
   12019 	{
   12020 	case PACKET_UNKNOWN:
   12021 	  error (_("Target does not support this command."));
   12022 	case PACKET_ERROR:
   12023 	  error (_("Protocol error with Rcmd: %s."), result.err_msg ());
   12024 	case PACKET_OK:
   12025 	  break;
   12026 	}
   12027 
   12028       if (strcmp (buf, "OK") != 0)
   12029 	{
   12030 	  for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
   12031 	    {
   12032 	      char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
   12033 	      gdb_putc (c, outbuf);
   12034 	    }
   12035 	}
   12036       break;
   12037     }
   12038 }
   12039 
   12040 std::vector<mem_region>
   12041 remote_target::memory_map ()
   12042 {
   12043   std::vector<mem_region> result;
   12044   std::optional<gdb::char_vector> text
   12045     = target_read_stralloc (current_inferior ()->top_target (),
   12046 			    TARGET_OBJECT_MEMORY_MAP, NULL);
   12047 
   12048   if (text)
   12049     result = parse_memory_map (text->data ());
   12050 
   12051   return result;
   12052 }
   12053 
   12054 /* Set of callbacks used to implement the 'maint packet' command.  */
   12055 
   12056 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
   12057 {
   12058   /* Called before the packet is sent.  BUF is the packet content before
   12059      the protocol specific prefix, suffix, and escaping is added.  */
   12060 
   12061   void sending (gdb::array_view<const char> &buf) override
   12062   {
   12063     gdb_puts ("sending: ");
   12064     print_packet (buf);
   12065     gdb_puts ("\n");
   12066   }
   12067 
   12068   /* Called with BUF, the reply from the remote target.  */
   12069 
   12070   void received (gdb::array_view<const char> &buf) override
   12071   {
   12072     gdb_puts ("received: \"");
   12073     print_packet (buf);
   12074     gdb_puts ("\"\n");
   12075   }
   12076 
   12077 private:
   12078 
   12079   /* Print BUF o gdb_stdout.  Any non-printable bytes in BUF are printed as
   12080      '\x??' with '??' replaced by the hexadecimal value of the byte.  */
   12081 
   12082   static void
   12083   print_packet (gdb::array_view<const char> &buf)
   12084   {
   12085     string_file stb;
   12086 
   12087     for (int i = 0; i < buf.size (); ++i)
   12088       {
   12089 	gdb_byte c = buf[i];
   12090 	if (isprint ((unsigned char)c))
   12091 	  gdb_putc (c, &stb);
   12092 	else
   12093 	  gdb_printf (&stb, "\\x%02x", (unsigned char) c);
   12094       }
   12095 
   12096     gdb_puts (stb.string ().c_str ());
   12097   }
   12098 };
   12099 
   12100 /* See remote.h.  */
   12101 
   12102 void
   12103 send_remote_packet (gdb::array_view<const char> &buf,
   12104 		    send_remote_packet_callbacks *callbacks)
   12105 {
   12106   if (buf.size () == 0 || buf.data ()[0] == '\0')
   12107     error (_("a remote packet must not be empty"));
   12108 
   12109   remote_target *remote = get_current_remote_target ();
   12110   if (remote == nullptr)
   12111     error (_("packets can only be sent to a remote target"));
   12112 
   12113   callbacks->sending (buf);
   12114 
   12115   remote->putpkt_binary (buf.data (), buf.size ());
   12116   remote_state *rs = remote->get_remote_state ();
   12117   int bytes = remote->getpkt (&rs->buf);
   12118 
   12119   if (bytes < 0)
   12120     error (_("error while fetching packet from remote target"));
   12121 
   12122   gdb::array_view<const char> view (&rs->buf[0], bytes);
   12123   callbacks->received (view);
   12124 }
   12125 
   12126 /* Entry point for the 'maint packet' command.  */
   12127 
   12128 static void
   12129 cli_packet_command (const char *args, int from_tty)
   12130 {
   12131   cli_packet_command_callbacks cb;
   12132   gdb::array_view<const char> view
   12133     = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
   12134   send_remote_packet (view, &cb);
   12135 }
   12136 
   12137 #if 0
   12138 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
   12139 
   12140 static void display_thread_info (struct gdb_ext_thread_info *info);
   12141 
   12142 static void threadset_test_cmd (char *cmd, int tty);
   12143 
   12144 static void threadalive_test (char *cmd, int tty);
   12145 
   12146 static void threadlist_test_cmd (char *cmd, int tty);
   12147 
   12148 int get_and_display_threadinfo (threadref *ref);
   12149 
   12150 static void threadinfo_test_cmd (char *cmd, int tty);
   12151 
   12152 static int thread_display_step (threadref *ref, void *context);
   12153 
   12154 static void threadlist_update_test_cmd (char *cmd, int tty);
   12155 
   12156 static void init_remote_threadtests (void);
   12157 
   12158 #define SAMPLE_THREAD  0x05060708	/* Truncated 64 bit threadid.  */
   12159 
   12160 static void
   12161 threadset_test_cmd (const char *cmd, int tty)
   12162 {
   12163   int sample_thread = SAMPLE_THREAD;
   12164 
   12165   gdb_printf (_("Remote threadset test\n"));
   12166   set_general_thread (sample_thread);
   12167 }
   12168 
   12169 
   12170 static void
   12171 threadalive_test (const char *cmd, int tty)
   12172 {
   12173   int sample_thread = SAMPLE_THREAD;
   12174   int pid = inferior_ptid.pid ();
   12175   ptid_t ptid = ptid_t (pid, sample_thread, 0);
   12176 
   12177   if (remote_thread_alive (ptid))
   12178     gdb_printf ("PASS: Thread alive test\n");
   12179   else
   12180     gdb_printf ("FAIL: Thread alive test\n");
   12181 }
   12182 
   12183 void output_threadid (char *title, threadref *ref);
   12184 
   12185 void
   12186 output_threadid (char *title, threadref *ref)
   12187 {
   12188   char hexid[20];
   12189 
   12190   pack_threadid (&hexid[0], ref);	/* Convert thread id into hex.  */
   12191   hexid[16] = 0;
   12192   gdb_printf ("%s  %s\n", title, (&hexid[0]));
   12193 }
   12194 
   12195 static void
   12196 threadlist_test_cmd (const char *cmd, int tty)
   12197 {
   12198   int startflag = 1;
   12199   threadref nextthread;
   12200   int done, result_count;
   12201   threadref threadlist[3];
   12202 
   12203   gdb_printf ("Remote Threadlist test\n");
   12204   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
   12205 			      &result_count, &threadlist[0]))
   12206     gdb_printf ("FAIL: threadlist test\n");
   12207   else
   12208     {
   12209       threadref *scan = threadlist;
   12210       threadref *limit = scan + result_count;
   12211 
   12212       while (scan < limit)
   12213 	output_threadid (" thread ", scan++);
   12214     }
   12215 }
   12216 
   12217 void
   12218 display_thread_info (struct gdb_ext_thread_info *info)
   12219 {
   12220   output_threadid ("Threadid: ", &info->threadid);
   12221   gdb_printf ("Name: %s\n ", info->shortname);
   12222   gdb_printf ("State: %s\n", info->display);
   12223   gdb_printf ("other: %s\n\n", info->more_display);
   12224 }
   12225 
   12226 int
   12227 get_and_display_threadinfo (threadref *ref)
   12228 {
   12229   int result;
   12230   int set;
   12231   struct gdb_ext_thread_info threadinfo;
   12232 
   12233   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
   12234     | TAG_MOREDISPLAY | TAG_DISPLAY;
   12235   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
   12236     display_thread_info (&threadinfo);
   12237   return result;
   12238 }
   12239 
   12240 static void
   12241 threadinfo_test_cmd (const char *cmd, int tty)
   12242 {
   12243   int athread = SAMPLE_THREAD;
   12244   threadref thread;
   12245   int set;
   12246 
   12247   int_to_threadref (&thread, athread);
   12248   gdb_printf ("Remote Threadinfo test\n");
   12249   if (!get_and_display_threadinfo (&thread))
   12250     gdb_printf ("FAIL cannot get thread info\n");
   12251 }
   12252 
   12253 static int
   12254 thread_display_step (threadref *ref, void *context)
   12255 {
   12256   /* output_threadid(" threadstep ",ref); *//* simple test */
   12257   return get_and_display_threadinfo (ref);
   12258 }
   12259 
   12260 static void
   12261 threadlist_update_test_cmd (const char *cmd, int tty)
   12262 {
   12263   gdb_printf ("Remote Threadlist update test\n");
   12264   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
   12265 }
   12266 
   12267 static void
   12268 init_remote_threadtests (void)
   12269 {
   12270   add_com ("tlist", class_obscure, threadlist_test_cmd,
   12271 	   _("Fetch and print the remote list of "
   12272 	     "thread identifiers, one pkt only."));
   12273   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
   12274 	   _("Fetch and display info about one thread."));
   12275   add_com ("tset", class_obscure, threadset_test_cmd,
   12276 	   _("Test setting to a different thread."));
   12277   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
   12278 	   _("Iterate through updating all remote thread info."));
   12279   add_com ("talive", class_obscure, threadalive_test,
   12280 	   _("Remote thread alive test."));
   12281 }
   12282 
   12283 #endif /* 0 */
   12284 
   12285 /* Convert a thread ID to a string.  */
   12286 
   12287 std::string
   12288 remote_target::pid_to_str (ptid_t ptid)
   12289 {
   12290   if (ptid == null_ptid)
   12291     return normal_pid_to_str (ptid);
   12292   else if (ptid.is_pid ())
   12293     {
   12294       /* Printing an inferior target id.  */
   12295 
   12296       /* When multi-process extensions are off, there's no way in the
   12297 	 remote protocol to know the remote process id, if there's any
   12298 	 at all.  There's one exception --- when we're connected with
   12299 	 target extended-remote, and we manually attached to a process
   12300 	 with "attach PID".  We don't record anywhere a flag that
   12301 	 allows us to distinguish that case from the case of
   12302 	 connecting with extended-remote and the stub already being
   12303 	 attached to a process, and reporting yes to qAttached, hence
   12304 	 no smart special casing here.  */
   12305       if (!m_features.remote_multi_process_p ())
   12306 	return "Remote target";
   12307 
   12308       return normal_pid_to_str (ptid);
   12309     }
   12310   else
   12311     {
   12312       if (magic_null_ptid == ptid)
   12313 	return "Thread <main>";
   12314       else if (m_features.remote_multi_process_p ())
   12315 	if (ptid.lwp () == 0)
   12316 	  return normal_pid_to_str (ptid);
   12317 	else
   12318 	  return string_printf ("Thread %d.%ld",
   12319 				ptid.pid (), ptid.lwp ());
   12320       else
   12321 	return string_printf ("Thread %ld", ptid.lwp ());
   12322     }
   12323 }
   12324 
   12325 /* Get the address of the thread local variable in OBJFILE which is
   12326    stored at OFFSET within the thread local storage for thread PTID.  */
   12327 
   12328 CORE_ADDR
   12329 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
   12330 					 CORE_ADDR offset)
   12331 {
   12332   if (m_features.packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
   12333     {
   12334       struct remote_state *rs = get_remote_state ();
   12335       char *p = rs->buf.data ();
   12336       char *endp = p + get_remote_packet_size ();
   12337 
   12338       strcpy (p, "qGetTLSAddr:");
   12339       p += strlen (p);
   12340       p = write_ptid (p, endp, ptid);
   12341       *p++ = ',';
   12342       p += hexnumstr (p, offset);
   12343       *p++ = ',';
   12344       p += hexnumstr (p, lm);
   12345       *p++ = '\0';
   12346 
   12347       putpkt (rs->buf);
   12348       getpkt (&rs->buf);
   12349       packet_result result = m_features.packet_ok (rs->buf, PACKET_qGetTLSAddr);
   12350       if (result.status () == PACKET_OK)
   12351 	{
   12352 	  ULONGEST addr;
   12353 
   12354 	  unpack_varlen_hex (rs->buf.data (), &addr);
   12355 	  return addr;
   12356 	}
   12357       else if (result.status () == PACKET_UNKNOWN)
   12358 	throw_error (TLS_GENERIC_ERROR,
   12359 		     _("Remote target doesn't support qGetTLSAddr packet"));
   12360       else
   12361 	throw_error (TLS_GENERIC_ERROR,
   12362 		     _("Remote target failed to process qGetTLSAddr request"));
   12363     }
   12364   else
   12365     throw_error (TLS_GENERIC_ERROR,
   12366 		 _("TLS not supported or disabled on this target"));
   12367   /* Not reached.  */
   12368   return 0;
   12369 }
   12370 
   12371 /* Provide thread local base, i.e. Thread Information Block address.
   12372    Returns 1 if ptid is found and thread_local_base is non zero.  */
   12373 
   12374 bool
   12375 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
   12376 {
   12377   if (m_features.packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
   12378     {
   12379       struct remote_state *rs = get_remote_state ();
   12380       char *p = rs->buf.data ();
   12381       char *endp = p + get_remote_packet_size ();
   12382 
   12383       strcpy (p, "qGetTIBAddr:");
   12384       p += strlen (p);
   12385       p = write_ptid (p, endp, ptid);
   12386       *p++ = '\0';
   12387 
   12388       putpkt (rs->buf);
   12389       getpkt (&rs->buf);
   12390       packet_result result = m_features.packet_ok (rs->buf, PACKET_qGetTIBAddr);
   12391       if (result.status () == PACKET_OK)
   12392 	{
   12393 	  ULONGEST val;
   12394 	  unpack_varlen_hex (rs->buf.data (), &val);
   12395 	  if (addr)
   12396 	    *addr = (CORE_ADDR) val;
   12397 	  return true;
   12398 	}
   12399       else if (result.status () == PACKET_UNKNOWN)
   12400 	error (_("Remote target doesn't support qGetTIBAddr packet"));
   12401       else
   12402 	error (_("Remote target failed to process qGetTIBAddr request, %s"),
   12403 		 result.err_msg ());
   12404     }
   12405   else
   12406     error (_("qGetTIBAddr not supported or disabled on this target"));
   12407   /* Not reached.  */
   12408   return false;
   12409 }
   12410 
   12411 /* Support for inferring a target description based on the current
   12412    architecture and the size of a 'g' packet.  While the 'g' packet
   12413    can have any size (since optional registers can be left off the
   12414    end), some sizes are easily recognizable given knowledge of the
   12415    approximate architecture.  */
   12416 
   12417 struct remote_g_packet_guess
   12418 {
   12419   remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
   12420     : bytes (bytes_),
   12421       tdesc (tdesc_)
   12422   {
   12423   }
   12424 
   12425   int bytes;
   12426   const struct target_desc *tdesc;
   12427 };
   12428 
   12429 struct remote_g_packet_data
   12430 {
   12431   std::vector<remote_g_packet_guess> guesses;
   12432 };
   12433 
   12434 static const registry<gdbarch>::key<struct remote_g_packet_data>
   12435      remote_g_packet_data_handle;
   12436 
   12437 static struct remote_g_packet_data *
   12438 get_g_packet_data (struct gdbarch *gdbarch)
   12439 {
   12440   struct remote_g_packet_data *data
   12441     = remote_g_packet_data_handle.get (gdbarch);
   12442   if (data == nullptr)
   12443     data = remote_g_packet_data_handle.emplace (gdbarch);
   12444   return data;
   12445 }
   12446 
   12447 void
   12448 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
   12449 				const struct target_desc *tdesc)
   12450 {
   12451   struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
   12452 
   12453   gdb_assert (tdesc != NULL);
   12454 
   12455   for (const remote_g_packet_guess &guess : data->guesses)
   12456     if (guess.bytes == bytes)
   12457       internal_error (_("Duplicate g packet description added for size %d"),
   12458 		      bytes);
   12459 
   12460   data->guesses.emplace_back (bytes, tdesc);
   12461 }
   12462 
   12463 /* Return true if remote_read_description would do anything on this target
   12464    and architecture, false otherwise.  */
   12465 
   12466 static bool
   12467 remote_read_description_p (struct target_ops *target)
   12468 {
   12469   remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
   12470 
   12471   return !data->guesses.empty ();
   12472 }
   12473 
   12474 const struct target_desc *
   12475 remote_target::read_description ()
   12476 {
   12477   remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
   12478 
   12479   /* Do not try this during initial connection, when we do not know
   12480      whether there is a running but stopped thread.  */
   12481   if (!target_has_execution () || inferior_ptid == null_ptid)
   12482     return beneath ()->read_description ();
   12483 
   12484   if (!data->guesses.empty ())
   12485     {
   12486       int bytes = send_g_packet ();
   12487 
   12488       for (const remote_g_packet_guess &guess : data->guesses)
   12489 	if (guess.bytes == bytes)
   12490 	  return guess.tdesc;
   12491 
   12492       /* We discard the g packet.  A minor optimization would be to
   12493 	 hold on to it, and fill the register cache once we have selected
   12494 	 an architecture, but it's too tricky to do safely.  */
   12495     }
   12496 
   12497   return beneath ()->read_description ();
   12498 }
   12499 
   12500 /* Remote file transfer support.  This is host-initiated I/O, not
   12501    target-initiated; for target-initiated, see remote-fileio.c.  */
   12502 
   12503 /* If *LEFT is at least the length of STRING, copy STRING to
   12504    *BUFFER, update *BUFFER to point to the new end of the buffer, and
   12505    decrease *LEFT.  Otherwise raise an error.  */
   12506 
   12507 static void
   12508 remote_buffer_add_string (char **buffer, int *left, const char *string)
   12509 {
   12510   int len = strlen (string);
   12511 
   12512   if (len > *left)
   12513     error (_("Packet too long for target."));
   12514 
   12515   memcpy (*buffer, string, len);
   12516   *buffer += len;
   12517   *left -= len;
   12518 
   12519   /* NUL-terminate the buffer as a convenience, if there is
   12520      room.  */
   12521   if (*left)
   12522     **buffer = '\0';
   12523 }
   12524 
   12525 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
   12526    *BUFFER, update *BUFFER to point to the new end of the buffer, and
   12527    decrease *LEFT.  Otherwise raise an error.  */
   12528 
   12529 static void
   12530 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
   12531 			 int len)
   12532 {
   12533   if (2 * len > *left)
   12534     error (_("Packet too long for target."));
   12535 
   12536   bin2hex (bytes, *buffer, len);
   12537   *buffer += 2 * len;
   12538   *left -= 2 * len;
   12539 
   12540   /* NUL-terminate the buffer as a convenience, if there is
   12541      room.  */
   12542   if (*left)
   12543     **buffer = '\0';
   12544 }
   12545 
   12546 /* If *LEFT is large enough, convert VALUE to hex and add it to
   12547    *BUFFER, update *BUFFER to point to the new end of the buffer, and
   12548    decrease *LEFT.  Otherwise raise an error.  */
   12549 
   12550 static void
   12551 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
   12552 {
   12553   int len = hexnumlen (value);
   12554 
   12555   if (len > *left)
   12556     error (_("Packet too long for target."));
   12557 
   12558   hexnumstr (*buffer, value);
   12559   *buffer += len;
   12560   *left -= len;
   12561 
   12562   /* NUL-terminate the buffer as a convenience, if there is
   12563      room.  */
   12564   if (*left)
   12565     **buffer = '\0';
   12566 }
   12567 
   12568 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
   12569    value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
   12570    was included, and *ATTACHMENT to point to the start of the annex
   12571    if any.  The length of the packet isn't needed here; there may
   12572    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
   12573 
   12574    Return 0 if the packet could be parsed, -1 if it could not.  If
   12575    -1 is returned, the other variables may not be initialized.  */
   12576 
   12577 static int
   12578 remote_hostio_parse_result (const char *buffer, int *retcode,
   12579 			    fileio_error *remote_errno, const char **attachment)
   12580 {
   12581   char *p, *p2;
   12582 
   12583   *remote_errno = FILEIO_SUCCESS;
   12584   *attachment = NULL;
   12585 
   12586   if (buffer[0] != 'F')
   12587     return -1;
   12588 
   12589   errno = 0;
   12590   *retcode = strtol (&buffer[1], &p, 16);
   12591   if (errno != 0 || p == &buffer[1])
   12592     return -1;
   12593 
   12594   /* Check for ",errno".  */
   12595   if (*p == ',')
   12596     {
   12597       errno = 0;
   12598       *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
   12599       if (errno != 0 || p + 1 == p2)
   12600 	return -1;
   12601       p = p2;
   12602     }
   12603 
   12604   /* Check for ";attachment".  If there is no attachment, the
   12605      packet should end here.  */
   12606   if (*p == ';')
   12607     {
   12608       *attachment = p + 1;
   12609       return 0;
   12610     }
   12611   else if (*p == '\0')
   12612     return 0;
   12613   else
   12614     return -1;
   12615 }
   12616 
   12617 /* Send a prepared I/O packet to the target and read its response.
   12618    The prepared packet is in the global RS->BUF before this function
   12619    is called, and the answer is there when we return.
   12620 
   12621    COMMAND_BYTES is the length of the request to send, which may include
   12622    binary data.  WHICH_PACKET is the packet configuration to check
   12623    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
   12624    is set to the error number and -1 is returned.  Otherwise the value
   12625    returned by the function is returned.
   12626 
   12627    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
   12628    attachment is expected; an error will be reported if there's a
   12629    mismatch.  If one is found, *ATTACHMENT will be set to point into
   12630    the packet buffer and *ATTACHMENT_LEN will be set to the
   12631    attachment's length.  */
   12632 
   12633 int
   12634 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
   12635 					   fileio_error *remote_errno, const char **attachment,
   12636 					   int *attachment_len)
   12637 {
   12638   struct remote_state *rs = get_remote_state ();
   12639   int ret, bytes_read;
   12640   const char *attachment_tmp;
   12641 
   12642   if (m_features.packet_support (which_packet) == PACKET_DISABLE)
   12643     {
   12644       *remote_errno = FILEIO_ENOSYS;
   12645       return -1;
   12646     }
   12647 
   12648   putpkt_binary (rs->buf.data (), command_bytes);
   12649   bytes_read = getpkt (&rs->buf);
   12650 
   12651   /* If it timed out, something is wrong.  Don't try to parse the
   12652      buffer.  */
   12653   if (bytes_read < 0)
   12654     {
   12655       *remote_errno = FILEIO_EINVAL;
   12656       return -1;
   12657     }
   12658 
   12659   switch (m_features.packet_ok (rs->buf, which_packet).status ())
   12660     {
   12661     case PACKET_ERROR:
   12662       *remote_errno = FILEIO_EINVAL;
   12663       return -1;
   12664     case PACKET_UNKNOWN:
   12665       *remote_errno = FILEIO_ENOSYS;
   12666       return -1;
   12667     case PACKET_OK:
   12668       break;
   12669     }
   12670 
   12671   if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
   12672 				  &attachment_tmp))
   12673     {
   12674       *remote_errno = FILEIO_EINVAL;
   12675       return -1;
   12676     }
   12677 
   12678   /* Make sure we saw an attachment if and only if we expected one.  */
   12679   if ((attachment_tmp == NULL && attachment != NULL)
   12680       || (attachment_tmp != NULL && attachment == NULL))
   12681     {
   12682       *remote_errno = FILEIO_EINVAL;
   12683       return -1;
   12684     }
   12685 
   12686   /* If an attachment was found, it must point into the packet buffer;
   12687      work out how many bytes there were.  */
   12688   if (attachment_tmp != NULL)
   12689     {
   12690       *attachment = attachment_tmp;
   12691       *attachment_len = bytes_read - (*attachment - rs->buf.data ());
   12692     }
   12693 
   12694   return ret;
   12695 }
   12696 
   12697 /* See declaration.h.  */
   12698 
   12699 void
   12700 readahead_cache::invalidate ()
   12701 {
   12702   this->fd = -1;
   12703 }
   12704 
   12705 /* See declaration.h.  */
   12706 
   12707 void
   12708 readahead_cache::invalidate_fd (int fd)
   12709 {
   12710   if (this->fd == fd)
   12711     this->fd = -1;
   12712 }
   12713 
   12714 /* Set the filesystem remote_hostio functions that take FILENAME
   12715    arguments will use.  Return 0 on success, or -1 if an error
   12716    occurs (and set *REMOTE_ERRNO).  */
   12717 
   12718 int
   12719 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
   12720 					     fileio_error *remote_errno)
   12721 {
   12722   struct remote_state *rs = get_remote_state ();
   12723   int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
   12724   char *p = rs->buf.data ();
   12725   int left = get_remote_packet_size () - 1;
   12726   char arg[9];
   12727   int ret;
   12728 
   12729   if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
   12730     return 0;
   12731 
   12732   if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
   12733     return 0;
   12734 
   12735   remote_buffer_add_string (&p, &left, "vFile:setfs:");
   12736 
   12737   xsnprintf (arg, sizeof (arg), "%x", required_pid);
   12738   remote_buffer_add_string (&p, &left, arg);
   12739 
   12740   ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
   12741 				    remote_errno, NULL, NULL);
   12742 
   12743   if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
   12744     return 0;
   12745 
   12746   if (ret == 0)
   12747     rs->fs_pid = required_pid;
   12748 
   12749   return ret;
   12750 }
   12751 
   12752 /* Implementation of to_fileio_open.  */
   12753 
   12754 int
   12755 remote_target::remote_hostio_open (inferior *inf, const char *filename,
   12756 				   int flags, int mode, int warn_if_slow,
   12757 				   fileio_error *remote_errno)
   12758 {
   12759   struct remote_state *rs = get_remote_state ();
   12760   char *p = rs->buf.data ();
   12761   int left = get_remote_packet_size () - 1;
   12762 
   12763   if (warn_if_slow)
   12764     {
   12765       static int warning_issued = 0;
   12766 
   12767       gdb_printf (_("Reading %s from remote target...\n"),
   12768 		  filename);
   12769 
   12770       if (!warning_issued)
   12771 	{
   12772 	  warning (_("File transfers from remote targets can be slow."
   12773 		     " Use \"set sysroot\" to access files locally"
   12774 		     " instead."));
   12775 	  warning_issued = 1;
   12776 	}
   12777     }
   12778 
   12779   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
   12780     return -1;
   12781 
   12782   remote_buffer_add_string (&p, &left, "vFile:open:");
   12783 
   12784   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
   12785 			   strlen (filename));
   12786   remote_buffer_add_string (&p, &left, ",");
   12787 
   12788   remote_buffer_add_int (&p, &left, flags);
   12789   remote_buffer_add_string (&p, &left, ",");
   12790 
   12791   remote_buffer_add_int (&p, &left, mode);
   12792 
   12793   return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
   12794 				     remote_errno, NULL, NULL);
   12795 }
   12796 
   12797 int
   12798 remote_target::fileio_open (struct inferior *inf, const char *filename,
   12799 			    int flags, int mode, int warn_if_slow,
   12800 			    fileio_error *remote_errno)
   12801 {
   12802   return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
   12803 			     remote_errno);
   12804 }
   12805 
   12806 /* Implementation of to_fileio_pwrite.  */
   12807 
   12808 int
   12809 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
   12810 				     ULONGEST offset, fileio_error *remote_errno)
   12811 {
   12812   struct remote_state *rs = get_remote_state ();
   12813   char *p = rs->buf.data ();
   12814   int left = get_remote_packet_size ();
   12815   int out_len;
   12816 
   12817   rs->readahead_cache.invalidate_fd (fd);
   12818 
   12819   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
   12820 
   12821   remote_buffer_add_int (&p, &left, fd);
   12822   remote_buffer_add_string (&p, &left, ",");
   12823 
   12824   remote_buffer_add_int (&p, &left, offset);
   12825   remote_buffer_add_string (&p, &left, ",");
   12826 
   12827   p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
   12828 			     (get_remote_packet_size ()
   12829 			      - (p - rs->buf.data ())));
   12830 
   12831   return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
   12832 				     remote_errno, NULL, NULL);
   12833 }
   12834 
   12835 int
   12836 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
   12837 			      ULONGEST offset, fileio_error *remote_errno)
   12838 {
   12839   return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
   12840 }
   12841 
   12842 /* Helper for the implementation of to_fileio_pread.  Read the file
   12843    from the remote side with vFile:pread.  */
   12844 
   12845 int
   12846 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
   12847 					  ULONGEST offset, fileio_error *remote_errno)
   12848 {
   12849   struct remote_state *rs = get_remote_state ();
   12850   char *p = rs->buf.data ();
   12851   const char *attachment;
   12852   int left = get_remote_packet_size ();
   12853   int ret, attachment_len;
   12854   int read_len;
   12855 
   12856   remote_buffer_add_string (&p, &left, "vFile:pread:");
   12857 
   12858   remote_buffer_add_int (&p, &left, fd);
   12859   remote_buffer_add_string (&p, &left, ",");
   12860 
   12861   remote_buffer_add_int (&p, &left, len);
   12862   remote_buffer_add_string (&p, &left, ",");
   12863 
   12864   remote_buffer_add_int (&p, &left, offset);
   12865 
   12866   ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
   12867 				    remote_errno, &attachment,
   12868 				    &attachment_len);
   12869 
   12870   if (ret < 0)
   12871     return ret;
   12872 
   12873   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
   12874 				    read_buf, len);
   12875   if (read_len != ret)
   12876     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
   12877 
   12878   return ret;
   12879 }
   12880 
   12881 /* See declaration.h.  */
   12882 
   12883 int
   12884 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
   12885 			ULONGEST offset)
   12886 {
   12887   if (this->fd == fd
   12888       && this->offset <= offset
   12889       && offset < this->offset + this->buf.size ())
   12890     {
   12891       ULONGEST max = this->offset + this->buf.size ();
   12892 
   12893       if (offset + len > max)
   12894 	len = max - offset;
   12895 
   12896       memcpy (read_buf, &this->buf[offset - this->offset], len);
   12897       return len;
   12898     }
   12899 
   12900   return 0;
   12901 }
   12902 
   12903 /* Implementation of to_fileio_pread.  */
   12904 
   12905 int
   12906 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
   12907 				    ULONGEST offset, fileio_error *remote_errno)
   12908 {
   12909   int ret;
   12910   struct remote_state *rs = get_remote_state ();
   12911   readahead_cache *cache = &rs->readahead_cache;
   12912 
   12913   ret = cache->pread (fd, read_buf, len, offset);
   12914   if (ret > 0)
   12915     {
   12916       cache->hit_count++;
   12917 
   12918       remote_debug_printf ("readahead cache hit %s",
   12919 			   pulongest (cache->hit_count));
   12920       return ret;
   12921     }
   12922 
   12923   cache->miss_count++;
   12924 
   12925   remote_debug_printf ("readahead cache miss %s",
   12926 		       pulongest (cache->miss_count));
   12927 
   12928   cache->fd = fd;
   12929   cache->offset = offset;
   12930   cache->buf.resize (get_remote_packet_size ());
   12931 
   12932   ret = remote_hostio_pread_vFile (cache->fd, &cache->buf[0],
   12933 				   cache->buf.size (),
   12934 				   cache->offset, remote_errno);
   12935   if (ret <= 0)
   12936     {
   12937       cache->invalidate_fd (fd);
   12938       return ret;
   12939     }
   12940 
   12941   cache->buf.resize (ret);
   12942   return cache->pread (fd, read_buf, len, offset);
   12943 }
   12944 
   12945 int
   12946 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
   12947 			     ULONGEST offset, fileio_error *remote_errno)
   12948 {
   12949   return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
   12950 }
   12951 
   12952 /* Implementation of to_fileio_close.  */
   12953 
   12954 int
   12955 remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
   12956 {
   12957   struct remote_state *rs = get_remote_state ();
   12958   char *p = rs->buf.data ();
   12959   int left = get_remote_packet_size () - 1;
   12960 
   12961   rs->readahead_cache.invalidate_fd (fd);
   12962 
   12963   remote_buffer_add_string (&p, &left, "vFile:close:");
   12964 
   12965   remote_buffer_add_int (&p, &left, fd);
   12966 
   12967   return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
   12968 				     remote_errno, NULL, NULL);
   12969 }
   12970 
   12971 int
   12972 remote_target::fileio_close (int fd, fileio_error *remote_errno)
   12973 {
   12974   return remote_hostio_close (fd, remote_errno);
   12975 }
   12976 
   12977 /* Implementation of to_fileio_unlink.  */
   12978 
   12979 int
   12980 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
   12981 				     fileio_error *remote_errno)
   12982 {
   12983   struct remote_state *rs = get_remote_state ();
   12984   char *p = rs->buf.data ();
   12985   int left = get_remote_packet_size () - 1;
   12986 
   12987   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
   12988     return -1;
   12989 
   12990   remote_buffer_add_string (&p, &left, "vFile:unlink:");
   12991 
   12992   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
   12993 			   strlen (filename));
   12994 
   12995   return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
   12996 				     remote_errno, NULL, NULL);
   12997 }
   12998 
   12999 int
   13000 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
   13001 			      fileio_error *remote_errno)
   13002 {
   13003   return remote_hostio_unlink (inf, filename, remote_errno);
   13004 }
   13005 
   13006 /* Implementation of to_fileio_readlink.  */
   13007 
   13008 std::optional<std::string>
   13009 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
   13010 				fileio_error *remote_errno)
   13011 {
   13012   struct remote_state *rs = get_remote_state ();
   13013   char *p = rs->buf.data ();
   13014   const char *attachment;
   13015   int left = get_remote_packet_size ();
   13016   int len, attachment_len;
   13017   int read_len;
   13018 
   13019   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
   13020     return {};
   13021 
   13022   remote_buffer_add_string (&p, &left, "vFile:readlink:");
   13023 
   13024   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
   13025 			   strlen (filename));
   13026 
   13027   len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
   13028 				    remote_errno, &attachment,
   13029 				    &attachment_len);
   13030 
   13031   if (len < 0)
   13032     return {};
   13033 
   13034   std::string ret (len, '\0');
   13035 
   13036   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
   13037 				    (gdb_byte *) &ret[0], len);
   13038   if (read_len != len)
   13039     error (_("Readlink returned %d, but %d bytes."), len, read_len);
   13040 
   13041   return ret;
   13042 }
   13043 
   13044 /* Implementation of to_fileio_fstat.  */
   13045 
   13046 int
   13047 remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
   13048 {
   13049   struct remote_state *rs = get_remote_state ();
   13050   char *p = rs->buf.data ();
   13051   int left = get_remote_packet_size ();
   13052   int attachment_len, ret;
   13053   const char *attachment;
   13054   struct fio_stat fst;
   13055   int read_len;
   13056 
   13057   remote_buffer_add_string (&p, &left, "vFile:fstat:");
   13058 
   13059   remote_buffer_add_int (&p, &left, fd);
   13060 
   13061   ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
   13062 				    remote_errno, &attachment,
   13063 				    &attachment_len);
   13064   if (ret < 0)
   13065     {
   13066       if (*remote_errno != FILEIO_ENOSYS)
   13067 	return ret;
   13068 
   13069       /* Strictly we should return -1, ENOSYS here, but when
   13070 	 "set sysroot remote:" was implemented in August 2008
   13071 	 BFD's need for a stat function was sidestepped with
   13072 	 this hack.  This was not remedied until March 2015
   13073 	 so we retain the previous behavior to avoid breaking
   13074 	 compatibility.
   13075 
   13076 	 Note that the memset is a March 2015 addition; older
   13077 	 GDBs set st_size *and nothing else* so the structure
   13078 	 would have garbage in all other fields.  This might
   13079 	 break something but retaining the previous behavior
   13080 	 here would be just too wrong.  */
   13081 
   13082       memset (st, 0, sizeof (struct stat));
   13083       st->st_size = INT_MAX;
   13084       return 0;
   13085     }
   13086 
   13087   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
   13088 				    (gdb_byte *) &fst, sizeof (fst));
   13089 
   13090   if (read_len != ret)
   13091     error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
   13092 
   13093   if (read_len != sizeof (fst))
   13094     error (_("vFile:fstat returned %d bytes, but expecting %d."),
   13095 	   read_len, (int) sizeof (fst));
   13096 
   13097   remote_fileio_to_host_stat (&fst, st);
   13098 
   13099   return 0;
   13100 }
   13101 
   13102 /* Implementation of to_filesystem_is_local.  */
   13103 
   13104 bool
   13105 remote_target::filesystem_is_local ()
   13106 {
   13107   /* Valgrind GDB presents itself as a remote target but works
   13108      on the local filesystem: it does not implement remote get
   13109      and users are not expected to set a sysroot.  To handle
   13110      this case we treat the remote filesystem as local if the
   13111      sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
   13112      does not support vFile:open.  */
   13113   if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
   13114     {
   13115       packet_support ps = m_features.packet_support (PACKET_vFile_open);
   13116 
   13117       if (ps == PACKET_SUPPORT_UNKNOWN)
   13118 	{
   13119 	  int fd;
   13120 	  fileio_error remote_errno;
   13121 
   13122 	  /* Try opening a file to probe support.  The supplied
   13123 	     filename is irrelevant, we only care about whether
   13124 	     the stub recognizes the packet or not.  */
   13125 	  fd = remote_hostio_open (NULL, "just probing",
   13126 				   FILEIO_O_RDONLY, 0700, 0,
   13127 				   &remote_errno);
   13128 
   13129 	  if (fd >= 0)
   13130 	    remote_hostio_close (fd, &remote_errno);
   13131 
   13132 	  ps = m_features.packet_support (PACKET_vFile_open);
   13133 	}
   13134 
   13135       if (ps == PACKET_DISABLE)
   13136 	{
   13137 	  static int warning_issued = 0;
   13138 
   13139 	  if (!warning_issued)
   13140 	    {
   13141 	      warning (_("remote target does not support file"
   13142 			 " transfer, attempting to access files"
   13143 			 " from local filesystem."));
   13144 	      warning_issued = 1;
   13145 	    }
   13146 
   13147 	  return true;
   13148 	}
   13149     }
   13150 
   13151   return false;
   13152 }
   13153 
   13154 static char *
   13155 remote_hostio_error (fileio_error errnum)
   13156 {
   13157   int host_error = fileio_error_to_host (errnum);
   13158 
   13159   if (host_error == -1)
   13160     error (_("Unknown remote I/O error %d"), errnum);
   13161   else
   13162     error (_("Remote I/O error: %s"), safe_strerror (host_error));
   13163 }
   13164 
   13165 /* A RAII wrapper around a remote file descriptor.  */
   13166 
   13167 class scoped_remote_fd
   13168 {
   13169 public:
   13170   scoped_remote_fd (remote_target *remote, int fd)
   13171     : m_remote (remote), m_fd (fd)
   13172   {
   13173   }
   13174 
   13175   ~scoped_remote_fd ()
   13176   {
   13177     if (m_fd != -1)
   13178       {
   13179 	try
   13180 	  {
   13181 	    fileio_error remote_errno;
   13182 	    m_remote->remote_hostio_close (m_fd, &remote_errno);
   13183 	  }
   13184 	catch (...)
   13185 	  {
   13186 	    /* Swallow exception before it escapes the dtor.  If
   13187 	       something goes wrong, likely the connection is gone,
   13188 	       and there's nothing else that can be done.  */
   13189 	  }
   13190       }
   13191   }
   13192 
   13193   DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
   13194 
   13195   /* Release ownership of the file descriptor, and return it.  */
   13196   ATTRIBUTE_UNUSED_RESULT int release () noexcept
   13197   {
   13198     int fd = m_fd;
   13199     m_fd = -1;
   13200     return fd;
   13201   }
   13202 
   13203   /* Return the owned file descriptor.  */
   13204   int get () const noexcept
   13205   {
   13206     return m_fd;
   13207   }
   13208 
   13209 private:
   13210   /* The remote target.  */
   13211   remote_target *m_remote;
   13212 
   13213   /* The owned remote I/O file descriptor.  */
   13214   int m_fd;
   13215 };
   13216 
   13217 void
   13218 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
   13219 {
   13220   remote_target *remote = get_current_remote_target ();
   13221 
   13222   if (remote == nullptr)
   13223     error (_("command can only be used with remote target"));
   13224 
   13225   remote->remote_file_put (local_file, remote_file, from_tty);
   13226 }
   13227 
   13228 void
   13229 remote_target::remote_file_put (const char *local_file, const char *remote_file,
   13230 				int from_tty)
   13231 {
   13232   int retcode, bytes, io_size;
   13233   fileio_error remote_errno;
   13234   int bytes_in_buffer;
   13235   int saw_eof;
   13236   ULONGEST offset;
   13237 
   13238   gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
   13239   if (file == NULL)
   13240     perror_with_name (local_file);
   13241 
   13242   scoped_remote_fd fd
   13243     (this, remote_hostio_open (NULL,
   13244 			       remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
   13245 					     | FILEIO_O_TRUNC),
   13246 			       0700, 0, &remote_errno));
   13247   if (fd.get () == -1)
   13248     remote_hostio_error (remote_errno);
   13249 
   13250   /* Send up to this many bytes at once.  They won't all fit in the
   13251      remote packet limit, so we'll transfer slightly fewer.  */
   13252   io_size = get_remote_packet_size ();
   13253   gdb::byte_vector buffer (io_size);
   13254 
   13255   bytes_in_buffer = 0;
   13256   saw_eof = 0;
   13257   offset = 0;
   13258   while (bytes_in_buffer || !saw_eof)
   13259     {
   13260       if (!saw_eof)
   13261 	{
   13262 	  bytes = fread (buffer.data () + bytes_in_buffer, 1,
   13263 			 io_size - bytes_in_buffer,
   13264 			 file.get ());
   13265 	  if (bytes == 0)
   13266 	    {
   13267 	      if (ferror (file.get ()))
   13268 		error (_("Error reading %s."), local_file);
   13269 	      else
   13270 		{
   13271 		  /* EOF.  Unless there is something still in the
   13272 		     buffer from the last iteration, we are done.  */
   13273 		  saw_eof = 1;
   13274 		  if (bytes_in_buffer == 0)
   13275 		    break;
   13276 		}
   13277 	    }
   13278 	}
   13279       else
   13280 	bytes = 0;
   13281 
   13282       bytes += bytes_in_buffer;
   13283       bytes_in_buffer = 0;
   13284 
   13285       retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
   13286 				      offset, &remote_errno);
   13287 
   13288       if (retcode < 0)
   13289 	remote_hostio_error (remote_errno);
   13290       else if (retcode == 0)
   13291 	error (_("Remote write of %d bytes returned 0!"), bytes);
   13292       else if (retcode < bytes)
   13293 	{
   13294 	  /* Short write.  Save the rest of the read data for the next
   13295 	     write.  */
   13296 	  bytes_in_buffer = bytes - retcode;
   13297 	  memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
   13298 	}
   13299 
   13300       offset += retcode;
   13301     }
   13302 
   13303   if (remote_hostio_close (fd.release (), &remote_errno))
   13304     remote_hostio_error (remote_errno);
   13305 
   13306   if (from_tty)
   13307     gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
   13308 }
   13309 
   13310 void
   13311 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
   13312 {
   13313   remote_target *remote = get_current_remote_target ();
   13314 
   13315   if (remote == nullptr)
   13316     error (_("command can only be used with remote target"));
   13317 
   13318   remote->remote_file_get (remote_file, local_file, from_tty);
   13319 }
   13320 
   13321 void
   13322 remote_target::remote_file_get (const char *remote_file, const char *local_file,
   13323 				int from_tty)
   13324 {
   13325   fileio_error remote_errno;
   13326   int bytes, io_size;
   13327   ULONGEST offset;
   13328 
   13329   scoped_remote_fd fd
   13330     (this, remote_hostio_open (NULL,
   13331 			       remote_file, FILEIO_O_RDONLY, 0, 0,
   13332 			       &remote_errno));
   13333   if (fd.get () == -1)
   13334     remote_hostio_error (remote_errno);
   13335 
   13336   gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
   13337   if (file == NULL)
   13338     perror_with_name (local_file);
   13339 
   13340   /* Send up to this many bytes at once.  They won't all fit in the
   13341      remote packet limit, so we'll transfer slightly fewer.  */
   13342   io_size = get_remote_packet_size ();
   13343   gdb::byte_vector buffer (io_size);
   13344 
   13345   offset = 0;
   13346   while (1)
   13347     {
   13348       bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
   13349 				   &remote_errno);
   13350       if (bytes == 0)
   13351 	/* Success, but no bytes, means end-of-file.  */
   13352 	break;
   13353       if (bytes == -1)
   13354 	remote_hostio_error (remote_errno);
   13355 
   13356       offset += bytes;
   13357 
   13358       bytes = fwrite (buffer.data (), 1, bytes, file.get ());
   13359       if (bytes == 0)
   13360 	perror_with_name (local_file);
   13361     }
   13362 
   13363   if (remote_hostio_close (fd.release (), &remote_errno))
   13364     remote_hostio_error (remote_errno);
   13365 
   13366   if (from_tty)
   13367     gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
   13368 }
   13369 
   13370 void
   13371 remote_file_delete (const char *remote_file, int from_tty)
   13372 {
   13373   remote_target *remote = get_current_remote_target ();
   13374 
   13375   if (remote == nullptr)
   13376     error (_("command can only be used with remote target"));
   13377 
   13378   remote->remote_file_delete (remote_file, from_tty);
   13379 }
   13380 
   13381 void
   13382 remote_target::remote_file_delete (const char *remote_file, int from_tty)
   13383 {
   13384   int retcode;
   13385   fileio_error remote_errno;
   13386 
   13387   retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
   13388   if (retcode == -1)
   13389     remote_hostio_error (remote_errno);
   13390 
   13391   if (from_tty)
   13392     gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
   13393 }
   13394 
   13395 static void
   13396 remote_put_command (const char *args, int from_tty)
   13397 {
   13398   if (args == NULL)
   13399     error_no_arg (_("file to put"));
   13400 
   13401   gdb_argv argv (args);
   13402   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
   13403     error (_("Invalid parameters to remote put"));
   13404 
   13405   remote_file_put (argv[0], argv[1], from_tty);
   13406 }
   13407 
   13408 static void
   13409 remote_get_command (const char *args, int from_tty)
   13410 {
   13411   if (args == NULL)
   13412     error_no_arg (_("file to get"));
   13413 
   13414   gdb_argv argv (args);
   13415   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
   13416     error (_("Invalid parameters to remote get"));
   13417 
   13418   remote_file_get (argv[0], argv[1], from_tty);
   13419 }
   13420 
   13421 static void
   13422 remote_delete_command (const char *args, int from_tty)
   13423 {
   13424   if (args == NULL)
   13425     error_no_arg (_("file to delete"));
   13426 
   13427   gdb_argv argv (args);
   13428   if (argv[0] == NULL || argv[1] != NULL)
   13429     error (_("Invalid parameters to remote delete"));
   13430 
   13431   remote_file_delete (argv[0], from_tty);
   13432 }
   13433 
   13434 bool
   13435 remote_target::can_execute_reverse ()
   13436 {
   13437   if (m_features.packet_support (PACKET_bs) == PACKET_ENABLE
   13438       || m_features.packet_support (PACKET_bc) == PACKET_ENABLE)
   13439     return true;
   13440   else
   13441     return false;
   13442 }
   13443 
   13444 bool
   13445 remote_target::supports_non_stop ()
   13446 {
   13447   return true;
   13448 }
   13449 
   13450 bool
   13451 remote_target::supports_disable_randomization ()
   13452 {
   13453   /* Only supported in extended mode.  */
   13454   return false;
   13455 }
   13456 
   13457 bool
   13458 remote_target::supports_multi_process ()
   13459 {
   13460   return m_features.remote_multi_process_p ();
   13461 }
   13462 
   13463 int
   13464 remote_target::remote_supports_cond_tracepoints ()
   13465 {
   13466   return (m_features.packet_support (PACKET_ConditionalTracepoints)
   13467 	  == PACKET_ENABLE);
   13468 }
   13469 
   13470 bool
   13471 remote_target::supports_evaluation_of_breakpoint_conditions ()
   13472 {
   13473   return (m_features.packet_support (PACKET_ConditionalBreakpoints)
   13474 	  == PACKET_ENABLE);
   13475 }
   13476 
   13477 int
   13478 remote_target::remote_supports_fast_tracepoints ()
   13479 {
   13480   return m_features.packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
   13481 }
   13482 
   13483 int
   13484 remote_target::remote_supports_static_tracepoints ()
   13485 {
   13486   return m_features.packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
   13487 }
   13488 
   13489 int
   13490 remote_target::remote_supports_install_in_trace ()
   13491 {
   13492   return m_features.packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
   13493 }
   13494 
   13495 bool
   13496 remote_target::supports_enable_disable_tracepoint ()
   13497 {
   13498   return (m_features.packet_support (PACKET_EnableDisableTracepoints_feature)
   13499 	  == PACKET_ENABLE);
   13500 }
   13501 
   13502 bool
   13503 remote_target::supports_string_tracing ()
   13504 {
   13505   return m_features.packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
   13506 }
   13507 
   13508 bool
   13509 remote_target::can_run_breakpoint_commands ()
   13510 {
   13511   return m_features.packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
   13512 }
   13513 
   13514 void
   13515 remote_target::trace_init ()
   13516 {
   13517   struct remote_state *rs = get_remote_state ();
   13518 
   13519   putpkt ("QTinit");
   13520   remote_get_noisy_reply ();
   13521   if (strcmp (rs->buf.data (), "OK") != 0)
   13522     error (_("Target does not support this command."));
   13523 }
   13524 
   13525 /* Recursive routine to walk through command list including loops, and
   13526    download packets for each command.  */
   13527 
   13528 void
   13529 remote_target::remote_download_command_source (int num, ULONGEST addr,
   13530 					       struct command_line *cmds)
   13531 {
   13532   struct remote_state *rs = get_remote_state ();
   13533   struct command_line *cmd;
   13534 
   13535   for (cmd = cmds; cmd; cmd = cmd->next)
   13536     {
   13537       QUIT;	/* Allow user to bail out with ^C.  */
   13538       strcpy (rs->buf.data (), "QTDPsrc:");
   13539       encode_source_string (num, addr, "cmd", cmd->line,
   13540 			    rs->buf.data () + strlen (rs->buf.data ()),
   13541 			    rs->buf.size () - strlen (rs->buf.data ()));
   13542       putpkt (rs->buf);
   13543       remote_get_noisy_reply ();
   13544       if (strcmp (rs->buf.data (), "OK"))
   13545 	warning (_("Target does not support source download."));
   13546 
   13547       if (cmd->control_type == while_control
   13548 	  || cmd->control_type == while_stepping_control)
   13549 	{
   13550 	  remote_download_command_source (num, addr, cmd->body_list_0.get ());
   13551 
   13552 	  QUIT;	/* Allow user to bail out with ^C.  */
   13553 	  strcpy (rs->buf.data (), "QTDPsrc:");
   13554 	  encode_source_string (num, addr, "cmd", "end",
   13555 				rs->buf.data () + strlen (rs->buf.data ()),
   13556 				rs->buf.size () - strlen (rs->buf.data ()));
   13557 	  putpkt (rs->buf);
   13558 	  remote_get_noisy_reply ();
   13559 	  if (strcmp (rs->buf.data (), "OK"))
   13560 	    warning (_("Target does not support source download."));
   13561 	}
   13562     }
   13563 }
   13564 
   13565 void
   13566 remote_target::download_tracepoint (struct bp_location *loc)
   13567 {
   13568   CORE_ADDR tpaddr;
   13569   char addrbuf[40];
   13570   std::vector<std::string> tdp_actions;
   13571   std::vector<std::string> stepping_actions;
   13572   char *pkt;
   13573   struct breakpoint *b = loc->owner;
   13574   tracepoint *t = gdb::checked_static_cast<tracepoint *> (b);
   13575   struct remote_state *rs = get_remote_state ();
   13576   int ret;
   13577   const char *err_msg = _("Tracepoint packet too large for target.");
   13578   size_t size_left;
   13579 
   13580   /* We use a buffer other than rs->buf because we'll build strings
   13581      across multiple statements, and other statements in between could
   13582      modify rs->buf.  */
   13583   gdb::char_vector buf (get_remote_packet_size ());
   13584 
   13585   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
   13586 
   13587   tpaddr = loc->address;
   13588   strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
   13589   ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
   13590 		  b->number, addrbuf, /* address */
   13591 		  (b->enable_state == bp_enabled ? 'E' : 'D'),
   13592 		  t->step_count, t->pass_count);
   13593 
   13594   if (ret < 0 || ret >= buf.size ())
   13595     error ("%s", err_msg);
   13596 
   13597   /* Fast tracepoints are mostly handled by the target, but we can
   13598      tell the target how big of an instruction block should be moved
   13599      around.  */
   13600   if (b->type == bp_fast_tracepoint)
   13601     {
   13602       /* Only test for support at download time; we may not know
   13603 	 target capabilities at definition time.  */
   13604       if (remote_supports_fast_tracepoints ())
   13605 	{
   13606 	  if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
   13607 						NULL))
   13608 	    {
   13609 	      size_left = buf.size () - strlen (buf.data ());
   13610 	      ret = snprintf (buf.data () + strlen (buf.data ()),
   13611 			      size_left, ":F%x",
   13612 			      gdb_insn_length (loc->gdbarch, tpaddr));
   13613 
   13614 	      if (ret < 0 || ret >= size_left)
   13615 		error ("%s", err_msg);
   13616 	    }
   13617 	  else
   13618 	    /* If it passed validation at definition but fails now,
   13619 	       something is very wrong.  */
   13620 	    internal_error (_("Fast tracepoint not valid during download"));
   13621 	}
   13622       else
   13623 	/* Fast tracepoints are functionally identical to regular
   13624 	   tracepoints, so don't take lack of support as a reason to
   13625 	   give up on the trace run.  */
   13626 	warning (_("Target does not support fast tracepoints, "
   13627 		   "downloading %d as regular tracepoint"), b->number);
   13628     }
   13629   else if (b->type == bp_static_tracepoint
   13630 	   || b->type == bp_static_marker_tracepoint)
   13631     {
   13632       /* Only test for support at download time; we may not know
   13633 	 target capabilities at definition time.  */
   13634       if (remote_supports_static_tracepoints ())
   13635 	{
   13636 	  struct static_tracepoint_marker marker;
   13637 
   13638 	  if (target_static_tracepoint_marker_at (tpaddr, &marker))
   13639 	    {
   13640 	      size_left = buf.size () - strlen (buf.data ());
   13641 	      ret = snprintf (buf.data () + strlen (buf.data ()),
   13642 			      size_left, ":S");
   13643 
   13644 	      if (ret < 0 || ret >= size_left)
   13645 		error ("%s", err_msg);
   13646 	    }
   13647 	  else
   13648 	    error (_("Static tracepoint not valid during download"));
   13649 	}
   13650       else
   13651 	/* Fast tracepoints are functionally identical to regular
   13652 	   tracepoints, so don't take lack of support as a reason
   13653 	   to give up on the trace run.  */
   13654 	error (_("Target does not support static tracepoints"));
   13655     }
   13656   /* If the tracepoint has a conditional, make it into an agent
   13657      expression and append to the definition.  */
   13658   if (loc->cond)
   13659     {
   13660       /* Only test support at download time, we may not know target
   13661 	 capabilities at definition time.  */
   13662       if (remote_supports_cond_tracepoints ())
   13663 	{
   13664 	  agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
   13665 						   loc->cond.get ());
   13666 
   13667 	  size_left = buf.size () - strlen (buf.data ());
   13668 
   13669 	  ret = snprintf (buf.data () + strlen (buf.data ()),
   13670 			  size_left, ":X%x,", (int) aexpr->buf.size ());
   13671 
   13672 	  if (ret < 0 || ret >= size_left)
   13673 	    error ("%s", err_msg);
   13674 
   13675 	  size_left = buf.size () - strlen (buf.data ());
   13676 
   13677 	  /* Two bytes to encode each aexpr byte, plus the terminating
   13678 	     null byte.  */
   13679 	  if (aexpr->buf.size () * 2 + 1 > size_left)
   13680 	    error ("%s", err_msg);
   13681 
   13682 	  pkt = buf.data () + strlen (buf.data ());
   13683 
   13684 	  for (int ndx = 0; ndx < aexpr->buf.size (); ++ndx)
   13685 	    pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
   13686 	  *pkt = '\0';
   13687 	}
   13688       else
   13689 	warning (_("Target does not support conditional tracepoints, "
   13690 		   "ignoring tp %d cond"), b->number);
   13691     }
   13692 
   13693   if (b->commands || !default_collect.empty ())
   13694     {
   13695       size_left = buf.size () - strlen (buf.data ());
   13696 
   13697       ret = snprintf (buf.data () + strlen (buf.data ()),
   13698 		      size_left, "-");
   13699 
   13700       if (ret < 0 || ret >= size_left)
   13701 	error ("%s", err_msg);
   13702     }
   13703 
   13704   putpkt (buf.data ());
   13705   remote_get_noisy_reply ();
   13706   if (strcmp (rs->buf.data (), "OK"))
   13707     error (_("Target does not support tracepoints."));
   13708 
   13709   /* do_single_steps (t); */
   13710   for (auto action_it = tdp_actions.begin ();
   13711        action_it != tdp_actions.end (); action_it++)
   13712     {
   13713       QUIT;	/* Allow user to bail out with ^C.  */
   13714 
   13715       bool has_more = ((action_it + 1) != tdp_actions.end ()
   13716 		       || !stepping_actions.empty ());
   13717 
   13718       ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
   13719 		      b->number, addrbuf, /* address */
   13720 		      action_it->c_str (),
   13721 		      has_more ? '-' : 0);
   13722 
   13723       if (ret < 0 || ret >= buf.size ())
   13724 	error ("%s", err_msg);
   13725 
   13726       putpkt (buf.data ());
   13727       remote_get_noisy_reply ();
   13728       if (strcmp (rs->buf.data (), "OK"))
   13729 	error (_("Error on target while setting tracepoints."));
   13730     }
   13731 
   13732   for (auto action_it = stepping_actions.begin ();
   13733        action_it != stepping_actions.end (); action_it++)
   13734     {
   13735       QUIT;	/* Allow user to bail out with ^C.  */
   13736 
   13737       bool is_first = action_it == stepping_actions.begin ();
   13738       bool has_more = (action_it + 1) != stepping_actions.end ();
   13739 
   13740       ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
   13741 		      b->number, addrbuf, /* address */
   13742 		      is_first ? "S" : "",
   13743 		      action_it->c_str (),
   13744 		      has_more ? "-" : "");
   13745 
   13746       if (ret < 0 || ret >= buf.size ())
   13747 	error ("%s", err_msg);
   13748 
   13749       putpkt (buf.data ());
   13750       remote_get_noisy_reply ();
   13751       if (strcmp (rs->buf.data (), "OK"))
   13752 	error (_("Error on target while setting tracepoints."));
   13753     }
   13754 
   13755   if (m_features.packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
   13756     {
   13757       if (b->locspec != nullptr)
   13758 	{
   13759 	  ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
   13760 
   13761 	  if (ret < 0 || ret >= buf.size ())
   13762 	    error ("%s", err_msg);
   13763 
   13764 	  const char *str = b->locspec->to_string ();
   13765 	  encode_source_string (b->number, loc->address, "at", str,
   13766 				buf.data () + strlen (buf.data ()),
   13767 				buf.size () - strlen (buf.data ()));
   13768 	  putpkt (buf.data ());
   13769 	  remote_get_noisy_reply ();
   13770 	  if (strcmp (rs->buf.data (), "OK"))
   13771 	    warning (_("Target does not support source download."));
   13772 	}
   13773       if (b->cond_string)
   13774 	{
   13775 	  ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
   13776 
   13777 	  if (ret < 0 || ret >= buf.size ())
   13778 	    error ("%s", err_msg);
   13779 
   13780 	  encode_source_string (b->number, loc->address,
   13781 				"cond", b->cond_string.get (),
   13782 				buf.data () + strlen (buf.data ()),
   13783 				buf.size () - strlen (buf.data ()));
   13784 	  putpkt (buf.data ());
   13785 	  remote_get_noisy_reply ();
   13786 	  if (strcmp (rs->buf.data (), "OK"))
   13787 	    warning (_("Target does not support source download."));
   13788 	}
   13789       remote_download_command_source (b->number, loc->address,
   13790 				      breakpoint_commands (b));
   13791     }
   13792 }
   13793 
   13794 bool
   13795 remote_target::can_download_tracepoint ()
   13796 {
   13797   struct remote_state *rs = get_remote_state ();
   13798   struct trace_status *ts;
   13799   int status;
   13800 
   13801   /* Don't try to install tracepoints until we've relocated our
   13802      symbols, and fetched and merged the target's tracepoint list with
   13803      ours.  */
   13804   if (rs->starting_up)
   13805     return false;
   13806 
   13807   ts = current_trace_status ();
   13808   status = get_trace_status (ts);
   13809 
   13810   if (status == -1 || !ts->running_known || !ts->running)
   13811     return false;
   13812 
   13813   /* If we are in a tracing experiment, but remote stub doesn't support
   13814      installing tracepoint in trace, we have to return.  */
   13815   if (!remote_supports_install_in_trace ())
   13816     return false;
   13817 
   13818   return true;
   13819 }
   13820 
   13821 
   13822 void
   13823 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
   13824 {
   13825   struct remote_state *rs = get_remote_state ();
   13826   char *p;
   13827 
   13828   xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
   13829 	     tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
   13830 	     tsv.builtin);
   13831   p = rs->buf.data () + strlen (rs->buf.data ());
   13832   if ((p - rs->buf.data ()) + tsv.name.length () * 2
   13833       >= get_remote_packet_size ())
   13834     error (_("Trace state variable name too long for tsv definition packet"));
   13835   p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
   13836   *p++ = '\0';
   13837   putpkt (rs->buf);
   13838   remote_get_noisy_reply ();
   13839   if (rs->buf[0] == '\0')
   13840     error (_("Target does not support this command."));
   13841   if (strcmp (rs->buf.data (), "OK") != 0)
   13842     error (_("Error on target while downloading trace state variable."));
   13843 }
   13844 
   13845 void
   13846 remote_target::enable_tracepoint (struct bp_location *location)
   13847 {
   13848   struct remote_state *rs = get_remote_state ();
   13849 
   13850   xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
   13851 	     location->owner->number,
   13852 	     phex (location->address, sizeof (CORE_ADDR)));
   13853   putpkt (rs->buf);
   13854   remote_get_noisy_reply ();
   13855   if (rs->buf[0] == '\0')
   13856     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
   13857   if (strcmp (rs->buf.data (), "OK") != 0)
   13858     error (_("Error on target while enabling tracepoint."));
   13859 }
   13860 
   13861 void
   13862 remote_target::disable_tracepoint (struct bp_location *location)
   13863 {
   13864   struct remote_state *rs = get_remote_state ();
   13865 
   13866   xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
   13867 	     location->owner->number,
   13868 	     phex (location->address, sizeof (CORE_ADDR)));
   13869   putpkt (rs->buf);
   13870   remote_get_noisy_reply ();
   13871   if (rs->buf[0] == '\0')
   13872     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
   13873   if (strcmp (rs->buf.data (), "OK") != 0)
   13874     error (_("Error on target while disabling tracepoint."));
   13875 }
   13876 
   13877 void
   13878 remote_target::trace_set_readonly_regions ()
   13879 {
   13880   asection *s;
   13881   bfd_size_type size;
   13882   bfd_vma vma;
   13883   int anysecs = 0;
   13884   int offset = 0;
   13885   bfd *abfd = current_program_space->exec_bfd ();
   13886 
   13887   if (!abfd)
   13888     return;			/* No information to give.  */
   13889 
   13890   struct remote_state *rs = get_remote_state ();
   13891 
   13892   strcpy (rs->buf.data (), "QTro");
   13893   offset = strlen (rs->buf.data ());
   13894   for (s = abfd->sections; s; s = s->next)
   13895     {
   13896       char tmp1[40], tmp2[40];
   13897       int sec_length;
   13898 
   13899       if ((s->flags & SEC_LOAD) == 0
   13900 	  /* || (s->flags & SEC_CODE) == 0 */
   13901 	  || (s->flags & SEC_READONLY) == 0)
   13902 	continue;
   13903 
   13904       anysecs = 1;
   13905       vma = bfd_section_vma (s);
   13906       size = bfd_section_size (s);
   13907       bfd_sprintf_vma (abfd, tmp1, vma);
   13908       bfd_sprintf_vma (abfd, tmp2, vma + size);
   13909       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
   13910       if (offset + sec_length + 1 > rs->buf.size ())
   13911 	{
   13912 	  if (m_features.packet_support (PACKET_qXfer_traceframe_info)
   13913 	      != PACKET_ENABLE)
   13914 	    warning (_("\
   13915 Too many sections for read-only sections definition packet."));
   13916 	  break;
   13917 	}
   13918       xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
   13919 		 tmp1, tmp2);
   13920       offset += sec_length;
   13921     }
   13922   if (anysecs)
   13923     {
   13924       putpkt (rs->buf);
   13925       getpkt (&rs->buf);
   13926     }
   13927 }
   13928 
   13929 void
   13930 remote_target::trace_start ()
   13931 {
   13932   struct remote_state *rs = get_remote_state ();
   13933 
   13934   putpkt ("QTStart");
   13935   remote_get_noisy_reply ();
   13936   if (rs->buf[0] == '\0')
   13937     error (_("Target does not support this command."));
   13938   if (strcmp (rs->buf.data (), "OK") != 0)
   13939     error (_("Bogus reply from target: %s"), rs->buf.data ());
   13940 }
   13941 
   13942 int
   13943 remote_target::get_trace_status (struct trace_status *ts)
   13944 {
   13945   /* Initialize it just to avoid a GCC false warning.  */
   13946   char *p = NULL;
   13947   struct remote_state *rs = get_remote_state ();
   13948 
   13949   if (m_features.packet_support (PACKET_qTStatus) == PACKET_DISABLE)
   13950     return -1;
   13951 
   13952   /* FIXME we need to get register block size some other way.  */
   13953   trace_regblock_size
   13954     = rs->get_remote_arch_state (current_inferior ()->arch ())->sizeof_g_packet;
   13955 
   13956   putpkt ("qTStatus");
   13957 
   13958   try
   13959     {
   13960       p = remote_get_noisy_reply ();
   13961     }
   13962   catch (const gdb_exception_error &ex)
   13963     {
   13964       if (ex.error != TARGET_CLOSE_ERROR)
   13965 	{
   13966 	  exception_fprintf (gdb_stderr, ex, "qTStatus: ");
   13967 	  return -1;
   13968 	}
   13969       throw;
   13970     }
   13971 
   13972   packet_result result = m_features.packet_ok (p, PACKET_qTStatus);
   13973 
   13974   switch (result.status ())
   13975     {
   13976     case PACKET_ERROR:
   13977       error (_("Remote failure reply: %s"), result.err_msg ());
   13978     /* If the remote target doesn't do tracing, flag it.  */
   13979     case PACKET_UNKNOWN:
   13980       return -1;
   13981     }
   13982 
   13983   /* We're working with a live target.  */
   13984   ts->filename = NULL;
   13985 
   13986   if (*p++ != 'T')
   13987     error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
   13988 
   13989   /* Function 'parse_trace_status' sets default value of each field of
   13990      'ts' at first, so we don't have to do it here.  */
   13991   parse_trace_status (p, ts);
   13992 
   13993   return ts->running;
   13994 }
   13995 
   13996 void
   13997 remote_target::get_tracepoint_status (tracepoint *tp,
   13998 				      struct uploaded_tp *utp)
   13999 {
   14000   struct remote_state *rs = get_remote_state ();
   14001   char *reply;
   14002   size_t size = get_remote_packet_size ();
   14003 
   14004   if (tp)
   14005     {
   14006       tp->hit_count = 0;
   14007       tp->traceframe_usage = 0;
   14008       for (bp_location &loc : tp->locations ())
   14009 	{
   14010 	  /* If the tracepoint was never downloaded, don't go asking for
   14011 	     any status.  */
   14012 	  if (tp->number_on_target == 0)
   14013 	    continue;
   14014 	  xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
   14015 		     phex_nz (loc.address, 0));
   14016 	  putpkt (rs->buf);
   14017 	  reply = remote_get_noisy_reply ();
   14018 	  if (reply && *reply)
   14019 	    {
   14020 	      if (*reply == 'V')
   14021 		parse_tracepoint_status (reply + 1, tp, utp);
   14022 	    }
   14023 	}
   14024     }
   14025   else if (utp)
   14026     {
   14027       utp->hit_count = 0;
   14028       utp->traceframe_usage = 0;
   14029       xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
   14030 		 phex_nz (utp->addr, 0));
   14031       putpkt (rs->buf);
   14032       reply = remote_get_noisy_reply ();
   14033       if (reply && *reply)
   14034 	{
   14035 	  if (*reply == 'V')
   14036 	    parse_tracepoint_status (reply + 1, tp, utp);
   14037 	}
   14038     }
   14039 }
   14040 
   14041 void
   14042 remote_target::trace_stop ()
   14043 {
   14044   struct remote_state *rs = get_remote_state ();
   14045 
   14046   putpkt ("QTStop");
   14047   remote_get_noisy_reply ();
   14048   if (rs->buf[0] == '\0')
   14049     error (_("Target does not support this command."));
   14050   if (strcmp (rs->buf.data (), "OK") != 0)
   14051     error (_("Bogus reply from target: %s"), rs->buf.data ());
   14052 }
   14053 
   14054 int
   14055 remote_target::trace_find (enum trace_find_type type, int num,
   14056 			   CORE_ADDR addr1, CORE_ADDR addr2,
   14057 			   int *tpp)
   14058 {
   14059   struct remote_state *rs = get_remote_state ();
   14060   char *endbuf = rs->buf.data () + get_remote_packet_size ();
   14061   char *p, *reply;
   14062   int target_frameno = -1, target_tracept = -1;
   14063 
   14064   /* Lookups other than by absolute frame number depend on the current
   14065      trace selected, so make sure it is correct on the remote end
   14066      first.  */
   14067   if (type != tfind_number)
   14068     set_remote_traceframe ();
   14069 
   14070   p = rs->buf.data ();
   14071   strcpy (p, "QTFrame:");
   14072   p = strchr (p, '\0');
   14073   switch (type)
   14074     {
   14075     case tfind_number:
   14076       xsnprintf (p, endbuf - p, "%x", num);
   14077       break;
   14078     case tfind_pc:
   14079       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
   14080       break;
   14081     case tfind_tp:
   14082       xsnprintf (p, endbuf - p, "tdp:%x", num);
   14083       break;
   14084     case tfind_range:
   14085       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
   14086 		 phex_nz (addr2, 0));
   14087       break;
   14088     case tfind_outside:
   14089       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
   14090 		 phex_nz (addr2, 0));
   14091       break;
   14092     default:
   14093       error (_("Unknown trace find type %d"), type);
   14094     }
   14095 
   14096   putpkt (rs->buf);
   14097   reply = remote_get_noisy_reply ();
   14098   if (*reply == '\0')
   14099     error (_("Target does not support this command."));
   14100 
   14101   while (reply && *reply)
   14102     switch (*reply)
   14103       {
   14104       case 'F':
   14105 	p = ++reply;
   14106 	target_frameno = (int) strtol (p, &reply, 16);
   14107 	if (reply == p)
   14108 	  error (_("Unable to parse trace frame number"));
   14109 	/* Don't update our remote traceframe number cache on failure
   14110 	   to select a remote traceframe.  */
   14111 	if (target_frameno == -1)
   14112 	  return -1;
   14113 	break;
   14114       case 'T':
   14115 	p = ++reply;
   14116 	target_tracept = (int) strtol (p, &reply, 16);
   14117 	if (reply == p)
   14118 	  error (_("Unable to parse tracepoint number"));
   14119 	break;
   14120       case 'O':		/* "OK"? */
   14121 	if (reply[1] == 'K' && reply[2] == '\0')
   14122 	  reply += 2;
   14123 	else
   14124 	  error (_("Bogus reply from target: %s"), reply);
   14125 	break;
   14126       default:
   14127 	error (_("Bogus reply from target: %s"), reply);
   14128       }
   14129   if (tpp)
   14130     *tpp = target_tracept;
   14131 
   14132   rs->remote_traceframe_number = target_frameno;
   14133   return target_frameno;
   14134 }
   14135 
   14136 bool
   14137 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
   14138 {
   14139   struct remote_state *rs = get_remote_state ();
   14140   char *reply;
   14141   ULONGEST uval;
   14142 
   14143   set_remote_traceframe ();
   14144 
   14145   xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
   14146   putpkt (rs->buf);
   14147   reply = remote_get_noisy_reply ();
   14148   if (reply && *reply)
   14149     {
   14150       if (*reply == 'V')
   14151 	{
   14152 	  unpack_varlen_hex (reply + 1, &uval);
   14153 	  *val = (LONGEST) uval;
   14154 	  return true;
   14155 	}
   14156     }
   14157   return false;
   14158 }
   14159 
   14160 int
   14161 remote_target::save_trace_data (const char *filename)
   14162 {
   14163   struct remote_state *rs = get_remote_state ();
   14164   char *p, *reply;
   14165 
   14166   p = rs->buf.data ();
   14167   strcpy (p, "QTSave:");
   14168   p += strlen (p);
   14169   if ((p - rs->buf.data ()) + strlen (filename) * 2
   14170       >= get_remote_packet_size ())
   14171     error (_("Remote file name too long for trace save packet"));
   14172   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
   14173   *p++ = '\0';
   14174   putpkt (rs->buf);
   14175   reply = remote_get_noisy_reply ();
   14176   if (*reply == '\0')
   14177     error (_("Target does not support this command."));
   14178   if (strcmp (reply, "OK") != 0)
   14179     error (_("Bogus reply from target: %s"), reply);
   14180   return 0;
   14181 }
   14182 
   14183 /* This is basically a memory transfer, but needs to be its own packet
   14184    because we don't know how the target actually organizes its trace
   14185    memory, plus we want to be able to ask for as much as possible, but
   14186    not be unhappy if we don't get as much as we ask for.  */
   14187 
   14188 LONGEST
   14189 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
   14190 {
   14191   struct remote_state *rs = get_remote_state ();
   14192   char *reply;
   14193   char *p;
   14194   int rslt;
   14195 
   14196   p = rs->buf.data ();
   14197   strcpy (p, "qTBuffer:");
   14198   p += strlen (p);
   14199   p += hexnumstr (p, offset);
   14200   *p++ = ',';
   14201   p += hexnumstr (p, len);
   14202   *p++ = '\0';
   14203 
   14204   putpkt (rs->buf);
   14205   reply = remote_get_noisy_reply ();
   14206   if (reply && *reply)
   14207     {
   14208       /* 'l' by itself means we're at the end of the buffer and
   14209 	 there is nothing more to get.  */
   14210       if (*reply == 'l')
   14211 	return 0;
   14212 
   14213       /* Convert the reply into binary.  Limit the number of bytes to
   14214 	 convert according to our passed-in buffer size, rather than
   14215 	 what was returned in the packet; if the target is
   14216 	 unexpectedly generous and gives us a bigger reply than we
   14217 	 asked for, we don't want to crash.  */
   14218       rslt = hex2bin (reply, buf, len);
   14219       return rslt;
   14220     }
   14221 
   14222   /* Something went wrong, flag as an error.  */
   14223   return -1;
   14224 }
   14225 
   14226 void
   14227 remote_target::set_disconnected_tracing (int val)
   14228 {
   14229   struct remote_state *rs = get_remote_state ();
   14230 
   14231   if (m_features.packet_support (PACKET_DisconnectedTracing_feature)
   14232       == PACKET_ENABLE)
   14233     {
   14234       char *reply;
   14235 
   14236       xsnprintf (rs->buf.data (), get_remote_packet_size (),
   14237 		 "QTDisconnected:%x", val);
   14238       putpkt (rs->buf);
   14239       reply = remote_get_noisy_reply ();
   14240       if (*reply == '\0')
   14241 	error (_("Target does not support this command."));
   14242       if (strcmp (reply, "OK") != 0)
   14243 	error (_("Bogus reply from target: %s"), reply);
   14244     }
   14245   else if (val)
   14246     warning (_("Target does not support disconnected tracing."));
   14247 }
   14248 
   14249 int
   14250 remote_target::core_of_thread (ptid_t ptid)
   14251 {
   14252   thread_info *info = this->find_thread (ptid);
   14253 
   14254   if (info != NULL && info->priv != NULL)
   14255     return get_remote_thread_info (info)->core;
   14256 
   14257   return -1;
   14258 }
   14259 
   14260 void
   14261 remote_target::set_circular_trace_buffer (int val)
   14262 {
   14263   struct remote_state *rs = get_remote_state ();
   14264   char *reply;
   14265 
   14266   xsnprintf (rs->buf.data (), get_remote_packet_size (),
   14267 	     "QTBuffer:circular:%x", val);
   14268   putpkt (rs->buf);
   14269   reply = remote_get_noisy_reply ();
   14270   if (*reply == '\0')
   14271     error (_("Target does not support this command."));
   14272   if (strcmp (reply, "OK") != 0)
   14273     error (_("Bogus reply from target: %s"), reply);
   14274 }
   14275 
   14276 traceframe_info_up
   14277 remote_target::traceframe_info ()
   14278 {
   14279   std::optional<gdb::char_vector> text
   14280     = target_read_stralloc (current_inferior ()->top_target (),
   14281 			    TARGET_OBJECT_TRACEFRAME_INFO,
   14282 			    NULL);
   14283   if (text)
   14284     return parse_traceframe_info (text->data ());
   14285 
   14286   return NULL;
   14287 }
   14288 
   14289 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
   14290    instruction on which a fast tracepoint may be placed.  Returns -1
   14291    if the packet is not supported, and 0 if the minimum instruction
   14292    length is unknown.  */
   14293 
   14294 int
   14295 remote_target::get_min_fast_tracepoint_insn_len ()
   14296 {
   14297   struct remote_state *rs = get_remote_state ();
   14298   char *reply;
   14299 
   14300   /* If we're not debugging a process yet, the IPA can't be
   14301      loaded.  */
   14302   if (!target_has_execution ())
   14303     return 0;
   14304 
   14305   /* Make sure the remote is pointing at the right process.  */
   14306   set_general_process ();
   14307 
   14308   xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
   14309   putpkt (rs->buf);
   14310   reply = remote_get_noisy_reply ();
   14311   if (*reply == '\0')
   14312     return -1;
   14313   else
   14314     {
   14315       ULONGEST min_insn_len;
   14316 
   14317       unpack_varlen_hex (reply, &min_insn_len);
   14318 
   14319       return (int) min_insn_len;
   14320     }
   14321 }
   14322 
   14323 void
   14324 remote_target::set_trace_buffer_size (LONGEST val)
   14325 {
   14326   if (m_features.packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
   14327     {
   14328       struct remote_state *rs = get_remote_state ();
   14329       char *buf = rs->buf.data ();
   14330       char *endbuf = buf + get_remote_packet_size ();
   14331 
   14332       gdb_assert (val >= 0 || val == -1);
   14333       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
   14334       /* Send -1 as literal "-1" to avoid host size dependency.  */
   14335       if (val < 0)
   14336 	{
   14337 	  *buf++ = '-';
   14338 	  buf += hexnumstr (buf, (ULONGEST) -val);
   14339 	}
   14340       else
   14341 	buf += hexnumstr (buf, (ULONGEST) val);
   14342 
   14343       putpkt (rs->buf);
   14344       remote_get_noisy_reply ();
   14345       packet_result result = m_features.packet_ok (rs->buf, PACKET_QTBuffer_size);
   14346       switch (result.status ())
   14347 	{
   14348 	case PACKET_ERROR:
   14349 	  warning (_("Error reply from target: %s"), result.err_msg ());
   14350 	  break;
   14351 	case PACKET_UNKNOWN:
   14352 	  warning (_("Remote target failed to process the request "));
   14353 	}
   14354     }
   14355 }
   14356 
   14357 bool
   14358 remote_target::set_trace_notes (const char *user, const char *notes,
   14359 				const char *stop_notes)
   14360 {
   14361   struct remote_state *rs = get_remote_state ();
   14362   char *reply;
   14363   char *buf = rs->buf.data ();
   14364   char *endbuf = buf + get_remote_packet_size ();
   14365   int nbytes;
   14366 
   14367   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
   14368   if (user)
   14369     {
   14370       buf += xsnprintf (buf, endbuf - buf, "user:");
   14371       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
   14372       buf += 2 * nbytes;
   14373       *buf++ = ';';
   14374     }
   14375   if (notes)
   14376     {
   14377       buf += xsnprintf (buf, endbuf - buf, "notes:");
   14378       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
   14379       buf += 2 * nbytes;
   14380       *buf++ = ';';
   14381     }
   14382   if (stop_notes)
   14383     {
   14384       buf += xsnprintf (buf, endbuf - buf, "tstop:");
   14385       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
   14386       buf += 2 * nbytes;
   14387       *buf++ = ';';
   14388     }
   14389   /* Ensure the buffer is terminated.  */
   14390   *buf = '\0';
   14391 
   14392   putpkt (rs->buf);
   14393   reply = remote_get_noisy_reply ();
   14394   if (*reply == '\0')
   14395     return false;
   14396 
   14397   if (strcmp (reply, "OK") != 0)
   14398     error (_("Bogus reply from target: %s"), reply);
   14399 
   14400   return true;
   14401 }
   14402 
   14403 bool
   14404 remote_target::use_agent (bool use)
   14405 {
   14406   if (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE)
   14407     {
   14408       struct remote_state *rs = get_remote_state ();
   14409 
   14410       /* If the stub supports QAgent.  */
   14411       xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
   14412       putpkt (rs->buf);
   14413       getpkt (&rs->buf);
   14414 
   14415       if (strcmp (rs->buf.data (), "OK") == 0)
   14416 	{
   14417 	  ::use_agent = use;
   14418 	  return true;
   14419 	}
   14420     }
   14421 
   14422   return false;
   14423 }
   14424 
   14425 bool
   14426 remote_target::can_use_agent ()
   14427 {
   14428   return (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE);
   14429 }
   14430 
   14431 #if defined (HAVE_LIBEXPAT)
   14432 
   14433 /* Check the btrace document version.  */
   14434 
   14435 static void
   14436 check_xml_btrace_version (struct gdb_xml_parser *parser,
   14437 			  const struct gdb_xml_element *element,
   14438 			  void *user_data,
   14439 			  std::vector<gdb_xml_value> &attributes)
   14440 {
   14441   const char *version
   14442     = (const char *) xml_find_attribute (attributes, "version")->value.get ();
   14443 
   14444   if (strcmp (version, "1.0") != 0)
   14445     gdb_xml_error (parser, _("Unsupported btrace version: \"%s\""), version);
   14446 }
   14447 
   14448 /* Parse a btrace "block" xml record.  */
   14449 
   14450 static void
   14451 parse_xml_btrace_block (struct gdb_xml_parser *parser,
   14452 			const struct gdb_xml_element *element,
   14453 			void *user_data,
   14454 			std::vector<gdb_xml_value> &attributes)
   14455 {
   14456   struct btrace_data *btrace;
   14457   ULONGEST *begin, *end;
   14458 
   14459   btrace = (struct btrace_data *) user_data;
   14460 
   14461   switch (btrace->format)
   14462     {
   14463     case BTRACE_FORMAT_BTS:
   14464       break;
   14465 
   14466     case BTRACE_FORMAT_NONE:
   14467       btrace->format = BTRACE_FORMAT_BTS;
   14468       btrace->variant.bts.blocks = new std::vector<btrace_block>;
   14469       break;
   14470 
   14471     default:
   14472       gdb_xml_error (parser, _("Btrace format error."));
   14473     }
   14474 
   14475   begin = (ULONGEST *) xml_find_attribute (attributes, "begin")->value.get ();
   14476   end = (ULONGEST *) xml_find_attribute (attributes, "end")->value.get ();
   14477   btrace->variant.bts.blocks->emplace_back (*begin, *end);
   14478 }
   14479 
   14480 /* Parse a "raw" xml record.  */
   14481 
   14482 static void
   14483 parse_xml_raw (struct gdb_xml_parser *parser, const char *body_text,
   14484 	       gdb_byte **pdata, size_t *psize)
   14485 {
   14486   gdb_byte *bin;
   14487   size_t len, size;
   14488 
   14489   len = strlen (body_text);
   14490   if (len % 2 != 0)
   14491     gdb_xml_error (parser, _("Bad raw data size."));
   14492 
   14493   size = len / 2;
   14494 
   14495   gdb::unique_xmalloc_ptr<gdb_byte> data ((gdb_byte *) xmalloc (size));
   14496   bin = data.get ();
   14497 
   14498   /* We use hex encoding - see gdbsupport/rsp-low.h.  */
   14499   while (len > 0)
   14500     {
   14501       char hi, lo;
   14502 
   14503       hi = *body_text++;
   14504       lo = *body_text++;
   14505 
   14506       if (hi == 0 || lo == 0)
   14507 	gdb_xml_error (parser, _("Bad hex encoding."));
   14508 
   14509       *bin++ = fromhex (hi) * 16 + fromhex (lo);
   14510       len -= 2;
   14511     }
   14512 
   14513   *pdata = data.release ();
   14514   *psize = size;
   14515 }
   14516 
   14517 /* Parse a btrace pt-config "cpu" xml record.  */
   14518 
   14519 static void
   14520 parse_xml_btrace_pt_config_cpu (struct gdb_xml_parser *parser,
   14521 				const struct gdb_xml_element *element,
   14522 				void *user_data,
   14523 				std::vector<gdb_xml_value> &attributes)
   14524 {
   14525   struct btrace_data *btrace;
   14526   const char *vendor;
   14527   ULONGEST *family, *model, *stepping;
   14528 
   14529   vendor
   14530     = (const char *) xml_find_attribute (attributes, "vendor")->value.get ();
   14531   family
   14532     = (ULONGEST *) xml_find_attribute (attributes, "family")->value.get ();
   14533   model
   14534     = (ULONGEST *) xml_find_attribute (attributes, "model")->value.get ();
   14535   stepping
   14536     = (ULONGEST *) xml_find_attribute (attributes, "stepping")->value.get ();
   14537 
   14538   btrace = (struct btrace_data *) user_data;
   14539 
   14540   if (strcmp (vendor, "GenuineIntel") == 0)
   14541     btrace->variant.pt.config.cpu.vendor = CV_INTEL;
   14542 
   14543   btrace->variant.pt.config.cpu.family = *family;
   14544   btrace->variant.pt.config.cpu.model = *model;
   14545   btrace->variant.pt.config.cpu.stepping = *stepping;
   14546 }
   14547 
   14548 /* Parse a btrace pt "raw" xml record.  */
   14549 
   14550 static void
   14551 parse_xml_btrace_pt_raw (struct gdb_xml_parser *parser,
   14552 			 const struct gdb_xml_element *element,
   14553 			 void *user_data, const char *body_text)
   14554 {
   14555   struct btrace_data *btrace;
   14556 
   14557   btrace = (struct btrace_data *) user_data;
   14558   parse_xml_raw (parser, body_text, &btrace->variant.pt.data,
   14559 		 &btrace->variant.pt.size);
   14560 }
   14561 
   14562 /* Parse a btrace "pt" xml record.  */
   14563 
   14564 static void
   14565 parse_xml_btrace_pt (struct gdb_xml_parser *parser,
   14566 		     const struct gdb_xml_element *element,
   14567 		     void *user_data,
   14568 		     std::vector<gdb_xml_value> &attributes)
   14569 {
   14570   struct btrace_data *btrace;
   14571 
   14572   btrace = (struct btrace_data *) user_data;
   14573   btrace->format = BTRACE_FORMAT_PT;
   14574   btrace->variant.pt.config.cpu.vendor = CV_UNKNOWN;
   14575   btrace->variant.pt.data = NULL;
   14576   btrace->variant.pt.size = 0;
   14577 }
   14578 
   14579 static const struct gdb_xml_attribute block_attributes[] = {
   14580   { "begin", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
   14581   { "end", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
   14582   { NULL, GDB_XML_AF_NONE, NULL, NULL }
   14583 };
   14584 
   14585 static const struct gdb_xml_attribute btrace_pt_config_cpu_attributes[] = {
   14586   { "vendor", GDB_XML_AF_NONE, NULL, NULL },
   14587   { "family", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
   14588   { "model", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
   14589   { "stepping", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
   14590   { NULL, GDB_XML_AF_NONE, NULL, NULL }
   14591 };
   14592 
   14593 static const struct gdb_xml_element btrace_pt_config_children[] = {
   14594   { "cpu", btrace_pt_config_cpu_attributes, NULL, GDB_XML_EF_OPTIONAL,
   14595     parse_xml_btrace_pt_config_cpu, NULL },
   14596   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
   14597 };
   14598 
   14599 static const struct gdb_xml_element btrace_pt_children[] = {
   14600   { "pt-config", NULL, btrace_pt_config_children, GDB_XML_EF_OPTIONAL, NULL,
   14601     NULL },
   14602   { "raw", NULL, NULL, GDB_XML_EF_OPTIONAL, NULL, parse_xml_btrace_pt_raw },
   14603   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
   14604 };
   14605 
   14606 static const struct gdb_xml_attribute btrace_attributes[] = {
   14607   { "version", GDB_XML_AF_NONE, NULL, NULL },
   14608   { NULL, GDB_XML_AF_NONE, NULL, NULL }
   14609 };
   14610 
   14611 static const struct gdb_xml_element btrace_children[] = {
   14612   { "block", block_attributes, NULL,
   14613     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL, parse_xml_btrace_block, NULL },
   14614   { "pt", NULL, btrace_pt_children, GDB_XML_EF_OPTIONAL, parse_xml_btrace_pt,
   14615     NULL },
   14616   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
   14617 };
   14618 
   14619 static const struct gdb_xml_element btrace_elements[] = {
   14620   { "btrace", btrace_attributes, btrace_children, GDB_XML_EF_NONE,
   14621     check_xml_btrace_version, NULL },
   14622   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
   14623 };
   14624 
   14625 #endif /* defined (HAVE_LIBEXPAT) */
   14626 
   14627 /* Parse a branch trace xml document XML into DATA.  */
   14628 
   14629 static void
   14630 parse_xml_btrace (struct btrace_data *btrace, const char *buffer)
   14631 {
   14632 #if defined (HAVE_LIBEXPAT)
   14633 
   14634   int errcode;
   14635   btrace_data result;
   14636   result.format = BTRACE_FORMAT_NONE;
   14637 
   14638   errcode = gdb_xml_parse_quick (_("btrace"), "btrace.dtd", btrace_elements,
   14639 				 buffer, &result);
   14640   if (errcode != 0)
   14641     error (_("Error parsing branch trace."));
   14642 
   14643   /* Keep parse results.  */
   14644   *btrace = std::move (result);
   14645 
   14646 #else  /* !defined (HAVE_LIBEXPAT) */
   14647 
   14648   error (_("Cannot process branch trace.  XML support was disabled at "
   14649 	   "compile time."));
   14650 
   14651 #endif  /* !defined (HAVE_LIBEXPAT) */
   14652 }
   14653 
   14654 #if defined (HAVE_LIBEXPAT)
   14655 
   14656 /* Parse a btrace-conf "bts" xml record.  */
   14657 
   14658 static void
   14659 parse_xml_btrace_conf_bts (struct gdb_xml_parser *parser,
   14660 			  const struct gdb_xml_element *element,
   14661 			  void *user_data,
   14662 			  std::vector<gdb_xml_value> &attributes)
   14663 {
   14664   struct btrace_config *conf;
   14665   struct gdb_xml_value *size;
   14666 
   14667   conf = (struct btrace_config *) user_data;
   14668   conf->format = BTRACE_FORMAT_BTS;
   14669   conf->bts.size = 0;
   14670 
   14671   size = xml_find_attribute (attributes, "size");
   14672   if (size != NULL)
   14673     conf->bts.size = (unsigned int) *(ULONGEST *) size->value.get ();
   14674 }
   14675 
   14676 /* Parse a btrace-conf "pt" xml record.  */
   14677 
   14678 static void
   14679 parse_xml_btrace_conf_pt (struct gdb_xml_parser *parser,
   14680 			  const struct gdb_xml_element *element,
   14681 			  void *user_data,
   14682 			  std::vector<gdb_xml_value> &attributes)
   14683 {
   14684   struct btrace_config *conf;
   14685   struct gdb_xml_value *size;
   14686 
   14687   conf = (struct btrace_config *) user_data;
   14688   conf->format = BTRACE_FORMAT_PT;
   14689   conf->pt.size = 0;
   14690 
   14691   size = xml_find_attribute (attributes, "size");
   14692   if (size != NULL)
   14693     conf->pt.size = (unsigned int) *(ULONGEST *) size->value.get ();
   14694 }
   14695 
   14696 static const struct gdb_xml_attribute btrace_conf_pt_attributes[] = {
   14697   { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
   14698   { NULL, GDB_XML_AF_NONE, NULL, NULL }
   14699 };
   14700 
   14701 static const struct gdb_xml_attribute btrace_conf_bts_attributes[] = {
   14702   { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
   14703   { NULL, GDB_XML_AF_NONE, NULL, NULL }
   14704 };
   14705 
   14706 static const struct gdb_xml_element btrace_conf_children[] = {
   14707   { "bts", btrace_conf_bts_attributes, NULL, GDB_XML_EF_OPTIONAL,
   14708     parse_xml_btrace_conf_bts, NULL },
   14709   { "pt", btrace_conf_pt_attributes, NULL, GDB_XML_EF_OPTIONAL,
   14710     parse_xml_btrace_conf_pt, NULL },
   14711   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
   14712 };
   14713 
   14714 static const struct gdb_xml_attribute btrace_conf_attributes[] = {
   14715   { "version", GDB_XML_AF_NONE, NULL, NULL },
   14716   { NULL, GDB_XML_AF_NONE, NULL, NULL }
   14717 };
   14718 
   14719 static const struct gdb_xml_element btrace_conf_elements[] = {
   14720   { "btrace-conf", btrace_conf_attributes, btrace_conf_children,
   14721     GDB_XML_EF_NONE, NULL, NULL },
   14722   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
   14723 };
   14724 
   14725 #endif /* defined (HAVE_LIBEXPAT) */
   14726 
   14727 /* Parse a branch trace configuration xml document XML into CONF.  */
   14728 
   14729 static void
   14730 parse_xml_btrace_conf (struct btrace_config *conf, const char *xml)
   14731 {
   14732 #if defined (HAVE_LIBEXPAT)
   14733 
   14734   int errcode;
   14735   errcode = gdb_xml_parse_quick (_("btrace-conf"), "btrace-conf.dtd",
   14736 				 btrace_conf_elements, xml, conf);
   14737   if (errcode != 0)
   14738     error (_("Error parsing branch trace configuration."));
   14739 
   14740 #else  /* !defined (HAVE_LIBEXPAT) */
   14741 
   14742   error (_("Cannot process the branch trace configuration.  XML support "
   14743 	   "was disabled at compile time."));
   14744 
   14745 #endif  /* !defined (HAVE_LIBEXPAT) */
   14746 }
   14747 
   14748 /* Reset our idea of our target's btrace configuration.  */
   14749 
   14750 static void
   14751 remote_btrace_reset (remote_state *rs)
   14752 {
   14753   memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
   14754 }
   14755 
   14756 /* Synchronize the configuration with the target.  */
   14757 
   14758 void
   14759 remote_target::btrace_sync_conf (const btrace_config *conf)
   14760 {
   14761   struct remote_state *rs;
   14762   char *buf, *pos, *endbuf;
   14763 
   14764   rs = get_remote_state ();
   14765   buf = rs->buf.data ();
   14766   endbuf = buf + get_remote_packet_size ();
   14767 
   14768   if (m_features.packet_support (PACKET_Qbtrace_conf_bts_size) == PACKET_ENABLE
   14769       && conf->bts.size != rs->btrace_config.bts.size)
   14770     {
   14771       pos = buf;
   14772       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
   14773 			packets_descriptions[PACKET_Qbtrace_conf_bts_size].name,
   14774 			conf->bts.size);
   14775 
   14776       putpkt (buf);
   14777       getpkt (&rs->buf);
   14778 
   14779       packet_result result = m_features.packet_ok (buf, PACKET_Qbtrace_conf_bts_size);
   14780       if (result.status () == PACKET_ERROR)
   14781 	error (_("Failed to configure the BTS buffer size: %s"), result.err_msg ());
   14782 
   14783       rs->btrace_config.bts.size = conf->bts.size;
   14784     }
   14785 
   14786   if (m_features.packet_support (PACKET_Qbtrace_conf_pt_size) == PACKET_ENABLE
   14787       && conf->pt.size != rs->btrace_config.pt.size)
   14788     {
   14789       pos = buf;
   14790       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
   14791 			packets_descriptions[PACKET_Qbtrace_conf_pt_size].name,
   14792 			conf->pt.size);
   14793 
   14794       putpkt (buf);
   14795       getpkt (&rs->buf);
   14796 
   14797       packet_result result = m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_size);
   14798       if (result.status () == PACKET_ERROR)
   14799 	error (_("Failed to configure the trace buffer size: %s"), result.err_msg ());
   14800 
   14801       rs->btrace_config.pt.size = conf->pt.size;
   14802     }
   14803 }
   14804 
   14805 /* Read TP's btrace configuration from the target and store it into CONF.  */
   14806 
   14807 static void
   14808 btrace_read_config (thread_info *tp, btrace_config *conf)
   14809 {
   14810   /* target_read_stralloc relies on INFERIOR_PTID.  */
   14811   scoped_restore_current_thread restore_thread;
   14812   switch_to_thread (tp);
   14813 
   14814   std::optional<gdb::char_vector> xml
   14815     = target_read_stralloc (current_inferior ()->top_target (),
   14816 			    TARGET_OBJECT_BTRACE_CONF, "");
   14817   if (xml)
   14818     parse_xml_btrace_conf (conf, xml->data ());
   14819 }
   14820 
   14821 /* Maybe reopen target btrace.  */
   14822 
   14823 void
   14824 remote_target::remote_btrace_maybe_reopen ()
   14825 {
   14826   struct remote_state *rs = get_remote_state ();
   14827   int btrace_target_pushed = 0;
   14828 #if !defined (HAVE_LIBIPT)
   14829   int warned = 0;
   14830 #endif
   14831 
   14832   /* Don't bother walking the entirety of the remote thread list when
   14833      we know the feature isn't supported by the remote.  */
   14834   if (m_features.packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
   14835     return;
   14836 
   14837   for (thread_info *tp : all_non_exited_threads (this))
   14838     {
   14839       memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
   14840       btrace_read_config (tp, &rs->btrace_config);
   14841 
   14842       if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
   14843 	continue;
   14844 
   14845 #if !defined (HAVE_LIBIPT)
   14846       if (rs->btrace_config.format == BTRACE_FORMAT_PT)
   14847 	{
   14848 	  if (!warned)
   14849 	    {
   14850 	      warned = 1;
   14851 	      warning (_("Target is recording using Intel Processor Trace "
   14852 			 "but support was disabled at compile time."));
   14853 	    }
   14854 
   14855 	  continue;
   14856 	}
   14857 #endif /* !defined (HAVE_LIBIPT) */
   14858 
   14859       /* Push target, once, but before anything else happens.  This way our
   14860 	 changes to the threads will be cleaned up by unpushing the target
   14861 	 in case btrace_read_config () throws.  */
   14862       if (!btrace_target_pushed)
   14863 	{
   14864 	  btrace_target_pushed = 1;
   14865 	  record_btrace_push_target ();
   14866 	  gdb_printf (_("Target is recording using %s.\n"),
   14867 		      btrace_format_string (rs->btrace_config.format));
   14868 	}
   14869 
   14870       tp->btrace.target
   14871 	= new btrace_target_info { tp->ptid, rs->btrace_config };
   14872     }
   14873 }
   14874 
   14875 /* Enable branch tracing.  */
   14876 
   14877 struct btrace_target_info *
   14878 remote_target::enable_btrace (thread_info *tp,
   14879 			      const struct btrace_config *conf)
   14880 {
   14881   struct packet_config *packet = NULL;
   14882   struct remote_state *rs = get_remote_state ();
   14883   char *buf = rs->buf.data ();
   14884   char *endbuf = buf + get_remote_packet_size ();
   14885 
   14886   unsigned int which_packet;
   14887   switch (conf->format)
   14888     {
   14889       case BTRACE_FORMAT_BTS:
   14890 	which_packet = PACKET_Qbtrace_bts;
   14891 	break;
   14892       case BTRACE_FORMAT_PT:
   14893 	which_packet = PACKET_Qbtrace_pt;
   14894 	break;
   14895       default:
   14896 	internal_error (_("Bad branch btrace format: %u."),
   14897 			(unsigned int) conf->format);
   14898     }
   14899 
   14900   packet = &m_features.m_protocol_packets[which_packet];
   14901   if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
   14902     error (_("Target does not support branch tracing."));
   14903 
   14904   btrace_sync_conf (conf);
   14905 
   14906   ptid_t ptid = tp->ptid;
   14907   set_general_thread (ptid);
   14908 
   14909   buf += xsnprintf (buf, endbuf - buf, "%s",
   14910 		    packets_descriptions[which_packet].name);
   14911   putpkt (rs->buf);
   14912   getpkt (&rs->buf);
   14913 
   14914   packet_result result = m_features.packet_ok (rs->buf, which_packet);
   14915   if (result.status () == PACKET_ERROR)
   14916     error (_("Could not enable branch tracing for %s: %s"),
   14917 	   target_pid_to_str (ptid).c_str (), result.err_msg ());
   14918 
   14919   btrace_target_info *tinfo = new btrace_target_info { ptid };
   14920 
   14921   /* If we fail to read the configuration, we lose some information, but the
   14922      tracing itself is not impacted.  */
   14923   try
   14924     {
   14925       btrace_read_config (tp, &tinfo->conf);
   14926     }
   14927   catch (const gdb_exception_error &err)
   14928     {
   14929       if (err.message != NULL)
   14930 	warning ("%s", err.what ());
   14931     }
   14932 
   14933   return tinfo;
   14934 }
   14935 
   14936 /* Disable branch tracing.  */
   14937 
   14938 void
   14939 remote_target::disable_btrace (struct btrace_target_info *tinfo)
   14940 {
   14941   struct remote_state *rs = get_remote_state ();
   14942   char *buf = rs->buf.data ();
   14943   char *endbuf = buf + get_remote_packet_size ();
   14944 
   14945   if (m_features.packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
   14946     error (_("Target does not support branch tracing."));
   14947 
   14948   set_general_thread (tinfo->ptid);
   14949 
   14950   buf += xsnprintf (buf, endbuf - buf, "%s",
   14951 		    packets_descriptions[PACKET_Qbtrace_off].name);
   14952   putpkt (rs->buf);
   14953   getpkt (&rs->buf);
   14954 
   14955   packet_result result = m_features.packet_ok (rs->buf, PACKET_Qbtrace_off);
   14956   if (result.status () == PACKET_ERROR)
   14957 	error (_("Could not disable branch tracing for %s: %s"),
   14958 	       target_pid_to_str (tinfo->ptid).c_str (), result.err_msg ());
   14959 
   14960   delete tinfo;
   14961 }
   14962 
   14963 /* Teardown branch tracing.  */
   14964 
   14965 void
   14966 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
   14967 {
   14968   /* We must not talk to the target during teardown.  */
   14969   delete tinfo;
   14970 }
   14971 
   14972 /* Read the branch trace.  */
   14973 
   14974 enum btrace_error
   14975 remote_target::read_btrace (struct btrace_data *btrace,
   14976 			    struct btrace_target_info *tinfo,
   14977 			    enum btrace_read_type type)
   14978 {
   14979   const char *annex;
   14980 
   14981   if (m_features.packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
   14982     error (_("Target does not support branch tracing."));
   14983 
   14984 #if !defined(HAVE_LIBEXPAT)
   14985   error (_("Cannot process branch tracing result. XML parsing not supported."));
   14986 #endif
   14987 
   14988   switch (type)
   14989     {
   14990     case BTRACE_READ_ALL:
   14991       annex = "all";
   14992       break;
   14993     case BTRACE_READ_NEW:
   14994       annex = "new";
   14995       break;
   14996     case BTRACE_READ_DELTA:
   14997       annex = "delta";
   14998       break;
   14999     default:
   15000       internal_error (_("Bad branch tracing read type: %u."),
   15001 		      (unsigned int) type);
   15002     }
   15003 
   15004   std::optional<gdb::char_vector> xml
   15005     = target_read_stralloc (current_inferior ()->top_target (),
   15006 			    TARGET_OBJECT_BTRACE, annex);
   15007   if (!xml)
   15008     return BTRACE_ERR_UNKNOWN;
   15009 
   15010   parse_xml_btrace (btrace, xml->data ());
   15011 
   15012   return BTRACE_ERR_NONE;
   15013 }
   15014 
   15015 const struct btrace_config *
   15016 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
   15017 {
   15018   return &tinfo->conf;
   15019 }
   15020 
   15021 bool
   15022 remote_target::augmented_libraries_svr4_read ()
   15023 {
   15024   return
   15025     (m_features.packet_support (PACKET_augmented_libraries_svr4_read_feature)
   15026      == PACKET_ENABLE);
   15027 }
   15028 
   15029 /* Implementation of to_load.  */
   15030 
   15031 void
   15032 remote_target::load (const char *name, int from_tty)
   15033 {
   15034   generic_load (name, from_tty);
   15035 }
   15036 
   15037 /* Accepts an integer PID; returns a string representing a file that
   15038    can be opened on the remote side to get the symbols for the child
   15039    process.  Returns NULL if the operation is not supported.  */
   15040 
   15041 const char *
   15042 remote_target::pid_to_exec_file (int pid)
   15043 {
   15044   static std::optional<gdb::char_vector> filename;
   15045   char *annex = NULL;
   15046 
   15047   if (m_features.packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
   15048     return NULL;
   15049 
   15050   inferior *inf = find_inferior_pid (this, pid);
   15051   if (inf == NULL)
   15052     internal_error (_("not currently attached to process %d"), pid);
   15053 
   15054   if (!inf->fake_pid_p)
   15055     {
   15056       const int annex_size = 9;
   15057 
   15058       annex = (char *) alloca (annex_size);
   15059       xsnprintf (annex, annex_size, "%x", pid);
   15060     }
   15061 
   15062   filename = target_read_stralloc (current_inferior ()->top_target (),
   15063 				   TARGET_OBJECT_EXEC_FILE, annex);
   15064 
   15065   return filename ? filename->data () : nullptr;
   15066 }
   15067 
   15068 /* Implement the to_can_do_single_step target_ops method.  */
   15069 
   15070 int
   15071 remote_target::can_do_single_step ()
   15072 {
   15073   /* We can only tell whether target supports single step or not by
   15074      supported s and S vCont actions if the stub supports vContSupported
   15075      feature.  If the stub doesn't support vContSupported feature,
   15076      we have conservatively to think target doesn't supports single
   15077      step.  */
   15078   if (m_features.packet_support (PACKET_vContSupported) == PACKET_ENABLE)
   15079     {
   15080       struct remote_state *rs = get_remote_state ();
   15081 
   15082       return rs->supports_vCont.s && rs->supports_vCont.S;
   15083     }
   15084   else
   15085     return 0;
   15086 }
   15087 
   15088 /* Implementation of the to_execution_direction method for the remote
   15089    target.  */
   15090 
   15091 enum exec_direction_kind
   15092 remote_target::execution_direction ()
   15093 {
   15094   struct remote_state *rs = get_remote_state ();
   15095 
   15096   return rs->last_resume_exec_dir;
   15097 }
   15098 
   15099 /* Return pointer to the thread_info struct which corresponds to
   15100    THREAD_HANDLE (having length HANDLE_LEN).  */
   15101 
   15102 thread_info *
   15103 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
   15104 					     int handle_len,
   15105 					     inferior *inf)
   15106 {
   15107   for (thread_info *tp : all_non_exited_threads (this))
   15108     {
   15109       remote_thread_info *priv = get_remote_thread_info (tp);
   15110 
   15111       if (tp->inf == inf && priv != NULL)
   15112 	{
   15113 	  if (handle_len != priv->thread_handle.size ())
   15114 	    error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
   15115 		   handle_len, priv->thread_handle.size ());
   15116 	  if (memcmp (thread_handle, priv->thread_handle.data (),
   15117 		      handle_len) == 0)
   15118 	    return tp;
   15119 	}
   15120     }
   15121 
   15122   return NULL;
   15123 }
   15124 
   15125 gdb::array_view<const gdb_byte>
   15126 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
   15127 {
   15128   remote_thread_info *priv = get_remote_thread_info (tp);
   15129   return priv->thread_handle;
   15130 }
   15131 
   15132 bool
   15133 remote_target::can_async_p ()
   15134 {
   15135   /* This flag should be checked in the common target.c code.  */
   15136   gdb_assert (target_async_permitted);
   15137 
   15138   /* We're async whenever the serial device can.  */
   15139   return get_remote_state ()->can_async_p ();
   15140 }
   15141 
   15142 bool
   15143 remote_target::is_async_p ()
   15144 {
   15145   /* We're async whenever the serial device is.  */
   15146   return get_remote_state ()->is_async_p ();
   15147 }
   15148 
   15149 /* Pass the SERIAL event on and up to the client.  One day this code
   15150    will be able to delay notifying the client of an event until the
   15151    point where an entire packet has been received.  */
   15152 
   15153 static serial_event_ftype remote_async_serial_handler;
   15154 
   15155 static void
   15156 remote_async_serial_handler (struct serial *scb, void *context)
   15157 {
   15158   /* Don't propogate error information up to the client.  Instead let
   15159      the client find out about the error by querying the target.  */
   15160   inferior_event_handler (INF_REG_EVENT);
   15161 }
   15162 
   15163 int
   15164 remote_target::async_wait_fd ()
   15165 {
   15166   struct remote_state *rs = get_remote_state ();
   15167   return rs->remote_desc->fd;
   15168 }
   15169 
   15170 void
   15171 remote_target::async (bool enable)
   15172 {
   15173   struct remote_state *rs = get_remote_state ();
   15174 
   15175   if (enable)
   15176     {
   15177       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
   15178 
   15179       /* If there are pending events in the stop reply queue tell the
   15180 	 event loop to process them.  */
   15181       if (!rs->stop_reply_queue.empty ())
   15182 	rs->mark_async_event_handler ();
   15183 
   15184       /* For simplicity, below we clear the pending events token
   15185 	 without remembering whether it is marked, so here we always
   15186 	 mark it.  If there's actually no pending notification to
   15187 	 process, this ends up being a no-op (other than a spurious
   15188 	 event-loop wakeup).  */
   15189       if (target_is_non_stop_p ())
   15190 	mark_async_event_handler (rs->notif_state->get_pending_events_token);
   15191     }
   15192   else
   15193     {
   15194       serial_async (rs->remote_desc, NULL, NULL);
   15195       /* If the core is disabling async, it doesn't want to be
   15196 	 disturbed with target events.  Clear all async event sources
   15197 	 too.  */
   15198       rs->clear_async_event_handler ();
   15199 
   15200       if (target_is_non_stop_p ())
   15201 	clear_async_event_handler (rs->notif_state->get_pending_events_token);
   15202     }
   15203 }
   15204 
   15205 /* Implementation of the to_thread_events method.  */
   15206 
   15207 void
   15208 remote_target::thread_events (int enable)
   15209 {
   15210   struct remote_state *rs = get_remote_state ();
   15211   size_t size = get_remote_packet_size ();
   15212 
   15213   if (m_features.packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
   15214     return;
   15215 
   15216   if (rs->last_thread_events == enable)
   15217     return;
   15218 
   15219   xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
   15220   putpkt (rs->buf);
   15221   getpkt (&rs->buf);
   15222 
   15223   packet_result result = m_features.packet_ok (rs->buf, PACKET_QThreadEvents);
   15224   switch (result.status ())
   15225     {
   15226     case PACKET_OK:
   15227       if (strcmp (rs->buf.data (), "OK") != 0)
   15228 	error (_("Remote refused setting thread events: %s"), rs->buf.data ());
   15229       rs->last_thread_events = enable;
   15230       break;
   15231     case PACKET_ERROR:
   15232       warning (_("Remote failure reply: %s"), result.err_msg ());
   15233       break;
   15234     case PACKET_UNKNOWN:
   15235       break;
   15236     }
   15237 }
   15238 
   15239 /* Implementation of the supports_set_thread_options target
   15240    method.  */
   15241 
   15242 bool
   15243 remote_target::supports_set_thread_options (gdb_thread_options options)
   15244 {
   15245   remote_state *rs = get_remote_state ();
   15246   return (m_features.packet_support (PACKET_QThreadOptions) == PACKET_ENABLE
   15247 	  && (rs->supported_thread_options & options) == options);
   15248 }
   15249 
   15250 /* For coalescing reasons, actually sending the options to the target
   15251    happens at resume time, via this function.  See target_resume for
   15252    all-stop, and target_commit_resumed for non-stop.  */
   15253 
   15254 void
   15255 remote_target::commit_requested_thread_options ()
   15256 {
   15257   struct remote_state *rs = get_remote_state ();
   15258 
   15259   if (m_features.packet_support (PACKET_QThreadOptions) != PACKET_ENABLE)
   15260     return;
   15261 
   15262   char *p = rs->buf.data ();
   15263   char *endp = p + get_remote_packet_size ();
   15264 
   15265   /* Clear options for all threads by default.  Note that unlike
   15266      vCont, the rightmost options that match a thread apply, so we
   15267      don't have to worry about whether we can use wildcard ptids.  */
   15268   strcpy (p, "QThreadOptions;0");
   15269   p += strlen (p);
   15270 
   15271   /* Send the QThreadOptions packet stored in P.  */
   15272   auto flush = [&] ()
   15273     {
   15274       *p++ = '\0';
   15275 
   15276       putpkt (rs->buf);
   15277       getpkt (&rs->buf, 0);
   15278 
   15279       packet_result result = m_features.packet_ok (rs->buf, PACKET_QThreadOptions);
   15280       switch (result.status ())
   15281 	{
   15282 	case PACKET_OK:
   15283 	  if (strcmp (rs->buf.data (), "OK") != 0)
   15284 	    error (_("Remote refused setting thread options: %s"), rs->buf.data ());
   15285 	  break;
   15286 	case PACKET_ERROR:
   15287 	  error (_("Remote failure reply: %s"), result.err_msg ());
   15288 	case PACKET_UNKNOWN:
   15289 	  gdb_assert_not_reached ("PACKET_UNKNOWN");
   15290 	  break;
   15291 	}
   15292     };
   15293 
   15294   /* Prepare P for another QThreadOptions packet.  */
   15295   auto restart = [&] ()
   15296     {
   15297       p = rs->buf.data ();
   15298       strcpy (p, "QThreadOptions");
   15299       p += strlen (p);
   15300     };
   15301 
   15302   /* Now set non-zero options for threads that need them.  We don't
   15303      bother with the case of all threads of a process wanting the same
   15304      non-zero options as that's not an expected scenario.  */
   15305   for (thread_info *tp : all_non_exited_threads (this))
   15306     {
   15307       gdb_thread_options options = tp->thread_options ();
   15308 
   15309       if (options == 0)
   15310 	continue;
   15311 
   15312       /* It might be possible to we have more threads with options
   15313 	 than can fit a single QThreadOptions packet.  So build each
   15314 	 options/thread pair in this separate buffer to make sure it
   15315 	 fits.  */
   15316       constexpr size_t max_options_size = 100;
   15317       char obuf[max_options_size];
   15318       char *obuf_p = obuf;
   15319       char *obuf_endp = obuf + max_options_size;
   15320 
   15321       *obuf_p++ = ';';
   15322       obuf_p += xsnprintf (obuf_p, obuf_endp - obuf_p, "%s",
   15323 			   phex_nz (options, sizeof (options)));
   15324       if (tp->ptid != magic_null_ptid)
   15325 	{
   15326 	  *obuf_p++ = ':';
   15327 	  obuf_p = write_ptid (obuf_p, obuf_endp, tp->ptid);
   15328 	}
   15329 
   15330       size_t osize = obuf_p - obuf;
   15331       if (osize > endp - p)
   15332 	{
   15333 	  /* This new options/thread pair doesn't fit the packet
   15334 	     buffer.  Send what we have already.  */
   15335 	  flush ();
   15336 	  restart ();
   15337 
   15338 	  /* Should now fit.  */
   15339 	  gdb_assert (osize <= endp - p);
   15340 	}
   15341 
   15342       memcpy (p, obuf, osize);
   15343       p += osize;
   15344     }
   15345 
   15346   flush ();
   15347 }
   15348 
   15349 static void
   15350 show_remote_cmd (const char *args, int from_tty)
   15351 {
   15352   /* We can't just use cmd_show_list here, because we want to skip
   15353      the redundant "show remote Z-packet" and the legacy aliases.  */
   15354   struct cmd_list_element *list = remote_show_cmdlist;
   15355   struct ui_out *uiout = current_uiout;
   15356 
   15357   ui_out_emit_tuple tuple_emitter (uiout, "showlist");
   15358   for (; list != NULL; list = list->next)
   15359     if (strcmp (list->name, "Z-packet") == 0)
   15360       continue;
   15361     else if (list->type == not_set_cmd)
   15362       /* Alias commands are exactly like the original, except they
   15363 	 don't have the normal type.  */
   15364       continue;
   15365     else
   15366       {
   15367 	ui_out_emit_tuple option_emitter (uiout, "option");
   15368 
   15369 	uiout->field_string ("name", list->name);
   15370 	uiout->text (":  ");
   15371 	if (list->type == show_cmd)
   15372 	  do_show_command (NULL, from_tty, list);
   15373 	else
   15374 	  cmd_func (list, NULL, from_tty);
   15375       }
   15376 }
   15377 
   15378 /* Some change happened in PSPACE's objfile list (obfiles added or removed),
   15379    offer all inferiors using that program space a change to look up symbols.  */
   15380 
   15381 static void
   15382 remote_objfile_changed_check_symbols (program_space *pspace)
   15383 {
   15384   /* The affected program space is possibly shared by multiple inferiors.
   15385      Consider sending a qSymbol packet for each of the inferiors using that
   15386      program space.  */
   15387   for (inferior *inf : all_inferiors ())
   15388     {
   15389       if (inf->pspace != pspace)
   15390 	continue;
   15391 
   15392       /* Check whether the inferior's process target is a remote target.  */
   15393       remote_target *remote = as_remote_target (inf->process_target ());
   15394       if (remote == nullptr)
   15395 	continue;
   15396 
   15397       /* When we are attaching or handling a fork child and the shared library
   15398 	 subsystem reads the list of loaded libraries, we receive new objfile
   15399 	 events in between each found library.  The libraries are read in an
   15400 	 undefined order, so if we gave the remote side a chance to look up
   15401 	 symbols between each objfile, we might give it an inconsistent picture
   15402 	 of the inferior.  It could appear that a library A appears loaded but
   15403 	 a library B does not, even though library A requires library B.  That
   15404 	 would present a state that couldn't normally exist in the inferior.
   15405 
   15406 	 So, skip these events, we'll give the remote a chance to look up
   15407 	 symbols once all the loaded libraries and their symbols are known to
   15408 	 GDB.  */
   15409       if (inf->in_initial_library_scan)
   15410 	continue;
   15411 
   15412       if (!remote->has_execution (inf))
   15413 	continue;
   15414 
   15415       /* Need to switch to a specific thread, because remote_check_symbols will
   15416 	 set the general thread using INFERIOR_PTID.
   15417 
   15418 	 It's possible to have inferiors with no thread here, because we are
   15419 	 called very early in the connection process, while the inferior is
   15420 	 being set up, before threads are added.  Just skip it, start_remote_1
   15421 	 also calls remote_check_symbols when it's done setting things up.  */
   15422       thread_info *thread = any_thread_of_inferior (inf);
   15423       if (thread != nullptr)
   15424 	{
   15425 	  scoped_restore_current_thread restore_thread;
   15426 	  switch_to_thread (thread);
   15427 	  remote->remote_check_symbols ();
   15428 	}
   15429   }
   15430 }
   15431 
   15432 /* Function to be called whenever a new objfile (shlib) is detected.  */
   15433 
   15434 static void
   15435 remote_new_objfile (struct objfile *objfile)
   15436 {
   15437   remote_objfile_changed_check_symbols (objfile->pspace);
   15438 }
   15439 
   15440 /* Pull all the tracepoints defined on the target and create local
   15441    data structures representing them.  We don't want to create real
   15442    tracepoints yet, we don't want to mess up the user's existing
   15443    collection.  */
   15444 
   15445 int
   15446 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
   15447 {
   15448   struct remote_state *rs = get_remote_state ();
   15449   char *p;
   15450 
   15451   /* Ask for a first packet of tracepoint definition.  */
   15452   putpkt ("qTfP");
   15453   getpkt (&rs->buf);
   15454   p = rs->buf.data ();
   15455   while (*p && *p != 'l')
   15456     {
   15457       parse_tracepoint_definition (p, utpp);
   15458       /* Ask for another packet of tracepoint definition.  */
   15459       putpkt ("qTsP");
   15460       getpkt (&rs->buf);
   15461       p = rs->buf.data ();
   15462     }
   15463   return 0;
   15464 }
   15465 
   15466 int
   15467 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
   15468 {
   15469   struct remote_state *rs = get_remote_state ();
   15470   char *p;
   15471 
   15472   /* Ask for a first packet of variable definition.  */
   15473   putpkt ("qTfV");
   15474   getpkt (&rs->buf);
   15475   p = rs->buf.data ();
   15476   while (*p && *p != 'l')
   15477     {
   15478       parse_tsv_definition (p, utsvp);
   15479       /* Ask for another packet of variable definition.  */
   15480       putpkt ("qTsV");
   15481       getpkt (&rs->buf);
   15482       p = rs->buf.data ();
   15483     }
   15484   return 0;
   15485 }
   15486 
   15487 /* The "set/show range-stepping" show hook.  */
   15488 
   15489 static void
   15490 show_range_stepping (struct ui_file *file, int from_tty,
   15491 		     struct cmd_list_element *c,
   15492 		     const char *value)
   15493 {
   15494   gdb_printf (file,
   15495 	      _("Debugger's willingness to use range stepping "
   15496 		"is %s.\n"), value);
   15497 }
   15498 
   15499 /* Return true if the vCont;r action is supported by the remote
   15500    stub.  */
   15501 
   15502 bool
   15503 remote_target::vcont_r_supported ()
   15504 {
   15505   return (m_features.packet_support (PACKET_vCont) == PACKET_ENABLE
   15506 	  && get_remote_state ()->supports_vCont.r);
   15507 }
   15508 
   15509 /* The "set/show range-stepping" set hook.  */
   15510 
   15511 static void
   15512 set_range_stepping (const char *ignore_args, int from_tty,
   15513 		    struct cmd_list_element *c)
   15514 {
   15515   /* When enabling, check whether range stepping is actually supported
   15516      by the target, and warn if not.  */
   15517   if (use_range_stepping)
   15518     {
   15519       remote_target *remote = get_current_remote_target ();
   15520       if (remote == NULL
   15521 	  || !remote->vcont_r_supported ())
   15522 	warning (_("Range stepping is not supported by the current target"));
   15523     }
   15524 }
   15525 
   15526 static void
   15527 show_remote_debug (struct ui_file *file, int from_tty,
   15528 		   struct cmd_list_element *c, const char *value)
   15529 {
   15530   gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
   15531 	      value);
   15532 }
   15533 
   15534 static void
   15535 show_remote_timeout (struct ui_file *file, int from_tty,
   15536 		     struct cmd_list_element *c, const char *value)
   15537 {
   15538   gdb_printf (file,
   15539 	      _("Timeout limit to wait for target to respond is %s.\n"),
   15540 	      value);
   15541 }
   15542 
   15543 /* Implement the "supports_memory_tagging" target_ops method.  */
   15544 
   15545 bool
   15546 remote_target::supports_memory_tagging ()
   15547 {
   15548   return m_features.remote_memory_tagging_p ();
   15549 }
   15550 
   15551 /* Create the qMemTags packet given ADDRESS, LEN and TYPE.  */
   15552 
   15553 static void
   15554 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
   15555 			      size_t len, int type)
   15556 {
   15557   int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
   15558 
   15559   std::string request = string_printf ("qMemTags:%s,%s:%s",
   15560 				       phex_nz (address, addr_size),
   15561 				       phex_nz (len, sizeof (len)),
   15562 				       phex_nz (type, sizeof (type)));
   15563 
   15564   strcpy (packet.data (), request.c_str ());
   15565 }
   15566 
   15567 /* Parse the qMemTags packet reply into TAGS.
   15568 
   15569    Return true if successful, false otherwise.  */
   15570 
   15571 static bool
   15572 parse_fetch_memtags_reply (const gdb::char_vector &reply,
   15573 			   gdb::byte_vector &tags)
   15574 {
   15575   if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
   15576     return false;
   15577 
   15578   /* Copy the tag data.  */
   15579   tags = hex2bin (reply.data () + 1);
   15580 
   15581   return true;
   15582 }
   15583 
   15584 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS.  */
   15585 
   15586 static void
   15587 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
   15588 			      size_t len, int type,
   15589 			      const gdb::byte_vector &tags)
   15590 {
   15591   int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
   15592 
   15593   /* Put together the main packet, address and length.  */
   15594   std::string request = string_printf ("QMemTags:%s,%s:%s:",
   15595 				       phex_nz (address, addr_size),
   15596 				       phex_nz (len, sizeof (len)),
   15597 				       phex_nz (type, sizeof (type)));
   15598   request += bin2hex (tags.data (), tags.size ());
   15599 
   15600   /* Check if we have exceeded the maximum packet size.  */
   15601   if (packet.size () < request.length ())
   15602     error (_("Contents too big for packet QMemTags."));
   15603 
   15604   strcpy (packet.data (), request.c_str ());
   15605 }
   15606 
   15607 static void
   15608 create_is_address_tagged_request (gdbarch *gdbarch, gdb::char_vector &packet,
   15609 				  CORE_ADDR address)
   15610 {
   15611   int addr_size;
   15612   std::string request;
   15613 
   15614   addr_size = gdbarch_addr_bit (gdbarch) / 8;
   15615   request = string_printf ("qIsAddressTagged:%s", phex_nz (address, addr_size));
   15616 
   15617   if (packet.size () < request.length () + 1)
   15618     error (_("Contents too big for packet qIsAddressTagged."));
   15619 
   15620   strcpy (packet.data (), request.c_str ());
   15621 }
   15622 
   15623 static bool
   15624 check_is_address_tagged_reply (remote_target *remote, gdb::char_vector &packet,
   15625 			       bool &tagged)
   15626 {
   15627   gdb_assert (remote != nullptr);
   15628   /* Check reply and disable qIsAddressTagged usage if it's not supported.  */
   15629   packet_result result = remote->m_features.packet_ok (packet,
   15630 						       PACKET_qIsAddressTagged);
   15631 
   15632   /* Return false on error (Exx), empty reply (packet not supported), or reply
   15633      size doesn't match 2 hex digits.  */
   15634   if ((result.status () != PACKET_OK) || (strlen (packet.data ()) != 2))
   15635     return false;
   15636 
   15637   gdb_byte reply;
   15638   /* Convert only 2 hex digits, i.e. 1 byte in hex format.  */
   15639   hex2bin (packet.data (), &reply, 1);
   15640 
   15641   if (reply == 0x00 || reply == 0x01)
   15642     {
   15643       tagged = !!reply;
   15644       return true;
   15645     }
   15646 
   15647   /* Invalid reply.  */
   15648   return false;
   15649 }
   15650 
   15651 /* Implement the "fetch_memtags" target_ops method.  */
   15652 
   15653 bool
   15654 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
   15655 			      gdb::byte_vector &tags, int type)
   15656 {
   15657   /* Make sure the qMemTags packet is supported.  */
   15658   if (!m_features.remote_memory_tagging_p ())
   15659     gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
   15660 
   15661   struct remote_state *rs = get_remote_state ();
   15662 
   15663   create_fetch_memtags_request (rs->buf, address, len, type);
   15664 
   15665   putpkt (rs->buf);
   15666   getpkt (&rs->buf);
   15667 
   15668   return parse_fetch_memtags_reply (rs->buf, tags);
   15669 }
   15670 
   15671 /* Implement the "store_memtags" target_ops method.  */
   15672 
   15673 bool
   15674 remote_target::store_memtags (CORE_ADDR address, size_t len,
   15675 			      const gdb::byte_vector &tags, int type)
   15676 {
   15677   /* Make sure the QMemTags packet is supported.  */
   15678   if (!m_features.remote_memory_tagging_p ())
   15679     gdb_assert_not_reached ("remote store_memtags called with packet disabled");
   15680 
   15681   struct remote_state *rs = get_remote_state ();
   15682 
   15683   create_store_memtags_request (rs->buf, address, len, type, tags);
   15684 
   15685   putpkt (rs->buf);
   15686   getpkt (&rs->buf);
   15687 
   15688   /* Verify if the request was successful.  */
   15689   return packet_check_result (rs->buf, true).status () == PACKET_OK;
   15690 }
   15691 
   15692 /* Implement the "is_address_tagged" target_ops method.  */
   15693 
   15694 bool
   15695 remote_target::is_address_tagged (gdbarch *gdbarch, CORE_ADDR address)
   15696 {
   15697   /* Firstly, attempt to check the address using the qIsAddressTagged
   15698      packet.  */
   15699   if (m_features.packet_support (PACKET_qIsAddressTagged) != PACKET_DISABLE)
   15700     {
   15701       remote_target *remote = get_current_remote_target ();
   15702       struct remote_state *rs = get_remote_state ();
   15703       bool is_addr_tagged;
   15704 
   15705       create_is_address_tagged_request (gdbarch, rs->buf, address);
   15706 
   15707       putpkt (rs->buf);
   15708       getpkt (&rs->buf);
   15709 
   15710       /* If qIsAddressTagged is not supported PACKET_qIsAddressTagged will be
   15711 	 set to PACKET_DISABLE so no further attempt is made to check addresses
   15712 	 using this packet and the fallback mechanism below will be used
   15713 	 instead.  Also, if the check fails due to an error (Exx reply) the
   15714 	 fallback is used too.  Otherwise, the qIsAddressTagged query succeeded
   15715 	 and is_addr_tagged is valid.  */
   15716       if (check_is_address_tagged_reply (remote, rs->buf, is_addr_tagged))
   15717 	return is_addr_tagged;
   15718     }
   15719 
   15720   /* Fallback to arch-specific method of checking whether an address is tagged
   15721      in case check via qIsAddressTagged fails.  */
   15722   return gdbarch_tagged_address_p (gdbarch, address);
   15723 }
   15724 
   15725 /* Return true if remote target T is non-stop.  */
   15726 
   15727 bool
   15728 remote_target_is_non_stop_p (remote_target *t)
   15729 {
   15730   scoped_restore_current_thread restore_thread;
   15731   switch_to_target_no_thread (t);
   15732 
   15733   return target_is_non_stop_p ();
   15734 }
   15735 
   15736 #if GDB_SELF_TEST
   15737 
   15738 namespace selftests {
   15739 
   15740 static void
   15741 test_memory_tagging_functions ()
   15742 {
   15743   remote_target remote;
   15744 
   15745   struct packet_config *config
   15746     = &remote.m_features.m_protocol_packets[PACKET_memory_tagging_feature];
   15747 
   15748   scoped_restore restore_memtag_support_
   15749     = make_scoped_restore (&config->support);
   15750 
   15751   struct gdbarch *gdbarch = current_inferior ()->arch ();
   15752 
   15753   /* Test memory tagging packet support.  */
   15754   config->support = PACKET_SUPPORT_UNKNOWN;
   15755   SELF_CHECK (remote.supports_memory_tagging () == false);
   15756   config->support = PACKET_DISABLE;
   15757   SELF_CHECK (remote.supports_memory_tagging () == false);
   15758   config->support = PACKET_ENABLE;
   15759   SELF_CHECK (remote.supports_memory_tagging () == true);
   15760 
   15761   /* Setup testing.  */
   15762   gdb::char_vector packet;
   15763   gdb::byte_vector tags, bv;
   15764   std::string expected, reply;
   15765   packet.resize (32000);
   15766 
   15767   /* Test creating a qMemTags request.  */
   15768 
   15769   expected = "qMemTags:0,0:0";
   15770   create_fetch_memtags_request (packet, 0x0, 0x0, 0);
   15771   SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
   15772 
   15773   expected = "qMemTags:deadbeef,10:1";
   15774   create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
   15775   SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
   15776 
   15777   /* Test parsing a qMemTags reply.  */
   15778 
   15779   /* Error reply, tags vector unmodified.  */
   15780   reply = "E00";
   15781   strcpy (packet.data (), reply.c_str ());
   15782   tags.resize (0);
   15783   SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
   15784   SELF_CHECK (tags.size () == 0);
   15785 
   15786   /* Valid reply, tags vector updated.  */
   15787   tags.resize (0);
   15788   bv.resize (0);
   15789 
   15790   for (int i = 0; i < 5; i++)
   15791     bv.push_back (i);
   15792 
   15793   reply = "m" + bin2hex (bv.data (), bv.size ());
   15794   strcpy (packet.data (), reply.c_str ());
   15795 
   15796   SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
   15797   SELF_CHECK (tags.size () == 5);
   15798 
   15799   for (int i = 0; i < 5; i++)
   15800     SELF_CHECK (tags[i] == i);
   15801 
   15802   /* Test creating a QMemTags request.  */
   15803 
   15804   /* Empty tag data.  */
   15805   tags.resize (0);
   15806   expected = "QMemTags:0,0:0:";
   15807   create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
   15808   SELF_CHECK (memcmp (packet.data (), expected.c_str (),
   15809 		      expected.length ()) == 0);
   15810 
   15811   /* Non-empty tag data.  */
   15812   tags.resize (0);
   15813   for (int i = 0; i < 5; i++)
   15814     tags.push_back (i);
   15815   expected = "QMemTags:deadbeef,ff:1:0001020304";
   15816   create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
   15817   SELF_CHECK (memcmp (packet.data (), expected.c_str (),
   15818 		      expected.length ()) == 0);
   15819 
   15820   /* Test creating a qIsAddressTagged request.  */
   15821   expected = "qIsAddressTagged:deadbeef";
   15822   create_is_address_tagged_request (gdbarch, packet, 0xdeadbeef);
   15823   SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
   15824 
   15825   /* Test error reply on qIsAddressTagged request.  */
   15826   reply = "E00";
   15827   strcpy (packet.data (), reply.c_str ());
   15828   /* is_tagged must not change, hence it's tested too.  */
   15829   bool is_tagged = false;
   15830   SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
   15831 	      false);
   15832   SELF_CHECK (is_tagged == false);
   15833 
   15834   /* Test 'tagged' as reply.  */
   15835   reply = "01";
   15836   strcpy (packet.data (), reply.c_str ());
   15837   /* Because the byte is 01, is_tagged should be set to true.  */
   15838   is_tagged = false;
   15839   SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
   15840 	      true);
   15841   SELF_CHECK (is_tagged == true);
   15842 
   15843   /* Test 'not tagged' as reply.  */
   15844   reply = "00";
   15845   strcpy (packet.data (), reply.c_str ());
   15846   /* Because the byte is 00, is_tagged should be set to false.  */
   15847   is_tagged = true;
   15848   SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
   15849 	      true);
   15850   SELF_CHECK (is_tagged == false);
   15851 
   15852   /* Test an invalid reply (neither 00 nor 01).  */
   15853   reply = "04";
   15854   strcpy (packet.data (), reply.c_str ());
   15855   /* Because the byte is invalid is_tagged must not change.  */
   15856   is_tagged = false;
   15857   SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
   15858 	      false);
   15859   SELF_CHECK (is_tagged == false);
   15860 
   15861   /* Test malformed reply of incorrect length.  */
   15862   reply = "0104A590001234006";
   15863   strcpy (packet.data (), reply.c_str ());
   15864   /* Because this is a malformed reply is_tagged must not change.  */
   15865   is_tagged = false;
   15866   SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
   15867 	      false);
   15868   SELF_CHECK (is_tagged == false);
   15869 
   15870   /* Test empty reply.  */
   15871   reply = "";
   15872   strcpy (packet.data (), reply.c_str ());
   15873   /* is_tagged must not change, hence it's tested too.  */
   15874   is_tagged = true;
   15875   /* On the previous tests, qIsAddressTagged packet was auto detected and set
   15876      as supported.  But an empty reply means the packet is unsupported, so for
   15877      testing the empty reply the support is reset to unknown state, otherwise
   15878      packet_ok will complain.   */
   15879   remote.m_features.m_protocol_packets[PACKET_qIsAddressTagged].support =
   15880     PACKET_SUPPORT_UNKNOWN;
   15881   SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
   15882 	      false);
   15883   SELF_CHECK (is_tagged == true);
   15884 }
   15885 
   15886 static void
   15887 test_packet_check_result ()
   15888 {
   15889   std::string buf = "E.msg";
   15890   packet_result result = packet_check_result (buf.data (), true);
   15891 
   15892   SELF_CHECK (result.status () == PACKET_ERROR);
   15893   SELF_CHECK (strcmp(result.err_msg (), "msg") == 0);
   15894 
   15895   result = packet_check_result ("E01", true);
   15896   SELF_CHECK (result.status () == PACKET_ERROR);
   15897   SELF_CHECK (strcmp(result.err_msg (), "01") == 0);
   15898 
   15899   SELF_CHECK (packet_check_result ("E1", true).status () == PACKET_OK);
   15900 
   15901   SELF_CHECK (packet_check_result ("E000", true).status () == PACKET_OK);
   15902 
   15903   result = packet_check_result ("E.", true);
   15904   SELF_CHECK (result.status () == PACKET_ERROR);
   15905   SELF_CHECK (strcmp(result.err_msg (), "no error provided") == 0);
   15906 
   15907   SELF_CHECK (packet_check_result ("some response", true).status () == PACKET_OK);
   15908 
   15909   SELF_CHECK (packet_check_result ("", true).status () == PACKET_UNKNOWN);
   15910 
   15911   result = packet_check_result ("E.msg", false);
   15912   SELF_CHECK (result.status () == PACKET_OK);
   15913 }
   15914 } // namespace selftests
   15915 #endif /* GDB_SELF_TEST */
   15916 
   15917 void _initialize_remote ();
   15918 void
   15919 _initialize_remote ()
   15920 {
   15921   add_target (remote_target_info, remote_target::open);
   15922   add_target (extended_remote_target_info, extended_remote_target::open);
   15923 
   15924   /* Hook into new objfile notification.  */
   15925   gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
   15926   gdb::observers::all_objfiles_removed.attach
   15927     (remote_objfile_changed_check_symbols, "remote");
   15928 
   15929 #if 0
   15930   init_remote_threadtests ();
   15931 #endif
   15932 
   15933   /* set/show remote ...  */
   15934 
   15935   add_basic_prefix_cmd ("remote", class_maintenance, _("\
   15936 Remote protocol specific variables.\n\
   15937 Configure various remote-protocol specific variables such as\n\
   15938 the packets being used."),
   15939 			&remote_set_cmdlist,
   15940 			0 /* allow-unknown */, &setlist);
   15941   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
   15942 Remote protocol specific variables.\n\
   15943 Configure various remote-protocol specific variables such as\n\
   15944 the packets being used."),
   15945 		  &remote_show_cmdlist,
   15946 		  0 /* allow-unknown */, &showlist);
   15947 
   15948   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
   15949 Compare section data on target to the exec file.\n\
   15950 Argument is a single section name (default: all loaded sections).\n\
   15951 To compare only read-only loaded sections, specify the -r option."),
   15952 	   &cmdlist);
   15953 
   15954   add_cmd ("packet", class_maintenance, cli_packet_command, _("\
   15955 Send an arbitrary packet to a remote target.\n\
   15956    maintenance packet TEXT\n\
   15957 If GDB is talking to an inferior via the GDB serial protocol, then\n\
   15958 this command sends the string TEXT to the inferior, and displays the\n\
   15959 response packet.  GDB supplies the initial `$' character, and the\n\
   15960 terminating `#' character and checksum."),
   15961 	   &maintenancelist);
   15962 
   15963   set_show_commands remotebreak_cmds
   15964     = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
   15965 Set whether to send break if interrupted."), _("\
   15966 Show whether to send break if interrupted."), _("\
   15967 If set, a break, instead of a cntrl-c, is sent to the remote target."),
   15968 			       set_remotebreak, show_remotebreak,
   15969 			       &setlist, &showlist);
   15970   deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
   15971   deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
   15972 
   15973   add_setshow_enum_cmd ("interrupt-sequence", class_support,
   15974 			interrupt_sequence_modes, &interrupt_sequence_mode,
   15975 			_("\
   15976 Set interrupt sequence to remote target."), _("\
   15977 Show interrupt sequence to remote target."), _("\
   15978 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
   15979 			NULL, show_interrupt_sequence,
   15980 			&remote_set_cmdlist,
   15981 			&remote_show_cmdlist);
   15982 
   15983   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
   15984 			   &interrupt_on_connect, _("\
   15985 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
   15986 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
   15987 If set, interrupt sequence is sent to remote target."),
   15988 			   NULL, NULL,
   15989 			   &remote_set_cmdlist, &remote_show_cmdlist);
   15990 
   15991   /* Install commands for configuring memory read/write packets.  */
   15992 
   15993   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
   15994 Set the maximum number of bytes per memory write packet (deprecated)."),
   15995 	   &setlist);
   15996   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
   15997 Show the maximum number of bytes per memory write packet (deprecated)."),
   15998 	   &showlist);
   15999   add_cmd ("memory-write-packet-size", no_class,
   16000 	   set_memory_write_packet_size, _("\
   16001 Set the maximum number of bytes per memory-write packet.\n\
   16002 Specify the number of bytes in a packet or 0 (zero) for the\n\
   16003 default packet size.  The actual limit is further reduced\n\
   16004 dependent on the target.  Specify \"fixed\" to disable the\n\
   16005 further restriction and \"limit\" to enable that restriction."),
   16006 	   &remote_set_cmdlist);
   16007   add_cmd ("memory-read-packet-size", no_class,
   16008 	   set_memory_read_packet_size, _("\
   16009 Set the maximum number of bytes per memory-read packet.\n\
   16010 Specify the number of bytes in a packet or 0 (zero) for the\n\
   16011 default packet size.  The actual limit is further reduced\n\
   16012 dependent on the target.  Specify \"fixed\" to disable the\n\
   16013 further restriction and \"limit\" to enable that restriction."),
   16014 	   &remote_set_cmdlist);
   16015   add_cmd ("memory-write-packet-size", no_class,
   16016 	   show_memory_write_packet_size,
   16017 	   _("Show the maximum number of bytes per memory-write packet."),
   16018 	   &remote_show_cmdlist);
   16019   add_cmd ("memory-read-packet-size", no_class,
   16020 	   show_memory_read_packet_size,
   16021 	   _("Show the maximum number of bytes per memory-read packet."),
   16022 	   &remote_show_cmdlist);
   16023 
   16024   add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
   16025 			    &remote_hw_watchpoint_limit, _("\
   16026 Set the maximum number of target hardware watchpoints."), _("\
   16027 Show the maximum number of target hardware watchpoints."), _("\
   16028 Specify \"unlimited\" for unlimited hardware watchpoints."),
   16029 			    NULL, show_hardware_watchpoint_limit,
   16030 			    &remote_set_cmdlist,
   16031 			    &remote_show_cmdlist);
   16032   add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
   16033 			    no_class,
   16034 			    &remote_hw_watchpoint_length_limit, _("\
   16035 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
   16036 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
   16037 Specify \"unlimited\" to allow watchpoints of unlimited size."),
   16038 			    NULL, show_hardware_watchpoint_length_limit,
   16039 			    &remote_set_cmdlist, &remote_show_cmdlist);
   16040   add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
   16041 			    &remote_hw_breakpoint_limit, _("\
   16042 Set the maximum number of target hardware breakpoints."), _("\
   16043 Show the maximum number of target hardware breakpoints."), _("\
   16044 Specify \"unlimited\" for unlimited hardware breakpoints."),
   16045 			    NULL, show_hardware_breakpoint_limit,
   16046 			    &remote_set_cmdlist, &remote_show_cmdlist);
   16047 
   16048   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
   16049 			     &remote_address_size, _("\
   16050 Set the maximum size of the address (in bits) in a memory packet."), _("\
   16051 Show the maximum size of the address (in bits) in a memory packet."), NULL,
   16052 			     NULL,
   16053 			     NULL, /* FIXME: i18n: */
   16054 			     &setlist, &showlist);
   16055 
   16056   init_all_packet_configs ();
   16057 
   16058   add_packet_config_cmd (PACKET_X, "X", "binary-download", 1);
   16059 
   16060   add_packet_config_cmd (PACKET_vCont, "vCont", "verbose-resume", 0);
   16061 
   16062   add_packet_config_cmd (PACKET_QPassSignals, "QPassSignals", "pass-signals",
   16063 			 0);
   16064 
   16065   add_packet_config_cmd (PACKET_QCatchSyscalls, "QCatchSyscalls",
   16066 			 "catch-syscalls", 0);
   16067 
   16068   add_packet_config_cmd (PACKET_QProgramSignals, "QProgramSignals",
   16069 			 "program-signals", 0);
   16070 
   16071   add_packet_config_cmd (PACKET_QSetWorkingDir, "QSetWorkingDir",
   16072 			 "set-working-dir", 0);
   16073 
   16074   add_packet_config_cmd (PACKET_QStartupWithShell, "QStartupWithShell",
   16075 			 "startup-with-shell", 0);
   16076 
   16077   add_packet_config_cmd (PACKET_QEnvironmentHexEncoded,"QEnvironmentHexEncoded",
   16078 			 "environment-hex-encoded", 0);
   16079 
   16080   add_packet_config_cmd (PACKET_QEnvironmentReset, "QEnvironmentReset",
   16081 			 "environment-reset", 0);
   16082 
   16083   add_packet_config_cmd (PACKET_QEnvironmentUnset, "QEnvironmentUnset",
   16084 			 "environment-unset", 0);
   16085 
   16086   add_packet_config_cmd (PACKET_qSymbol, "qSymbol", "symbol-lookup", 0);
   16087 
   16088   add_packet_config_cmd (PACKET_P, "P", "set-register", 1);
   16089 
   16090   add_packet_config_cmd (PACKET_p, "p", "fetch-register", 1);
   16091 
   16092   add_packet_config_cmd (PACKET_Z0, "Z0", "software-breakpoint", 0);
   16093 
   16094   add_packet_config_cmd (PACKET_Z1, "Z1", "hardware-breakpoint", 0);
   16095 
   16096   add_packet_config_cmd (PACKET_Z2, "Z2", "write-watchpoint", 0);
   16097 
   16098   add_packet_config_cmd (PACKET_Z3, "Z3", "read-watchpoint", 0);
   16099 
   16100   add_packet_config_cmd (PACKET_Z4, "Z4", "access-watchpoint", 0);
   16101 
   16102   add_packet_config_cmd (PACKET_qXfer_auxv, "qXfer:auxv:read",
   16103 			 "read-aux-vector", 0);
   16104 
   16105   add_packet_config_cmd (PACKET_qXfer_exec_file, "qXfer:exec-file:read",
   16106 			 "pid-to-exec-file", 0);
   16107 
   16108   add_packet_config_cmd (PACKET_qXfer_features,
   16109 			 "qXfer:features:read", "target-features", 0);
   16110 
   16111   add_packet_config_cmd (PACKET_qXfer_libraries, "qXfer:libraries:read",
   16112 			 "library-info", 0);
   16113 
   16114   add_packet_config_cmd (PACKET_qXfer_libraries_svr4,
   16115 			 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
   16116 
   16117   add_packet_config_cmd (PACKET_qXfer_memory_map, "qXfer:memory-map:read",
   16118 			 "memory-map", 0);
   16119 
   16120   add_packet_config_cmd (PACKET_qXfer_osdata, "qXfer:osdata:read", "osdata", 0);
   16121 
   16122   add_packet_config_cmd (PACKET_qXfer_threads, "qXfer:threads:read", "threads",
   16123 			 0);
   16124 
   16125   add_packet_config_cmd (PACKET_qXfer_siginfo_read, "qXfer:siginfo:read",
   16126 			 "read-siginfo-object", 0);
   16127 
   16128   add_packet_config_cmd (PACKET_qXfer_siginfo_write, "qXfer:siginfo:write",
   16129 			 "write-siginfo-object", 0);
   16130 
   16131   add_packet_config_cmd (PACKET_qXfer_traceframe_info,
   16132 			 "qXfer:traceframe-info:read", "traceframe-info", 0);
   16133 
   16134   add_packet_config_cmd (PACKET_qXfer_uib, "qXfer:uib:read",
   16135 			 "unwind-info-block", 0);
   16136 
   16137   add_packet_config_cmd (PACKET_qGetTLSAddr, "qGetTLSAddr",
   16138 			 "get-thread-local-storage-address", 0);
   16139 
   16140   add_packet_config_cmd (PACKET_qGetTIBAddr, "qGetTIBAddr",
   16141 			 "get-thread-information-block-address", 0);
   16142 
   16143   add_packet_config_cmd (PACKET_bc, "bc", "reverse-continue", 0);
   16144 
   16145   add_packet_config_cmd (PACKET_bs, "bs", "reverse-step", 0);
   16146 
   16147   add_packet_config_cmd (PACKET_qSupported, "qSupported", "supported-packets",
   16148 			 0);
   16149 
   16150   add_packet_config_cmd (PACKET_qSearch_memory, "qSearch:memory",
   16151 			 "search-memory", 0);
   16152 
   16153   add_packet_config_cmd (PACKET_qTStatus, "qTStatus", "trace-status", 0);
   16154 
   16155   add_packet_config_cmd (PACKET_vFile_setfs, "vFile:setfs", "hostio-setfs", 0);
   16156 
   16157   add_packet_config_cmd (PACKET_vFile_open, "vFile:open", "hostio-open", 0);
   16158 
   16159   add_packet_config_cmd (PACKET_vFile_pread, "vFile:pread", "hostio-pread", 0);
   16160 
   16161   add_packet_config_cmd (PACKET_vFile_pwrite, "vFile:pwrite", "hostio-pwrite",
   16162 			 0);
   16163 
   16164   add_packet_config_cmd (PACKET_vFile_close, "vFile:close", "hostio-close", 0);
   16165 
   16166   add_packet_config_cmd (PACKET_vFile_unlink, "vFile:unlink", "hostio-unlink",
   16167 			 0);
   16168 
   16169   add_packet_config_cmd (PACKET_vFile_readlink, "vFile:readlink",
   16170 			 "hostio-readlink", 0);
   16171 
   16172   add_packet_config_cmd (PACKET_vFile_fstat, "vFile:fstat", "hostio-fstat", 0);
   16173 
   16174   add_packet_config_cmd (PACKET_vAttach, "vAttach", "attach", 0);
   16175 
   16176   add_packet_config_cmd (PACKET_vRun, "vRun", "run", 0);
   16177 
   16178   add_packet_config_cmd (PACKET_QStartNoAckMode, "QStartNoAckMode", "noack", 0);
   16179 
   16180   add_packet_config_cmd (PACKET_vKill, "vKill", "kill", 0);
   16181 
   16182   add_packet_config_cmd (PACKET_qAttached, "qAttached", "query-attached", 0);
   16183 
   16184   add_packet_config_cmd (PACKET_ConditionalTracepoints,
   16185 			 "ConditionalTracepoints", "conditional-tracepoints",
   16186 			 0);
   16187 
   16188   add_packet_config_cmd (PACKET_ConditionalBreakpoints,
   16189 			 "ConditionalBreakpoints", "conditional-breakpoints",
   16190 			 0);
   16191 
   16192   add_packet_config_cmd (PACKET_BreakpointCommands, "BreakpointCommands",
   16193 			 "breakpoint-commands", 0);
   16194 
   16195   add_packet_config_cmd (PACKET_FastTracepoints, "FastTracepoints",
   16196 			 "fast-tracepoints", 0);
   16197 
   16198   add_packet_config_cmd (PACKET_TracepointSource, "TracepointSource",
   16199 			 "TracepointSource", 0);
   16200 
   16201   add_packet_config_cmd (PACKET_QAllow, "QAllow", "allow", 0);
   16202 
   16203   add_packet_config_cmd (PACKET_StaticTracepoints, "StaticTracepoints",
   16204 			 "static-tracepoints", 0);
   16205 
   16206   add_packet_config_cmd (PACKET_InstallInTrace, "InstallInTrace",
   16207 			 "install-in-trace", 0);
   16208 
   16209   add_packet_config_cmd (PACKET_qXfer_statictrace_read,
   16210 			 "qXfer:statictrace:read", "read-sdata-object", 0);
   16211 
   16212   add_packet_config_cmd (PACKET_qXfer_fdpic, "qXfer:fdpic:read",
   16213 			 "read-fdpic-loadmap", 0);
   16214 
   16215   add_packet_config_cmd (PACKET_QDisableRandomization, "QDisableRandomization",
   16216 			 "disable-randomization", 0);
   16217 
   16218   add_packet_config_cmd (PACKET_QAgent, "QAgent", "agent", 0);
   16219 
   16220   add_packet_config_cmd (PACKET_QTBuffer_size, "QTBuffer:size",
   16221 			 "trace-buffer-size", 0);
   16222 
   16223   add_packet_config_cmd (PACKET_Qbtrace_off, "Qbtrace:off", "disable-btrace",
   16224 			 0);
   16225 
   16226   add_packet_config_cmd (PACKET_Qbtrace_bts, "Qbtrace:bts", "enable-btrace-bts",
   16227 			 0);
   16228 
   16229   add_packet_config_cmd (PACKET_Qbtrace_pt, "Qbtrace:pt", "enable-btrace-pt",
   16230 			 0);
   16231 
   16232   add_packet_config_cmd (PACKET_qXfer_btrace, "qXfer:btrace", "read-btrace", 0);
   16233 
   16234   add_packet_config_cmd (PACKET_qXfer_btrace_conf, "qXfer:btrace-conf",
   16235 			 "read-btrace-conf", 0);
   16236 
   16237   add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size, "Qbtrace-conf:bts:size",
   16238 			 "btrace-conf-bts-size", 0);
   16239 
   16240   add_packet_config_cmd (PACKET_multiprocess_feature, "multiprocess-feature",
   16241 			 "multiprocess-feature", 0);
   16242 
   16243   add_packet_config_cmd (PACKET_swbreak_feature, "swbreak-feature",
   16244 			 "swbreak-feature", 0);
   16245 
   16246   add_packet_config_cmd (PACKET_hwbreak_feature, "hwbreak-feature",
   16247 			 "hwbreak-feature", 0);
   16248 
   16249   add_packet_config_cmd (PACKET_fork_event_feature, "fork-event-feature",
   16250 			 "fork-event-feature", 0);
   16251 
   16252   add_packet_config_cmd (PACKET_vfork_event_feature, "vfork-event-feature",
   16253 			 "vfork-event-feature", 0);
   16254 
   16255   add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size, "Qbtrace-conf:pt:size",
   16256 			 "btrace-conf-pt-size", 0);
   16257 
   16258   add_packet_config_cmd (PACKET_vContSupported, "vContSupported",
   16259 			 "verbose-resume-supported", 0);
   16260 
   16261   add_packet_config_cmd (PACKET_exec_event_feature, "exec-event-feature",
   16262 			 "exec-event-feature", 0);
   16263 
   16264   add_packet_config_cmd (PACKET_vCtrlC, "vCtrlC", "ctrl-c", 0);
   16265 
   16266   add_packet_config_cmd (PACKET_QThreadEvents, "QThreadEvents", "thread-events",
   16267 			 0);
   16268 
   16269   add_packet_config_cmd (PACKET_QThreadOptions, "QThreadOptions",
   16270 			 "thread-options", 0);
   16271 
   16272   add_packet_config_cmd (PACKET_no_resumed, "N stop reply",
   16273 			 "no-resumed-stop-reply", 0);
   16274 
   16275   add_packet_config_cmd (PACKET_memory_tagging_feature,
   16276 			 "memory-tagging-feature", "memory-tagging-feature", 0);
   16277 
   16278   add_packet_config_cmd (PACKET_qIsAddressTagged,
   16279 			 "qIsAddressTagged", "memory-tagging-address-check", 0);
   16280 
   16281   /* Assert that we've registered "set remote foo-packet" commands
   16282      for all packet configs.  */
   16283   {
   16284     int i;
   16285 
   16286     for (i = 0; i < PACKET_MAX; i++)
   16287       {
   16288 	/* Ideally all configs would have a command associated.  Some
   16289 	   still don't though.  */
   16290 	int excepted;
   16291 
   16292 	switch (i)
   16293 	  {
   16294 	  case PACKET_QNonStop:
   16295 	  case PACKET_EnableDisableTracepoints_feature:
   16296 	  case PACKET_tracenz_feature:
   16297 	  case PACKET_DisconnectedTracing_feature:
   16298 	  case PACKET_augmented_libraries_svr4_read_feature:
   16299 	  case PACKET_qCRC:
   16300 	    /* Additions to this list need to be well justified:
   16301 	       pre-existing packets are OK; new packets are not.  */
   16302 	    excepted = 1;
   16303 	    break;
   16304 	  default:
   16305 	    excepted = 0;
   16306 	    break;
   16307 	  }
   16308 
   16309 	/* This catches both forgetting to add a config command, and
   16310 	   forgetting to remove a packet from the exception list.  */
   16311 	gdb_assert (excepted == (packets_descriptions[i].name == NULL));
   16312       }
   16313   }
   16314 
   16315   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
   16316      Z sub-packet has its own set and show commands, but users may
   16317      have sets to this variable in their .gdbinit files (or in their
   16318      documentation).  */
   16319   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
   16320 				&remote_Z_packet_detect, _("\
   16321 Set use of remote protocol `Z' packets."), _("\
   16322 Show use of remote protocol `Z' packets."), _("\
   16323 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
   16324 packets."),
   16325 				set_remote_protocol_Z_packet_cmd,
   16326 				show_remote_protocol_Z_packet_cmd,
   16327 				/* FIXME: i18n: Use of remote protocol
   16328 				   `Z' packets is %s.  */
   16329 				&remote_set_cmdlist, &remote_show_cmdlist);
   16330 
   16331   add_basic_prefix_cmd ("remote", class_files, _("\
   16332 Manipulate files on the remote system.\n\
   16333 Transfer files to and from the remote target system."),
   16334 			&remote_cmdlist,
   16335 			0 /* allow-unknown */, &cmdlist);
   16336 
   16337   add_cmd ("put", class_files, remote_put_command,
   16338 	   _("Copy a local file to the remote system."),
   16339 	   &remote_cmdlist);
   16340 
   16341   add_cmd ("get", class_files, remote_get_command,
   16342 	   _("Copy a remote file to the local system."),
   16343 	   &remote_cmdlist);
   16344 
   16345   add_cmd ("delete", class_files, remote_delete_command,
   16346 	   _("Delete a remote file."),
   16347 	   &remote_cmdlist);
   16348 
   16349   add_setshow_string_noescape_cmd ("exec-file", class_files,
   16350 				   &remote_exec_file_var, _("\
   16351 Set the remote pathname for \"run\"."), _("\
   16352 Show the remote pathname for \"run\"."), NULL,
   16353 				   set_remote_exec_file,
   16354 				   show_remote_exec_file,
   16355 				   &remote_set_cmdlist,
   16356 				   &remote_show_cmdlist);
   16357 
   16358   add_setshow_boolean_cmd ("range-stepping", class_run,
   16359 			   &use_range_stepping, _("\
   16360 Enable or disable range stepping."), _("\
   16361 Show whether target-assisted range stepping is enabled."), _("\
   16362 If on, and the target supports it, when stepping a source line, GDB\n\
   16363 tells the target to step the corresponding range of addresses itself instead\n\
   16364 of issuing multiple single-steps.  This speeds up source level\n\
   16365 stepping.  If off, GDB always issues single-steps, even if range\n\
   16366 stepping is supported by the target.  The default is on."),
   16367 			   set_range_stepping,
   16368 			   show_range_stepping,
   16369 			   &setlist,
   16370 			   &showlist);
   16371 
   16372   add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
   16373 Set watchdog timer."), _("\
   16374 Show watchdog timer."), _("\
   16375 When non-zero, this timeout is used instead of waiting forever for a target\n\
   16376 to finish a low-level step or continue operation.  If the specified amount\n\
   16377 of time passes without a response from the target, an error occurs."),
   16378 			    NULL,
   16379 			    show_watchdog,
   16380 			    &setlist, &showlist);
   16381 
   16382   add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
   16383 				       &remote_packet_max_chars, _("\
   16384 Set the maximum number of characters to display for each remote packet."), _("\
   16385 Show the maximum number of characters to display for each remote packet."), _("\
   16386 Specify \"unlimited\" to display all the characters."),
   16387 				       NULL, show_remote_packet_max_chars,
   16388 				       &setdebuglist, &showdebuglist);
   16389 
   16390   add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
   16391 			   _("Set debugging of remote protocol."),
   16392 			   _("Show debugging of remote protocol."),
   16393 			   _("\
   16394 When enabled, each packet sent or received with the remote target\n\
   16395 is displayed."),
   16396 			   NULL,
   16397 			   show_remote_debug,
   16398 			   &setdebuglist, &showdebuglist);
   16399 
   16400   add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
   16401 				       &remote_timeout, _("\
   16402 Set timeout limit to wait for target to respond."), _("\
   16403 Show timeout limit to wait for target to respond."), _("\
   16404 This value is used to set the time limit for gdb to wait for a response\n\
   16405 from the target."),
   16406 				       NULL,
   16407 				       show_remote_timeout,
   16408 				       &setlist, &showlist);
   16409 
   16410   /* Eventually initialize fileio.  See fileio.c */
   16411   initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
   16412 
   16413 #if GDB_SELF_TEST
   16414   selftests::register_test ("remote_memory_tagging",
   16415 			    selftests::test_memory_tagging_functions);
   16416   selftests::register_test ("packet_check_result",
   16417 			    selftests::test_packet_check_result);
   16418 #endif
   16419 }
   16420