gdb/remote.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Remote target communications for serial-line targets in custom GDB protocol

  2.    Copyright (C) 1988-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  14. /* See the GDB User Guide for details of the GDB remote protocol.  */

  15. #include "defs.h"
  16. #include <ctype.h>
  17. #include <fcntl.h>
  18. #include "inferior.h"
  19. #include "infrun.h"
  20. #include "bfd.h"
  21. #include "symfile.h"
  22. #include "target.h"
  23. /*#include "terminal.h" */
  24. #include "gdbcmd.h"
  25. #include "objfiles.h"
  26. #include "gdb-stabs.h"
  27. #include "gdbthread.h"
  28. #include "remote.h"
  29. #include "remote-notif.h"
  30. #include "regcache.h"
  31. #include "value.h"
  32. #include "observer.h"
  33. #include "solib.h"
  34. #include "cli/cli-decode.h"
  35. #include "cli/cli-setshow.h"
  36. #include "target-descriptions.h"
  37. #include "gdb_bfd.h"
  38. #include "filestuff.h"
  39. #include "rsp-low.h"

  40. #include <sys/time.h>

  41. #include "event-loop.h"
  42. #include "event-top.h"
  43. #include "inf-loop.h"

  44. #include <signal.h>
  45. #include "serial.h"

  46. #include "gdbcore.h" /* for exec_bfd */

  47. #include "remote-fileio.h"
  48. #include "gdb/fileio.h"
  49. #include <sys/stat.h>
  50. #include "xml-support.h"

  51. #include "memory-map.h"

  52. #include "tracepoint.h"
  53. #include "ax.h"
  54. #include "ax-gdb.h"
  55. #include "agent.h"
  56. #include "btrace.h"

  57. /* Temp hacks for tracepoint encoding migration.  */
  58. static char *target_buf;
  59. static long target_buf_size;

  60. /* The size to align memory write packets, when practical.  The protocol
  61.    does not guarantee any alignment, and gdb will generate short
  62.    writes and unaligned writes, but even as a best-effort attempt this
  63.    can improve bulk transfers.  For instance, if a write is misaligned
  64.    relative to the target's data bus, the stub may need to make an extra
  65.    round trip fetching data from the target.  This doesn't make a
  66.    huge difference, but it's easy to do, so we try to be helpful.

  67.    The alignment chosen is arbitrary; usually data bus width is
  68.    important here, not the possibly larger cache line size.  */
  69. enum { REMOTE_ALIGN_WRITES = 16 };

  70. /* Prototypes for local functions.  */
  71. static void async_cleanup_sigint_signal_handler (void *dummy);
  72. static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
  73. static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
  74.                                  int forever, int *is_notif);

  75. static void async_handle_remote_sigint (int);
  76. static void async_handle_remote_sigint_twice (int);

  77. static void remote_files_info (struct target_ops *ignore);

  78. static void remote_prepare_to_store (struct target_ops *self,
  79.                                      struct regcache *regcache);

  80. static void remote_open_1 (const char *, int, struct target_ops *,
  81.                            int extended_p);

  82. static void remote_close (struct target_ops *self);

  83. static void remote_mourn (struct target_ops *ops);

  84. static void extended_remote_restart (void);

  85. static void extended_remote_mourn (struct target_ops *);

  86. static void remote_mourn_1 (struct target_ops *);

  87. static void remote_send (char **buf, long *sizeof_buf_p);

  88. static int readchar (int timeout);

  89. static void remote_serial_write (const char *str, int len);

  90. static void remote_kill (struct target_ops *ops);

  91. static int remote_can_async_p (struct target_ops *);

  92. static int remote_is_async_p (struct target_ops *);

  93. static void remote_async (struct target_ops *ops,
  94.                           void (*callback) (enum inferior_event_type event_type,
  95.                                             void *context),
  96.                           void *context);

  97. static void sync_remote_interrupt_twice (int signo);

  98. static void interrupt_query (void);

  99. static void set_general_thread (struct ptid ptid);
  100. static void set_continue_thread (struct ptid ptid);

  101. static void get_offsets (void);

  102. static void skip_frame (void);

  103. static long read_frame (char **buf_p, long *sizeof_buf);

  104. static int hexnumlen (ULONGEST num);

  105. static void init_remote_ops (void);

  106. static void init_extended_remote_ops (void);

  107. static void remote_stop (struct target_ops *self, ptid_t);

  108. static int stubhex (int ch);

  109. static int hexnumstr (char *, ULONGEST);

  110. static int hexnumnstr (char *, ULONGEST, int);

  111. static CORE_ADDR remote_address_masked (CORE_ADDR);

  112. static void print_packet (const char *);

  113. static void compare_sections_command (char *, int);

  114. static void packet_command (char *, int);

  115. static int stub_unpack_int (char *buff, int fieldlength);

  116. static ptid_t remote_current_thread (ptid_t oldptid);

  117. static int putpkt_binary (const char *buf, int cnt);

  118. static void check_binary_download (CORE_ADDR addr);

  119. struct packet_config;

  120. static void show_packet_config_cmd (struct packet_config *config);

  121. static void show_remote_protocol_packet_cmd (struct ui_file *file,
  122.                                              int from_tty,
  123.                                              struct cmd_list_element *c,
  124.                                              const char *value);

  125. static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
  126. static ptid_t read_ptid (char *buf, char **obuf);

  127. static void remote_set_permissions (struct target_ops *self);

  128. struct remote_state;
  129. static int remote_get_trace_status (struct target_ops *self,
  130.                                     struct trace_status *ts);

  131. static int remote_upload_tracepoints (struct target_ops *self,
  132.                                       struct uploaded_tp **utpp);

  133. static int remote_upload_trace_state_variables (struct target_ops *self,
  134.                                                 struct uploaded_tsv **utsvp);

  135. static void remote_query_supported (void);

  136. static void remote_check_symbols (void);

  137. void _initialize_remote (void);

  138. struct stop_reply;
  139. static void stop_reply_xfree (struct stop_reply *);
  140. static void remote_parse_stop_reply (char *, struct stop_reply *);
  141. static void push_stop_reply (struct stop_reply *);
  142. static void discard_pending_stop_replies_in_queue (struct remote_state *);
  143. static int peek_stop_reply (ptid_t ptid);

  144. static void remote_async_inferior_event_handler (gdb_client_data);

  145. static void remote_terminal_ours (struct target_ops *self);

  146. static int remote_read_description_p (struct target_ops *target);

  147. static void remote_console_output (char *msg);

  148. static int remote_supports_cond_breakpoints (struct target_ops *self);

  149. static int remote_can_run_breakpoint_commands (struct target_ops *self);

  150. /* For "remote".  */

  151. static struct cmd_list_element *remote_cmdlist;

  152. /* For "set remote" and "show remote".  */

  153. static struct cmd_list_element *remote_set_cmdlist;
  154. static struct cmd_list_element *remote_show_cmdlist;

  155. /* Stub vCont actions support.

  156.    Each field is a boolean flag indicating whether the stub reports
  157.    support for the corresponding action.  */

  158. struct vCont_action_support
  159. {
  160.   /* vCont;t */
  161.   int t;

  162.   /* vCont;r */
  163.   int r;
  164. };

  165. /* Controls whether GDB is willing to use range stepping.  */

  166. static int use_range_stepping = 1;

  167. #define OPAQUETHREADBYTES 8

  168. /* a 64 bit opaque identifier */
  169. typedef unsigned char threadref[OPAQUETHREADBYTES];

  170. /* About this many threadisds fit in a packet.  */

  171. #define MAXTHREADLISTRESULTS 32

  172. /* Description of the remote protocol state for the currently
  173.    connected target.  This is per-target state, and independent of the
  174.    selected architecture.  */

  175. struct remote_state
  176. {
  177.   /* A buffer to use for incoming packets, and its current size.  The
  178.      buffer is grown dynamically for larger incoming packets.
  179.      Outgoing packets may also be constructed in this buffer.
  180.      BUF_SIZE is always at least REMOTE_PACKET_SIZE;
  181.      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
  182.      packets.  */
  183.   char *buf;
  184.   long buf_size;

  185.   /* True if we're going through initial connection setup (finding out
  186.      about the remote side's threads, relocating symbols, etc.).  */
  187.   int starting_up;

  188.   /* If we negotiated packet size explicitly (and thus can bypass
  189.      heuristics for the largest packet size that will not overflow
  190.      a buffer in the stub), this will be set to that packet size.
  191.      Otherwise zero, meaning to use the guessed size.  */
  192.   long explicit_packet_size;

  193.   /* remote_wait is normally called when the target is running and
  194.      waits for a stop reply packet.  But sometimes we need to call it
  195.      when the target is already stopped.  We can send a "?" packet
  196.      and have remote_wait read the response.  Or, if we already have
  197.      the response, we can stash it in BUF and tell remote_wait to
  198.      skip calling getpkt.  This flag is set when BUF contains a
  199.      stop reply packet and the target is not waiting.  */
  200.   int cached_wait_status;

  201.   /* True, if in no ack mode.  That is, neither GDB nor the stub will
  202.      expect acks from each other.  The connection is assumed to be
  203.      reliable.  */
  204.   int noack_mode;

  205.   /* True if we're connected in extended remote mode.  */
  206.   int extended;

  207.   /* True if we resumed the target and we're waiting for the target to
  208.      stop.  In the mean time, we can't start another command/query.
  209.      The remote server wouldn't be ready to process it, so we'd
  210.      timeout waiting for a reply that would never come and eventually
  211.      we'd close the connection.  This can happen in asynchronous mode
  212.      because we allow GDB commands while the target is running.  */
  213.   int waiting_for_stop_reply;

  214.   /* The status of the stub support for the various vCont actions.  */
  215.   struct vCont_action_support supports_vCont;

  216.   /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
  217.      responded to that.  */
  218.   int ctrlc_pending_p;

  219.   /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
  220.      remote_open knows that we don't have a file open when the program
  221.      starts.  */
  222.   struct serial *remote_desc;

  223.   /* These are the threads which we last sent to the remote system.  The
  224.      TID member will be -1 for all or -2 for not sent yet.  */
  225.   ptid_t general_thread;
  226.   ptid_t continue_thread;

  227.   /* This is the traceframe which we last selected on the remote system.
  228.      It will be -1 if no traceframe is selected.  */
  229.   int remote_traceframe_number;

  230.   char *last_pass_packet;

  231.   /* The last QProgramSignals packet sent to the target.  We bypass
  232.      sending a new program signals list down to the target if the new
  233.      packet is exactly the same as the last we sent.  IOW, we only let
  234.      the target know about program signals list changes.  */
  235.   char *last_program_signals_packet;

  236.   enum gdb_signal last_sent_signal;

  237.   int last_sent_step;

  238.   char *finished_object;
  239.   char *finished_annex;
  240.   ULONGEST finished_offset;

  241.   /* Should we try the 'ThreadInfo' query packet?

  242.      This variable (NOT available to the user: auto-detect only!)
  243.      determines whether GDB will use the new, simpler "ThreadInfo"
  244.      query or the older, more complex syntax for thread queries.
  245.      This is an auto-detect variable (set to true at each connect,
  246.      and set to false when the target fails to recognize it).  */
  247.   int use_threadinfo_query;
  248.   int use_threadextra_query;

  249.   void (*async_client_callback) (enum inferior_event_type event_type,
  250.                                  void *context);
  251.   void *async_client_context;

  252.   /* This is set to the data address of the access causing the target
  253.      to stop for a watchpoint.  */
  254.   CORE_ADDR remote_watch_data_address;

  255.   /* This is non-zero if target stopped for a watchpoint.  */
  256.   int remote_stopped_by_watchpoint_p;

  257.   threadref echo_nextthread;
  258.   threadref nextthread;
  259.   threadref resultthreadlist[MAXTHREADLISTRESULTS];

  260.   /* The state of remote notification.  */
  261.   struct remote_notif_state *notif_state;
  262. };

  263. /* Private data that we'll store in (struct thread_info)->private.  */
  264. struct private_thread_info
  265. {
  266.   char *extra;
  267.   int core;
  268. };

  269. static void
  270. free_private_thread_info (struct private_thread_info *info)
  271. {
  272.   xfree (info->extra);
  273.   xfree (info);
  274. }

  275. /* This data could be associated with a target, but we do not always
  276.    have access to the current target when we need it, so for now it is
  277.    static.  This will be fine for as long as only one target is in use
  278.    at a time.  */
  279. static struct remote_state *remote_state;

  280. static struct remote_state *
  281. get_remote_state_raw (void)
  282. {
  283.   return remote_state;
  284. }

  285. /* Allocate a new struct remote_state with xmalloc, initialize it, and
  286.    return it.  */

  287. static struct remote_state *
  288. new_remote_state (void)
  289. {
  290.   struct remote_state *result = XCNEW (struct remote_state);

  291.   /* The default buffer size is unimportant; it will be expanded
  292.      whenever a larger buffer is needed. */
  293.   result->buf_size = 400;
  294.   result->buf = xmalloc (result->buf_size);
  295.   result->remote_traceframe_number = -1;
  296.   result->last_sent_signal = GDB_SIGNAL_0;

  297.   return result;
  298. }

  299. /* Description of the remote protocol for a given architecture.  */

  300. struct packet_reg
  301. {
  302.   long offset; /* Offset into G packet.  */
  303.   long regnum; /* GDB's internal register number.  */
  304.   LONGEST pnum; /* Remote protocol register number.  */
  305.   int in_g_packet; /* Always part of G packet.  */
  306.   /* long size in bytes;  == register_size (target_gdbarch (), regnum);
  307.      at present.  */
  308.   /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
  309.      at present.  */
  310. };

  311. struct remote_arch_state
  312. {
  313.   /* Description of the remote protocol registers.  */
  314.   long sizeof_g_packet;

  315.   /* Description of the remote protocol registers indexed by REGNUM
  316.      (making an array gdbarch_num_regs in size).  */
  317.   struct packet_reg *regs;

  318.   /* This is the size (in chars) of the first response to the ``g''
  319.      packet.  It is used as a heuristic when determining the maximum
  320.      size of memory-read and memory-write packets.  A target will
  321.      typically only reserve a buffer large enough to hold the ``g''
  322.      packet.  The size does not include packet overhead (headers and
  323.      trailers).  */
  324.   long actual_register_packet_size;

  325.   /* This is the maximum size (in chars) of a non read/write packet.
  326.      It is also used as a cap on the size of read/write packets.  */
  327.   long remote_packet_size;
  328. };

  329. /* Utility: generate error from an incoming stub packet.  */
  330. static void
  331. trace_error (char *buf)
  332. {
  333.   if (*buf++ != 'E')
  334.     return;                        /* not an error msg */
  335.   switch (*buf)
  336.     {
  337.     case '1':                        /* malformed packet error */
  338.       if (*++buf == '0')        /*   general case: */
  339.         error (_("remote.c: error in outgoing packet."));
  340.       else
  341.         error (_("remote.c: error in outgoing packet at field #%ld."),
  342.                strtol (buf, NULL, 16));
  343.     default:
  344.       error (_("Target returns error code '%s'."), buf);
  345.     }
  346. }

  347. /* Utility: wait for reply from stub, while accepting "O" packets.  */
  348. static char *
  349. remote_get_noisy_reply (char **buf_p,
  350.                         long *sizeof_buf)
  351. {
  352.   do                                /* Loop on reply from remote stub.  */
  353.     {
  354.       char *buf;

  355.       QUIT;                        /* Allow user to bail out with ^C.  */
  356.       getpkt (buf_p, sizeof_buf, 0);
  357.       buf = *buf_p;
  358.       if (buf[0] == 'E')
  359.         trace_error (buf);
  360.       else if (strncmp (buf, "qRelocInsn:", strlen ("qRelocInsn:")) == 0)
  361.         {
  362.           ULONGEST ul;
  363.           CORE_ADDR from, to, org_to;
  364.           char *p, *pp;
  365.           int adjusted_size = 0;
  366.           volatile struct gdb_exception ex;

  367.           p = buf + strlen ("qRelocInsn:");
  368.           pp = unpack_varlen_hex (p, &ul);
  369.           if (*pp != ';')
  370.             error (_("invalid qRelocInsn packet: %s"), buf);
  371.           from = ul;

  372.           p = pp + 1;
  373.           unpack_varlen_hex (p, &ul);
  374.           to = ul;

  375.           org_to = to;

  376.           TRY_CATCH (ex, RETURN_MASK_ALL)
  377.             {
  378.               gdbarch_relocate_instruction (target_gdbarch (), &to, from);
  379.             }
  380.           if (ex.reason >= 0)
  381.             {
  382.               adjusted_size = to - org_to;

  383.               xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
  384.               putpkt (buf);
  385.             }
  386.           else if (ex.reason < 0 && ex.error == MEMORY_ERROR)
  387.             {
  388.               /* Propagate memory errors silently back to the target.
  389.                  The stub may have limited the range of addresses we
  390.                  can write to, for example.  */
  391.               putpkt ("E01");
  392.             }
  393.           else
  394.             {
  395.               /* Something unexpectedly bad happened.  Be verbose so
  396.                  we can tell what, and propagate the error back to the
  397.                  stub, so it doesn't get stuck waiting for a
  398.                  response.  */
  399.               exception_fprintf (gdb_stderr, ex,
  400.                                  _("warning: relocating instruction: "));
  401.               putpkt ("E01");
  402.             }
  403.         }
  404.       else if (buf[0] == 'O' && buf[1] != 'K')
  405.         remote_console_output (buf + 1);        /* 'O' message from stub */
  406.       else
  407.         return buf;                /* Here's the actual reply.  */
  408.     }
  409.   while (1);
  410. }

  411. /* Handle for retreving the remote protocol data from gdbarch.  */
  412. static struct gdbarch_data *remote_gdbarch_data_handle;

  413. static struct remote_arch_state *
  414. get_remote_arch_state (void)
  415. {
  416.   return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
  417. }

  418. /* Fetch the global remote target state.  */

  419. static struct remote_state *
  420. get_remote_state (void)
  421. {
  422.   /* Make sure that the remote architecture state has been
  423.      initialized, because doing so might reallocate rs->buf.  Any
  424.      function which calls getpkt also needs to be mindful of changes
  425.      to rs->buf, but this call limits the number of places which run
  426.      into trouble.  */
  427.   get_remote_arch_state ();

  428.   return get_remote_state_raw ();
  429. }

  430. static int
  431. compare_pnums (const void *lhs_, const void *rhs_)
  432. {
  433.   const struct packet_reg * const *lhs = lhs_;
  434.   const struct packet_reg * const *rhs = rhs_;

  435.   if ((*lhs)->pnum < (*rhs)->pnum)
  436.     return -1;
  437.   else if ((*lhs)->pnum == (*rhs)->pnum)
  438.     return 0;
  439.   else
  440.     return 1;
  441. }

  442. static int
  443. map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
  444. {
  445.   int regnum, num_remote_regs, offset;
  446.   struct packet_reg **remote_regs;

  447.   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
  448.     {
  449.       struct packet_reg *r = &regs[regnum];

  450.       if (register_size (gdbarch, regnum) == 0)
  451.         /* Do not try to fetch zero-sized (placeholder) registers.  */
  452.         r->pnum = -1;
  453.       else
  454.         r->pnum = gdbarch_remote_register_number (gdbarch, regnum);

  455.       r->regnum = regnum;
  456.     }

  457.   /* Define the g/G packet format as the contents of each register
  458.      with a remote protocol number, in order of ascending protocol
  459.      number.  */

  460.   remote_regs = alloca (gdbarch_num_regs (gdbarch)
  461.                         * sizeof (struct packet_reg *));
  462.   for (num_remote_regs = 0, regnum = 0;
  463.        regnum < gdbarch_num_regs (gdbarch);
  464.        regnum++)
  465.     if (regs[regnum].pnum != -1)
  466.       remote_regs[num_remote_regs++] = &regs[regnum];

  467.   qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
  468.          compare_pnums);

  469.   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
  470.     {
  471.       remote_regs[regnum]->in_g_packet = 1;
  472.       remote_regs[regnum]->offset = offset;
  473.       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
  474.     }

  475.   return offset;
  476. }

  477. /* Given the architecture described by GDBARCH, return the remote
  478.    protocol register's number and the register's offset in the g/G
  479.    packets of GDB register REGNUM, in PNUM and POFFSET respectively.
  480.    If the target does not have a mapping for REGNUM, return false,
  481.    otherwise, return true.  */

  482. int
  483. remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
  484.                                    int *pnum, int *poffset)
  485. {
  486.   int sizeof_g_packet;
  487.   struct packet_reg *regs;
  488.   struct cleanup *old_chain;

  489.   gdb_assert (regnum < gdbarch_num_regs (gdbarch));

  490.   regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
  491.   old_chain = make_cleanup (xfree, regs);

  492.   sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);

  493.   *pnum = regs[regnum].pnum;
  494.   *poffset = regs[regnum].offset;

  495.   do_cleanups (old_chain);

  496.   return *pnum != -1;
  497. }

  498. static void *
  499. init_remote_state (struct gdbarch *gdbarch)
  500. {
  501.   struct remote_state *rs = get_remote_state_raw ();
  502.   struct remote_arch_state *rsa;

  503.   rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);

  504.   /* Use the architecture to build a regnum<->pnum table, which will be
  505.      1:1 unless a feature set specifies otherwise.  */
  506.   rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
  507.                                       gdbarch_num_regs (gdbarch),
  508.                                       struct packet_reg);

  509.   /* Record the maximum possible size of the g packet - it may turn out
  510.      to be smaller.  */
  511.   rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);

  512.   /* Default maximum number of characters in a packet body.  Many
  513.      remote stubs have a hardwired buffer size of 400 bytes
  514.      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
  515.      as the maximum packet-size to ensure that the packet and an extra
  516.      NUL character can always fit in the buffer.  This stops GDB
  517.      trashing stubs that try to squeeze an extra NUL into what is
  518.      already a full buffer (As of 1999-12-04 that was most stubs).  */
  519.   rsa->remote_packet_size = 400 - 1;

  520.   /* This one is filled in when a ``g'' packet is received.  */
  521.   rsa->actual_register_packet_size = 0;

  522.   /* Should rsa->sizeof_g_packet needs more space than the
  523.      default, adjust the size accordingly.  Remember that each byte is
  524.      encoded as two characters.  32 is the overhead for the packet
  525.      header / footer.  NOTE: cagney/1999-10-26: I suspect that 8
  526.      (``$NN:G...#NN'') is a better guess, the below has been padded a
  527.      little.  */
  528.   if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
  529.     rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);

  530.   /* Make sure that the packet buffer is plenty big enough for
  531.      this architecture.  */
  532.   if (rs->buf_size < rsa->remote_packet_size)
  533.     {
  534.       rs->buf_size = 2 * rsa->remote_packet_size;
  535.       rs->buf = xrealloc (rs->buf, rs->buf_size);
  536.     }

  537.   return rsa;
  538. }

  539. /* Return the current allowed size of a remote packet.  This is
  540.    inferred from the current architecture, and should be used to
  541.    limit the length of outgoing packets.  */
  542. static long
  543. get_remote_packet_size (void)
  544. {
  545.   struct remote_state *rs = get_remote_state ();
  546.   struct remote_arch_state *rsa = get_remote_arch_state ();

  547.   if (rs->explicit_packet_size)
  548.     return rs->explicit_packet_size;

  549.   return rsa->remote_packet_size;
  550. }

  551. static struct packet_reg *
  552. packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
  553. {
  554.   if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
  555.     return NULL;
  556.   else
  557.     {
  558.       struct packet_reg *r = &rsa->regs[regnum];

  559.       gdb_assert (r->regnum == regnum);
  560.       return r;
  561.     }
  562. }

  563. static struct packet_reg *
  564. packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
  565. {
  566.   int i;

  567.   for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
  568.     {
  569.       struct packet_reg *r = &rsa->regs[i];

  570.       if (r->pnum == pnum)
  571.         return r;
  572.     }
  573.   return NULL;
  574. }

  575. static struct target_ops remote_ops;

  576. static struct target_ops extended_remote_ops;

  577. /* FIXME: cagney/1999-09-23: Even though getpkt was called with
  578.    ``forever'' still use the normal timeout mechanism.  This is
  579.    currently used by the ASYNC code to guarentee that target reads
  580.    during the initial connect always time-out.  Once getpkt has been
  581.    modified to return a timeout indication and, in turn
  582.    remote_wait()/wait_for_inferior() have gained a timeout parameter
  583.    this can go away.  */
  584. static int wait_forever_enabled_p = 1;

  585. /* Allow the user to specify what sequence to send to the remote
  586.    when he requests a program interruption: Although ^C is usually
  587.    what remote systems expect (this is the default, here), it is
  588.    sometimes preferable to send a break.  On other systems such
  589.    as the Linux kernel, a break followed by g, which is Magic SysRq g
  590.    is required in order to interrupt the execution.  */
  591. const char interrupt_sequence_control_c[] = "Ctrl-C";
  592. const char interrupt_sequence_break[] = "BREAK";
  593. const char interrupt_sequence_break_g[] = "BREAK-g";
  594. static const char *const interrupt_sequence_modes[] =
  595.   {
  596.     interrupt_sequence_control_c,
  597.     interrupt_sequence_break,
  598.     interrupt_sequence_break_g,
  599.     NULL
  600.   };
  601. static const char *interrupt_sequence_mode = interrupt_sequence_control_c;

  602. static void
  603. show_interrupt_sequence (struct ui_file *file, int from_tty,
  604.                          struct cmd_list_element *c,
  605.                          const char *value)
  606. {
  607.   if (interrupt_sequence_mode == interrupt_sequence_control_c)
  608.     fprintf_filtered (file,
  609.                       _("Send the ASCII ETX character (Ctrl-c) "
  610.                         "to the remote target to interrupt the "
  611.                         "execution of the program.\n"));
  612.   else if (interrupt_sequence_mode == interrupt_sequence_break)
  613.     fprintf_filtered (file,
  614.                       _("send a break signal to the remote target "
  615.                         "to interrupt the execution of the program.\n"));
  616.   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
  617.     fprintf_filtered (file,
  618.                       _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
  619.                         "the remote target to interrupt the execution "
  620.                         "of Linux kernel.\n"));
  621.   else
  622.     internal_error (__FILE__, __LINE__,
  623.                     _("Invalid value for interrupt_sequence_mode: %s."),
  624.                     interrupt_sequence_mode);
  625. }

  626. /* This boolean variable specifies whether interrupt_sequence is sent
  627.    to the remote target when gdb connects to it.
  628.    This is mostly needed when you debug the Linux kernel: The Linux kernel
  629.    expects BREAK g which is Magic SysRq g for connecting gdb.  */
  630. static int interrupt_on_connect = 0;

  631. /* This variable is used to implement the "set/show remotebreak" commands.
  632.    Since these commands are now deprecated in favor of "set/show remote
  633.    interrupt-sequence", it no longer has any effect on the code.  */
  634. static int remote_break;

  635. static void
  636. set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
  637. {
  638.   if (remote_break)
  639.     interrupt_sequence_mode = interrupt_sequence_break;
  640.   else
  641.     interrupt_sequence_mode = interrupt_sequence_control_c;
  642. }

  643. static void
  644. show_remotebreak (struct ui_file *file, int from_tty,
  645.                   struct cmd_list_element *c,
  646.                   const char *value)
  647. {
  648. }

  649. /* This variable sets the number of bits in an address that are to be
  650.    sent in a memory ("M" or "m") packet.  Normally, after stripping
  651.    leading zeros, the entire address would be sent.  This variable
  652.    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
  653.    initial implementation of remote.c restricted the address sent in
  654.    memory packets to ``host::sizeof long'' bytes - (typically 32
  655.    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
  656.    address was never sent.  Since fixing this bug may cause a break in
  657.    some remote targets this variable is principly provided to
  658.    facilitate backward compatibility.  */

  659. static unsigned int remote_address_size;

  660. /* Temporary to track who currently owns the terminal.  See
  661.    remote_terminal_* for more details.  */

  662. static int remote_async_terminal_ours_p;

  663. /* The executable file to use for "run" on the remote side.  */

  664. static char *remote_exec_file = "";


  665. /* User configurable variables for the number of characters in a
  666.    memory read/write packet.  MIN (rsa->remote_packet_size,
  667.    rsa->sizeof_g_packet) is the default.  Some targets need smaller
  668.    values (fifo overruns, et.al.) and some users need larger values
  669.    (speed up transfers).  The variables ``preferred_*'' (the user
  670.    request), ``current_*'' (what was actually set) and ``forced_*''
  671.    (Positive - a soft limit, negative - a hard limit).  */

  672. struct memory_packet_config
  673. {
  674.   char *name;
  675.   long size;
  676.   int fixed_p;
  677. };

  678. /* Compute the current size of a read/write packet.  Since this makes
  679.    use of ``actual_register_packet_size'' the computation is dynamic.  */

  680. static long
  681. get_memory_packet_size (struct memory_packet_config *config)
  682. {
  683.   struct remote_state *rs = get_remote_state ();
  684.   struct remote_arch_state *rsa = get_remote_arch_state ();

  685.   /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
  686.      law?) that some hosts don't cope very well with large alloca()
  687.      calls.  Eventually the alloca() code will be replaced by calls to
  688.      xmalloc() and make_cleanups() allowing this restriction to either
  689.      be lifted or removed.  */
  690. #ifndef MAX_REMOTE_PACKET_SIZE
  691. #define MAX_REMOTE_PACKET_SIZE 16384
  692. #endif
  693.   /* NOTE: 20 ensures we can write at least one byte.  */
  694. #ifndef MIN_REMOTE_PACKET_SIZE
  695. #define MIN_REMOTE_PACKET_SIZE 20
  696. #endif
  697.   long what_they_get;
  698.   if (config->fixed_p)
  699.     {
  700.       if (config->size <= 0)
  701.         what_they_get = MAX_REMOTE_PACKET_SIZE;
  702.       else
  703.         what_they_get = config->size;
  704.     }
  705.   else
  706.     {
  707.       what_they_get = get_remote_packet_size ();
  708.       /* Limit the packet to the size specified by the user.  */
  709.       if (config->size > 0
  710.           && what_they_get > config->size)
  711.         what_they_get = config->size;

  712.       /* Limit it to the size of the targets ``g'' response unless we have
  713.          permission from the stub to use a larger packet size.  */
  714.       if (rs->explicit_packet_size == 0
  715.           && rsa->actual_register_packet_size > 0
  716.           && what_they_get > rsa->actual_register_packet_size)
  717.         what_they_get = rsa->actual_register_packet_size;
  718.     }
  719.   if (what_they_get > MAX_REMOTE_PACKET_SIZE)
  720.     what_they_get = MAX_REMOTE_PACKET_SIZE;
  721.   if (what_they_get < MIN_REMOTE_PACKET_SIZE)
  722.     what_they_get = MIN_REMOTE_PACKET_SIZE;

  723.   /* Make sure there is room in the global buffer for this packet
  724.      (including its trailing NUL byte).  */
  725.   if (rs->buf_size < what_they_get + 1)
  726.     {
  727.       rs->buf_size = 2 * what_they_get;
  728.       rs->buf = xrealloc (rs->buf, 2 * what_they_get);
  729.     }

  730.   return what_they_get;
  731. }

  732. /* Update the size of a read/write packet.  If they user wants
  733.    something really big then do a sanity check.  */

  734. static void
  735. set_memory_packet_size (char *args, struct memory_packet_config *config)
  736. {
  737.   int fixed_p = config->fixed_p;
  738.   long size = config->size;

  739.   if (args == NULL)
  740.     error (_("Argument required (integer, `fixed' or `limited')."));
  741.   else if (strcmp (args, "hard") == 0
  742.       || strcmp (args, "fixed") == 0)
  743.     fixed_p = 1;
  744.   else if (strcmp (args, "soft") == 0
  745.            || strcmp (args, "limit") == 0)
  746.     fixed_p = 0;
  747.   else
  748.     {
  749.       char *end;

  750.       size = strtoul (args, &end, 0);
  751.       if (args == end)
  752.         error (_("Invalid %s (bad syntax)."), config->name);
  753. #if 0
  754.       /* Instead of explicitly capping the size of a packet to
  755.          MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
  756.          instead allowed to set the size to something arbitrarily
  757.          large.  */
  758.       if (size > MAX_REMOTE_PACKET_SIZE)
  759.         error (_("Invalid %s (too large)."), config->name);
  760. #endif
  761.     }
  762.   /* Extra checks?  */
  763.   if (fixed_p && !config->fixed_p)
  764.     {
  765.       if (! query (_("The target may not be able to correctly handle a %s\n"
  766.                    "of %ld bytes. Change the packet size? "),
  767.                    config->name, size))
  768.         error (_("Packet size not changed."));
  769.     }
  770.   /* Update the config.  */
  771.   config->fixed_p = fixed_p;
  772.   config->size = size;
  773. }

  774. static void
  775. show_memory_packet_size (struct memory_packet_config *config)
  776. {
  777.   printf_filtered (_("The %s is %ld. "), config->name, config->size);
  778.   if (config->fixed_p)
  779.     printf_filtered (_("Packets are fixed at %ld bytes.\n"),
  780.                      get_memory_packet_size (config));
  781.   else
  782.     printf_filtered (_("Packets are limited to %ld bytes.\n"),
  783.                      get_memory_packet_size (config));
  784. }

  785. static struct memory_packet_config memory_write_packet_config =
  786. {
  787.   "memory-write-packet-size",
  788. };

  789. static void
  790. set_memory_write_packet_size (char *args, int from_tty)
  791. {
  792.   set_memory_packet_size (args, &memory_write_packet_config);
  793. }

  794. static void
  795. show_memory_write_packet_size (char *args, int from_tty)
  796. {
  797.   show_memory_packet_size (&memory_write_packet_config);
  798. }

  799. static long
  800. get_memory_write_packet_size (void)
  801. {
  802.   return get_memory_packet_size (&memory_write_packet_config);
  803. }

  804. static struct memory_packet_config memory_read_packet_config =
  805. {
  806.   "memory-read-packet-size",
  807. };

  808. static void
  809. set_memory_read_packet_size (char *args, int from_tty)
  810. {
  811.   set_memory_packet_size (args, &memory_read_packet_config);
  812. }

  813. static void
  814. show_memory_read_packet_size (char *args, int from_tty)
  815. {
  816.   show_memory_packet_size (&memory_read_packet_config);
  817. }

  818. static long
  819. get_memory_read_packet_size (void)
  820. {
  821.   long size = get_memory_packet_size (&memory_read_packet_config);

  822.   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
  823.      extra buffer size argument before the memory read size can be
  824.      increased beyond this.  */
  825.   if (size > get_remote_packet_size ())
  826.     size = get_remote_packet_size ();
  827.   return size;
  828. }


  829. /* Generic configuration support for packets the stub optionally
  830.    supports.  Allows the user to specify the use of the packet as well
  831.    as allowing GDB to auto-detect support in the remote stub.  */

  832. enum packet_support
  833.   {
  834.     PACKET_SUPPORT_UNKNOWN = 0,
  835.     PACKET_ENABLE,
  836.     PACKET_DISABLE
  837.   };

  838. struct packet_config
  839.   {
  840.     const char *name;
  841.     const char *title;

  842.     /* If auto, GDB auto-detects support for this packet or feature,
  843.        either through qSupported, or by trying the packet and looking
  844.        at the response.  If true, GDB assumes the target supports this
  845.        packet.  If false, the packet is disabled.  Configs that don't
  846.        have an associated command always have this set to auto.  */
  847.     enum auto_boolean detect;

  848.     /* Does the target support this packet?  */
  849.     enum packet_support support;
  850.   };

  851. /* Analyze a packet's return value and update the packet config
  852.    accordingly.  */

  853. enum packet_result
  854. {
  855.   PACKET_ERROR,
  856.   PACKET_OK,
  857.   PACKET_UNKNOWN
  858. };

  859. static enum packet_support packet_config_support (struct packet_config *config);
  860. static enum packet_support packet_support (int packet);

  861. static void
  862. show_packet_config_cmd (struct packet_config *config)
  863. {
  864.   char *support = "internal-error";

  865.   switch (packet_config_support (config))
  866.     {
  867.     case PACKET_ENABLE:
  868.       support = "enabled";
  869.       break;
  870.     case PACKET_DISABLE:
  871.       support = "disabled";
  872.       break;
  873.     case PACKET_SUPPORT_UNKNOWN:
  874.       support = "unknown";
  875.       break;
  876.     }
  877.   switch (config->detect)
  878.     {
  879.     case AUTO_BOOLEAN_AUTO:
  880.       printf_filtered (_("Support for the `%s' packet "
  881.                          "is auto-detected, currently %s.\n"),
  882.                        config->name, support);
  883.       break;
  884.     case AUTO_BOOLEAN_TRUE:
  885.     case AUTO_BOOLEAN_FALSE:
  886.       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
  887.                        config->name, support);
  888.       break;
  889.     }
  890. }

  891. static void
  892. add_packet_config_cmd (struct packet_config *config, const char *name,
  893.                        const char *title, int legacy)
  894. {
  895.   char *set_doc;
  896.   char *show_doc;
  897.   char *cmd_name;

  898.   config->name = name;
  899.   config->title = title;
  900.   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
  901.                         name, title);
  902.   show_doc = xstrprintf ("Show current use of remote "
  903.                          "protocol `%s' (%s) packet",
  904.                          name, title);
  905.   /* set/show TITLE-packet {auto,on,off} */
  906.   cmd_name = xstrprintf ("%s-packet", title);
  907.   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
  908.                                 &config->detect, set_doc,
  909.                                 show_doc, NULL, /* help_doc */
  910.                                 NULL,
  911.                                 show_remote_protocol_packet_cmd,
  912.                                 &remote_set_cmdlist, &remote_show_cmdlist);
  913.   /* The command code copies the documentation strings.  */
  914.   xfree (set_doc);
  915.   xfree (show_doc);
  916.   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
  917.   if (legacy)
  918.     {
  919.       char *legacy_name;

  920.       legacy_name = xstrprintf ("%s-packet", name);
  921.       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
  922.                      &remote_set_cmdlist);
  923.       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
  924.                      &remote_show_cmdlist);
  925.     }
  926. }

  927. static enum packet_result
  928. packet_check_result (const char *buf)
  929. {
  930.   if (buf[0] != '\0')
  931.     {
  932.       /* The stub recognized the packet request.  Check that the
  933.          operation succeeded.  */
  934.       if (buf[0] == 'E'
  935.           && isxdigit (buf[1]) && isxdigit (buf[2])
  936.           && buf[3] == '\0')
  937.         /* "Enn"  - definitly an error.  */
  938.         return PACKET_ERROR;

  939.       /* Always treat "E." as an error.  This will be used for
  940.          more verbose error messages, such as E.memtypes.  */
  941.       if (buf[0] == 'E' && buf[1] == '.')
  942.         return PACKET_ERROR;

  943.       /* The packet may or may not be OK.  Just assume it is.  */
  944.       return PACKET_OK;
  945.     }
  946.   else
  947.     /* The stub does not support the packet.  */
  948.     return PACKET_UNKNOWN;
  949. }

  950. static enum packet_result
  951. packet_ok (const char *buf, struct packet_config *config)
  952. {
  953.   enum packet_result result;

  954.   if (config->detect != AUTO_BOOLEAN_TRUE
  955.       && config->support == PACKET_DISABLE)
  956.     internal_error (__FILE__, __LINE__,
  957.                     _("packet_ok: attempt to use a disabled packet"));

  958.   result = packet_check_result (buf);
  959.   switch (result)
  960.     {
  961.     case PACKET_OK:
  962.     case PACKET_ERROR:
  963.       /* The stub recognized the packet request.  */
  964.       if (config->support == PACKET_SUPPORT_UNKNOWN)
  965.         {
  966.           if (remote_debug)
  967.             fprintf_unfiltered (gdb_stdlog,
  968.                                 "Packet %s (%s) is supported\n",
  969.                                 config->name, config->title);
  970.           config->support = PACKET_ENABLE;
  971.         }
  972.       break;
  973.     case PACKET_UNKNOWN:
  974.       /* The stub does not support the packet.  */
  975.       if (config->detect == AUTO_BOOLEAN_AUTO
  976.           && config->support == PACKET_ENABLE)
  977.         {
  978.           /* If the stub previously indicated that the packet was
  979.              supported then there is a protocol error.  */
  980.           error (_("Protocol error: %s (%s) conflicting enabled responses."),
  981.                  config->name, config->title);
  982.         }
  983.       else if (config->detect == AUTO_BOOLEAN_TRUE)
  984.         {
  985.           /* The user set it wrong.  */
  986.           error (_("Enabled packet %s (%s) not recognized by stub"),
  987.                  config->name, config->title);
  988.         }

  989.       if (remote_debug)
  990.         fprintf_unfiltered (gdb_stdlog,
  991.                             "Packet %s (%s) is NOT supported\n",
  992.                             config->name, config->title);
  993.       config->support = PACKET_DISABLE;
  994.       break;
  995.     }

  996.   return result;
  997. }

  998. enum {
  999.   PACKET_vCont = 0,
  1000.   PACKET_X,
  1001.   PACKET_qSymbol,
  1002.   PACKET_P,
  1003.   PACKET_p,
  1004.   PACKET_Z0,
  1005.   PACKET_Z1,
  1006.   PACKET_Z2,
  1007.   PACKET_Z3,
  1008.   PACKET_Z4,
  1009.   PACKET_vFile_open,
  1010.   PACKET_vFile_pread,
  1011.   PACKET_vFile_pwrite,
  1012.   PACKET_vFile_close,
  1013.   PACKET_vFile_unlink,
  1014.   PACKET_vFile_readlink,
  1015.   PACKET_qXfer_auxv,
  1016.   PACKET_qXfer_features,
  1017.   PACKET_qXfer_libraries,
  1018.   PACKET_qXfer_libraries_svr4,
  1019.   PACKET_qXfer_memory_map,
  1020.   PACKET_qXfer_spu_read,
  1021.   PACKET_qXfer_spu_write,
  1022.   PACKET_qXfer_osdata,
  1023.   PACKET_qXfer_threads,
  1024.   PACKET_qXfer_statictrace_read,
  1025.   PACKET_qXfer_traceframe_info,
  1026.   PACKET_qXfer_uib,
  1027.   PACKET_qGetTIBAddr,
  1028.   PACKET_qGetTLSAddr,
  1029.   PACKET_qSupported,
  1030.   PACKET_qTStatus,
  1031.   PACKET_QPassSignals,
  1032.   PACKET_QProgramSignals,
  1033.   PACKET_qCRC,
  1034.   PACKET_qSearch_memory,
  1035.   PACKET_vAttach,
  1036.   PACKET_vRun,
  1037.   PACKET_QStartNoAckMode,
  1038.   PACKET_vKill,
  1039.   PACKET_qXfer_siginfo_read,
  1040.   PACKET_qXfer_siginfo_write,
  1041.   PACKET_qAttached,

  1042.   /* Support for conditional tracepoints.  */
  1043.   PACKET_ConditionalTracepoints,

  1044.   /* Support for target-side breakpoint conditions.  */
  1045.   PACKET_ConditionalBreakpoints,

  1046.   /* Support for target-side breakpoint commands.  */
  1047.   PACKET_BreakpointCommands,

  1048.   /* Support for fast tracepoints.  */
  1049.   PACKET_FastTracepoints,

  1050.   /* Support for static tracepoints.  */
  1051.   PACKET_StaticTracepoints,

  1052.   /* Support for installing tracepoints while a trace experiment is
  1053.      running.  */
  1054.   PACKET_InstallInTrace,

  1055.   PACKET_bc,
  1056.   PACKET_bs,
  1057.   PACKET_TracepointSource,
  1058.   PACKET_QAllow,
  1059.   PACKET_qXfer_fdpic,
  1060.   PACKET_QDisableRandomization,
  1061.   PACKET_QAgent,
  1062.   PACKET_QTBuffer_size,
  1063.   PACKET_Qbtrace_off,
  1064.   PACKET_Qbtrace_bts,
  1065.   PACKET_qXfer_btrace,

  1066.   /* Support for the QNonStop packet.  */
  1067.   PACKET_QNonStop,

  1068.   /* Support for multi-process extensions.  */
  1069.   PACKET_multiprocess_feature,

  1070.   /* Support for enabling and disabling tracepoints while a trace
  1071.      experiment is running.  */
  1072.   PACKET_EnableDisableTracepoints_feature,

  1073.   /* Support for collecting strings using the tracenz bytecode.  */
  1074.   PACKET_tracenz_feature,

  1075.   /* Support for continuing to run a trace experiment while GDB is
  1076.      disconnected.  */
  1077.   PACKET_DisconnectedTracing_feature,

  1078.   /* Support for qXfer:libraries-svr4:read with a non-empty annex.  */
  1079.   PACKET_augmented_libraries_svr4_read_feature,

  1080.   PACKET_MAX
  1081. };

  1082. static struct packet_config remote_protocol_packets[PACKET_MAX];

  1083. /* Returns whether a given packet or feature is supported.  This takes
  1084.    into account the state of the corresponding "set remote foo-packet"
  1085.    command, which may be used to bypass auto-detection.  */

  1086. static enum packet_support
  1087. packet_config_support (struct packet_config *config)
  1088. {
  1089.   switch (config->detect)
  1090.     {
  1091.     case AUTO_BOOLEAN_TRUE:
  1092.       return PACKET_ENABLE;
  1093.     case AUTO_BOOLEAN_FALSE:
  1094.       return PACKET_DISABLE;
  1095.     case AUTO_BOOLEAN_AUTO:
  1096.       return config->support;
  1097.     default:
  1098.       gdb_assert_not_reached (_("bad switch"));
  1099.     }
  1100. }

  1101. /* Same as packet_config_support, but takes the packet's enum value as
  1102.    argument.  */

  1103. static enum packet_support
  1104. packet_support (int packet)
  1105. {
  1106.   struct packet_config *config = &remote_protocol_packets[packet];

  1107.   return packet_config_support (config);
  1108. }

  1109. static void
  1110. show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
  1111.                                  struct cmd_list_element *c,
  1112.                                  const char *value)
  1113. {
  1114.   struct packet_config *packet;

  1115.   for (packet = remote_protocol_packets;
  1116.        packet < &remote_protocol_packets[PACKET_MAX];
  1117.        packet++)
  1118.     {
  1119.       if (&packet->detect == c->var)
  1120.         {
  1121.           show_packet_config_cmd (packet);
  1122.           return;
  1123.         }
  1124.     }
  1125.   internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
  1126.                   c->name);
  1127. }

  1128. /* Should we try one of the 'Z' requests?  */

  1129. enum Z_packet_type
  1130. {
  1131.   Z_PACKET_SOFTWARE_BP,
  1132.   Z_PACKET_HARDWARE_BP,
  1133.   Z_PACKET_WRITE_WP,
  1134.   Z_PACKET_READ_WP,
  1135.   Z_PACKET_ACCESS_WP,
  1136.   NR_Z_PACKET_TYPES
  1137. };

  1138. /* For compatibility with older distributions.  Provide a ``set remote
  1139.    Z-packet ...'' command that updates all the Z packet types.  */

  1140. static enum auto_boolean remote_Z_packet_detect;

  1141. static void
  1142. set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
  1143.                                   struct cmd_list_element *c)
  1144. {
  1145.   int i;

  1146.   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
  1147.     remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
  1148. }

  1149. static void
  1150. show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
  1151.                                    struct cmd_list_element *c,
  1152.                                    const char *value)
  1153. {
  1154.   int i;

  1155.   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
  1156.     {
  1157.       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
  1158.     }
  1159. }

  1160. /* Returns true if the multi-process extensions are in effect.  */

  1161. static int
  1162. remote_multi_process_p (struct remote_state *rs)
  1163. {
  1164.   return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
  1165. }

  1166. /* Tokens for use by the asynchronous signal handlers for SIGINT.  */
  1167. static struct async_signal_handler *async_sigint_remote_twice_token;
  1168. static struct async_signal_handler *async_sigint_remote_token;


  1169. /* Asynchronous signal handle registered as event loop source for
  1170.    when we have pending events ready to be passed to the core.  */

  1171. static struct async_event_handler *remote_async_inferior_event_token;



  1172. static ptid_t magic_null_ptid;
  1173. static ptid_t not_sent_ptid;
  1174. static ptid_t any_thread_ptid;

  1175. /* Find out if the stub attached to PID (and hence GDB should offer to
  1176.    detach instead of killing it when bailing out).  */

  1177. static int
  1178. remote_query_attached (int pid)
  1179. {
  1180.   struct remote_state *rs = get_remote_state ();
  1181.   size_t size = get_remote_packet_size ();

  1182.   if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
  1183.     return 0;

  1184.   if (remote_multi_process_p (rs))
  1185.     xsnprintf (rs->buf, size, "qAttached:%x", pid);
  1186.   else
  1187.     xsnprintf (rs->buf, size, "qAttached");

  1188.   putpkt (rs->buf);
  1189.   getpkt (&rs->buf, &rs->buf_size, 0);

  1190.   switch (packet_ok (rs->buf,
  1191.                      &remote_protocol_packets[PACKET_qAttached]))
  1192.     {
  1193.     case PACKET_OK:
  1194.       if (strcmp (rs->buf, "1") == 0)
  1195.         return 1;
  1196.       break;
  1197.     case PACKET_ERROR:
  1198.       warning (_("Remote failure reply: %s"), rs->buf);
  1199.       break;
  1200.     case PACKET_UNKNOWN:
  1201.       break;
  1202.     }

  1203.   return 0;
  1204. }

  1205. /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
  1206.    has been invented by GDB, instead of reported by the target.  Since
  1207.    we can be connected to a remote system before before knowing about
  1208.    any inferior, mark the target with execution when we find the first
  1209.    inferior.  If ATTACHED is 1, then we had just attached to this
  1210.    inferior.  If it is 0, then we just created this inferior.  If it
  1211.    is -1, then try querying the remote stub to find out if it had
  1212.    attached to the inferior or not.  */

  1213. static struct inferior *
  1214. remote_add_inferior (int fake_pid_p, int pid, int attached)
  1215. {
  1216.   struct inferior *inf;

  1217.   /* Check whether this process we're learning about is to be
  1218.      considered attached, or if is to be considered to have been
  1219.      spawned by the stub.  */
  1220.   if (attached == -1)
  1221.     attached = remote_query_attached (pid);

  1222.   if (gdbarch_has_global_solist (target_gdbarch ()))
  1223.     {
  1224.       /* If the target shares code across all inferiors, then every
  1225.          attach adds a new inferior.  */
  1226.       inf = add_inferior (pid);

  1227.       /* ... and every inferior is bound to the same program space.
  1228.          However, each inferior may still have its own address
  1229.          space.  */
  1230.       inf->aspace = maybe_new_address_space ();
  1231.       inf->pspace = current_program_space;
  1232.     }
  1233.   else
  1234.     {
  1235.       /* In the traditional debugging scenario, there's a 1-1 match
  1236.          between program/address spaces.  We simply bind the inferior
  1237.          to the program space's address space.  */
  1238.       inf = current_inferior ();
  1239.       inferior_appeared (inf, pid);
  1240.     }

  1241.   inf->attach_flag = attached;
  1242.   inf->fake_pid_p = fake_pid_p;

  1243.   return inf;
  1244. }

  1245. /* Add thread PTID to GDB's thread list.  Tag it as executing/running
  1246.    according to RUNNING.  */

  1247. static void
  1248. remote_add_thread (ptid_t ptid, int running)
  1249. {
  1250.   struct remote_state *rs = get_remote_state ();

  1251.   /* GDB historically didn't pull threads in the initial connection
  1252.      setup.  If the remote target doesn't even have a concept of
  1253.      threads (e.g., a bare-metal target), even if internally we
  1254.      consider that a single-threaded target, mentioning a new thread
  1255.      might be confusing to the user.  Be silent then, preserving the
  1256.      age old behavior.  */
  1257.   if (rs->starting_up)
  1258.     add_thread_silent (ptid);
  1259.   else
  1260.     add_thread (ptid);

  1261.   set_executing (ptid, running);
  1262.   set_running (ptid, running);
  1263. }

  1264. /* Come here when we learn about a thread id from the remote target.
  1265.    It may be the first time we hear about such thread, so take the
  1266.    opportunity to add it to GDB's thread list.  In case this is the
  1267.    first time we're noticing its corresponding inferior, add it to
  1268.    GDB's inferior list as well.  */

  1269. static void
  1270. remote_notice_new_inferior (ptid_t currthread, int running)
  1271. {
  1272.   /* If this is a new thread, add it to GDB's thread list.
  1273.      If we leave it up to WFI to do this, bad things will happen.  */

  1274.   if (in_thread_list (currthread) && is_exited (currthread))
  1275.     {
  1276.       /* We're seeing an event on a thread id we knew had exited.
  1277.          This has to be a new thread reusing the old id.  Add it.  */
  1278.       remote_add_thread (currthread, running);
  1279.       return;
  1280.     }

  1281.   if (!in_thread_list (currthread))
  1282.     {
  1283.       struct inferior *inf = NULL;
  1284.       int pid = ptid_get_pid (currthread);

  1285.       if (ptid_is_pid (inferior_ptid)
  1286.           && pid == ptid_get_pid (inferior_ptid))
  1287.         {
  1288.           /* inferior_ptid has no thread member yet.  This can happen
  1289.              with the vAttach -> remote_wait,"TAAthread:" path if the
  1290.              stub doesn't support qC.  This is the first stop reported
  1291.              after an attach, so this is the main thread.  Update the
  1292.              ptid in the thread list.  */
  1293.           if (in_thread_list (pid_to_ptid (pid)))
  1294.             thread_change_ptid (inferior_ptid, currthread);
  1295.           else
  1296.             {
  1297.               remote_add_thread (currthread, running);
  1298.               inferior_ptid = currthread;
  1299.             }
  1300.           return;
  1301.         }

  1302.       if (ptid_equal (magic_null_ptid, inferior_ptid))
  1303.         {
  1304.           /* inferior_ptid is not set yet.  This can happen with the
  1305.              vRun -> remote_wait,"TAAthread:" path if the stub
  1306.              doesn't support qC.  This is the first stop reported
  1307.              after an attach, so this is the main thread.  Update the
  1308.              ptid in the thread list.  */
  1309.           thread_change_ptid (inferior_ptid, currthread);
  1310.           return;
  1311.         }

  1312.       /* When connecting to a target remote, or to a target
  1313.          extended-remote which already was debugging an inferior, we
  1314.          may not know about it yet.  Add it before adding its child
  1315.          thread, so notifications are emitted in a sensible order.  */
  1316.       if (!in_inferior_list (ptid_get_pid (currthread)))
  1317.         {
  1318.           struct remote_state *rs = get_remote_state ();
  1319.           int fake_pid_p = !remote_multi_process_p (rs);

  1320.           inf = remote_add_inferior (fake_pid_p,
  1321.                                      ptid_get_pid (currthread), -1);
  1322.         }

  1323.       /* This is really a new thread.  Add it.  */
  1324.       remote_add_thread (currthread, running);

  1325.       /* If we found a new inferior, let the common code do whatever
  1326.          it needs to with it (e.g., read shared libraries, insert
  1327.          breakpoints), unless we're just setting up an all-stop
  1328.          connection.  */
  1329.       if (inf != NULL)
  1330.         {
  1331.           struct remote_state *rs = get_remote_state ();

  1332.           if (non_stop || !rs->starting_up)
  1333.             notice_new_inferior (currthread, running, 0);
  1334.         }
  1335.     }
  1336. }

  1337. /* Return the private thread data, creating it if necessary.  */

  1338. static struct private_thread_info *
  1339. demand_private_info (ptid_t ptid)
  1340. {
  1341.   struct thread_info *info = find_thread_ptid (ptid);

  1342.   gdb_assert (info);

  1343.   if (!info->private)
  1344.     {
  1345.       info->private = xmalloc (sizeof (*(info->private)));
  1346.       info->private_dtor = free_private_thread_info;
  1347.       info->private->core = -1;
  1348.       info->private->extra = 0;
  1349.     }

  1350.   return info->private;
  1351. }

  1352. /* Call this function as a result of
  1353.    1) A halt indication (T packet) containing a thread id
  1354.    2) A direct query of currthread
  1355.    3) Successful execution of set thread */

  1356. static void
  1357. record_currthread (struct remote_state *rs, ptid_t currthread)
  1358. {
  1359.   rs->general_thread = currthread;
  1360. }

  1361. /* If 'QPassSignals' is supported, tell the remote stub what signals
  1362.    it can simply pass through to the inferior without reporting.  */

  1363. static void
  1364. remote_pass_signals (struct target_ops *self,
  1365.                      int numsigs, unsigned char *pass_signals)
  1366. {
  1367.   if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
  1368.     {
  1369.       char *pass_packet, *p;
  1370.       int count = 0, i;
  1371.       struct remote_state *rs = get_remote_state ();

  1372.       gdb_assert (numsigs < 256);
  1373.       for (i = 0; i < numsigs; i++)
  1374.         {
  1375.           if (pass_signals[i])
  1376.             count++;
  1377.         }
  1378.       pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
  1379.       strcpy (pass_packet, "QPassSignals:");
  1380.       p = pass_packet + strlen (pass_packet);
  1381.       for (i = 0; i < numsigs; i++)
  1382.         {
  1383.           if (pass_signals[i])
  1384.             {
  1385.               if (i >= 16)
  1386.                 *p++ = tohex (i >> 4);
  1387.               *p++ = tohex (i & 15);
  1388.               if (count)
  1389.                 *p++ = ';';
  1390.               else
  1391.                 break;
  1392.               count--;
  1393.             }
  1394.         }
  1395.       *p = 0;
  1396.       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
  1397.         {
  1398.           putpkt (pass_packet);
  1399.           getpkt (&rs->buf, &rs->buf_size, 0);
  1400.           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
  1401.           if (rs->last_pass_packet)
  1402.             xfree (rs->last_pass_packet);
  1403.           rs->last_pass_packet = pass_packet;
  1404.         }
  1405.       else
  1406.         xfree (pass_packet);
  1407.     }
  1408. }

  1409. /* If 'QProgramSignals' is supported, tell the remote stub what
  1410.    signals it should pass through to the inferior when detaching.  */

  1411. static void
  1412. remote_program_signals (struct target_ops *self,
  1413.                         int numsigs, unsigned char *signals)
  1414. {
  1415.   if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
  1416.     {
  1417.       char *packet, *p;
  1418.       int count = 0, i;
  1419.       struct remote_state *rs = get_remote_state ();

  1420.       gdb_assert (numsigs < 256);
  1421.       for (i = 0; i < numsigs; i++)
  1422.         {
  1423.           if (signals[i])
  1424.             count++;
  1425.         }
  1426.       packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
  1427.       strcpy (packet, "QProgramSignals:");
  1428.       p = packet + strlen (packet);
  1429.       for (i = 0; i < numsigs; i++)
  1430.         {
  1431.           if (signal_pass_state (i))
  1432.             {
  1433.               if (i >= 16)
  1434.                 *p++ = tohex (i >> 4);
  1435.               *p++ = tohex (i & 15);
  1436.               if (count)
  1437.                 *p++ = ';';
  1438.               else
  1439.                 break;
  1440.               count--;
  1441.             }
  1442.         }
  1443.       *p = 0;
  1444.       if (!rs->last_program_signals_packet
  1445.           || strcmp (rs->last_program_signals_packet, packet) != 0)
  1446.         {
  1447.           putpkt (packet);
  1448.           getpkt (&rs->buf, &rs->buf_size, 0);
  1449.           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
  1450.           xfree (rs->last_program_signals_packet);
  1451.           rs->last_program_signals_packet = packet;
  1452.         }
  1453.       else
  1454.         xfree (packet);
  1455.     }
  1456. }

  1457. /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
  1458.    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
  1459.    thread.  If GEN is set, set the general thread, if not, then set
  1460.    the step/continue thread.  */
  1461. static void
  1462. set_thread (struct ptid ptid, int gen)
  1463. {
  1464.   struct remote_state *rs = get_remote_state ();
  1465.   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
  1466.   char *buf = rs->buf;
  1467.   char *endbuf = rs->buf + get_remote_packet_size ();

  1468.   if (ptid_equal (state, ptid))
  1469.     return;

  1470.   *buf++ = 'H';
  1471.   *buf++ = gen ? 'g' : 'c';
  1472.   if (ptid_equal (ptid, magic_null_ptid))
  1473.     xsnprintf (buf, endbuf - buf, "0");
  1474.   else if (ptid_equal (ptid, any_thread_ptid))
  1475.     xsnprintf (buf, endbuf - buf, "0");
  1476.   else if (ptid_equal (ptid, minus_one_ptid))
  1477.     xsnprintf (buf, endbuf - buf, "-1");
  1478.   else
  1479.     write_ptid (buf, endbuf, ptid);
  1480.   putpkt (rs->buf);
  1481.   getpkt (&rs->buf, &rs->buf_size, 0);
  1482.   if (gen)
  1483.     rs->general_thread = ptid;
  1484.   else
  1485.     rs->continue_thread = ptid;
  1486. }

  1487. static void
  1488. set_general_thread (struct ptid ptid)
  1489. {
  1490.   set_thread (ptid, 1);
  1491. }

  1492. static void
  1493. set_continue_thread (struct ptid ptid)
  1494. {
  1495.   set_thread (ptid, 0);
  1496. }

  1497. /* Change the remote current process.  Which thread within the process
  1498.    ends up selected isn't important, as long as it is the same process
  1499.    as what INFERIOR_PTID points to.

  1500.    This comes from that fact that there is no explicit notion of
  1501.    "selected process" in the protocol.  The selected process for
  1502.    general operations is the process the selected general thread
  1503.    belongs to.  */

  1504. static void
  1505. set_general_process (void)
  1506. {
  1507.   struct remote_state *rs = get_remote_state ();

  1508.   /* If the remote can't handle multiple processes, don't bother.  */
  1509.   if (!rs->extended || !remote_multi_process_p (rs))
  1510.     return;

  1511.   /* We only need to change the remote current thread if it's pointing
  1512.      at some other process.  */
  1513.   if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
  1514.     set_general_thread (inferior_ptid);
  1515. }


  1516. /* Return nonzero if this is the main thread that we made up ourselves
  1517.    to model non-threaded targets as single-threaded.  */

  1518. static int
  1519. remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
  1520. {
  1521.   struct remote_state *rs = get_remote_state ();
  1522.   char *p, *endp;

  1523.   if (ptid_equal (ptid, magic_null_ptid))
  1524.     /* The main thread is always alive.  */
  1525.     return 1;

  1526.   if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
  1527.     /* The main thread is always alive.  This can happen after a
  1528.        vAttach, if the remote side doesn't support
  1529.        multi-threading.  */
  1530.     return 1;

  1531.   return 0;
  1532. }

  1533. /* Return nonzero if the thread PTID is still alive on the remote
  1534.    system.  */

  1535. static int
  1536. remote_thread_alive (struct target_ops *ops, ptid_t ptid)
  1537. {
  1538.   struct remote_state *rs = get_remote_state ();
  1539.   char *p, *endp;

  1540.   /* Check if this is a thread that we made up ourselves to model
  1541.      non-threaded targets as single-threaded.  */
  1542.   if (remote_thread_always_alive (ops, ptid))
  1543.     return 1;

  1544.   p = rs->buf;
  1545.   endp = rs->buf + get_remote_packet_size ();

  1546.   *p++ = 'T';
  1547.   write_ptid (p, endp, ptid);

  1548.   putpkt (rs->buf);
  1549.   getpkt (&rs->buf, &rs->buf_size, 0);
  1550.   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
  1551. }

  1552. /* About these extended threadlist and threadinfo packets.  They are
  1553.    variable length packets but, the fields within them are often fixed
  1554.    length.  They are redundent enough to send over UDP as is the
  1555.    remote protocol in general.  There is a matching unit test module
  1556.    in libstub.  */

  1557. /* WARNING: This threadref data structure comes from the remote O.S.,
  1558.    libstub protocol encoding, and remote.c.  It is not particularly
  1559.    changable.  */

  1560. /* Right now, the internal structure is int. We want it to be bigger.
  1561.    Plan to fix this.  */

  1562. typedef int gdb_threadref;        /* Internal GDB thread reference.  */

  1563. /* gdb_ext_thread_info is an internal GDB data structure which is
  1564.    equivalent to the reply of the remote threadinfo packet.  */

  1565. struct gdb_ext_thread_info
  1566.   {
  1567.     threadref threadid;                /* External form of thread reference.  */
  1568.     int active;                        /* Has state interesting to GDB?
  1569.                                    regs, stack.  */
  1570.     char display[256];                /* Brief state display, name,
  1571.                                    blocked/suspended.  */
  1572.     char shortname[32];                /* To be used to name threads.  */
  1573.     char more_display[256];        /* Long info, statistics, queue depth,
  1574.                                    whatever.  */
  1575.   };

  1576. /* The volume of remote transfers can be limited by submitting
  1577.    a mask containing bits specifying the desired information.
  1578.    Use a union of these values as the 'selection' parameter to
  1579.    get_thread_info.  FIXME: Make these TAG names more thread specific.  */

  1580. #define TAG_THREADID 1
  1581. #define TAG_EXISTS 2
  1582. #define TAG_DISPLAY 4
  1583. #define TAG_THREADNAME 8
  1584. #define TAG_MOREDISPLAY 16

  1585. #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)

  1586. static char *unpack_nibble (char *buf, int *val);

  1587. static char *unpack_byte (char *buf, int *value);

  1588. static char *pack_int (char *buf, int value);

  1589. static char *unpack_int (char *buf, int *value);

  1590. static char *unpack_string (char *src, char *dest, int length);

  1591. static char *pack_threadid (char *pkt, threadref *id);

  1592. static char *unpack_threadid (char *inbuf, threadref *id);

  1593. void int_to_threadref (threadref *id, int value);

  1594. static int threadref_to_int (threadref *ref);

  1595. static void copy_threadref (threadref *dest, threadref *src);

  1596. static int threadmatch (threadref *dest, threadref *src);

  1597. static char *pack_threadinfo_request (char *pkt, int mode,
  1598.                                       threadref *id);

  1599. static int remote_unpack_thread_info_response (char *pkt,
  1600.                                                threadref *expectedref,
  1601.                                                struct gdb_ext_thread_info
  1602.                                                *info);


  1603. static int remote_get_threadinfo (threadref *threadid,
  1604.                                   int fieldset,        /*TAG mask */
  1605.                                   struct gdb_ext_thread_info *info);

  1606. static char *pack_threadlist_request (char *pkt, int startflag,
  1607.                                       int threadcount,
  1608.                                       threadref *nextthread);

  1609. static int parse_threadlist_response (char *pkt,
  1610.                                       int result_limit,
  1611.                                       threadref *original_echo,
  1612.                                       threadref *resultlist,
  1613.                                       int *doneflag);

  1614. static int remote_get_threadlist (int startflag,
  1615.                                   threadref *nextthread,
  1616.                                   int result_limit,
  1617.                                   int *done,
  1618.                                   int *result_count,
  1619.                                   threadref *threadlist);

  1620. typedef int (*rmt_thread_action) (threadref *ref, void *context);

  1621. static int remote_threadlist_iterator (rmt_thread_action stepfunction,
  1622.                                        void *context, int looplimit);

  1623. static int remote_newthread_step (threadref *ref, void *context);


  1624. /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
  1625.    buffer we're allowed to write to.  Returns
  1626.    BUF+CHARACTERS_WRITTEN.  */

  1627. static char *
  1628. write_ptid (char *buf, const char *endbuf, ptid_t ptid)
  1629. {
  1630.   int pid, tid;
  1631.   struct remote_state *rs = get_remote_state ();

  1632.   if (remote_multi_process_p (rs))
  1633.     {
  1634.       pid = ptid_get_pid (ptid);
  1635.       if (pid < 0)
  1636.         buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
  1637.       else
  1638.         buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
  1639.     }
  1640.   tid = ptid_get_lwp (ptid);
  1641.   if (tid < 0)
  1642.     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
  1643.   else
  1644.     buf += xsnprintf (buf, endbuf - buf, "%x", tid);

  1645.   return buf;
  1646. }

  1647. /* Extract a PTID from BUF.  If non-null, OBUF is set to the to one
  1648.    passed the last parsed char.  Returns null_ptid on error.  */

  1649. static ptid_t
  1650. read_ptid (char *buf, char **obuf)
  1651. {
  1652.   char *p = buf;
  1653.   char *pp;
  1654.   ULONGEST pid = 0, tid = 0;

  1655.   if (*p == 'p')
  1656.     {
  1657.       /* Multi-process ptid.  */
  1658.       pp = unpack_varlen_hex (p + 1, &pid);
  1659.       if (*pp != '.')
  1660.         error (_("invalid remote ptid: %s"), p);

  1661.       p = pp;
  1662.       pp = unpack_varlen_hex (p + 1, &tid);
  1663.       if (obuf)
  1664.         *obuf = pp;
  1665.       return ptid_build (pid, tid, 0);
  1666.     }

  1667.   /* No multi-process.  Just a tid.  */
  1668.   pp = unpack_varlen_hex (p, &tid);

  1669.   /* Since the stub is not sending a process id, then default to
  1670.      what's in inferior_ptid, unless it's null at this point.  If so,
  1671.      then since there's no way to know the pid of the reported
  1672.      threads, use the magic number.  */
  1673.   if (ptid_equal (inferior_ptid, null_ptid))
  1674.     pid = ptid_get_pid (magic_null_ptid);
  1675.   else
  1676.     pid = ptid_get_pid (inferior_ptid);

  1677.   if (obuf)
  1678.     *obuf = pp;
  1679.   return ptid_build (pid, tid, 0);
  1680. }

  1681. static int
  1682. stubhex (int ch)
  1683. {
  1684.   if (ch >= 'a' && ch <= 'f')
  1685.     return ch - 'a' + 10;
  1686.   if (ch >= '0' && ch <= '9')
  1687.     return ch - '0';
  1688.   if (ch >= 'A' && ch <= 'F')
  1689.     return ch - 'A' + 10;
  1690.   return -1;
  1691. }

  1692. static int
  1693. stub_unpack_int (char *buff, int fieldlength)
  1694. {
  1695.   int nibble;
  1696.   int retval = 0;

  1697.   while (fieldlength)
  1698.     {
  1699.       nibble = stubhex (*buff++);
  1700.       retval |= nibble;
  1701.       fieldlength--;
  1702.       if (fieldlength)
  1703.         retval = retval << 4;
  1704.     }
  1705.   return retval;
  1706. }

  1707. static char *
  1708. unpack_nibble (char *buf, int *val)
  1709. {
  1710.   *val = fromhex (*buf++);
  1711.   return buf;
  1712. }

  1713. static char *
  1714. unpack_byte (char *buf, int *value)
  1715. {
  1716.   *value = stub_unpack_int (buf, 2);
  1717.   return buf + 2;
  1718. }

  1719. static char *
  1720. pack_int (char *buf, int value)
  1721. {
  1722.   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
  1723.   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
  1724.   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
  1725.   buf = pack_hex_byte (buf, (value & 0xff));
  1726.   return buf;
  1727. }

  1728. static char *
  1729. unpack_int (char *buf, int *value)
  1730. {
  1731.   *value = stub_unpack_int (buf, 8);
  1732.   return buf + 8;
  1733. }

  1734. #if 0                        /* Currently unused, uncomment when needed.  */
  1735. static char *pack_string (char *pkt, char *string);

  1736. static char *
  1737. pack_string (char *pkt, char *string)
  1738. {
  1739.   char ch;
  1740.   int len;

  1741.   len = strlen (string);
  1742.   if (len > 200)
  1743.     len = 200;                /* Bigger than most GDB packets, junk???  */
  1744.   pkt = pack_hex_byte (pkt, len);
  1745.   while (len-- > 0)
  1746.     {
  1747.       ch = *string++;
  1748.       if ((ch == '\0') || (ch == '#'))
  1749.         ch = '*';                /* Protect encapsulation.  */
  1750.       *pkt++ = ch;
  1751.     }
  1752.   return pkt;
  1753. }
  1754. #endif /* 0 (unused) */

  1755. static char *
  1756. unpack_string (char *src, char *dest, int length)
  1757. {
  1758.   while (length--)
  1759.     *dest++ = *src++;
  1760.   *dest = '\0';
  1761.   return src;
  1762. }

  1763. static char *
  1764. pack_threadid (char *pkt, threadref *id)
  1765. {
  1766.   char *limit;
  1767.   unsigned char *altid;

  1768.   altid = (unsigned char *) id;
  1769.   limit = pkt + BUF_THREAD_ID_SIZE;
  1770.   while (pkt < limit)
  1771.     pkt = pack_hex_byte (pkt, *altid++);
  1772.   return pkt;
  1773. }


  1774. static char *
  1775. unpack_threadid (char *inbuf, threadref *id)
  1776. {
  1777.   char *altref;
  1778.   char *limit = inbuf + BUF_THREAD_ID_SIZE;
  1779.   int x, y;

  1780.   altref = (char *) id;

  1781.   while (inbuf < limit)
  1782.     {
  1783.       x = stubhex (*inbuf++);
  1784.       y = stubhex (*inbuf++);
  1785.       *altref++ = (x << 4) | y;
  1786.     }
  1787.   return inbuf;
  1788. }

  1789. /* Externally, threadrefs are 64 bits but internally, they are still
  1790.    ints.  This is due to a mismatch of specifications.  We would like
  1791.    to use 64bit thread references internally.  This is an adapter
  1792.    function.  */

  1793. void
  1794. int_to_threadref (threadref *id, int value)
  1795. {
  1796.   unsigned char *scan;

  1797.   scan = (unsigned char *) id;
  1798.   {
  1799.     int i = 4;
  1800.     while (i--)
  1801.       *scan++ = 0;
  1802.   }
  1803.   *scan++ = (value >> 24) & 0xff;
  1804.   *scan++ = (value >> 16) & 0xff;
  1805.   *scan++ = (value >> 8) & 0xff;
  1806.   *scan++ = (value & 0xff);
  1807. }

  1808. static int
  1809. threadref_to_int (threadref *ref)
  1810. {
  1811.   int i, value = 0;
  1812.   unsigned char *scan;

  1813.   scan = *ref;
  1814.   scan += 4;
  1815.   i = 4;
  1816.   while (i-- > 0)
  1817.     value = (value << 8) | ((*scan++) & 0xff);
  1818.   return value;
  1819. }

  1820. static void
  1821. copy_threadref (threadref *dest, threadref *src)
  1822. {
  1823.   int i;
  1824.   unsigned char *csrc, *cdest;

  1825.   csrc = (unsigned char *) src;
  1826.   cdest = (unsigned char *) dest;
  1827.   i = 8;
  1828.   while (i--)
  1829.     *cdest++ = *csrc++;
  1830. }

  1831. static int
  1832. threadmatch (threadref *dest, threadref *src)
  1833. {
  1834.   /* Things are broken right now, so just assume we got a match.  */
  1835. #if 0
  1836.   unsigned char *srcp, *destp;
  1837.   int i, result;
  1838.   srcp = (char *) src;
  1839.   destp = (char *) dest;

  1840.   result = 1;
  1841.   while (i-- > 0)
  1842.     result &= (*srcp++ == *destp++) ? 1 : 0;
  1843.   return result;
  1844. #endif
  1845.   return 1;
  1846. }

  1847. /*
  1848.    threadid:1,        # always request threadid
  1849.    context_exists:2,
  1850.    display:4,
  1851.    unique_name:8,
  1852.    more_display:16
  1853. */

  1854. /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */

  1855. static char *
  1856. pack_threadinfo_request (char *pkt, int mode, threadref *id)
  1857. {
  1858.   *pkt++ = 'q';                                /* Info Query */
  1859.   *pkt++ = 'P';                                /* process or thread info */
  1860.   pkt = pack_int (pkt, mode);                /* mode */
  1861.   pkt = pack_threadid (pkt, id);        /* threadid */
  1862.   *pkt = '\0';                                /* terminate */
  1863.   return pkt;
  1864. }

  1865. /* These values tag the fields in a thread info response packet.  */
  1866. /* Tagging the fields allows us to request specific fields and to
  1867.    add more fields as time goes by.  */

  1868. #define TAG_THREADID 1                /* Echo the thread identifier.  */
  1869. #define TAG_EXISTS 2                /* Is this process defined enough to
  1870.                                    fetch registers and its stack?  */
  1871. #define TAG_DISPLAY 4                /* A short thing maybe to put on a window */
  1872. #define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is.  */
  1873. #define TAG_MOREDISPLAY 16        /* Whatever the kernel wants to say about
  1874.                                    the process.  */

  1875. static int
  1876. remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
  1877.                                     struct gdb_ext_thread_info *info)
  1878. {
  1879.   struct remote_state *rs = get_remote_state ();
  1880.   int mask, length;
  1881.   int tag;
  1882.   threadref ref;
  1883.   char *limit = pkt + rs->buf_size; /* Plausible parsing limit.  */
  1884.   int retval = 1;

  1885.   /* info->threadid = 0; FIXME: implement zero_threadref.  */
  1886.   info->active = 0;
  1887.   info->display[0] = '\0';
  1888.   info->shortname[0] = '\0';
  1889.   info->more_display[0] = '\0';

  1890.   /* Assume the characters indicating the packet type have been
  1891.      stripped.  */
  1892.   pkt = unpack_int (pkt, &mask);        /* arg mask */
  1893.   pkt = unpack_threadid (pkt, &ref);

  1894.   if (mask == 0)
  1895.     warning (_("Incomplete response to threadinfo request."));
  1896.   if (!threadmatch (&ref, expectedref))
  1897.     {                        /* This is an answer to a different request.  */
  1898.       warning (_("ERROR RMT Thread info mismatch."));
  1899.       return 0;
  1900.     }
  1901.   copy_threadref (&info->threadid, &ref);

  1902.   /* Loop on tagged fields , try to bail if somthing goes wrong.  */

  1903.   /* Packets are terminated with nulls.  */
  1904.   while ((pkt < limit) && mask && *pkt)
  1905.     {
  1906.       pkt = unpack_int (pkt, &tag);        /* tag */
  1907.       pkt = unpack_byte (pkt, &length);        /* length */
  1908.       if (!(tag & mask))                /* Tags out of synch with mask.  */
  1909.         {
  1910.           warning (_("ERROR RMT: threadinfo tag mismatch."));
  1911.           retval = 0;
  1912.           break;
  1913.         }
  1914.       if (tag == TAG_THREADID)
  1915.         {
  1916.           if (length != 16)
  1917.             {
  1918.               warning (_("ERROR RMT: length of threadid is not 16."));
  1919.               retval = 0;
  1920.               break;
  1921.             }
  1922.           pkt = unpack_threadid (pkt, &ref);
  1923.           mask = mask & ~TAG_THREADID;
  1924.           continue;
  1925.         }
  1926.       if (tag == TAG_EXISTS)
  1927.         {
  1928.           info->active = stub_unpack_int (pkt, length);
  1929.           pkt += length;
  1930.           mask = mask & ~(TAG_EXISTS);
  1931.           if (length > 8)
  1932.             {
  1933.               warning (_("ERROR RMT: 'exists' length too long."));
  1934.               retval = 0;
  1935.               break;
  1936.             }
  1937.           continue;
  1938.         }
  1939.       if (tag == TAG_THREADNAME)
  1940.         {
  1941.           pkt = unpack_string (pkt, &info->shortname[0], length);
  1942.           mask = mask & ~TAG_THREADNAME;
  1943.           continue;
  1944.         }
  1945.       if (tag == TAG_DISPLAY)
  1946.         {
  1947.           pkt = unpack_string (pkt, &info->display[0], length);
  1948.           mask = mask & ~TAG_DISPLAY;
  1949.           continue;
  1950.         }
  1951.       if (tag == TAG_MOREDISPLAY)
  1952.         {
  1953.           pkt = unpack_string (pkt, &info->more_display[0], length);
  1954.           mask = mask & ~TAG_MOREDISPLAY;
  1955.           continue;
  1956.         }
  1957.       warning (_("ERROR RMT: unknown thread info tag."));
  1958.       break;                        /* Not a tag we know about.  */
  1959.     }
  1960.   return retval;
  1961. }

  1962. static int
  1963. remote_get_threadinfo (threadref *threadid, int fieldset,        /* TAG mask */
  1964.                        struct gdb_ext_thread_info *info)
  1965. {
  1966.   struct remote_state *rs = get_remote_state ();
  1967.   int result;

  1968.   pack_threadinfo_request (rs->buf, fieldset, threadid);
  1969.   putpkt (rs->buf);
  1970.   getpkt (&rs->buf, &rs->buf_size, 0);

  1971.   if (rs->buf[0] == '\0')
  1972.     return 0;

  1973.   result = remote_unpack_thread_info_response (rs->buf + 2,
  1974.                                                threadid, info);
  1975.   return result;
  1976. }

  1977. /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */

  1978. static char *
  1979. pack_threadlist_request (char *pkt, int startflag, int threadcount,
  1980.                          threadref *nextthread)
  1981. {
  1982.   *pkt++ = 'q';                        /* info query packet */
  1983.   *pkt++ = 'L';                        /* Process LIST or threadLIST request */
  1984.   pkt = pack_nibble (pkt, startflag);                /* initflag 1 bytes */
  1985.   pkt = pack_hex_byte (pkt, threadcount);        /* threadcount 2 bytes */
  1986.   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
  1987.   *pkt = '\0';
  1988.   return pkt;
  1989. }

  1990. /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */

  1991. static int
  1992. parse_threadlist_response (char *pkt, int result_limit,
  1993.                            threadref *original_echo, threadref *resultlist,
  1994.                            int *doneflag)
  1995. {
  1996.   struct remote_state *rs = get_remote_state ();
  1997.   char *limit;
  1998.   int count, resultcount, done;

  1999.   resultcount = 0;
  2000.   /* Assume the 'q' and 'M chars have been stripped.  */
  2001.   limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
  2002.   /* done parse past here */
  2003.   pkt = unpack_byte (pkt, &count);        /* count field */
  2004.   pkt = unpack_nibble (pkt, &done);
  2005.   /* The first threadid is the argument threadid.  */
  2006.   pkt = unpack_threadid (pkt, original_echo);        /* should match query packet */
  2007.   while ((count-- > 0) && (pkt < limit))
  2008.     {
  2009.       pkt = unpack_threadid (pkt, resultlist++);
  2010.       if (resultcount++ >= result_limit)
  2011.         break;
  2012.     }
  2013.   if (doneflag)
  2014.     *doneflag = done;
  2015.   return resultcount;
  2016. }

  2017. /* Fetch the next batch of threads from the remote.  Returns -1 if the
  2018.    qL packet is not supported, 0 on error and 1 on success.  */

  2019. static int
  2020. remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
  2021.                        int *done, int *result_count, threadref *threadlist)
  2022. {
  2023.   struct remote_state *rs = get_remote_state ();
  2024.   int result = 1;

  2025.   /* Trancate result limit to be smaller than the packet size.  */
  2026.   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
  2027.       >= get_remote_packet_size ())
  2028.     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;

  2029.   pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
  2030.   putpkt (rs->buf);
  2031.   getpkt (&rs->buf, &rs->buf_size, 0);
  2032.   if (*rs->buf == '\0')
  2033.     {
  2034.       /* Packet not supported.  */
  2035.       return -1;
  2036.     }

  2037.   *result_count =
  2038.     parse_threadlist_response (rs->buf + 2, result_limit,
  2039.                                &rs->echo_nextthread, threadlist, done);

  2040.   if (!threadmatch (&rs->echo_nextthread, nextthread))
  2041.     {
  2042.       /* FIXME: This is a good reason to drop the packet.  */
  2043.       /* Possably, there is a duplicate response.  */
  2044.       /* Possabilities :
  2045.          retransmit immediatly - race conditions
  2046.          retransmit after timeout - yes
  2047.          exit
  2048.          wait for packet, then exit
  2049.        */
  2050.       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
  2051.       return 0;                        /* I choose simply exiting.  */
  2052.     }
  2053.   if (*result_count <= 0)
  2054.     {
  2055.       if (*done != 1)
  2056.         {
  2057.           warning (_("RMT ERROR : failed to get remote thread list."));
  2058.           result = 0;
  2059.         }
  2060.       return result;                /* break; */
  2061.     }
  2062.   if (*result_count > result_limit)
  2063.     {
  2064.       *result_count = 0;
  2065.       warning (_("RMT ERROR: threadlist response longer than requested."));
  2066.       return 0;
  2067.     }
  2068.   return result;
  2069. }

  2070. /* Fetch the list of remote threads, with the qL packet, and call
  2071.    STEPFUNCTION for each thread found.  Stops iterating and returns 1
  2072.    if STEPFUNCTION returns true.  Stops iterating and returns 0 if the
  2073.    STEPFUNCTION returns false.  If the packet is not supported,
  2074.    returns -1.  */

  2075. static int
  2076. remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
  2077.                             int looplimit)
  2078. {
  2079.   struct remote_state *rs = get_remote_state ();
  2080.   int done, i, result_count;
  2081.   int startflag = 1;
  2082.   int result = 1;
  2083.   int loopcount = 0;

  2084.   done = 0;
  2085.   while (!done)
  2086.     {
  2087.       if (loopcount++ > looplimit)
  2088.         {
  2089.           result = 0;
  2090.           warning (_("Remote fetch threadlist -infinite loop-."));
  2091.           break;
  2092.         }
  2093.       result = remote_get_threadlist (startflag, &rs->nextthread,
  2094.                                       MAXTHREADLISTRESULTS,
  2095.                                       &done, &result_count,
  2096.                                       rs->resultthreadlist);
  2097.       if (result <= 0)
  2098.         break;
  2099.       /* Clear for later iterations.  */
  2100.       startflag = 0;
  2101.       /* Setup to resume next batch of thread references, set nextthread.  */
  2102.       if (result_count >= 1)
  2103.         copy_threadref (&rs->nextthread,
  2104.                         &rs->resultthreadlist[result_count - 1]);
  2105.       i = 0;
  2106.       while (result_count--)
  2107.         {
  2108.           if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
  2109.             {
  2110.               result = 0;
  2111.               break;
  2112.             }
  2113.         }
  2114.     }
  2115.   return result;
  2116. }

  2117. /* A thread found on the remote target.  */

  2118. typedef struct thread_item
  2119. {
  2120.   /* The thread's PTID.  */
  2121.   ptid_t ptid;

  2122.   /* The thread's extra info.  May be NULL.  */
  2123.   char *extra;

  2124.   /* The core the thread was running on.  -1 if not known.  */
  2125.   int core;
  2126. } thread_item_t;
  2127. DEF_VEC_O(thread_item_t);

  2128. /* Context passed around to the various methods listing remote
  2129.    threads.  As new threads are found, they're added to the ITEMS
  2130.    vector.  */

  2131. struct threads_listing_context
  2132. {
  2133.   /* The threads found on the remote target.  */
  2134.   VEC (thread_item_t) *items;
  2135. };

  2136. /* Discard the contents of the constructed thread listing context.  */

  2137. static void
  2138. clear_threads_listing_context (void *p)
  2139. {
  2140.   struct threads_listing_context *context = p;
  2141.   int i;
  2142.   struct thread_item *item;

  2143.   for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
  2144.     xfree (item->extra);

  2145.   VEC_free (thread_item_t, context->items);
  2146. }

  2147. static int
  2148. remote_newthread_step (threadref *ref, void *data)
  2149. {
  2150.   struct threads_listing_context *context = data;
  2151.   struct thread_item item;
  2152.   int pid = ptid_get_pid (inferior_ptid);

  2153.   item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
  2154.   item.core = -1;
  2155.   item.extra = NULL;

  2156.   VEC_safe_push (thread_item_t, context->items, &item);

  2157.   return 1;                        /* continue iterator */
  2158. }

  2159. #define CRAZY_MAX_THREADS 1000

  2160. static ptid_t
  2161. remote_current_thread (ptid_t oldpid)
  2162. {
  2163.   struct remote_state *rs = get_remote_state ();

  2164.   putpkt ("qC");
  2165.   getpkt (&rs->buf, &rs->buf_size, 0);
  2166.   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
  2167.     return read_ptid (&rs->buf[2], NULL);
  2168.   else
  2169.     return oldpid;
  2170. }

  2171. /* List remote threads using the deprecated qL packet.  */

  2172. static int
  2173. remote_get_threads_with_ql (struct target_ops *ops,
  2174.                             struct threads_listing_context *context)
  2175. {
  2176.   if (remote_threadlist_iterator (remote_newthread_step, context,
  2177.                                   CRAZY_MAX_THREADS) >= 0)
  2178.     return 1;

  2179.   return 0;
  2180. }

  2181. #if defined(HAVE_LIBEXPAT)

  2182. static void
  2183. start_thread (struct gdb_xml_parser *parser,
  2184.               const struct gdb_xml_element *element,
  2185.               void *user_data, VEC(gdb_xml_value_s) *attributes)
  2186. {
  2187.   struct threads_listing_context *data = user_data;

  2188.   struct thread_item item;
  2189.   char *id;
  2190.   struct gdb_xml_value *attr;

  2191.   id = xml_find_attribute (attributes, "id")->value;
  2192.   item.ptid = read_ptid (id, NULL);

  2193.   attr = xml_find_attribute (attributes, "core");
  2194.   if (attr != NULL)
  2195.     item.core = *(ULONGEST *) attr->value;
  2196.   else
  2197.     item.core = -1;

  2198.   item.extra = 0;

  2199.   VEC_safe_push (thread_item_t, data->items, &item);
  2200. }

  2201. static void
  2202. end_thread (struct gdb_xml_parser *parser,
  2203.             const struct gdb_xml_element *element,
  2204.             void *user_data, const char *body_text)
  2205. {
  2206.   struct threads_listing_context *data = user_data;

  2207.   if (body_text && *body_text)
  2208.     VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
  2209. }

  2210. const struct gdb_xml_attribute thread_attributes[] = {
  2211.   { "id", GDB_XML_AF_NONE, NULL, NULL },
  2212.   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
  2213.   { NULL, GDB_XML_AF_NONE, NULL, NULL }
  2214. };

  2215. const struct gdb_xml_element thread_children[] = {
  2216.   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
  2217. };

  2218. const struct gdb_xml_element threads_children[] = {
  2219.   { "thread", thread_attributes, thread_children,
  2220.     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
  2221.     start_thread, end_thread },
  2222.   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
  2223. };

  2224. const struct gdb_xml_element threads_elements[] = {
  2225.   { "threads", NULL, threads_children,
  2226.     GDB_XML_EF_NONE, NULL, NULL },
  2227.   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
  2228. };

  2229. #endif

  2230. /* List remote threads using qXfer:threads:read.  */

  2231. static int
  2232. remote_get_threads_with_qxfer (struct target_ops *ops,
  2233.                                struct threads_listing_context *context)
  2234. {
  2235. #if defined(HAVE_LIBEXPAT)
  2236.   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
  2237.     {
  2238.       char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
  2239.       struct cleanup *back_to = make_cleanup (xfree, xml);

  2240.       if (xml != NULL && *xml != '\0')
  2241.         {
  2242.           gdb_xml_parse_quick (_("threads"), "threads.dtd",
  2243.                                threads_elements, xml, context);
  2244.         }

  2245.       do_cleanups (back_to);
  2246.       return 1;
  2247.     }
  2248. #endif

  2249.   return 0;
  2250. }

  2251. /* List remote threads using qfThreadInfo/qsThreadInfo.  */

  2252. static int
  2253. remote_get_threads_with_qthreadinfo (struct target_ops *ops,
  2254.                                      struct threads_listing_context *context)
  2255. {
  2256.   struct remote_state *rs = get_remote_state ();

  2257.   if (rs->use_threadinfo_query)
  2258.     {
  2259.       char *bufp;

  2260.       putpkt ("qfThreadInfo");
  2261.       getpkt (&rs->buf, &rs->buf_size, 0);
  2262.       bufp = rs->buf;
  2263.       if (bufp[0] != '\0')                /* q packet recognized */
  2264.         {
  2265.           while (*bufp++ == 'm')        /* reply contains one or more TID */
  2266.             {
  2267.               do
  2268.                 {
  2269.                   struct thread_item item;

  2270.                   item.ptid = read_ptid (bufp, &bufp);
  2271.                   item.core = -1;
  2272.                   item.extra = NULL;

  2273.                   VEC_safe_push (thread_item_t, context->items, &item);
  2274.                 }
  2275.               while (*bufp++ == ',');        /* comma-separated list */
  2276.               putpkt ("qsThreadInfo");
  2277.               getpkt (&rs->buf, &rs->buf_size, 0);
  2278.               bufp = rs->buf;
  2279.             }
  2280.           return 1;
  2281.         }
  2282.       else
  2283.         {
  2284.           /* Packet not recognized.  */
  2285.           rs->use_threadinfo_query = 0;
  2286.         }
  2287.     }

  2288.   return 0;
  2289. }

  2290. /* Implement the to_update_thread_list function for the remote
  2291.    targets.  */

  2292. static void
  2293. remote_update_thread_list (struct target_ops *ops)
  2294. {
  2295.   struct remote_state *rs = get_remote_state ();
  2296.   struct threads_listing_context context;
  2297.   struct cleanup *old_chain;
  2298.   int got_list = 0;

  2299.   context.items = NULL;
  2300.   old_chain = make_cleanup (clear_threads_listing_context, &context);

  2301.   /* We have a few different mechanisms to fetch the thread list.  Try
  2302.      them all, starting with the most preferred one first, falling
  2303.      back to older methods.  */
  2304.   if (remote_get_threads_with_qxfer (ops, &context)
  2305.       || remote_get_threads_with_qthreadinfo (ops, &context)
  2306.       || remote_get_threads_with_ql (ops, &context))
  2307.     {
  2308.       int i;
  2309.       struct thread_item *item;
  2310.       struct thread_info *tp, *tmp;

  2311.       got_list = 1;

  2312.       if (VEC_empty (thread_item_t, context.items)
  2313.           && remote_thread_always_alive (ops, inferior_ptid))
  2314.         {
  2315.           /* Some targets don't really support threads, but still
  2316.              reply an (empty) thread list in response to the thread
  2317.              listing packets, instead of replying "packet not
  2318.              supported".  Exit early so we don't delete the main
  2319.              thread.  */
  2320.           do_cleanups (old_chain);
  2321.           return;
  2322.         }

  2323.       /* CONTEXT now holds the current thread list on the remote
  2324.          target end.  Delete GDB-side threads no longer found on the
  2325.          target.  */
  2326.       ALL_NON_EXITED_THREADS_SAFE (tp, tmp)
  2327.         {
  2328.           for (i = 0;
  2329.                VEC_iterate (thread_item_t, context.items, i, item);
  2330.                ++i)
  2331.             {
  2332.               if (ptid_equal (item->ptid, tp->ptid))
  2333.                 break;
  2334.             }

  2335.           if (i == VEC_length (thread_item_t, context.items))
  2336.             {
  2337.               /* Not found.  */
  2338.               delete_thread (tp->ptid);
  2339.             }
  2340.         }

  2341.       /* And now add threads we don't know about yet to our list.  */
  2342.       for (i = 0;
  2343.            VEC_iterate (thread_item_t, context.items, i, item);
  2344.            ++i)
  2345.         {
  2346.           if (!ptid_equal (item->ptid, null_ptid))
  2347.             {
  2348.               struct private_thread_info *info;
  2349.               /* In non-stop mode, we assume new found threads are
  2350.                  running until proven otherwise with a stop reply.  In
  2351.                  all-stop, we can only get here if all threads are
  2352.                  stopped.  */
  2353.               int running = non_stop ? 1 : 0;

  2354.               remote_notice_new_inferior (item->ptid, running);

  2355.               info = demand_private_info (item->ptid);
  2356.               info->core = item->core;
  2357.               info->extra = item->extra;
  2358.               item->extra = NULL;
  2359.             }
  2360.         }
  2361.     }

  2362.   if (!got_list)
  2363.     {
  2364.       /* If no thread listing method is supported, then query whether
  2365.          each known thread is alive, one by one, with the T packet.
  2366.          If the target doesn't support threads at all, then this is a
  2367.          no-op.  See remote_thread_alive.  */
  2368.       prune_threads ();
  2369.     }

  2370.   do_cleanups (old_chain);
  2371. }

  2372. /*
  2373. * Collect a descriptive string about the given thread.
  2374. * The target may say anything it wants to about the thread
  2375. * (typically info about its blocked / runnable state, name, etc.).
  2376. * This string will appear in the info threads display.
  2377. *
  2378. * Optional: targets are not required to implement this function.
  2379. */

  2380. static char *
  2381. remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
  2382. {
  2383.   struct remote_state *rs = get_remote_state ();
  2384.   int result;
  2385.   int set;
  2386.   threadref id;
  2387.   struct gdb_ext_thread_info threadinfo;
  2388.   static char display_buf[100];        /* arbitrary...  */
  2389.   int n = 0;                    /* position in display_buf */

  2390.   if (rs->remote_desc == 0)                /* paranoia */
  2391.     internal_error (__FILE__, __LINE__,
  2392.                     _("remote_threads_extra_info"));

  2393.   if (ptid_equal (tp->ptid, magic_null_ptid)
  2394.       || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
  2395.     /* This is the main thread which was added by GDB.  The remote
  2396.        server doesn't know about it.  */
  2397.     return NULL;

  2398.   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
  2399.     {
  2400.       struct thread_info *info = find_thread_ptid (tp->ptid);

  2401.       if (info && info->private)
  2402.         return info->private->extra;
  2403.       else
  2404.         return NULL;
  2405.     }

  2406.   if (rs->use_threadextra_query)
  2407.     {
  2408.       char *b = rs->buf;
  2409.       char *endb = rs->buf + get_remote_packet_size ();

  2410.       xsnprintf (b, endb - b, "qThreadExtraInfo,");
  2411.       b += strlen (b);
  2412.       write_ptid (b, endb, tp->ptid);

  2413.       putpkt (rs->buf);
  2414.       getpkt (&rs->buf, &rs->buf_size, 0);
  2415.       if (rs->buf[0] != 0)
  2416.         {
  2417.           n = min (strlen (rs->buf) / 2, sizeof (display_buf));
  2418.           result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
  2419.           display_buf [result] = '\0';
  2420.           return display_buf;
  2421.         }
  2422.     }

  2423.   /* If the above query fails, fall back to the old method.  */
  2424.   rs->use_threadextra_query = 0;
  2425.   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
  2426.     | TAG_MOREDISPLAY | TAG_DISPLAY;
  2427.   int_to_threadref (&id, ptid_get_lwp (tp->ptid));
  2428.   if (remote_get_threadinfo (&id, set, &threadinfo))
  2429.     if (threadinfo.active)
  2430.       {
  2431.         if (*threadinfo.shortname)
  2432.           n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
  2433.                           " Name: %s,", threadinfo.shortname);
  2434.         if (*threadinfo.display)
  2435.           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
  2436.                           " State: %s,", threadinfo.display);
  2437.         if (*threadinfo.more_display)
  2438.           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
  2439.                           " Priority: %s", threadinfo.more_display);

  2440.         if (n > 0)
  2441.           {
  2442.             /* For purely cosmetic reasons, clear up trailing commas.  */
  2443.             if (',' == display_buf[n-1])
  2444.               display_buf[n-1] = ' ';
  2445.             return display_buf;
  2446.           }
  2447.       }
  2448.   return NULL;
  2449. }


  2450. static int
  2451. remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
  2452.                                     struct static_tracepoint_marker *marker)
  2453. {
  2454.   struct remote_state *rs = get_remote_state ();
  2455.   char *p = rs->buf;

  2456.   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
  2457.   p += strlen (p);
  2458.   p += hexnumstr (p, addr);
  2459.   putpkt (rs->buf);
  2460.   getpkt (&rs->buf, &rs->buf_size, 0);
  2461.   p = rs->buf;

  2462.   if (*p == 'E')
  2463.     error (_("Remote failure reply: %s"), p);

  2464.   if (*p++ == 'm')
  2465.     {
  2466.       parse_static_tracepoint_marker_definition (p, &p, marker);
  2467.       return 1;
  2468.     }

  2469.   return 0;
  2470. }

  2471. static VEC(static_tracepoint_marker_p) *
  2472. remote_static_tracepoint_markers_by_strid (struct target_ops *self,
  2473.                                            const char *strid)
  2474. {
  2475.   struct remote_state *rs = get_remote_state ();
  2476.   VEC(static_tracepoint_marker_p) *markers = NULL;
  2477.   struct static_tracepoint_marker *marker = NULL;
  2478.   struct cleanup *old_chain;
  2479.   char *p;

  2480.   /* Ask for a first packet of static tracepoint marker
  2481.      definition.  */
  2482.   putpkt ("qTfSTM");
  2483.   getpkt (&rs->buf, &rs->buf_size, 0);
  2484.   p = rs->buf;
  2485.   if (*p == 'E')
  2486.     error (_("Remote failure reply: %s"), p);

  2487.   old_chain = make_cleanup (free_current_marker, &marker);

  2488.   while (*p++ == 'm')
  2489.     {
  2490.       if (marker == NULL)
  2491.         marker = XCNEW (struct static_tracepoint_marker);

  2492.       do
  2493.         {
  2494.           parse_static_tracepoint_marker_definition (p, &p, marker);

  2495.           if (strid == NULL || strcmp (strid, marker->str_id) == 0)
  2496.             {
  2497.               VEC_safe_push (static_tracepoint_marker_p,
  2498.                              markers, marker);
  2499.               marker = NULL;
  2500.             }
  2501.           else
  2502.             {
  2503.               release_static_tracepoint_marker (marker);
  2504.               memset (marker, 0, sizeof (*marker));
  2505.             }
  2506.         }
  2507.       while (*p++ == ',');        /* comma-separated list */
  2508.       /* Ask for another packet of static tracepoint definition.  */
  2509.       putpkt ("qTsSTM");
  2510.       getpkt (&rs->buf, &rs->buf_size, 0);
  2511.       p = rs->buf;
  2512.     }

  2513.   do_cleanups (old_chain);
  2514.   return markers;
  2515. }


  2516. /* Implement the to_get_ada_task_ptid function for the remote targets.  */

  2517. static ptid_t
  2518. remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
  2519. {
  2520.   return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
  2521. }


  2522. /* Restart the remote side; this is an extended protocol operation.  */

  2523. static void
  2524. extended_remote_restart (void)
  2525. {
  2526.   struct remote_state *rs = get_remote_state ();

  2527.   /* Send the restart command; for reasons I don't understand the
  2528.      remote side really expects a number after the "R".  */
  2529.   xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
  2530.   putpkt (rs->buf);

  2531.   remote_fileio_reset ();
  2532. }

  2533. /* Clean up connection to a remote debugger.  */

  2534. static void
  2535. remote_close (struct target_ops *self)
  2536. {
  2537.   struct remote_state *rs = get_remote_state ();

  2538.   if (rs->remote_desc == NULL)
  2539.     return; /* already closed */

  2540.   /* Make sure we leave stdin registered in the event loop, and we
  2541.      don't leave the async SIGINT signal handler installed.  */
  2542.   remote_terminal_ours (self);

  2543.   serial_close (rs->remote_desc);
  2544.   rs->remote_desc = NULL;

  2545.   /* We don't have a connection to the remote stub anymore.  Get rid
  2546.      of all the inferiors and their threads we were controlling.
  2547.      Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
  2548.      will be unable to find the thread corresponding to (pid, 0, 0).  */
  2549.   inferior_ptid = null_ptid;
  2550.   discard_all_inferiors ();

  2551.   /* We are closing the remote target, so we should discard
  2552.      everything of this target.  */
  2553.   discard_pending_stop_replies_in_queue (rs);

  2554.   if (remote_async_inferior_event_token)
  2555.     delete_async_event_handler (&remote_async_inferior_event_token);

  2556.   remote_notif_state_xfree (rs->notif_state);

  2557.   trace_reset_local_state ();
  2558. }

  2559. /* Query the remote side for the text, data and bss offsets.  */

  2560. static void
  2561. get_offsets (void)
  2562. {
  2563.   struct remote_state *rs = get_remote_state ();
  2564.   char *buf;
  2565.   char *ptr;
  2566.   int lose, num_segments = 0, do_sections, do_segments;
  2567.   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
  2568.   struct section_offsets *offs;
  2569.   struct symfile_segment_data *data;

  2570.   if (symfile_objfile == NULL)
  2571.     return;

  2572.   putpkt ("qOffsets");
  2573.   getpkt (&rs->buf, &rs->buf_size, 0);
  2574.   buf = rs->buf;

  2575.   if (buf[0] == '\000')
  2576.     return;                        /* Return silently.  Stub doesn't support
  2577.                                    this command.  */
  2578.   if (buf[0] == 'E')
  2579.     {
  2580.       warning (_("Remote failure reply: %s"), buf);
  2581.       return;
  2582.     }

  2583.   /* Pick up each field in turn.  This used to be done with scanf, but
  2584.      scanf will make trouble if CORE_ADDR size doesn't match
  2585.      conversion directives correctly.  The following code will work
  2586.      with any size of CORE_ADDR.  */
  2587.   text_addr = data_addr = bss_addr = 0;
  2588.   ptr = buf;
  2589.   lose = 0;

  2590.   if (strncmp (ptr, "Text=", 5) == 0)
  2591.     {
  2592.       ptr += 5;
  2593.       /* Don't use strtol, could lose on big values.  */
  2594.       while (*ptr && *ptr != ';')
  2595.         text_addr = (text_addr << 4) + fromhex (*ptr++);

  2596.       if (strncmp (ptr, ";Data=", 6) == 0)
  2597.         {
  2598.           ptr += 6;
  2599.           while (*ptr && *ptr != ';')
  2600.             data_addr = (data_addr << 4) + fromhex (*ptr++);
  2601.         }
  2602.       else
  2603.         lose = 1;

  2604.       if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
  2605.         {
  2606.           ptr += 5;
  2607.           while (*ptr && *ptr != ';')
  2608.             bss_addr = (bss_addr << 4) + fromhex (*ptr++);

  2609.           if (bss_addr != data_addr)
  2610.             warning (_("Target reported unsupported offsets: %s"), buf);
  2611.         }
  2612.       else
  2613.         lose = 1;
  2614.     }
  2615.   else if (strncmp (ptr, "TextSeg=", 8) == 0)
  2616.     {
  2617.       ptr += 8;
  2618.       /* Don't use strtol, could lose on big values.  */
  2619.       while (*ptr && *ptr != ';')
  2620.         text_addr = (text_addr << 4) + fromhex (*ptr++);
  2621.       num_segments = 1;

  2622.       if (strncmp (ptr, ";DataSeg=", 9) == 0)
  2623.         {
  2624.           ptr += 9;
  2625.           while (*ptr && *ptr != ';')
  2626.             data_addr = (data_addr << 4) + fromhex (*ptr++);
  2627.           num_segments++;
  2628.         }
  2629.     }
  2630.   else
  2631.     lose = 1;

  2632.   if (lose)
  2633.     error (_("Malformed response to offset query, %s"), buf);
  2634.   else if (*ptr != '\0')
  2635.     warning (_("Target reported unsupported offsets: %s"), buf);

  2636.   offs = ((struct section_offsets *)
  2637.           alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
  2638.   memcpy (offs, symfile_objfile->section_offsets,
  2639.           SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));

  2640.   data = get_symfile_segment_data (symfile_objfile->obfd);
  2641.   do_segments = (data != NULL);
  2642.   do_sections = num_segments == 0;

  2643.   if (num_segments > 0)
  2644.     {
  2645.       segments[0] = text_addr;
  2646.       segments[1] = data_addr;
  2647.     }
  2648.   /* If we have two segments, we can still try to relocate everything
  2649.      by assuming that the .text and .data offsets apply to the whole
  2650.      text and data segments.  Convert the offsets given in the packet
  2651.      to base addresses for symfile_map_offsets_to_segments.  */
  2652.   else if (data && data->num_segments == 2)
  2653.     {
  2654.       segments[0] = data->segment_bases[0] + text_addr;
  2655.       segments[1] = data->segment_bases[1] + data_addr;
  2656.       num_segments = 2;
  2657.     }
  2658.   /* If the object file has only one segment, assume that it is text
  2659.      rather than data; main programs with no writable data are rare,
  2660.      but programs with no code are useless.  Of course the code might
  2661.      have ended up in the data segment... to detect that we would need
  2662.      the permissions here.  */
  2663.   else if (data && data->num_segments == 1)
  2664.     {
  2665.       segments[0] = data->segment_bases[0] + text_addr;
  2666.       num_segments = 1;
  2667.     }
  2668.   /* There's no way to relocate by segment.  */
  2669.   else
  2670.     do_segments = 0;

  2671.   if (do_segments)
  2672.     {
  2673.       int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
  2674.                                                  offs, num_segments, segments);

  2675.       if (ret == 0 && !do_sections)
  2676.         error (_("Can not handle qOffsets TextSeg "
  2677.                  "response with this symbol file"));

  2678.       if (ret > 0)
  2679.         do_sections = 0;
  2680.     }

  2681.   if (data)
  2682.     free_symfile_segment_data (data);

  2683.   if (do_sections)
  2684.     {
  2685.       offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;

  2686.       /* This is a temporary kludge to force data and bss to use the
  2687.          same offsets because that's what nlmconv does now.  The real
  2688.          solution requires changes to the stub and remote.c that I
  2689.          don't have time to do right now.  */

  2690.       offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
  2691.       offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
  2692.     }

  2693.   objfile_relocate (symfile_objfile, offs);
  2694. }

  2695. /* Callback for iterate_over_threads.  Set the STOP_REQUESTED flags in
  2696.    threads we know are stopped already.  This is used during the
  2697.    initial remote connection in non-stop mode --- threads that are
  2698.    reported as already being stopped are left stopped.  */

  2699. static int
  2700. set_stop_requested_callback (struct thread_info *thread, void *data)
  2701. {
  2702.   /* If we have a stop reply for this thread, it must be stopped.  */
  2703.   if (peek_stop_reply (thread->ptid))
  2704.     set_stop_requested (thread->ptid, 1);

  2705.   return 0;
  2706. }

  2707. /* Send interrupt_sequence to remote target.  */
  2708. static void
  2709. send_interrupt_sequence (void)
  2710. {
  2711.   struct remote_state *rs = get_remote_state ();

  2712.   if (interrupt_sequence_mode == interrupt_sequence_control_c)
  2713.     remote_serial_write ("\x03", 1);
  2714.   else if (interrupt_sequence_mode == interrupt_sequence_break)
  2715.     serial_send_break (rs->remote_desc);
  2716.   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
  2717.     {
  2718.       serial_send_break (rs->remote_desc);
  2719.       remote_serial_write ("g", 1);
  2720.     }
  2721.   else
  2722.     internal_error (__FILE__, __LINE__,
  2723.                     _("Invalid value for interrupt_sequence_mode: %s."),
  2724.                     interrupt_sequence_mode);
  2725. }


  2726. /* If STOP_REPLY is a T stop reply, look for the "thread" register,
  2727.    and extract the PTID.  Returns NULL_PTID if not found.  */

  2728. static ptid_t
  2729. stop_reply_extract_thread (char *stop_reply)
  2730. {
  2731.   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
  2732.     {
  2733.       char *p;

  2734.       /* Txx r:val ; r:val (...)  */
  2735.       p = &stop_reply[3];

  2736.       /* Look for "register" named "thread".  */
  2737.       while (*p != '\0')
  2738.         {
  2739.           char *p1;

  2740.           p1 = strchr (p, ':');
  2741.           if (p1 == NULL)
  2742.             return null_ptid;

  2743.           if (strncmp (p, "thread", p1 - p) == 0)
  2744.             return read_ptid (++p1, &p);

  2745.           p1 = strchr (p, ';');
  2746.           if (p1 == NULL)
  2747.             return null_ptid;
  2748.           p1++;

  2749.           p = p1;
  2750.         }
  2751.     }

  2752.   return null_ptid;
  2753. }

  2754. /* Determine the remote side's current thread.  If we have a stop
  2755.    reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
  2756.    "thread" register we can extract the current thread from.  If not,
  2757.    ask the remote which is the current thread with qC.  The former
  2758.    method avoids a roundtrip.  */

  2759. static ptid_t
  2760. get_current_thread (char *wait_status)
  2761. {
  2762.   ptid_t ptid;

  2763.   /* Note we don't use remote_parse_stop_reply as that makes use of
  2764.      the target architecture, which we haven't yet fully determined at
  2765.      this point.  */
  2766.   if (wait_status != NULL)
  2767.     ptid = stop_reply_extract_thread (wait_status);
  2768.   if (ptid_equal (ptid, null_ptid))
  2769.     ptid = remote_current_thread (inferior_ptid);

  2770.   return ptid;
  2771. }

  2772. /* Query the remote target for which is the current thread/process,
  2773.    add it to our tables, and update INFERIOR_PTID.  The caller is
  2774.    responsible for setting the state such that the remote end is ready
  2775.    to return the current thread.

  2776.    This function is called after handling the '?' or 'vRun' packets,
  2777.    whose response is a stop reply from which we can also try
  2778.    extracting the thread.  If the target doesn't support the explicit
  2779.    qC query, we infer the current thread from that stop reply, passed
  2780.    in in WAIT_STATUS, which may be NULL.  */

  2781. static void
  2782. add_current_inferior_and_thread (char *wait_status)
  2783. {
  2784.   struct remote_state *rs = get_remote_state ();
  2785.   int fake_pid_p = 0;
  2786.   ptid_t ptid = null_ptid;

  2787.   inferior_ptid = null_ptid;

  2788.   /* Now, if we have thread information, update inferior_ptid.  */
  2789.   ptid = get_current_thread (wait_status);

  2790.   if (!ptid_equal (ptid, null_ptid))
  2791.     {
  2792.       if (!remote_multi_process_p (rs))
  2793.         fake_pid_p = 1;

  2794.       inferior_ptid = ptid;
  2795.     }
  2796.   else
  2797.     {
  2798.       /* Without this, some commands which require an active target
  2799.          (such as kill) won't work.  This variable serves (at least)
  2800.          double duty as both the pid of the target process (if it has
  2801.          such), and as a flag indicating that a target is active.  */
  2802.       inferior_ptid = magic_null_ptid;
  2803.       fake_pid_p = 1;
  2804.     }

  2805.   remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1);

  2806.   /* Add the main thread.  */
  2807.   add_thread_silent (inferior_ptid);
  2808. }

  2809. static void
  2810. remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
  2811. {
  2812.   struct remote_state *rs = get_remote_state ();
  2813.   struct packet_config *noack_config;
  2814.   char *wait_status = NULL;

  2815.   immediate_quit++;                /* Allow user to interrupt it.  */
  2816.   QUIT;

  2817.   if (interrupt_on_connect)
  2818.     send_interrupt_sequence ();

  2819.   /* Ack any packet which the remote side has already sent.  */
  2820.   serial_write (rs->remote_desc, "+", 1);

  2821.   /* Signal other parts that we're going through the initial setup,
  2822.      and so things may not be stable yet.  */
  2823.   rs->starting_up = 1;

  2824.   /* The first packet we send to the target is the optional "supported
  2825.      packets" request.  If the target can answer this, it will tell us
  2826.      which later probes to skip.  */
  2827.   remote_query_supported ();

  2828.   /* If the stub wants to get a QAllow, compose one and send it.  */
  2829.   if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
  2830.     remote_set_permissions (target);

  2831.   /* Next, we possibly activate noack mode.

  2832.      If the QStartNoAckMode packet configuration is set to AUTO,
  2833.      enable noack mode if the stub reported a wish for it with
  2834.      qSupported.

  2835.      If set to TRUE, then enable noack mode even if the stub didn't
  2836.      report it in qSupported.  If the stub doesn't reply OK, the
  2837.      session ends with an error.

  2838.      If FALSE, then don't activate noack mode, regardless of what the
  2839.      stub claimed should be the default with qSupported.  */

  2840.   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
  2841.   if (packet_config_support (noack_config) != PACKET_DISABLE)
  2842.     {
  2843.       putpkt ("QStartNoAckMode");
  2844.       getpkt (&rs->buf, &rs->buf_size, 0);
  2845.       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
  2846.         rs->noack_mode = 1;
  2847.     }

  2848.   if (extended_p)
  2849.     {
  2850.       /* Tell the remote that we are using the extended protocol.  */
  2851.       putpkt ("!");
  2852.       getpkt (&rs->buf, &rs->buf_size, 0);
  2853.     }

  2854.   /* Let the target know which signals it is allowed to pass down to
  2855.      the program.  */
  2856.   update_signals_program_target ();

  2857.   /* Next, if the target can specify a description, read it.  We do
  2858.      this before anything involving memory or registers.  */
  2859.   target_find_description ();

  2860.   /* Next, now that we know something about the target, update the
  2861.      address spaces in the program spaces.  */
  2862.   update_address_spaces ();

  2863.   /* On OSs where the list of libraries is global to all
  2864.      processes, we fetch them early.  */
  2865.   if (gdbarch_has_global_solist (target_gdbarch ()))
  2866.     solib_add (NULL, from_tty, target, auto_solib_add);

  2867.   if (non_stop)
  2868.     {
  2869.       if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
  2870.         error (_("Non-stop mode requested, but remote "
  2871.                  "does not support non-stop"));

  2872.       putpkt ("QNonStop:1");
  2873.       getpkt (&rs->buf, &rs->buf_size, 0);

  2874.       if (strcmp (rs->buf, "OK") != 0)
  2875.         error (_("Remote refused setting non-stop mode with: %s"), rs->buf);

  2876.       /* Find about threads and processes the stub is already
  2877.          controlling.  We default to adding them in the running state.
  2878.          The '?' query below will then tell us about which threads are
  2879.          stopped.  */
  2880.       remote_update_thread_list (target);
  2881.     }
  2882.   else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
  2883.     {
  2884.       /* Don't assume that the stub can operate in all-stop mode.
  2885.          Request it explicitly.  */
  2886.       putpkt ("QNonStop:0");
  2887.       getpkt (&rs->buf, &rs->buf_size, 0);

  2888.       if (strcmp (rs->buf, "OK") != 0)
  2889.         error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
  2890.     }

  2891.   /* Upload TSVs regardless of whether the target is running or not.  The
  2892.      remote stub, such as GDBserver, may have some predefined or builtin
  2893.      TSVs, even if the target is not running.  */
  2894.   if (remote_get_trace_status (target, current_trace_status ()) != -1)
  2895.     {
  2896.       struct uploaded_tsv *uploaded_tsvs = NULL;

  2897.       remote_upload_trace_state_variables (target, &uploaded_tsvs);
  2898.       merge_uploaded_trace_state_variables (&uploaded_tsvs);
  2899.     }

  2900.   /* Check whether the target is running now.  */
  2901.   putpkt ("?");
  2902.   getpkt (&rs->buf, &rs->buf_size, 0);

  2903.   if (!non_stop)
  2904.     {
  2905.       ptid_t ptid;
  2906.       int fake_pid_p = 0;
  2907.       struct inferior *inf;

  2908.       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
  2909.         {
  2910.           if (!extended_p)
  2911.             error (_("The target is not running (try extended-remote?)"));

  2912.           /* We're connected, but not running.  Drop out before we
  2913.              call start_remote.  */
  2914.           rs->starting_up = 0;
  2915.           return;
  2916.         }
  2917.       else
  2918.         {
  2919.           /* Save the reply for later.  */
  2920.           wait_status = alloca (strlen (rs->buf) + 1);
  2921.           strcpy (wait_status, rs->buf);
  2922.         }

  2923.       /* Fetch thread list.  */
  2924.       target_update_thread_list ();

  2925.       /* Let the stub know that we want it to return the thread.  */
  2926.       set_continue_thread (minus_one_ptid);

  2927.       if (thread_count () == 0)
  2928.         {
  2929.           /* Target has no concept of threads at all.  GDB treats
  2930.              non-threaded target as single-threaded; add a main
  2931.              thread.  */
  2932.           add_current_inferior_and_thread (wait_status);
  2933.         }
  2934.       else
  2935.         {
  2936.           /* We have thread information; select the thread the target
  2937.              says should be current.  If we're reconnecting to a
  2938.              multi-threaded program, this will ideally be the thread
  2939.              that last reported an event before GDB disconnected.  */
  2940.           inferior_ptid = get_current_thread (wait_status);
  2941.           if (ptid_equal (inferior_ptid, null_ptid))
  2942.             {
  2943.               /* Odd... The target was able to list threads, but not
  2944.                  tell us which thread was current (no "thread"
  2945.                  register in T stop reply?).  Just pick the first
  2946.                  thread in the thread list then.  */
  2947.               inferior_ptid = thread_list->ptid;
  2948.             }
  2949.         }

  2950.       /* init_wait_for_inferior should be called before get_offsets in order
  2951.          to manage `inserted' flag in bp loc in a correct state.
  2952.          breakpoint_init_inferior, called from init_wait_for_inferior, set
  2953.          `inserted' flag to 0, while before breakpoint_re_set, called from
  2954.          start_remote, set `inserted' flag to 1.  In the initialization of
  2955.          inferior, breakpoint_init_inferior should be called first, and then
  2956.          breakpoint_re_set can be called.  If this order is broken, state of
  2957.          `inserted' flag is wrong, and cause some problems on breakpoint
  2958.          manipulation.  */
  2959.       init_wait_for_inferior ();

  2960.       get_offsets ();                /* Get text, data & bss offsets.  */

  2961.       /* If we could not find a description using qXfer, and we know
  2962.          how to do it some other way, try again.  This is not
  2963.          supported for non-stop; it could be, but it is tricky if
  2964.          there are no stopped threads when we connect.  */
  2965.       if (remote_read_description_p (target)
  2966.           && gdbarch_target_desc (target_gdbarch ()) == NULL)
  2967.         {
  2968.           target_clear_description ();
  2969.           target_find_description ();
  2970.         }

  2971.       /* Use the previously fetched status.  */
  2972.       gdb_assert (wait_status != NULL);
  2973.       strcpy (rs->buf, wait_status);
  2974.       rs->cached_wait_status = 1;

  2975.       immediate_quit--;
  2976.       start_remote (from_tty); /* Initialize gdb process mechanisms.  */
  2977.     }
  2978.   else
  2979.     {
  2980.       /* Clear WFI global state.  Do this before finding about new
  2981.          threads and inferiors, and setting the current inferior.
  2982.          Otherwise we would clear the proceed status of the current
  2983.          inferior when we want its stop_soon state to be preserved
  2984.          (see notice_new_inferior).  */
  2985.       init_wait_for_inferior ();

  2986.       /* In non-stop, we will either get an "OK", meaning that there
  2987.          are no stopped threads at this time; or, a regular stop
  2988.          reply.  In the latter case, there may be more than one thread
  2989.          stopped --- we pull them all out using the vStopped
  2990.          mechanism.  */
  2991.       if (strcmp (rs->buf, "OK") != 0)
  2992.         {
  2993.           struct notif_client *notif = &notif_client_stop;

  2994.           /* remote_notif_get_pending_replies acks this one, and gets
  2995.              the rest out.  */
  2996.           rs->notif_state->pending_event[notif_client_stop.id]
  2997.             = remote_notif_parse (notif, rs->buf);
  2998.           remote_notif_get_pending_events (notif);

  2999.           /* Make sure that threads that were stopped remain
  3000.              stopped.  */
  3001.           iterate_over_threads (set_stop_requested_callback, NULL);
  3002.         }

  3003.       if (target_can_async_p ())
  3004.         target_async (inferior_event_handler, 0);

  3005.       if (thread_count () == 0)
  3006.         {
  3007.           if (!extended_p)
  3008.             error (_("The target is not running (try extended-remote?)"));

  3009.           /* We're connected, but not running.  Drop out before we
  3010.              call start_remote.  */
  3011.           rs->starting_up = 0;
  3012.           return;
  3013.         }

  3014.       /* Let the stub know that we want it to return the thread.  */

  3015.       /* Force the stub to choose a thread.  */
  3016.       set_general_thread (null_ptid);

  3017.       /* Query it.  */
  3018.       inferior_ptid = remote_current_thread (minus_one_ptid);
  3019.       if (ptid_equal (inferior_ptid, minus_one_ptid))
  3020.         error (_("remote didn't report the current thread in non-stop mode"));

  3021.       get_offsets ();                /* Get text, data & bss offsets.  */

  3022.       /* In non-stop mode, any cached wait status will be stored in
  3023.          the stop reply queue.  */
  3024.       gdb_assert (wait_status == NULL);

  3025.       /* Report all signals during attach/startup.  */
  3026.       remote_pass_signals (target, 0, NULL);
  3027.     }

  3028.   /* If we connected to a live target, do some additional setup.  */
  3029.   if (target_has_execution)
  3030.     {
  3031.       if (symfile_objfile)         /* No use without a symbol-file.  */
  3032.         remote_check_symbols ();
  3033.     }

  3034.   /* Possibly the target has been engaged in a trace run started
  3035.      previously; find out where things are at.  */
  3036.   if (remote_get_trace_status (target, current_trace_status ()) != -1)
  3037.     {
  3038.       struct uploaded_tp *uploaded_tps = NULL;

  3039.       if (current_trace_status ()->running)
  3040.         printf_filtered (_("Trace is already running on the target.\n"));

  3041.       remote_upload_tracepoints (target, &uploaded_tps);

  3042.       merge_uploaded_tracepoints (&uploaded_tps);
  3043.     }

  3044.   /* The thread and inferior lists are now synchronized with the
  3045.      target, our symbols have been relocated, and we're merged the
  3046.      target's tracepoints with ours.  We're done with basic start
  3047.      up.  */
  3048.   rs->starting_up = 0;

  3049.   /* Maybe breakpoints are global and need to be inserted now.  */
  3050.   if (breakpoints_should_be_inserted_now ())
  3051.     insert_breakpoints ();
  3052. }

  3053. /* Open a connection to a remote debugger.
  3054.    NAME is the filename used for communication.  */

  3055. static void
  3056. remote_open (const char *name, int from_tty)
  3057. {
  3058.   remote_open_1 (name, from_tty, &remote_ops, 0);
  3059. }

  3060. /* Open a connection to a remote debugger using the extended
  3061.    remote gdb protocol.  NAME is the filename used for communication.  */

  3062. static void
  3063. extended_remote_open (const char *name, int from_tty)
  3064. {
  3065.   remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
  3066. }

  3067. /* Reset all packets back to "unknown support".  Called when opening a
  3068.    new connection to a remote target.  */

  3069. static void
  3070. reset_all_packet_configs_support (void)
  3071. {
  3072.   int i;

  3073.   for (i = 0; i < PACKET_MAX; i++)
  3074.     remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
  3075. }

  3076. /* Initialize all packet configs.  */

  3077. static void
  3078. init_all_packet_configs (void)
  3079. {
  3080.   int i;

  3081.   for (i = 0; i < PACKET_MAX; i++)
  3082.     {
  3083.       remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
  3084.       remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
  3085.     }
  3086. }

  3087. /* Symbol look-up.  */

  3088. static void
  3089. remote_check_symbols (void)
  3090. {
  3091.   struct remote_state *rs = get_remote_state ();
  3092.   char *msg, *reply, *tmp;
  3093.   struct bound_minimal_symbol sym;
  3094.   int end;

  3095.   /* The remote side has no concept of inferiors that aren't running
  3096.      yet, it only knows about running processes.  If we're connected
  3097.      but our current inferior is not running, we should not invite the
  3098.      remote target to request symbol lookups related to its
  3099.      (unrelated) current process.  */
  3100.   if (!target_has_execution)
  3101.     return;

  3102.   if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
  3103.     return;

  3104.   /* Make sure the remote is pointing at the right process.  Note
  3105.      there's no way to select "no process".  */
  3106.   set_general_process ();

  3107.   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
  3108.      because we need both at the same time.  */
  3109.   msg = alloca (get_remote_packet_size ());

  3110.   /* Invite target to request symbol lookups.  */

  3111.   putpkt ("qSymbol::");
  3112.   getpkt (&rs->buf, &rs->buf_size, 0);
  3113.   packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
  3114.   reply = rs->buf;

  3115.   while (strncmp (reply, "qSymbol:", 8) == 0)
  3116.     {
  3117.       struct bound_minimal_symbol sym;

  3118.       tmp = &reply[8];
  3119.       end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
  3120.       msg[end] = '\0';
  3121.       sym = lookup_minimal_symbol (msg, NULL, NULL);
  3122.       if (sym.minsym == NULL)
  3123.         xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
  3124.       else
  3125.         {
  3126.           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
  3127.           CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);

  3128.           /* If this is a function address, return the start of code
  3129.              instead of any data function descriptor.  */
  3130.           sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
  3131.                                                          sym_addr,
  3132.                                                          &current_target);

  3133.           xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
  3134.                      phex_nz (sym_addr, addr_size), &reply[8]);
  3135.         }

  3136.       putpkt (msg);
  3137.       getpkt (&rs->buf, &rs->buf_size, 0);
  3138.       reply = rs->buf;
  3139.     }
  3140. }

  3141. static struct serial *
  3142. remote_serial_open (const char *name)
  3143. {
  3144.   static int udp_warning = 0;

  3145.   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
  3146.      of in ser-tcp.c, because it is the remote protocol assuming that the
  3147.      serial connection is reliable and not the serial connection promising
  3148.      to be.  */
  3149.   if (!udp_warning && strncmp (name, "udp:", 4) == 0)
  3150.     {
  3151.       warning (_("The remote protocol may be unreliable over UDP.\n"
  3152.                  "Some events may be lost, rendering further debugging "
  3153.                  "impossible."));
  3154.       udp_warning = 1;
  3155.     }

  3156.   return serial_open (name);
  3157. }

  3158. /* Inform the target of our permission settings.  The permission flags
  3159.    work without this, but if the target knows the settings, it can do
  3160.    a couple things.  First, it can add its own check, to catch cases
  3161.    that somehow manage to get by the permissions checks in target
  3162.    methods.  Second, if the target is wired to disallow particular
  3163.    settings (for instance, a system in the field that is not set up to
  3164.    be able to stop at a breakpoint), it can object to any unavailable
  3165.    permissions.  */

  3166. void
  3167. remote_set_permissions (struct target_ops *self)
  3168. {
  3169.   struct remote_state *rs = get_remote_state ();

  3170.   xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
  3171.              "WriteReg:%x;WriteMem:%x;"
  3172.              "InsertBreak:%x;InsertTrace:%x;"
  3173.              "InsertFastTrace:%x;Stop:%x",
  3174.              may_write_registers, may_write_memory,
  3175.              may_insert_breakpoints, may_insert_tracepoints,
  3176.              may_insert_fast_tracepoints, may_stop);
  3177.   putpkt (rs->buf);
  3178.   getpkt (&rs->buf, &rs->buf_size, 0);

  3179.   /* If the target didn't like the packet, warn the user.  Do not try
  3180.      to undo the user's settings, that would just be maddening.  */
  3181.   if (strcmp (rs->buf, "OK") != 0)
  3182.     warning (_("Remote refused setting permissions with: %s"), rs->buf);
  3183. }

  3184. /* This type describes each known response to the qSupported
  3185.    packet.  */
  3186. struct protocol_feature
  3187. {
  3188.   /* The name of this protocol feature.  */
  3189.   const char *name;

  3190.   /* The default for this protocol feature.  */
  3191.   enum packet_support default_support;

  3192.   /* The function to call when this feature is reported, or after
  3193.      qSupported processing if the feature is not supported.
  3194.      The first argument points to this structure.  The second
  3195.      argument indicates whether the packet requested support be
  3196.      enabled, disabled, or probed (or the default, if this function
  3197.      is being called at the end of processing and this feature was
  3198.      not reported).  The third argument may be NULL; if not NULL, it
  3199.      is a NUL-terminated string taken from the packet following
  3200.      this feature's name and an equals sign.  */
  3201.   void (*func) (const struct protocol_feature *, enum packet_support,
  3202.                 const char *);

  3203.   /* The corresponding packet for this feature.  Only used if
  3204.      FUNC is remote_supported_packet.  */
  3205.   int packet;
  3206. };

  3207. static void
  3208. remote_supported_packet (const struct protocol_feature *feature,
  3209.                          enum packet_support support,
  3210.                          const char *argument)
  3211. {
  3212.   if (argument)
  3213.     {
  3214.       warning (_("Remote qSupported response supplied an unexpected value for"
  3215.                  " \"%s\"."), feature->name);
  3216.       return;
  3217.     }

  3218.   remote_protocol_packets[feature->packet].support = support;
  3219. }

  3220. static void
  3221. remote_packet_size (const struct protocol_feature *feature,
  3222.                     enum packet_support support, const char *value)
  3223. {
  3224.   struct remote_state *rs = get_remote_state ();

  3225.   int packet_size;
  3226.   char *value_end;

  3227.   if (support != PACKET_ENABLE)
  3228.     return;

  3229.   if (value == NULL || *value == '\0')
  3230.     {
  3231.       warning (_("Remote target reported \"%s\" without a size."),
  3232.                feature->name);
  3233.       return;
  3234.     }

  3235.   errno = 0;
  3236.   packet_size = strtol (value, &value_end, 16);
  3237.   if (errno != 0 || *value_end != '\0' || packet_size < 0)
  3238.     {
  3239.       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
  3240.                feature->name, value);
  3241.       return;
  3242.     }

  3243.   if (packet_size > MAX_REMOTE_PACKET_SIZE)
  3244.     {
  3245.       warning (_("limiting remote suggested packet size (%d bytes) to %d"),
  3246.                packet_size, MAX_REMOTE_PACKET_SIZE);
  3247.       packet_size = MAX_REMOTE_PACKET_SIZE;
  3248.     }

  3249.   /* Record the new maximum packet size.  */
  3250.   rs->explicit_packet_size = packet_size;
  3251. }

  3252. static const struct protocol_feature remote_protocol_features[] = {
  3253.   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
  3254.   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
  3255.     PACKET_qXfer_auxv },
  3256.   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
  3257.     PACKET_qXfer_features },
  3258.   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
  3259.     PACKET_qXfer_libraries },
  3260.   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
  3261.     PACKET_qXfer_libraries_svr4 },
  3262.   { "augmented-libraries-svr4-read", PACKET_DISABLE,
  3263.     remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
  3264.   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
  3265.     PACKET_qXfer_memory_map },
  3266.   { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
  3267.     PACKET_qXfer_spu_read },
  3268.   { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
  3269.     PACKET_qXfer_spu_write },
  3270.   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
  3271.     PACKET_qXfer_osdata },
  3272.   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
  3273.     PACKET_qXfer_threads },
  3274.   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
  3275.     PACKET_qXfer_traceframe_info },
  3276.   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
  3277.     PACKET_QPassSignals },
  3278.   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
  3279.     PACKET_QProgramSignals },
  3280.   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
  3281.     PACKET_QStartNoAckMode },
  3282.   { "multiprocess", PACKET_DISABLE, remote_supported_packet,
  3283.     PACKET_multiprocess_feature },
  3284.   { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
  3285.   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
  3286.     PACKET_qXfer_siginfo_read },
  3287.   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
  3288.     PACKET_qXfer_siginfo_write },
  3289.   { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
  3290.     PACKET_ConditionalTracepoints },
  3291.   { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
  3292.     PACKET_ConditionalBreakpoints },
  3293.   { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
  3294.     PACKET_BreakpointCommands },
  3295.   { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
  3296.     PACKET_FastTracepoints },
  3297.   { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
  3298.     PACKET_StaticTracepoints },
  3299.   {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
  3300.    PACKET_InstallInTrace},
  3301.   { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
  3302.     PACKET_DisconnectedTracing_feature },
  3303.   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
  3304.     PACKET_bc },
  3305.   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
  3306.     PACKET_bs },
  3307.   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
  3308.     PACKET_TracepointSource },
  3309.   { "QAllow", PACKET_DISABLE, remote_supported_packet,
  3310.     PACKET_QAllow },
  3311.   { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
  3312.     PACKET_EnableDisableTracepoints_feature },
  3313.   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
  3314.     PACKET_qXfer_fdpic },
  3315.   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
  3316.     PACKET_qXfer_uib },
  3317.   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
  3318.     PACKET_QDisableRandomization },
  3319.   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
  3320.   { "QTBuffer:size", PACKET_DISABLE,
  3321.     remote_supported_packet, PACKET_QTBuffer_size},
  3322.   { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
  3323.   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
  3324.   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
  3325.   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
  3326.     PACKET_qXfer_btrace }
  3327. };

  3328. static char *remote_support_xml;

  3329. /* Register string appended to "xmlRegisters=" in qSupported query.  */

  3330. void
  3331. register_remote_support_xml (const char *xml)
  3332. {
  3333. #if defined(HAVE_LIBEXPAT)
  3334.   if (remote_support_xml == NULL)
  3335.     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
  3336.   else
  3337.     {
  3338.       char *copy = xstrdup (remote_support_xml + 13);
  3339.       char *p = strtok (copy, ",");

  3340.       do
  3341.         {
  3342.           if (strcmp (p, xml) == 0)
  3343.             {
  3344.               /* already there */
  3345.               xfree (copy);
  3346.               return;
  3347.             }
  3348.         }
  3349.       while ((p = strtok (NULL, ",")) != NULL);
  3350.       xfree (copy);

  3351.       remote_support_xml = reconcat (remote_support_xml,
  3352.                                      remote_support_xml, ",", xml,
  3353.                                      (char *) NULL);
  3354.     }
  3355. #endif
  3356. }

  3357. static char *
  3358. remote_query_supported_append (char *msg, const char *append)
  3359. {
  3360.   if (msg)
  3361.     return reconcat (msg, msg, ";", append, (char *) NULL);
  3362.   else
  3363.     return xstrdup (append);
  3364. }

  3365. static void
  3366. remote_query_supported (void)
  3367. {
  3368.   struct remote_state *rs = get_remote_state ();
  3369.   char *next;
  3370.   int i;
  3371.   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];

  3372.   /* The packet support flags are handled differently for this packet
  3373.      than for most others.  We treat an error, a disabled packet, and
  3374.      an empty response identically: any features which must be reported
  3375.      to be used will be automatically disabled.  An empty buffer
  3376.      accomplishes this, since that is also the representation for a list
  3377.      containing no features.  */

  3378.   rs->buf[0] = 0;
  3379.   if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
  3380.     {
  3381.       char *q = NULL;
  3382.       struct cleanup *old_chain = make_cleanup (free_current_contents, &q);

  3383.       q = remote_query_supported_append (q, "multiprocess+");

  3384.       if (remote_support_xml)
  3385.         q = remote_query_supported_append (q, remote_support_xml);

  3386.       q = remote_query_supported_append (q, "qRelocInsn+");

  3387.       q = reconcat (q, "qSupported:", q, (char *) NULL);
  3388.       putpkt (q);

  3389.       do_cleanups (old_chain);

  3390.       getpkt (&rs->buf, &rs->buf_size, 0);

  3391.       /* If an error occured, warn, but do not return - just reset the
  3392.          buffer to empty and go on to disable features.  */
  3393.       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
  3394.           == PACKET_ERROR)
  3395.         {
  3396.           warning (_("Remote failure reply: %s"), rs->buf);
  3397.           rs->buf[0] = 0;
  3398.         }
  3399.     }

  3400.   memset (seen, 0, sizeof (seen));

  3401.   next = rs->buf;
  3402.   while (*next)
  3403.     {
  3404.       enum packet_support is_supported;
  3405.       char *p, *end, *name_end, *value;

  3406.       /* First separate out this item from the rest of the packet.  If
  3407.          there's another item after this, we overwrite the separator
  3408.          (terminated strings are much easier to work with).  */
  3409.       p = next;
  3410.       end = strchr (p, ';');
  3411.       if (end == NULL)
  3412.         {
  3413.           end = p + strlen (p);
  3414.           next = end;
  3415.         }
  3416.       else
  3417.         {
  3418.           *end = '\0';
  3419.           next = end + 1;

  3420.           if (end == p)
  3421.             {
  3422.               warning (_("empty item in \"qSupported\" response"));
  3423.               continue;
  3424.             }
  3425.         }

  3426.       name_end = strchr (p, '=');
  3427.       if (name_end)
  3428.         {
  3429.           /* This is a name=value entry.  */
  3430.           is_supported = PACKET_ENABLE;
  3431.           value = name_end + 1;
  3432.           *name_end = '\0';
  3433.         }
  3434.       else
  3435.         {
  3436.           value = NULL;
  3437.           switch (end[-1])
  3438.             {
  3439.             case '+':
  3440.               is_supported = PACKET_ENABLE;
  3441.               break;

  3442.             case '-':
  3443.               is_supported = PACKET_DISABLE;
  3444.               break;

  3445.             case '?':
  3446.               is_supported = PACKET_SUPPORT_UNKNOWN;
  3447.               break;

  3448.             default:
  3449.               warning (_("unrecognized item \"%s\" "
  3450.                          "in \"qSupported\" response"), p);
  3451.               continue;
  3452.             }
  3453.           end[-1] = '\0';
  3454.         }

  3455.       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
  3456.         if (strcmp (remote_protocol_features[i].name, p) == 0)
  3457.           {
  3458.             const struct protocol_feature *feature;

  3459.             seen[i] = 1;
  3460.             feature = &remote_protocol_features[i];
  3461.             feature->func (feature, is_supported, value);
  3462.             break;
  3463.           }
  3464.     }

  3465.   /* If we increased the packet size, make sure to increase the global
  3466.      buffer size also.  We delay this until after parsing the entire
  3467.      qSupported packet, because this is the same buffer we were
  3468.      parsing.  */
  3469.   if (rs->buf_size < rs->explicit_packet_size)
  3470.     {
  3471.       rs->buf_size = rs->explicit_packet_size;
  3472.       rs->buf = xrealloc (rs->buf, rs->buf_size);
  3473.     }

  3474.   /* Handle the defaults for unmentioned features.  */
  3475.   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
  3476.     if (!seen[i])
  3477.       {
  3478.         const struct protocol_feature *feature;

  3479.         feature = &remote_protocol_features[i];
  3480.         feature->func (feature, feature->default_support, NULL);
  3481.       }
  3482. }

  3483. /* Remove any of the remote.c targets from target stack.  Upper targets depend
  3484.    on it so remove them first.  */

  3485. static void
  3486. remote_unpush_target (void)
  3487. {
  3488.   pop_all_targets_above (process_stratum - 1);
  3489. }

  3490. static void
  3491. remote_open_1 (const char *name, int from_tty,
  3492.                struct target_ops *target, int extended_p)
  3493. {
  3494.   struct remote_state *rs = get_remote_state ();

  3495.   if (name == 0)
  3496.     error (_("To open a remote debug connection, you need to specify what\n"
  3497.            "serial device is attached to the remote system\n"
  3498.            "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));

  3499.   /* See FIXME above.  */
  3500.   if (!target_async_permitted)
  3501.     wait_forever_enabled_p = 1;

  3502.   /* If we're connected to a running target, target_preopen will kill it.
  3503.      Ask this question first, before target_preopen has a chance to kill
  3504.      anything.  */
  3505.   if (rs->remote_desc != NULL && !have_inferiors ())
  3506.     {
  3507.       if (from_tty
  3508.           && !query (_("Already connected to a remote target.  Disconnect? ")))
  3509.         error (_("Still connected."));
  3510.     }

  3511.   /* Here the possibly existing remote target gets unpushed.  */
  3512.   target_preopen (from_tty);

  3513.   /* Make sure we send the passed signals list the next time we resume.  */
  3514.   xfree (rs->last_pass_packet);
  3515.   rs->last_pass_packet = NULL;

  3516.   /* Make sure we send the program signals list the next time we
  3517.      resume.  */
  3518.   xfree (rs->last_program_signals_packet);
  3519.   rs->last_program_signals_packet = NULL;

  3520.   remote_fileio_reset ();
  3521.   reopen_exec_file ();
  3522.   reread_symbols ();

  3523.   rs->remote_desc = remote_serial_open (name);
  3524.   if (!rs->remote_desc)
  3525.     perror_with_name (name);

  3526.   if (baud_rate != -1)
  3527.     {
  3528.       if (serial_setbaudrate (rs->remote_desc, baud_rate))
  3529.         {
  3530.           /* The requested speed could not be set.  Error out to
  3531.              top level after closing remote_desc.  Take care to
  3532.              set remote_desc to NULL to avoid closing remote_desc
  3533.              more than once.  */
  3534.           serial_close (rs->remote_desc);
  3535.           rs->remote_desc = NULL;
  3536.           perror_with_name (name);
  3537.         }
  3538.     }

  3539.   serial_raw (rs->remote_desc);

  3540.   /* If there is something sitting in the buffer we might take it as a
  3541.      response to a command, which would be bad.  */
  3542.   serial_flush_input (rs->remote_desc);

  3543.   if (from_tty)
  3544.     {
  3545.       puts_filtered ("Remote debugging using ");
  3546.       puts_filtered (name);
  3547.       puts_filtered ("\n");
  3548.     }
  3549.   push_target (target);                /* Switch to using remote target now.  */

  3550.   /* Register extra event sources in the event loop.  */
  3551.   remote_async_inferior_event_token
  3552.     = create_async_event_handler (remote_async_inferior_event_handler,
  3553.                                   NULL);
  3554.   rs->notif_state = remote_notif_state_allocate ();

  3555.   /* Reset the target state; these things will be queried either by
  3556.      remote_query_supported or as they are needed.  */
  3557.   reset_all_packet_configs_support ();
  3558.   rs->cached_wait_status = 0;
  3559.   rs->explicit_packet_size = 0;
  3560.   rs->noack_mode = 0;
  3561.   rs->extended = extended_p;
  3562.   rs->waiting_for_stop_reply = 0;
  3563.   rs->ctrlc_pending_p = 0;

  3564.   rs->general_thread = not_sent_ptid;
  3565.   rs->continue_thread = not_sent_ptid;
  3566.   rs->remote_traceframe_number = -1;

  3567.   /* Probe for ability to use "ThreadInfo" query, as required.  */
  3568.   rs->use_threadinfo_query = 1;
  3569.   rs->use_threadextra_query = 1;

  3570.   if (target_async_permitted)
  3571.     {
  3572.       /* With this target we start out by owning the terminal.  */
  3573.       remote_async_terminal_ours_p = 1;

  3574.       /* FIXME: cagney/1999-09-23: During the initial connection it is
  3575.          assumed that the target is already ready and able to respond to
  3576.          requests.  Unfortunately remote_start_remote() eventually calls
  3577.          wait_for_inferior() with no timeoutwait_forever_enabled_p gets
  3578.          around this.  Eventually a mechanism that allows
  3579.          wait_for_inferior() to expect/get timeouts will be
  3580.          implemented.  */
  3581.       wait_forever_enabled_p = 0;
  3582.     }

  3583.   /* First delete any symbols previously loaded from shared libraries.  */
  3584.   no_shared_libraries (NULL, 0);

  3585.   /* Start afresh.  */
  3586.   init_thread_list ();

  3587.   /* Start the remote connection.  If error() or QUIT, discard this
  3588.      target (we'd otherwise be in an inconsistent state) and then
  3589.      propogate the error on up the exception chain.  This ensures that
  3590.      the caller doesn't stumble along blindly assuming that the
  3591.      function succeeded.  The CLI doesn't have this problem but other
  3592.      UI's, such as MI do.

  3593.      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
  3594.      this function should return an error indication letting the
  3595.      caller restore the previous state.  Unfortunately the command
  3596.      ``target remote'' is directly wired to this function making that
  3597.      impossible.  On a positive note, the CLI side of this problem has
  3598.      been fixed - the function set_cmd_context() makes it possible for
  3599.      all the ``target ....'' commands to share a common callback
  3600.      function.  See cli-dump.c.  */
  3601.   {
  3602.     volatile struct gdb_exception ex;

  3603.     TRY_CATCH (ex, RETURN_MASK_ALL)
  3604.       {
  3605.         remote_start_remote (from_tty, target, extended_p);
  3606.       }
  3607.     if (ex.reason < 0)
  3608.       {
  3609.         /* Pop the partially set up target - unless something else did
  3610.            already before throwing the exception.  */
  3611.         if (rs->remote_desc != NULL)
  3612.           remote_unpush_target ();
  3613.         if (target_async_permitted)
  3614.           wait_forever_enabled_p = 1;
  3615.         throw_exception (ex);
  3616.       }
  3617.   }

  3618.   if (target_async_permitted)
  3619.     wait_forever_enabled_p = 1;
  3620. }

  3621. /* This takes a program previously attached to and detaches it.  After
  3622.    this is done, GDB can be used to debug some other program.  We
  3623.    better not have left any breakpoints in the target program or it'll
  3624.    die when it hits one.  */

  3625. static void
  3626. remote_detach_1 (const char *args, int from_tty, int extended)
  3627. {
  3628.   int pid = ptid_get_pid (inferior_ptid);
  3629.   struct remote_state *rs = get_remote_state ();

  3630.   if (args)
  3631.     error (_("Argument given to \"detach\" when remotely debugging."));

  3632.   if (!target_has_execution)
  3633.     error (_("No process to detach from."));

  3634.   if (from_tty)
  3635.     {
  3636.       char *exec_file = get_exec_file (0);
  3637.       if (exec_file == NULL)
  3638.         exec_file = "";
  3639.       printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
  3640.                          target_pid_to_str (pid_to_ptid (pid)));
  3641.       gdb_flush (gdb_stdout);
  3642.     }

  3643.   /* Tell the remote target to detach.  */
  3644.   if (remote_multi_process_p (rs))
  3645.     xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
  3646.   else
  3647.     strcpy (rs->buf, "D");

  3648.   putpkt (rs->buf);
  3649.   getpkt (&rs->buf, &rs->buf_size, 0);

  3650.   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
  3651.     ;
  3652.   else if (rs->buf[0] == '\0')
  3653.     error (_("Remote doesn't know how to detach"));
  3654.   else
  3655.     error (_("Can't detach process."));

  3656.   if (from_tty && !extended)
  3657.     puts_filtered (_("Ending remote debugging.\n"));

  3658.   target_mourn_inferior ();
  3659. }

  3660. static void
  3661. remote_detach (struct target_ops *ops, const char *args, int from_tty)
  3662. {
  3663.   remote_detach_1 (args, from_tty, 0);
  3664. }

  3665. static void
  3666. extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
  3667. {
  3668.   remote_detach_1 (args, from_tty, 1);
  3669. }

  3670. /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */

  3671. static void
  3672. remote_disconnect (struct target_ops *target, const char *args, int from_tty)
  3673. {
  3674.   if (args)
  3675.     error (_("Argument given to \"disconnect\" when remotely debugging."));

  3676.   /* Make sure we unpush even the extended remote targets; mourn
  3677.      won't do it.  So call remote_mourn_1 directly instead of
  3678.      target_mourn_inferior.  */
  3679.   remote_mourn_1 (target);

  3680.   if (from_tty)
  3681.     puts_filtered ("Ending remote debugging.\n");
  3682. }

  3683. /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
  3684.    be chatty about it.  */

  3685. static void
  3686. extended_remote_attach_1 (struct target_ops *target, const char *args,
  3687.                           int from_tty)
  3688. {
  3689.   struct remote_state *rs = get_remote_state ();
  3690.   int pid;
  3691.   char *wait_status = NULL;

  3692.   pid = parse_pid_to_attach (args);

  3693.   /* Remote PID can be freely equal to getpid, do not check it here the same
  3694.      way as in other targets.  */

  3695.   if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
  3696.     error (_("This target does not support attaching to a process"));

  3697.   if (from_tty)
  3698.     {
  3699.       char *exec_file = get_exec_file (0);

  3700.       if (exec_file)
  3701.         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
  3702.                            target_pid_to_str (pid_to_ptid (pid)));
  3703.       else
  3704.         printf_unfiltered (_("Attaching to %s\n"),
  3705.                            target_pid_to_str (pid_to_ptid (pid)));

  3706.       gdb_flush (gdb_stdout);
  3707.     }

  3708.   xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
  3709.   putpkt (rs->buf);
  3710.   getpkt (&rs->buf, &rs->buf_size, 0);

  3711.   switch (packet_ok (rs->buf,
  3712.                      &remote_protocol_packets[PACKET_vAttach]))
  3713.     {
  3714.     case PACKET_OK:
  3715.       if (!non_stop)
  3716.         {
  3717.           /* Save the reply for later.  */
  3718.           wait_status = alloca (strlen (rs->buf) + 1);
  3719.           strcpy (wait_status, rs->buf);
  3720.         }
  3721.       else if (strcmp (rs->buf, "OK") != 0)
  3722.         error (_("Attaching to %s failed with: %s"),
  3723.                target_pid_to_str (pid_to_ptid (pid)),
  3724.                rs->buf);
  3725.       break;
  3726.     case PACKET_UNKNOWN:
  3727.       error (_("This target does not support attaching to a process"));
  3728.     default:
  3729.       error (_("Attaching to %s failed"),
  3730.              target_pid_to_str (pid_to_ptid (pid)));
  3731.     }

  3732.   set_current_inferior (remote_add_inferior (0, pid, 1));

  3733.   inferior_ptid = pid_to_ptid (pid);

  3734.   if (non_stop)
  3735.     {
  3736.       struct thread_info *thread;

  3737.       /* Get list of threads.  */
  3738.       remote_update_thread_list (target);

  3739.       thread = first_thread_of_process (pid);
  3740.       if (thread)
  3741.         inferior_ptid = thread->ptid;
  3742.       else
  3743.         inferior_ptid = pid_to_ptid (pid);

  3744.       /* Invalidate our notion of the remote current thread.  */
  3745.       record_currthread (rs, minus_one_ptid);
  3746.     }
  3747.   else
  3748.     {
  3749.       /* Now, if we have thread information, update inferior_ptid.  */
  3750.       inferior_ptid = remote_current_thread (inferior_ptid);

  3751.       /* Add the main thread to the thread list.  */
  3752.       add_thread_silent (inferior_ptid);
  3753.     }

  3754.   /* Next, if the target can specify a description, read it.  We do
  3755.      this before anything involving memory or registers.  */
  3756.   target_find_description ();

  3757.   if (!non_stop)
  3758.     {
  3759.       /* Use the previously fetched status.  */
  3760.       gdb_assert (wait_status != NULL);

  3761.       if (target_can_async_p ())
  3762.         {
  3763.           struct notif_event *reply
  3764.             =  remote_notif_parse (&notif_client_stop, wait_status);

  3765.           push_stop_reply ((struct stop_reply *) reply);

  3766.           target_async (inferior_event_handler, 0);
  3767.         }
  3768.       else
  3769.         {
  3770.           gdb_assert (wait_status != NULL);
  3771.           strcpy (rs->buf, wait_status);
  3772.           rs->cached_wait_status = 1;
  3773.         }
  3774.     }
  3775.   else
  3776.     gdb_assert (wait_status == NULL);
  3777. }

  3778. static void
  3779. extended_remote_attach (struct target_ops *ops, const char *args, int from_tty)
  3780. {
  3781.   extended_remote_attach_1 (ops, args, from_tty);
  3782. }

  3783. /* Implementation of the to_post_attach method.  */

  3784. static void
  3785. extended_remote_post_attach (struct target_ops *ops, int pid)
  3786. {
  3787.   /* In certain cases GDB might not have had the chance to start
  3788.      symbol lookup up until now.  This could happen if the debugged
  3789.      binary is not using shared libraries, the vsyscall page is not
  3790.      present (on Linux) and the binary itself hadn't changed since the
  3791.      debugging process was started.  */
  3792.   if (symfile_objfile != NULL)
  3793.     remote_check_symbols();
  3794. }


  3795. /* Check for the availability of vCont.  This function should also check
  3796.    the response.  */

  3797. static void
  3798. remote_vcont_probe (struct remote_state *rs)
  3799. {
  3800.   char *buf;

  3801.   strcpy (rs->buf, "vCont?");
  3802.   putpkt (rs->buf);
  3803.   getpkt (&rs->buf, &rs->buf_size, 0);
  3804.   buf = rs->buf;

  3805.   /* Make sure that the features we assume are supported.  */
  3806.   if (strncmp (buf, "vCont", 5) == 0)
  3807.     {
  3808.       char *p = &buf[5];
  3809.       int support_s, support_S, support_c, support_C;

  3810.       support_s = 0;
  3811.       support_S = 0;
  3812.       support_c = 0;
  3813.       support_C = 0;
  3814.       rs->supports_vCont.t = 0;
  3815.       rs->supports_vCont.r = 0;
  3816.       while (p && *p == ';')
  3817.         {
  3818.           p++;
  3819.           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
  3820.             support_s = 1;
  3821.           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
  3822.             support_S = 1;
  3823.           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
  3824.             support_c = 1;
  3825.           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
  3826.             support_C = 1;
  3827.           else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
  3828.             rs->supports_vCont.t = 1;
  3829.           else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
  3830.             rs->supports_vCont.r = 1;

  3831.           p = strchr (p, ';');
  3832.         }

  3833.       /* If s, S, c, and C are not all supported, we can't use vCont.  Clearing
  3834.          BUF will make packet_ok disable the packet.  */
  3835.       if (!support_s || !support_S || !support_c || !support_C)
  3836.         buf[0] = 0;
  3837.     }

  3838.   packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
  3839. }

  3840. /* Helper function for building "vCont" resumptions.  Write a
  3841.    resumption to P.  ENDP points to one-passed-the-end of the buffer
  3842.    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
  3843.    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
  3844.    resumed thread should be single-stepped and/or signalled.  If PTID
  3845.    equals minus_one_ptid, then all threads are resumed; if PTID
  3846.    represents a process, then all threads of the process are resumed;
  3847.    the thread to be stepped and/or signalled is given in the global
  3848.    INFERIOR_PTID.  */

  3849. static char *
  3850. append_resumption (char *p, char *endp,
  3851.                    ptid_t ptid, int step, enum gdb_signal siggnal)
  3852. {
  3853.   struct remote_state *rs = get_remote_state ();

  3854.   if (step && siggnal != GDB_SIGNAL_0)
  3855.     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
  3856.   else if (step
  3857.            /* GDB is willing to range step.  */
  3858.            && use_range_stepping
  3859.            /* Target supports range stepping.  */
  3860.            && rs->supports_vCont.r
  3861.            /* We don't currently support range stepping multiple
  3862.               threads with a wildcard (though the protocol allows it,
  3863.               so stubs shouldn't make an active effort to forbid
  3864.               it).  */
  3865.            && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
  3866.     {
  3867.       struct thread_info *tp;

  3868.       if (ptid_equal (ptid, minus_one_ptid))
  3869.         {
  3870.           /* If we don't know about the target thread's tid, then
  3871.              we're resuming magic_null_ptid (see caller).  */
  3872.           tp = find_thread_ptid (magic_null_ptid);
  3873.         }
  3874.       else
  3875.         tp = find_thread_ptid (ptid);
  3876.       gdb_assert (tp != NULL);

  3877.       if (tp->control.may_range_step)
  3878.         {
  3879.           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;

  3880.           p += xsnprintf (p, endp - p, ";r%s,%s",
  3881.                           phex_nz (tp->control.step_range_start,
  3882.                                    addr_size),
  3883.                           phex_nz (tp->control.step_range_end,
  3884.                                    addr_size));
  3885.         }
  3886.       else
  3887.         p += xsnprintf (p, endp - p, ";s");
  3888.     }
  3889.   else if (step)
  3890.     p += xsnprintf (p, endp - p, ";s");
  3891.   else if (siggnal != GDB_SIGNAL_0)
  3892.     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
  3893.   else
  3894.     p += xsnprintf (p, endp - p, ";c");

  3895.   if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
  3896.     {
  3897.       ptid_t nptid;

  3898.       /* All (-1) threads of process.  */
  3899.       nptid = ptid_build (ptid_get_pid (ptid), -1, 0);

  3900.       p += xsnprintf (p, endp - p, ":");
  3901.       p = write_ptid (p, endp, nptid);
  3902.     }
  3903.   else if (!ptid_equal (ptid, minus_one_ptid))
  3904.     {
  3905.       p += xsnprintf (p, endp - p, ":");
  3906.       p = write_ptid (p, endp, ptid);
  3907.     }

  3908.   return p;
  3909. }

  3910. /* Append a vCont continue-with-signal action for threads that have a
  3911.    non-zero stop signal.  */

  3912. static char *
  3913. append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
  3914. {
  3915.   struct thread_info *thread;

  3916.   ALL_NON_EXITED_THREADS (thread)
  3917.     if (ptid_match (thread->ptid, ptid)
  3918.         && !ptid_equal (inferior_ptid, thread->ptid)
  3919.         && thread->suspend.stop_signal != GDB_SIGNAL_0)
  3920.       {
  3921.         p = append_resumption (p, endp, thread->ptid,
  3922.                                0, thread->suspend.stop_signal);
  3923.         thread->suspend.stop_signal = GDB_SIGNAL_0;
  3924.       }

  3925.   return p;
  3926. }

  3927. /* Resume the remote inferior by using a "vCont" packet.  The thread
  3928.    to be resumed is PTID; STEP and SIGGNAL indicate whether the
  3929.    resumed thread should be single-stepped and/or signalled.  If PTID
  3930.    equals minus_one_ptid, then all threads are resumed; the thread to
  3931.    be stepped and/or signalled is given in the global INFERIOR_PTID.
  3932.    This function returns non-zero iff it resumes the inferior.

  3933.    This function issues a strict subset of all possible vCont commands at the
  3934.    moment.  */

  3935. static int
  3936. remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
  3937. {
  3938.   struct remote_state *rs = get_remote_state ();
  3939.   char *p;
  3940.   char *endp;

  3941.   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
  3942.     remote_vcont_probe (rs);

  3943.   if (packet_support (PACKET_vCont) == PACKET_DISABLE)
  3944.     return 0;

  3945.   p = rs->buf;
  3946.   endp = rs->buf + get_remote_packet_size ();

  3947.   /* If we could generate a wider range of packets, we'd have to worry
  3948.      about overflowing BUF.  Should there be a generic
  3949.      "multi-part-packet" packet?  */

  3950.   p += xsnprintf (p, endp - p, "vCont");

  3951.   if (ptid_equal (ptid, magic_null_ptid))
  3952.     {
  3953.       /* MAGIC_NULL_PTID means that we don't have any active threads,
  3954.          so we don't have any TID numbers the inferior will
  3955.          understand.  Make sure to only send forms that do not specify
  3956.          a TID.  */
  3957.       append_resumption (p, endp, minus_one_ptid, step, siggnal);
  3958.     }
  3959.   else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
  3960.     {
  3961.       /* Resume all threads (of all processes, or of a single
  3962.          process), with preference for INFERIOR_PTID.  This assumes
  3963.          inferior_ptid belongs to the set of all threads we are about
  3964.          to resume.  */
  3965.       if (step || siggnal != GDB_SIGNAL_0)
  3966.         {
  3967.           /* Step inferior_ptid, with or without signal.  */
  3968.           p = append_resumption (p, endp, inferior_ptid, step, siggnal);
  3969.         }

  3970.       /* Also pass down any pending signaled resumption for other
  3971.          threads not the current.  */
  3972.       p = append_pending_thread_resumptions (p, endp, ptid);

  3973.       /* And continue others without a signal.  */
  3974.       append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
  3975.     }
  3976.   else
  3977.     {
  3978.       /* Scheduler locking; resume only PTID.  */
  3979.       append_resumption (p, endp, ptid, step, siggnal);
  3980.     }

  3981.   gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
  3982.   putpkt (rs->buf);

  3983.   if (non_stop)
  3984.     {
  3985.       /* In non-stop, the stub replies to vCont with "OK".  The stop
  3986.          reply will be reported asynchronously by means of a `%Stop'
  3987.          notification.  */
  3988.       getpkt (&rs->buf, &rs->buf_size, 0);
  3989.       if (strcmp (rs->buf, "OK") != 0)
  3990.         error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
  3991.     }

  3992.   return 1;
  3993. }

  3994. /* Tell the remote machine to resume.  */

  3995. static void
  3996. remote_resume (struct target_ops *ops,
  3997.                ptid_t ptid, int step, enum gdb_signal siggnal)
  3998. {
  3999.   struct remote_state *rs = get_remote_state ();
  4000.   char *buf;

  4001.   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
  4002.      (explained in remote-notif.c:handle_notification) so
  4003.      remote_notif_process is not called.  We need find a place where
  4004.      it is safe to start a 'vNotif' sequence.  It is good to do it
  4005.      before resuming inferior, because inferior was stopped and no RSP
  4006.      traffic at that moment.  */
  4007.   if (!non_stop)
  4008.     remote_notif_process (rs->notif_state, &notif_client_stop);

  4009.   rs->last_sent_signal = siggnal;
  4010.   rs->last_sent_step = step;

  4011.   /* The vCont packet doesn't need to specify threads via Hc.  */
  4012.   /* No reverse support (yet) for vCont.  */
  4013.   if (execution_direction != EXEC_REVERSE)
  4014.     if (remote_vcont_resume (ptid, step, siggnal))
  4015.       goto done;

  4016.   /* All other supported resume packets do use Hc, so set the continue
  4017.      thread.  */
  4018.   if (ptid_equal (ptid, minus_one_ptid))
  4019.     set_continue_thread (any_thread_ptid);
  4020.   else
  4021.     set_continue_thread (ptid);

  4022.   buf = rs->buf;
  4023.   if (execution_direction == EXEC_REVERSE)
  4024.     {
  4025.       /* We don't pass signals to the target in reverse exec mode.  */
  4026.       if (info_verbose && siggnal != GDB_SIGNAL_0)
  4027.         warning (_(" - Can't pass signal %d to target in reverse: ignored."),
  4028.                  siggnal);

  4029.       if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
  4030.         error (_("Remote reverse-step not supported."));
  4031.       if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
  4032.         error (_("Remote reverse-continue not supported."));

  4033.       strcpy (buf, step ? "bs" : "bc");
  4034.     }
  4035.   else if (siggnal != GDB_SIGNAL_0)
  4036.     {
  4037.       buf[0] = step ? 'S' : 'C';
  4038.       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
  4039.       buf[2] = tohex (((int) siggnal) & 0xf);
  4040.       buf[3] = '\0';
  4041.     }
  4042.   else
  4043.     strcpy (buf, step ? "s" : "c");

  4044.   putpkt (buf);

  4045. done:
  4046.   /* We are about to start executing the inferior, let's register it
  4047.      with the event loop.  NOTE: this is the one place where all the
  4048.      execution commands end up.  We could alternatively do this in each
  4049.      of the execution commands in infcmd.c.  */
  4050.   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
  4051.      into infcmd.c in order to allow inferior function calls to work
  4052.      NOT asynchronously.  */
  4053.   if (target_can_async_p ())
  4054.     target_async (inferior_event_handler, 0);

  4055.   /* We've just told the target to resume.  The remote server will
  4056.      wait for the inferior to stop, and then send a stop reply.  In
  4057.      the mean time, we can't start another command/query ourselves
  4058.      because the stub wouldn't be ready to process it.  This applies
  4059.      only to the base all-stop protocol, however.  In non-stop (which
  4060.      only supports vCont), the stub replies with an "OK", and is
  4061.      immediate able to process further serial input.  */
  4062.   if (!non_stop)
  4063.     rs->waiting_for_stop_reply = 1;
  4064. }


  4065. /* Set up the signal handler for SIGINT, while the target is
  4066.    executing, ovewriting the 'regular' SIGINT signal handler.  */
  4067. static void
  4068. async_initialize_sigint_signal_handler (void)
  4069. {
  4070.   signal (SIGINT, async_handle_remote_sigint);
  4071. }

  4072. /* Signal handler for SIGINT, while the target is executing.  */
  4073. static void
  4074. async_handle_remote_sigint (int sig)
  4075. {
  4076.   signal (sig, async_handle_remote_sigint_twice);
  4077.   /* Note we need to go through gdb_call_async_signal_handler in order
  4078.      to wake up the event loop on Windows.  */
  4079.   gdb_call_async_signal_handler (async_sigint_remote_token, 0);
  4080. }

  4081. /* Signal handler for SIGINT, installed after SIGINT has already been
  4082.    sent once.  It will take effect the second time that the user sends
  4083.    a ^C.  */
  4084. static void
  4085. async_handle_remote_sigint_twice (int sig)
  4086. {
  4087.   signal (sig, async_handle_remote_sigint);
  4088.   /* See note in async_handle_remote_sigint.  */
  4089.   gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
  4090. }

  4091. /* Perform the real interruption of the target execution, in response
  4092.    to a ^C.  */
  4093. static void
  4094. async_remote_interrupt (gdb_client_data arg)
  4095. {
  4096.   if (remote_debug)
  4097.     fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");

  4098.   target_stop (inferior_ptid);
  4099. }

  4100. /* Perform interrupt, if the first attempt did not succeed.  Just give
  4101.    up on the target alltogether.  */
  4102. static void
  4103. async_remote_interrupt_twice (gdb_client_data arg)
  4104. {
  4105.   if (remote_debug)
  4106.     fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");

  4107.   interrupt_query ();
  4108. }

  4109. /* Reinstall the usual SIGINT handlers, after the target has
  4110.    stopped.  */
  4111. static void
  4112. async_cleanup_sigint_signal_handler (void *dummy)
  4113. {
  4114.   signal (SIGINT, handle_sigint);
  4115. }

  4116. /* Send ^C to target to halt it.  Target will respond, and send us a
  4117.    packet.  */
  4118. static void (*ofunc) (int);

  4119. /* The command line interface's stop routine.  This function is installed
  4120.    as a signal handler for SIGINT.  The first time a user requests a
  4121.    stop, we call remote_stop to send a break or ^C.  If there is no
  4122.    response from the target (it didn't stop when the user requested it),
  4123.    we ask the user if he'd like to detach from the target.  */
  4124. static void
  4125. sync_remote_interrupt (int signo)
  4126. {
  4127.   /* If this doesn't work, try more severe steps.  */
  4128.   signal (signo, sync_remote_interrupt_twice);

  4129.   gdb_call_async_signal_handler (async_sigint_remote_token, 1);
  4130. }

  4131. /* The user typed ^C twice.  */

  4132. static void
  4133. sync_remote_interrupt_twice (int signo)
  4134. {
  4135.   signal (signo, ofunc);
  4136.   gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
  4137.   signal (signo, sync_remote_interrupt);
  4138. }

  4139. /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
  4140.    thread, all threads of a remote process, or all threads of all
  4141.    processes.  */

  4142. static void
  4143. remote_stop_ns (ptid_t ptid)
  4144. {
  4145.   struct remote_state *rs = get_remote_state ();
  4146.   char *p = rs->buf;
  4147.   char *endp = rs->buf + get_remote_packet_size ();

  4148.   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
  4149.     remote_vcont_probe (rs);

  4150.   if (!rs->supports_vCont.t)
  4151.     error (_("Remote server does not support stopping threads"));

  4152.   if (ptid_equal (ptid, minus_one_ptid)
  4153.       || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
  4154.     p += xsnprintf (p, endp - p, "vCont;t");
  4155.   else
  4156.     {
  4157.       ptid_t nptid;

  4158.       p += xsnprintf (p, endp - p, "vCont;t:");

  4159.       if (ptid_is_pid (ptid))
  4160.           /* All (-1) threads of process.  */
  4161.         nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
  4162.       else
  4163.         {
  4164.           /* Small optimization: if we already have a stop reply for
  4165.              this thread, no use in telling the stub we want this
  4166.              stopped.  */
  4167.           if (peek_stop_reply (ptid))
  4168.             return;

  4169.           nptid = ptid;
  4170.         }

  4171.       write_ptid (p, endp, nptid);
  4172.     }

  4173.   /* In non-stop, we get an immediate OK reply.  The stop reply will
  4174.      come in asynchronously by notification.  */
  4175.   putpkt (rs->buf);
  4176.   getpkt (&rs->buf, &rs->buf_size, 0);
  4177.   if (strcmp (rs->buf, "OK") != 0)
  4178.     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
  4179. }

  4180. /* All-stop version of target_stop.  Sends a break or a ^C to stop the
  4181.    remote target.  It is undefined which thread of which process
  4182.    reports the stop.  */

  4183. static void
  4184. remote_stop_as (ptid_t ptid)
  4185. {
  4186.   struct remote_state *rs = get_remote_state ();

  4187.   rs->ctrlc_pending_p = 1;

  4188.   /* If the inferior is stopped already, but the core didn't know
  4189.      about it yet, just ignore the request.  The cached wait status
  4190.      will be collected in remote_wait.  */
  4191.   if (rs->cached_wait_status)
  4192.     return;

  4193.   /* Send interrupt_sequence to remote target.  */
  4194.   send_interrupt_sequence ();
  4195. }

  4196. /* This is the generic stop called via the target vector.  When a target
  4197.    interrupt is requested, either by the command line or the GUI, we
  4198.    will eventually end up here.  */

  4199. static void
  4200. remote_stop (struct target_ops *self, ptid_t ptid)
  4201. {
  4202.   if (remote_debug)
  4203.     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");

  4204.   if (non_stop)
  4205.     remote_stop_ns (ptid);
  4206.   else
  4207.     remote_stop_as (ptid);
  4208. }

  4209. /* Ask the user what to do when an interrupt is received.  */

  4210. static void
  4211. interrupt_query (void)
  4212. {
  4213.   target_terminal_ours ();

  4214.   if (target_can_async_p ())
  4215.     {
  4216.       signal (SIGINT, handle_sigint);
  4217.       quit ();
  4218.     }
  4219.   else
  4220.     {
  4221.       if (query (_("Interrupted while waiting for the program.\n\
  4222. Give up (and stop debugging it)? ")))
  4223.         {
  4224.           remote_unpush_target ();
  4225.           quit ();
  4226.         }
  4227.     }

  4228.   target_terminal_inferior ();
  4229. }

  4230. /* Enable/disable target terminal ownership.  Most targets can use
  4231.    terminal groups to control terminal ownership.  Remote targets are
  4232.    different in that explicit transfer of ownership to/from GDB/target
  4233.    is required.  */

  4234. static void
  4235. remote_terminal_inferior (struct target_ops *self)
  4236. {
  4237.   if (!target_async_permitted)
  4238.     /* Nothing to do.  */
  4239.     return;

  4240.   /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
  4241.      idempotent.  The event-loop GDB talking to an asynchronous target
  4242.      with a synchronous command calls this function from both
  4243.      event-top.c and infrun.c/infcmd.c.  Once GDB stops trying to
  4244.      transfer the terminal to the target when it shouldn't this guard
  4245.      can go away.  */
  4246.   if (!remote_async_terminal_ours_p)
  4247.     return;
  4248.   delete_file_handler (input_fd);
  4249.   remote_async_terminal_ours_p = 0;
  4250.   async_initialize_sigint_signal_handler ();
  4251.   /* NOTE: At this point we could also register our selves as the
  4252.      recipient of all input.  Any characters typed could then be
  4253.      passed on down to the target.  */
  4254. }

  4255. static void
  4256. remote_terminal_ours (struct target_ops *self)
  4257. {
  4258.   if (!target_async_permitted)
  4259.     /* Nothing to do.  */
  4260.     return;

  4261.   /* See FIXME in remote_terminal_inferior.  */
  4262.   if (remote_async_terminal_ours_p)
  4263.     return;
  4264.   async_cleanup_sigint_signal_handler (NULL);
  4265.   add_file_handler (input_fd, stdin_event_handler, 0);
  4266.   remote_async_terminal_ours_p = 1;
  4267. }

  4268. static void
  4269. remote_console_output (char *msg)
  4270. {
  4271.   char *p;

  4272.   for (p = msg; p[0] && p[1]; p += 2)
  4273.     {
  4274.       char tb[2];
  4275.       char c = fromhex (p[0]) * 16 + fromhex (p[1]);

  4276.       tb[0] = c;
  4277.       tb[1] = 0;
  4278.       fputs_unfiltered (tb, gdb_stdtarg);
  4279.     }
  4280.   gdb_flush (gdb_stdtarg);
  4281. }

  4282. typedef struct cached_reg
  4283. {
  4284.   int num;
  4285.   gdb_byte data[MAX_REGISTER_SIZE];
  4286. } cached_reg_t;

  4287. DEF_VEC_O(cached_reg_t);

  4288. typedef struct stop_reply
  4289. {
  4290.   struct notif_event base;

  4291.   /* The identifier of the thread about this event  */
  4292.   ptid_t ptid;

  4293.   /* The remote state this event is associated with.  When the remote
  4294.      connection, represented by a remote_state object, is closed,
  4295.      all the associated stop_reply events should be released.  */
  4296.   struct remote_state *rs;

  4297.   struct target_waitstatus ws;

  4298.   /* Expedited registers.  This makes remote debugging a bit more
  4299.      efficient for those targets that provide critical registers as
  4300.      part of their normal status mechanism (as another roundtrip to
  4301.      fetch them is avoided).  */
  4302.   VEC(cached_reg_t) *regcache;

  4303.   int stopped_by_watchpoint_p;
  4304.   CORE_ADDR watch_data_address;

  4305.   int core;
  4306. } *stop_reply_p;

  4307. DECLARE_QUEUE_P (stop_reply_p);
  4308. DEFINE_QUEUE_P (stop_reply_p);
  4309. /* The list of already fetched and acknowledged stop events.  This
  4310.    queue is used for notification Stop, and other notifications
  4311.    don't need queue for their events, because the notification events
  4312.    of Stop can't be consumed immediately, so that events should be
  4313.    queued first, and be consumed by remote_wait_{ns,as} one per
  4314.    time.  Other notifications can consume their events immediately,
  4315.    so queue is not needed for them.  */
  4316. static QUEUE (stop_reply_p) *stop_reply_queue;

  4317. static void
  4318. stop_reply_xfree (struct stop_reply *r)
  4319. {
  4320.   notif_event_xfree ((struct notif_event *) r);
  4321. }

  4322. static void
  4323. remote_notif_stop_parse (struct notif_client *self, char *buf,
  4324.                          struct notif_event *event)
  4325. {
  4326.   remote_parse_stop_reply (buf, (struct stop_reply *) event);
  4327. }

  4328. static void
  4329. remote_notif_stop_ack (struct notif_client *self, char *buf,
  4330.                        struct notif_event *event)
  4331. {
  4332.   struct stop_reply *stop_reply = (struct stop_reply *) event;

  4333.   /* acknowledge */
  4334.   putpkt ((char *) self->ack_command);

  4335.   if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
  4336.       /* We got an unknown stop reply.  */
  4337.       error (_("Unknown stop reply"));

  4338.   push_stop_reply (stop_reply);
  4339. }

  4340. static int
  4341. remote_notif_stop_can_get_pending_events (struct notif_client *self)
  4342. {
  4343.   /* We can't get pending events in remote_notif_process for
  4344.      notification stop, and we have to do this in remote_wait_ns
  4345.      instead.  If we fetch all queued events from stub, remote stub
  4346.      may exit and we have no chance to process them back in
  4347.      remote_wait_ns.  */
  4348.   mark_async_event_handler (remote_async_inferior_event_token);
  4349.   return 0;
  4350. }

  4351. static void
  4352. stop_reply_dtr (struct notif_event *event)
  4353. {
  4354.   struct stop_reply *r = (struct stop_reply *) event;

  4355.   VEC_free (cached_reg_t, r->regcache);
  4356. }

  4357. static struct notif_event *
  4358. remote_notif_stop_alloc_reply (void)
  4359. {
  4360.   struct notif_event *r
  4361.     = (struct notif_event *) XNEW (struct stop_reply);

  4362.   r->dtr = stop_reply_dtr;

  4363.   return r;
  4364. }

  4365. /* A client of notification Stop.  */

  4366. struct notif_client notif_client_stop =
  4367. {
  4368.   "Stop",
  4369.   "vStopped",
  4370.   remote_notif_stop_parse,
  4371.   remote_notif_stop_ack,
  4372.   remote_notif_stop_can_get_pending_events,
  4373.   remote_notif_stop_alloc_reply,
  4374.   REMOTE_NOTIF_STOP,
  4375. };

  4376. /* A parameter to pass data in and out.  */

  4377. struct queue_iter_param
  4378. {
  4379.   void *input;
  4380.   struct stop_reply *output;
  4381. };

  4382. /* Remove stop replies in the queue if its pid is equal to the given
  4383.    inferior's pid.  */

  4384. static int
  4385. remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
  4386.                                 QUEUE_ITER (stop_reply_p) *iter,
  4387.                                 stop_reply_p event,
  4388.                                 void *data)
  4389. {
  4390.   struct queue_iter_param *param = data;
  4391.   struct inferior *inf = param->input;

  4392.   if (ptid_get_pid (event->ptid) == inf->pid)
  4393.     {
  4394.       stop_reply_xfree (event);
  4395.       QUEUE_remove_elem (stop_reply_p, q, iter);
  4396.     }

  4397.   return 1;
  4398. }

  4399. /* Discard all pending stop replies of inferior INF.  */

  4400. static void
  4401. discard_pending_stop_replies (struct inferior *inf)
  4402. {
  4403.   int i;
  4404.   struct queue_iter_param param;
  4405.   struct stop_reply *reply;
  4406.   struct remote_state *rs = get_remote_state ();
  4407.   struct remote_notif_state *rns = rs->notif_state;

  4408.   /* This function can be notified when an inferior exists.  When the
  4409.      target is not remote, the notification state is NULL.  */
  4410.   if (rs->remote_desc == NULL)
  4411.     return;

  4412.   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];

  4413.   /* Discard the in-flight notification.  */
  4414.   if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
  4415.     {
  4416.       stop_reply_xfree (reply);
  4417.       rns->pending_event[notif_client_stop.id] = NULL;
  4418.     }

  4419.   param.input = inf;
  4420.   param.output = NULL;
  4421.   /* Discard the stop replies we have already pulled with
  4422.      vStopped.  */
  4423.   QUEUE_iterate (stop_reply_p, stop_reply_queue,
  4424.                  remove_stop_reply_for_inferior, &param);
  4425. }

  4426. /* If its remote state is equal to the given remote state,
  4427.    remove EVENT from the stop reply queue.  */

  4428. static int
  4429. remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
  4430.                                    QUEUE_ITER (stop_reply_p) *iter,
  4431.                                    stop_reply_p event,
  4432.                                    void *data)
  4433. {
  4434.   struct queue_iter_param *param = data;
  4435.   struct remote_state *rs = param->input;

  4436.   if (event->rs == rs)
  4437.     {
  4438.       stop_reply_xfree (event);
  4439.       QUEUE_remove_elem (stop_reply_p, q, iter);
  4440.     }

  4441.   return 1;
  4442. }

  4443. /* Discard the stop replies for RS in stop_reply_queue.  */

  4444. static void
  4445. discard_pending_stop_replies_in_queue (struct remote_state *rs)
  4446. {
  4447.   struct queue_iter_param param;

  4448.   param.input = rs;
  4449.   param.output = NULL;
  4450.   /* Discard the stop replies we have already pulled with
  4451.      vStopped.  */
  4452.   QUEUE_iterate (stop_reply_p, stop_reply_queue,
  4453.                  remove_stop_reply_of_remote_state, &param);
  4454. }

  4455. /* A parameter to pass data in and out.  */

  4456. static int
  4457. remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
  4458.                                    QUEUE_ITER (stop_reply_p) *iter,
  4459.                                    stop_reply_p event,
  4460.                                    void *data)
  4461. {
  4462.   struct queue_iter_param *param = data;
  4463.   ptid_t *ptid = param->input;

  4464.   if (ptid_match (event->ptid, *ptid))
  4465.     {
  4466.       param->output = event;
  4467.       QUEUE_remove_elem (stop_reply_p, q, iter);
  4468.       return 0;
  4469.     }

  4470.   return 1;
  4471. }

  4472. /* Remove the first reply in 'stop_reply_queue' which matches
  4473.    PTID.  */

  4474. static struct stop_reply *
  4475. remote_notif_remove_queued_reply (ptid_t ptid)
  4476. {
  4477.   struct queue_iter_param param;

  4478.   param.input = &ptid;
  4479.   param.output = NULL;

  4480.   QUEUE_iterate (stop_reply_p, stop_reply_queue,
  4481.                  remote_notif_remove_once_on_match, &param);
  4482.   if (notif_debug)
  4483.     fprintf_unfiltered (gdb_stdlog,
  4484.                         "notif: discard queued event: 'Stop' in %s\n",
  4485.                         target_pid_to_str (ptid));

  4486.   return param.output;
  4487. }

  4488. /* Look for a queued stop reply belonging to PTID.  If one is found,
  4489.    remove it from the queue, and return it.  Returns NULL if none is
  4490.    found.  If there are still queued events left to process, tell the
  4491.    event loop to get back to target_wait soon.  */

  4492. static struct stop_reply *
  4493. queued_stop_reply (ptid_t ptid)
  4494. {
  4495.   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);

  4496.   if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
  4497.     /* There's still at least an event left.  */
  4498.     mark_async_event_handler (remote_async_inferior_event_token);

  4499.   return r;
  4500. }

  4501. /* Push a fully parsed stop reply in the stop reply queue.  Since we
  4502.    know that we now have at least one queued event left to pass to the
  4503.    core side, tell the event loop to get back to target_wait soon.  */

  4504. static void
  4505. push_stop_reply (struct stop_reply *new_event)
  4506. {
  4507.   QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);

  4508.   if (notif_debug)
  4509.     fprintf_unfiltered (gdb_stdlog,
  4510.                         "notif: push 'Stop' %s to queue %d\n",
  4511.                         target_pid_to_str (new_event->ptid),
  4512.                         QUEUE_length (stop_reply_p,
  4513.                                       stop_reply_queue));

  4514.   mark_async_event_handler (remote_async_inferior_event_token);
  4515. }

  4516. static int
  4517. stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
  4518.                               QUEUE_ITER (stop_reply_p) *iter,
  4519.                               struct stop_reply *event,
  4520.                               void *data)
  4521. {
  4522.   ptid_t *ptid = data;

  4523.   return !(ptid_equal (*ptid, event->ptid)
  4524.            && event->ws.kind == TARGET_WAITKIND_STOPPED);
  4525. }

  4526. /* Returns true if we have a stop reply for PTID.  */

  4527. static int
  4528. peek_stop_reply (ptid_t ptid)
  4529. {
  4530.   return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
  4531.                          stop_reply_match_ptid_and_ws, &ptid);
  4532. }

  4533. /* Parse the stop reply in BUF.  Either the function succeeds, and the
  4534.    result is stored in EVENT, or throws an error.  */

  4535. static void
  4536. remote_parse_stop_reply (char *buf, struct stop_reply *event)
  4537. {
  4538.   struct remote_arch_state *rsa = get_remote_arch_state ();
  4539.   ULONGEST addr;
  4540.   char *p;

  4541.   event->ptid = null_ptid;
  4542.   event->rs = get_remote_state ();
  4543.   event->ws.kind = TARGET_WAITKIND_IGNORE;
  4544.   event->ws.value.integer = 0;
  4545.   event->stopped_by_watchpoint_p = 0;
  4546.   event->regcache = NULL;
  4547.   event->core = -1;

  4548.   switch (buf[0])
  4549.     {
  4550.     case 'T':                /* Status with PC, SP, FP, ...        */
  4551.       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
  4552.       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
  4553.             ss = signal number
  4554.             n... = register number
  4555.             r... = register contents
  4556.       */

  4557.       p = &buf[3];        /* after Txx */
  4558.       while (*p)
  4559.         {
  4560.           char *p1;
  4561.           char *p_temp;
  4562.           int fieldsize;
  4563.           LONGEST pnum = 0;

  4564.           /* If the packet contains a register number, save it in
  4565.              pnum and set p1 to point to the character following it.
  4566.              Otherwise p1 points to p.  */

  4567.           /* If this packet is an awatch packet, don't parse the 'a'
  4568.              as a register number.  */

  4569.           if (strncmp (p, "awatch", strlen("awatch")) != 0
  4570.               && strncmp (p, "core", strlen ("core") != 0))
  4571.             {
  4572.               /* Read the ``P'' register number.  */
  4573.               pnum = strtol (p, &p_temp, 16);
  4574.               p1 = p_temp;
  4575.             }
  4576.           else
  4577.             p1 = p;

  4578.           if (p1 == p)        /* No register number present here.  */
  4579.             {
  4580.               p1 = strchr (p, ':');
  4581.               if (p1 == NULL)
  4582.                 error (_("Malformed packet(a) (missing colon): %s\n\
  4583. Packet: '%s'\n"),
  4584.                        p, buf);
  4585.               if (strncmp (p, "thread", p1 - p) == 0)
  4586.                 event->ptid = read_ptid (++p1, &p);
  4587.               else if ((strncmp (p, "watch", p1 - p) == 0)
  4588.                        || (strncmp (p, "rwatch", p1 - p) == 0)
  4589.                        || (strncmp (p, "awatch", p1 - p) == 0))
  4590.                 {
  4591.                   event->stopped_by_watchpoint_p = 1;
  4592.                   p = unpack_varlen_hex (++p1, &addr);
  4593.                   event->watch_data_address = (CORE_ADDR) addr;
  4594.                 }
  4595.               else if (strncmp (p, "library", p1 - p) == 0)
  4596.                 {
  4597.                   p1++;
  4598.                   p_temp = p1;
  4599.                   while (*p_temp && *p_temp != ';')
  4600.                     p_temp++;

  4601.                   event->ws.kind = TARGET_WAITKIND_LOADED;
  4602.                   p = p_temp;
  4603.                 }
  4604.               else if (strncmp (p, "replaylog", p1 - p) == 0)
  4605.                 {
  4606.                   event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
  4607.                   /* p1 will indicate "begin" or "end", but it makes
  4608.                      no difference for now, so ignore it.  */
  4609.                   p_temp = strchr (p1 + 1, ';');
  4610.                   if (p_temp)
  4611.                     p = p_temp;
  4612.                 }
  4613.               else if (strncmp (p, "core", p1 - p) == 0)
  4614.                 {
  4615.                   ULONGEST c;

  4616.                   p = unpack_varlen_hex (++p1, &c);
  4617.                   event->core = c;
  4618.                 }
  4619.               else
  4620.                 {
  4621.                   /* Silently skip unknown optional info.  */
  4622.                   p_temp = strchr (p1 + 1, ';');
  4623.                   if (p_temp)
  4624.                     p = p_temp;
  4625.                 }
  4626.             }
  4627.           else
  4628.             {
  4629.               struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
  4630.               cached_reg_t cached_reg;

  4631.               p = p1;

  4632.               if (*p != ':')
  4633.                 error (_("Malformed packet(b) (missing colon): %s\n\
  4634. Packet: '%s'\n"),
  4635.                        p, buf);
  4636.               ++p;

  4637.               if (reg == NULL)
  4638.                 error (_("Remote sent bad register number %s: %s\n\
  4639. Packet: '%s'\n"),
  4640.                        hex_string (pnum), p, buf);

  4641.               cached_reg.num = reg->regnum;

  4642.               fieldsize = hex2bin (p, cached_reg.data,
  4643.                                    register_size (target_gdbarch (),
  4644.                                                   reg->regnum));
  4645.               p += 2 * fieldsize;
  4646.               if (fieldsize < register_size (target_gdbarch (),
  4647.                                              reg->regnum))
  4648.                 warning (_("Remote reply is too short: %s"), buf);

  4649.               VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
  4650.             }

  4651.           if (*p != ';')
  4652.             error (_("Remote register badly formatted: %s\nhere: %s"),
  4653.                    buf, p);
  4654.           ++p;
  4655.         }

  4656.       if (event->ws.kind != TARGET_WAITKIND_IGNORE)
  4657.         break;

  4658.       /* fall through */
  4659.     case 'S':                /* Old style status, just signal only.  */
  4660.       {
  4661.         int sig;

  4662.         event->ws.kind = TARGET_WAITKIND_STOPPED;
  4663.         sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
  4664.         if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
  4665.           event->ws.value.sig = (enum gdb_signal) sig;
  4666.         else
  4667.           event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
  4668.       }
  4669.       break;
  4670.     case 'W':                /* Target exited.  */
  4671.     case 'X':
  4672.       {
  4673.         char *p;
  4674.         int pid;
  4675.         ULONGEST value;

  4676.         /* GDB used to accept only 2 hex chars here.  Stubs should
  4677.            only send more if they detect GDB supports multi-process
  4678.            support.  */
  4679.         p = unpack_varlen_hex (&buf[1], &value);

  4680.         if (buf[0] == 'W')
  4681.           {
  4682.             /* The remote process exited.  */
  4683.             event->ws.kind = TARGET_WAITKIND_EXITED;
  4684.             event->ws.value.integer = value;
  4685.           }
  4686.         else
  4687.           {
  4688.             /* The remote process exited with a signal.  */
  4689.             event->ws.kind = TARGET_WAITKIND_SIGNALLED;
  4690.             if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
  4691.               event->ws.value.sig = (enum gdb_signal) value;
  4692.             else
  4693.               event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
  4694.           }

  4695.         /* If no process is specified, assume inferior_ptid.  */
  4696.         pid = ptid_get_pid (inferior_ptid);
  4697.         if (*p == '\0')
  4698.           ;
  4699.         else if (*p == ';')
  4700.           {
  4701.             p++;

  4702.             if (p == '\0')
  4703.               ;
  4704.             else if (strncmp (p,
  4705.                               "process:", sizeof ("process:") - 1) == 0)
  4706.               {
  4707.                 ULONGEST upid;

  4708.                 p += sizeof ("process:") - 1;
  4709.                 unpack_varlen_hex (p, &upid);
  4710.                 pid = upid;
  4711.               }
  4712.             else
  4713.               error (_("unknown stop reply packet: %s"), buf);
  4714.           }
  4715.         else
  4716.           error (_("unknown stop reply packet: %s"), buf);
  4717.         event->ptid = pid_to_ptid (pid);
  4718.       }
  4719.       break;
  4720.     }

  4721.   if (non_stop && ptid_equal (event->ptid, null_ptid))
  4722.     error (_("No process or thread specified in stop reply: %s"), buf);
  4723. }

  4724. /* When the stub wants to tell GDB about a new notification reply, it
  4725.    sends a notification (%Stop, for example).  Those can come it at
  4726.    any time, hence, we have to make sure that any pending
  4727.    putpkt/getpkt sequence we're making is finished, before querying
  4728.    the stub for more events with the corresponding ack command
  4729.    (vStopped, for example).  E.g., if we started a vStopped sequence
  4730.    immediately upon receiving the notification, something like this
  4731.    could happen:

  4732.     1.1) --> Hg 1
  4733.     1.2) <-- OK
  4734.     1.3) --> g
  4735.     1.4) <-- %Stop
  4736.     1.5) --> vStopped
  4737.     1.6) <-- (registers reply to step #1.3)

  4738.    Obviously, the reply in step #1.6 would be unexpected to a vStopped
  4739.    query.

  4740.    To solve this, whenever we parse a %Stop notification successfully,
  4741.    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
  4742.    doing whatever we were doing:

  4743.     2.1) --> Hg 1
  4744.     2.2) <-- OK
  4745.     2.3) --> g
  4746.     2.4) <-- %Stop
  4747.       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
  4748.     2.5) <-- (registers reply to step #2.3)

  4749.    Eventualy after step #2.5, we return to the event loop, which
  4750.    notices there's an event on the
  4751.    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
  4752.    associated callback --- the function below.  At this point, we're
  4753.    always safe to start a vStopped sequence. :

  4754.     2.6) --> vStopped
  4755.     2.7) <-- T05 thread:2
  4756.     2.8) --> vStopped
  4757.     2.9) --> OK
  4758. */

  4759. void
  4760. remote_notif_get_pending_events (struct notif_client *nc)
  4761. {
  4762.   struct remote_state *rs = get_remote_state ();

  4763.   if (rs->notif_state->pending_event[nc->id] != NULL)
  4764.     {
  4765.       if (notif_debug)
  4766.         fprintf_unfiltered (gdb_stdlog,
  4767.                             "notif: process: '%s' ack pending event\n",
  4768.                             nc->name);

  4769.       /* acknowledge */
  4770.       nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
  4771.       rs->notif_state->pending_event[nc->id] = NULL;

  4772.       while (1)
  4773.         {
  4774.           getpkt (&rs->buf, &rs->buf_size, 0);
  4775.           if (strcmp (rs->buf, "OK") == 0)
  4776.             break;
  4777.           else
  4778.             remote_notif_ack (nc, rs->buf);
  4779.         }
  4780.     }
  4781.   else
  4782.     {
  4783.       if (notif_debug)
  4784.         fprintf_unfiltered (gdb_stdlog,
  4785.                             "notif: process: '%s' no pending reply\n",
  4786.                             nc->name);
  4787.     }
  4788. }

  4789. /* Called when it is decided that STOP_REPLY holds the info of the
  4790.    event that is to be returned to the core.  This function always
  4791.    destroys STOP_REPLY.  */

  4792. static ptid_t
  4793. process_stop_reply (struct stop_reply *stop_reply,
  4794.                     struct target_waitstatus *status)
  4795. {
  4796.   ptid_t ptid;

  4797.   *status = stop_reply->ws;
  4798.   ptid = stop_reply->ptid;

  4799.   /* If no thread/process was reported by the stub, assume the current
  4800.      inferior.  */
  4801.   if (ptid_equal (ptid, null_ptid))
  4802.     ptid = inferior_ptid;

  4803.   if (status->kind != TARGET_WAITKIND_EXITED
  4804.       && status->kind != TARGET_WAITKIND_SIGNALLED)
  4805.     {
  4806.       struct remote_state *rs = get_remote_state ();

  4807.       /* Expedited registers.  */
  4808.       if (stop_reply->regcache)
  4809.         {
  4810.           struct regcache *regcache
  4811.             = get_thread_arch_regcache (ptid, target_gdbarch ());
  4812.           cached_reg_t *reg;
  4813.           int ix;

  4814.           for (ix = 0;
  4815.                VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
  4816.                ix++)
  4817.             regcache_raw_supply (regcache, reg->num, reg->data);
  4818.           VEC_free (cached_reg_t, stop_reply->regcache);
  4819.         }

  4820.       rs->remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
  4821.       rs->remote_watch_data_address = stop_reply->watch_data_address;

  4822.       remote_notice_new_inferior (ptid, 0);
  4823.       demand_private_info (ptid)->core = stop_reply->core;
  4824.     }

  4825.   stop_reply_xfree (stop_reply);
  4826.   return ptid;
  4827. }

  4828. /* The non-stop mode version of target_wait.  */

  4829. static ptid_t
  4830. remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
  4831. {
  4832.   struct remote_state *rs = get_remote_state ();
  4833.   struct stop_reply *stop_reply;
  4834.   int ret;
  4835.   int is_notif = 0;

  4836.   /* If in non-stop mode, get out of getpkt even if a
  4837.      notification is received.        */

  4838.   ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
  4839.                               0 /* forever */, &is_notif);
  4840.   while (1)
  4841.     {
  4842.       if (ret != -1 && !is_notif)
  4843.         switch (rs->buf[0])
  4844.           {
  4845.           case 'E':                /* Error of some sort.        */
  4846.             /* We're out of sync with the target now.  Did it continue
  4847.                or not?  We can't tell which thread it was in non-stop,
  4848.                so just ignore this.  */
  4849.             warning (_("Remote failure reply: %s"), rs->buf);
  4850.             break;
  4851.           case 'O':                /* Console output.  */
  4852.             remote_console_output (rs->buf + 1);
  4853.             break;
  4854.           default:
  4855.             warning (_("Invalid remote reply: %s"), rs->buf);
  4856.             break;
  4857.           }

  4858.       /* Acknowledge a pending stop reply that may have arrived in the
  4859.          mean time.  */
  4860.       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
  4861.         remote_notif_get_pending_events (&notif_client_stop);

  4862.       /* If indeed we noticed a stop reply, we're done.  */
  4863.       stop_reply = queued_stop_reply (ptid);
  4864.       if (stop_reply != NULL)
  4865.         return process_stop_reply (stop_reply, status);

  4866.       /* Still no event.  If we're just polling for an event, then
  4867.          return to the event loop.  */
  4868.       if (options & TARGET_WNOHANG)
  4869.         {
  4870.           status->kind = TARGET_WAITKIND_IGNORE;
  4871.           return minus_one_ptid;
  4872.         }

  4873.       /* Otherwise do a blocking wait.  */
  4874.       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
  4875.                                   1 /* forever */, &is_notif);
  4876.     }
  4877. }

  4878. /* Wait until the remote machine stops, then return, storing status in
  4879.    STATUS just as `wait' would.  */

  4880. static ptid_t
  4881. remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
  4882. {
  4883.   struct remote_state *rs = get_remote_state ();
  4884.   ptid_t event_ptid = null_ptid;
  4885.   char *buf;
  4886.   struct stop_reply *stop_reply;

  4887. again:

  4888.   status->kind = TARGET_WAITKIND_IGNORE;
  4889.   status->value.integer = 0;

  4890.   stop_reply = queued_stop_reply (ptid);
  4891.   if (stop_reply != NULL)
  4892.     return process_stop_reply (stop_reply, status);

  4893.   if (rs->cached_wait_status)
  4894.     /* Use the cached wait status, but only once.  */
  4895.     rs->cached_wait_status = 0;
  4896.   else
  4897.     {
  4898.       int ret;
  4899.       int is_notif;

  4900.       if (!target_is_async_p ())
  4901.         {
  4902.           ofunc = signal (SIGINT, sync_remote_interrupt);
  4903.           /* If the user hit C-c before this packet, or between packets,
  4904.              pretend that it was hit right here.  */
  4905.           if (check_quit_flag ())
  4906.             {
  4907.               clear_quit_flag ();
  4908.               sync_remote_interrupt (SIGINT);
  4909.             }
  4910.         }

  4911.       /* FIXME: cagney/1999-09-27: If we're in async mode we should
  4912.          _never_ wait for ever -> test on target_is_async_p().
  4913.          However, before we do that we need to ensure that the caller
  4914.          knows how to take the target into/out of async mode.  */
  4915.       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
  4916.                                   wait_forever_enabled_p, &is_notif);

  4917.       if (!target_is_async_p ())
  4918.         signal (SIGINT, ofunc);

  4919.       /* GDB gets a notification.  Return to core as this event is
  4920.          not interesting.  */
  4921.       if (ret != -1 && is_notif)
  4922.         return minus_one_ptid;
  4923.     }

  4924.   buf = rs->buf;

  4925.   rs->remote_stopped_by_watchpoint_p = 0;

  4926.   /* We got something.  */
  4927.   rs->waiting_for_stop_reply = 0;

  4928.   /* Assume that the target has acknowledged Ctrl-C unless we receive
  4929.      an 'F' or 'O' packet.  */
  4930.   if (buf[0] != 'F' && buf[0] != 'O')
  4931.     rs->ctrlc_pending_p = 0;

  4932.   switch (buf[0])
  4933.     {
  4934.     case 'E':                /* Error of some sort.        */
  4935.       /* We're out of sync with the target now.  Did it continue or
  4936.          not?  Not is more likely, so report a stop.  */
  4937.       warning (_("Remote failure reply: %s"), buf);
  4938.       status->kind = TARGET_WAITKIND_STOPPED;
  4939.       status->value.sig = GDB_SIGNAL_0;
  4940.       break;
  4941.     case 'F':                /* File-I/O request.  */
  4942.       remote_fileio_request (buf, rs->ctrlc_pending_p);
  4943.       rs->ctrlc_pending_p = 0;
  4944.       break;
  4945.     case 'T': case 'S': case 'X': case 'W':
  4946.       {
  4947.         struct stop_reply *stop_reply
  4948.           = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
  4949.                                                       rs->buf);

  4950.         event_ptid = process_stop_reply (stop_reply, status);
  4951.         break;
  4952.       }
  4953.     case 'O':                /* Console output.  */
  4954.       remote_console_output (buf + 1);

  4955.       /* The target didn't really stop; keep waiting.  */
  4956.       rs->waiting_for_stop_reply = 1;

  4957.       break;
  4958.     case '\0':
  4959.       if (rs->last_sent_signal != GDB_SIGNAL_0)
  4960.         {
  4961.           /* Zero length reply means that we tried 'S' or 'C' and the
  4962.              remote system doesn't support it.  */
  4963.           target_terminal_ours_for_output ();
  4964.           printf_filtered
  4965.             ("Can't send signals to this remote system.  %s not sent.\n",
  4966.              gdb_signal_to_name (rs->last_sent_signal));
  4967.           rs->last_sent_signal = GDB_SIGNAL_0;
  4968.           target_terminal_inferior ();

  4969.           strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
  4970.           putpkt ((char *) buf);

  4971.           /* We just told the target to resume, so a stop reply is in
  4972.              order.  */
  4973.           rs->waiting_for_stop_reply = 1;
  4974.           break;
  4975.         }
  4976.       /* else fallthrough */
  4977.     default:
  4978.       warning (_("Invalid remote reply: %s"), buf);
  4979.       /* Keep waiting.  */
  4980.       rs->waiting_for_stop_reply = 1;
  4981.       break;
  4982.     }

  4983.   if (status->kind == TARGET_WAITKIND_IGNORE)
  4984.     {
  4985.       /* Nothing interesting happened.  If we're doing a non-blocking
  4986.          poll, we're done.  Otherwise, go back to waiting.  */
  4987.       if (options & TARGET_WNOHANG)
  4988.         return minus_one_ptid;
  4989.       else
  4990.         goto again;
  4991.     }
  4992.   else if (status->kind != TARGET_WAITKIND_EXITED
  4993.            && status->kind != TARGET_WAITKIND_SIGNALLED)
  4994.     {
  4995.       if (!ptid_equal (event_ptid, null_ptid))
  4996.         record_currthread (rs, event_ptid);
  4997.       else
  4998.         event_ptid = inferior_ptid;
  4999.     }
  5000.   else
  5001.     /* A process exit.  Invalidate our notion of current thread.  */
  5002.     record_currthread (rs, minus_one_ptid);

  5003.   return event_ptid;
  5004. }

  5005. /* Wait until the remote machine stops, then return, storing status in
  5006.    STATUS just as `wait' would.  */

  5007. static ptid_t
  5008. remote_wait (struct target_ops *ops,
  5009.              ptid_t ptid, struct target_waitstatus *status, int options)
  5010. {
  5011.   ptid_t event_ptid;

  5012.   if (non_stop)
  5013.     event_ptid = remote_wait_ns (ptid, status, options);
  5014.   else
  5015.     event_ptid = remote_wait_as (ptid, status, options);

  5016.   if (target_can_async_p ())
  5017.     {
  5018.       /* If there are are events left in the queue tell the event loop
  5019.          to return here.  */
  5020.       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
  5021.         mark_async_event_handler (remote_async_inferior_event_token);
  5022.     }

  5023.   return event_ptid;
  5024. }

  5025. /* Fetch a single register using a 'p' packet.  */

  5026. static int
  5027. fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
  5028. {
  5029.   struct remote_state *rs = get_remote_state ();
  5030.   char *buf, *p;
  5031.   char regp[MAX_REGISTER_SIZE];
  5032.   int i;

  5033.   if (packet_support (PACKET_p) == PACKET_DISABLE)
  5034.     return 0;

  5035.   if (reg->pnum == -1)
  5036.     return 0;

  5037.   p = rs->buf;
  5038.   *p++ = 'p';
  5039.   p += hexnumstr (p, reg->pnum);
  5040.   *p++ = '\0';
  5041.   putpkt (rs->buf);
  5042.   getpkt (&rs->buf, &rs->buf_size, 0);

  5043.   buf = rs->buf;

  5044.   switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
  5045.     {
  5046.     case PACKET_OK:
  5047.       break;
  5048.     case PACKET_UNKNOWN:
  5049.       return 0;
  5050.     case PACKET_ERROR:
  5051.       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
  5052.              gdbarch_register_name (get_regcache_arch (regcache),
  5053.                                     reg->regnum),
  5054.              buf);
  5055.     }

  5056.   /* If this register is unfetchable, tell the regcache.  */
  5057.   if (buf[0] == 'x')
  5058.     {
  5059.       regcache_raw_supply (regcache, reg->regnum, NULL);
  5060.       return 1;
  5061.     }

  5062.   /* Otherwise, parse and supply the value.  */
  5063.   p = buf;
  5064.   i = 0;
  5065.   while (p[0] != 0)
  5066.     {
  5067.       if (p[1] == 0)
  5068.         error (_("fetch_register_using_p: early buf termination"));

  5069.       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
  5070.       p += 2;
  5071.     }
  5072.   regcache_raw_supply (regcache, reg->regnum, regp);
  5073.   return 1;
  5074. }

  5075. /* Fetch the registers included in the target's 'g' packet.  */

  5076. static int
  5077. send_g_packet (void)
  5078. {
  5079.   struct remote_state *rs = get_remote_state ();
  5080.   int buf_len;

  5081.   xsnprintf (rs->buf, get_remote_packet_size (), "g");
  5082.   remote_send (&rs->buf, &rs->buf_size);

  5083.   /* We can get out of synch in various cases.  If the first character
  5084.      in the buffer is not a hex character, assume that has happened
  5085.      and try to fetch another packet to read.  */
  5086.   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
  5087.          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
  5088.          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
  5089.          && rs->buf[0] != 'x')        /* New: unavailable register value.  */
  5090.     {
  5091.       if (remote_debug)
  5092.         fprintf_unfiltered (gdb_stdlog,
  5093.                             "Bad register packet; fetching a new packet\n");
  5094.       getpkt (&rs->buf, &rs->buf_size, 0);
  5095.     }

  5096.   buf_len = strlen (rs->buf);

  5097.   /* Sanity check the received packet.  */
  5098.   if (buf_len % 2 != 0)
  5099.     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);

  5100.   return buf_len / 2;
  5101. }

  5102. static void
  5103. process_g_packet (struct regcache *regcache)
  5104. {
  5105.   struct gdbarch *gdbarch = get_regcache_arch (regcache);
  5106.   struct remote_state *rs = get_remote_state ();
  5107.   struct remote_arch_state *rsa = get_remote_arch_state ();
  5108.   int i, buf_len;
  5109.   char *p;
  5110.   char *regs;

  5111.   buf_len = strlen (rs->buf);

  5112.   /* Further sanity checks, with knowledge of the architecture.  */
  5113.   if (buf_len > 2 * rsa->sizeof_g_packet)
  5114.     error (_("Remote 'g' packet reply is too long: %s"), rs->buf);

  5115.   /* Save the size of the packet sent to us by the target.  It is used
  5116.      as a heuristic when determining the max size of packets that the
  5117.      target can safely receive.  */
  5118.   if (rsa->actual_register_packet_size == 0)
  5119.     rsa->actual_register_packet_size = buf_len;

  5120.   /* If this is smaller than we guessed the 'g' packet would be,
  5121.      update our records.  A 'g' reply that doesn't include a register's
  5122.      value implies either that the register is not available, or that
  5123.      the 'p' packet must be used.  */
  5124.   if (buf_len < 2 * rsa->sizeof_g_packet)
  5125.     {
  5126.       rsa->sizeof_g_packet = buf_len / 2;

  5127.       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
  5128.         {
  5129.           if (rsa->regs[i].pnum == -1)
  5130.             continue;

  5131.           if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
  5132.             rsa->regs[i].in_g_packet = 0;
  5133.           else
  5134.             rsa->regs[i].in_g_packet = 1;
  5135.         }
  5136.     }

  5137.   regs = alloca (rsa->sizeof_g_packet);

  5138.   /* Unimplemented registers read as all bits zero.  */
  5139.   memset (regs, 0, rsa->sizeof_g_packet);

  5140.   /* Reply describes registers byte by byte, each byte encoded as two
  5141.      hex characters.  Suck them all up, then supply them to the
  5142.      register cacheing/storage mechanism.  */

  5143.   p = rs->buf;
  5144.   for (i = 0; i < rsa->sizeof_g_packet; i++)
  5145.     {
  5146.       if (p[0] == 0 || p[1] == 0)
  5147.         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
  5148.         internal_error (__FILE__, __LINE__,
  5149.                         _("unexpected end of 'g' packet reply"));

  5150.       if (p[0] == 'x' && p[1] == 'x')
  5151.         regs[i] = 0;                /* 'x' */
  5152.       else
  5153.         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
  5154.       p += 2;
  5155.     }

  5156.   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
  5157.     {
  5158.       struct packet_reg *r = &rsa->regs[i];

  5159.       if (r->in_g_packet)
  5160.         {
  5161.           if (r->offset * 2 >= strlen (rs->buf))
  5162.             /* This shouldn't happen - we adjusted in_g_packet above.  */
  5163.             internal_error (__FILE__, __LINE__,
  5164.                             _("unexpected end of 'g' packet reply"));
  5165.           else if (rs->buf[r->offset * 2] == 'x')
  5166.             {
  5167.               gdb_assert (r->offset * 2 < strlen (rs->buf));
  5168.               /* The register isn't available, mark it as such (at
  5169.                  the same time setting the value to zero).  */
  5170.               regcache_raw_supply (regcache, r->regnum, NULL);
  5171.             }
  5172.           else
  5173.             regcache_raw_supply (regcache, r->regnum,
  5174.                                  regs + r->offset);
  5175.         }
  5176.     }
  5177. }

  5178. static void
  5179. fetch_registers_using_g (struct regcache *regcache)
  5180. {
  5181.   send_g_packet ();
  5182.   process_g_packet (regcache);
  5183. }

  5184. /* Make the remote selected traceframe match GDB's selected
  5185.    traceframe.  */

  5186. static void
  5187. set_remote_traceframe (void)
  5188. {
  5189.   int newnum;
  5190.   struct remote_state *rs = get_remote_state ();

  5191.   if (rs->remote_traceframe_number == get_traceframe_number ())
  5192.     return;

  5193.   /* Avoid recursion, remote_trace_find calls us again.  */
  5194.   rs->remote_traceframe_number = get_traceframe_number ();

  5195.   newnum = target_trace_find (tfind_number,
  5196.                               get_traceframe_number (), 0, 0, NULL);

  5197.   /* Should not happen.  If it does, all bets are off.  */
  5198.   if (newnum != get_traceframe_number ())
  5199.     warning (_("could not set remote traceframe"));
  5200. }

  5201. static void
  5202. remote_fetch_registers (struct target_ops *ops,
  5203.                         struct regcache *regcache, int regnum)
  5204. {
  5205.   struct remote_arch_state *rsa = get_remote_arch_state ();
  5206.   int i;

  5207.   set_remote_traceframe ();
  5208.   set_general_thread (inferior_ptid);

  5209.   if (regnum >= 0)
  5210.     {
  5211.       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);

  5212.       gdb_assert (reg != NULL);

  5213.       /* If this register might be in the 'g' packet, try that first -
  5214.          we are likely to read more than one register.  If this is the
  5215.          first 'g' packet, we might be overly optimistic about its
  5216.          contents, so fall back to 'p'.  */
  5217.       if (reg->in_g_packet)
  5218.         {
  5219.           fetch_registers_using_g (regcache);
  5220.           if (reg->in_g_packet)
  5221.             return;
  5222.         }

  5223.       if (fetch_register_using_p (regcache, reg))
  5224.         return;

  5225.       /* This register is not available.  */
  5226.       regcache_raw_supply (regcache, reg->regnum, NULL);

  5227.       return;
  5228.     }

  5229.   fetch_registers_using_g (regcache);

  5230.   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
  5231.     if (!rsa->regs[i].in_g_packet)
  5232.       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
  5233.         {
  5234.           /* This register is not available.  */
  5235.           regcache_raw_supply (regcache, i, NULL);
  5236.         }
  5237. }

  5238. /* Prepare to store registers.  Since we may send them all (using a
  5239.    'G' request), we have to read out the ones we don't want to change
  5240.    first.  */

  5241. static void
  5242. remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
  5243. {
  5244.   struct remote_arch_state *rsa = get_remote_arch_state ();
  5245.   int i;
  5246.   gdb_byte buf[MAX_REGISTER_SIZE];

  5247.   /* Make sure the entire registers array is valid.  */
  5248.   switch (packet_support (PACKET_P))
  5249.     {
  5250.     case PACKET_DISABLE:
  5251.     case PACKET_SUPPORT_UNKNOWN:
  5252.       /* Make sure all the necessary registers are cached.  */
  5253.       for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
  5254.         if (rsa->regs[i].in_g_packet)
  5255.           regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
  5256.       break;
  5257.     case PACKET_ENABLE:
  5258.       break;
  5259.     }
  5260. }

  5261. /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
  5262.    packet was not recognized.  */

  5263. static int
  5264. store_register_using_P (const struct regcache *regcache,
  5265.                         struct packet_reg *reg)
  5266. {
  5267.   struct gdbarch *gdbarch = get_regcache_arch (regcache);
  5268.   struct remote_state *rs = get_remote_state ();
  5269.   /* Try storing a single register.  */
  5270.   char *buf = rs->buf;
  5271.   gdb_byte regp[MAX_REGISTER_SIZE];
  5272.   char *p;

  5273.   if (packet_support (PACKET_P) == PACKET_DISABLE)
  5274.     return 0;

  5275.   if (reg->pnum == -1)
  5276.     return 0;

  5277.   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
  5278.   p = buf + strlen (buf);
  5279.   regcache_raw_collect (regcache, reg->regnum, regp);
  5280.   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
  5281.   putpkt (rs->buf);
  5282.   getpkt (&rs->buf, &rs->buf_size, 0);

  5283.   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
  5284.     {
  5285.     case PACKET_OK:
  5286.       return 1;
  5287.     case PACKET_ERROR:
  5288.       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
  5289.              gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
  5290.     case PACKET_UNKNOWN:
  5291.       return 0;
  5292.     default:
  5293.       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
  5294.     }
  5295. }

  5296. /* Store register REGNUM, or all registers if REGNUM == -1, from the
  5297.    contents of the register cache bufferFIXME: ignores errors.  */

  5298. static void
  5299. store_registers_using_G (const struct regcache *regcache)
  5300. {
  5301.   struct remote_state *rs = get_remote_state ();
  5302.   struct remote_arch_state *rsa = get_remote_arch_state ();
  5303.   gdb_byte *regs;
  5304.   char *p;

  5305.   /* Extract all the registers in the regcache copying them into a
  5306.      local buffer.  */
  5307.   {
  5308.     int i;

  5309.     regs = alloca (rsa->sizeof_g_packet);
  5310.     memset (regs, 0, rsa->sizeof_g_packet);
  5311.     for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
  5312.       {
  5313.         struct packet_reg *r = &rsa->regs[i];

  5314.         if (r->in_g_packet)
  5315.           regcache_raw_collect (regcache, r->regnum, regs + r->offset);
  5316.       }
  5317.   }

  5318.   /* Command describes registers byte by byte,
  5319.      each byte encoded as two hex characters.  */
  5320.   p = rs->buf;
  5321.   *p++ = 'G';
  5322.   /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
  5323.      updated.  */
  5324.   bin2hex (regs, p, rsa->sizeof_g_packet);
  5325.   putpkt (rs->buf);
  5326.   getpkt (&rs->buf, &rs->buf_size, 0);
  5327.   if (packet_check_result (rs->buf) == PACKET_ERROR)
  5328.     error (_("Could not write registers; remote failure reply '%s'"),
  5329.            rs->buf);
  5330. }

  5331. /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
  5332.    of the register cache bufferFIXME: ignores errors.  */

  5333. static void
  5334. remote_store_registers (struct target_ops *ops,
  5335.                         struct regcache *regcache, int regnum)
  5336. {
  5337.   struct remote_arch_state *rsa = get_remote_arch_state ();
  5338.   int i;

  5339.   set_remote_traceframe ();
  5340.   set_general_thread (inferior_ptid);

  5341.   if (regnum >= 0)
  5342.     {
  5343.       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);

  5344.       gdb_assert (reg != NULL);

  5345.       /* Always prefer to store registers using the 'P' packet if
  5346.          possible; we often change only a small number of registers.
  5347.          Sometimes we change a larger number; we'd need help from a
  5348.          higher layer to know to use 'G'.  */
  5349.       if (store_register_using_P (regcache, reg))
  5350.         return;

  5351.       /* For now, don't complain if we have no way to write the
  5352.          register.  GDB loses track of unavailable registers too
  5353.          easily.  Some day, this may be an error.  We don't have
  5354.          any way to read the register, either...  */
  5355.       if (!reg->in_g_packet)
  5356.         return;

  5357.       store_registers_using_G (regcache);
  5358.       return;
  5359.     }

  5360.   store_registers_using_G (regcache);

  5361.   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
  5362.     if (!rsa->regs[i].in_g_packet)
  5363.       if (!store_register_using_P (regcache, &rsa->regs[i]))
  5364.         /* See above for why we do not issue an error here.  */
  5365.         continue;
  5366. }


  5367. /* Return the number of hex digits in num.  */

  5368. static int
  5369. hexnumlen (ULONGEST num)
  5370. {
  5371.   int i;

  5372.   for (i = 0; num != 0; i++)
  5373.     num >>= 4;

  5374.   return max (i, 1);
  5375. }

  5376. /* Set BUF to the minimum number of hex digits representing NUM.  */

  5377. static int
  5378. hexnumstr (char *buf, ULONGEST num)
  5379. {
  5380.   int len = hexnumlen (num);

  5381.   return hexnumnstr (buf, num, len);
  5382. }


  5383. /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */

  5384. static int
  5385. hexnumnstr (char *buf, ULONGEST num, int width)
  5386. {
  5387.   int i;

  5388.   buf[width] = '\0';

  5389.   for (i = width - 1; i >= 0; i--)
  5390.     {
  5391.       buf[i] = "0123456789abcdef"[(num & 0xf)];
  5392.       num >>= 4;
  5393.     }

  5394.   return width;
  5395. }

  5396. /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */

  5397. static CORE_ADDR
  5398. remote_address_masked (CORE_ADDR addr)
  5399. {
  5400.   unsigned int address_size = remote_address_size;

  5401.   /* If "remoteaddresssize" was not set, default to target address size.  */
  5402.   if (!address_size)
  5403.     address_size = gdbarch_addr_bit (target_gdbarch ());

  5404.   if (address_size > 0
  5405.       && address_size < (sizeof (ULONGEST) * 8))
  5406.     {
  5407.       /* Only create a mask when that mask can safely be constructed
  5408.          in a ULONGEST variable.  */
  5409.       ULONGEST mask = 1;

  5410.       mask = (mask << address_size) - 1;
  5411.       addr &= mask;
  5412.     }
  5413.   return addr;
  5414. }

  5415. /* Determine whether the remote target supports binary downloading.
  5416.    This is accomplished by sending a no-op memory write of zero length
  5417.    to the target at the specified address. It does not suffice to send
  5418.    the whole packet, since many stubs strip the eighth bit and
  5419.    subsequently compute a wrong checksum, which causes real havoc with
  5420.    remote_write_bytes.

  5421.    NOTE: This can still lose if the serial line is not eight-bit
  5422.    clean.  In cases like this, the user should clear "remote
  5423.    X-packet".  */

  5424. static void
  5425. check_binary_download (CORE_ADDR addr)
  5426. {
  5427.   struct remote_state *rs = get_remote_state ();

  5428.   switch (packet_support (PACKET_X))
  5429.     {
  5430.     case PACKET_DISABLE:
  5431.       break;
  5432.     case PACKET_ENABLE:
  5433.       break;
  5434.     case PACKET_SUPPORT_UNKNOWN:
  5435.       {
  5436.         char *p;

  5437.         p = rs->buf;
  5438.         *p++ = 'X';
  5439.         p += hexnumstr (p, (ULONGEST) addr);
  5440.         *p++ = ',';
  5441.         p += hexnumstr (p, (ULONGEST) 0);
  5442.         *p++ = ':';
  5443.         *p = '\0';

  5444.         putpkt_binary (rs->buf, (int) (p - rs->buf));
  5445.         getpkt (&rs->buf, &rs->buf_size, 0);

  5446.         if (rs->buf[0] == '\0')
  5447.           {
  5448.             if (remote_debug)
  5449.               fprintf_unfiltered (gdb_stdlog,
  5450.                                   "binary downloading NOT "
  5451.                                   "supported by target\n");
  5452.             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
  5453.           }
  5454.         else
  5455.           {
  5456.             if (remote_debug)
  5457.               fprintf_unfiltered (gdb_stdlog,
  5458.                                   "binary downloading supported by target\n");
  5459.             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
  5460.           }
  5461.         break;
  5462.       }
  5463.     }
  5464. }

  5465. /* Write memory data directly to the remote machine.
  5466.    This does not inform the data cache; the data cache uses this.
  5467.    HEADER is the starting part of the packet.
  5468.    MEMADDR is the address in the remote memory space.
  5469.    MYADDR is the address of the buffer in our space.
  5470.    LEN is the number of bytes.
  5471.    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
  5472.    should send data as binary ('X'), or hex-encoded ('M').

  5473.    The function creates packet of the form
  5474.        <HEADER><ADDRESS>,<LENGTH>:<DATA>

  5475.    where encoding of <DATA> is termined by PACKET_FORMAT.

  5476.    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
  5477.    are omitted.

  5478.    Return the transferred status, error or OK (an
  5479.    'enum target_xfer_status' value).  Save the number of bytes
  5480.    transferred in *XFERED_LEN.  Only transfer a single packet.  */

  5481. static enum target_xfer_status
  5482. remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
  5483.                         const gdb_byte *myaddr, ULONGEST len,
  5484.                         ULONGEST *xfered_len, char packet_format,
  5485.                         int use_length)
  5486. {
  5487.   struct remote_state *rs = get_remote_state ();
  5488.   char *p;
  5489.   char *plen = NULL;
  5490.   int plenlen = 0;
  5491.   int todo;
  5492.   int nr_bytes;
  5493.   int payload_size;
  5494.   int payload_length;
  5495.   int header_length;

  5496.   if (packet_format != 'X' && packet_format != 'M')
  5497.     internal_error (__FILE__, __LINE__,
  5498.                     _("remote_write_bytes_aux: bad packet format"));

  5499.   if (len == 0)
  5500.     return TARGET_XFER_EOF;

  5501.   payload_size = get_memory_write_packet_size ();

  5502.   /* The packet buffer will be large enough for the payload;
  5503.      get_memory_packet_size ensures this.  */
  5504.   rs->buf[0] = '\0';

  5505.   /* Compute the size of the actual payload by subtracting out the
  5506.      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */

  5507.   payload_size -= strlen ("$,:#NN");
  5508.   if (!use_length)
  5509.     /* The comma won't be used.  */
  5510.     payload_size += 1;
  5511.   header_length = strlen (header);
  5512.   payload_size -= header_length;
  5513.   payload_size -= hexnumlen (memaddr);

  5514.   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */

  5515.   strcat (rs->buf, header);
  5516.   p = rs->buf + strlen (header);

  5517.   /* Compute a best guess of the number of bytes actually transfered.  */
  5518.   if (packet_format == 'X')
  5519.     {
  5520.       /* Best guess at number of bytes that will fit.  */
  5521.       todo = min (len, payload_size);
  5522.       if (use_length)
  5523.         payload_size -= hexnumlen (todo);
  5524.       todo = min (todo, payload_size);
  5525.     }
  5526.   else
  5527.     {
  5528.       /* Num bytes that will fit.  */
  5529.       todo = min (len, payload_size / 2);
  5530.       if (use_length)
  5531.         payload_size -= hexnumlen (todo);
  5532.       todo = min (todo, payload_size / 2);
  5533.     }

  5534.   if (todo <= 0)
  5535.     internal_error (__FILE__, __LINE__,
  5536.                     _("minimum packet size too small to write data"));

  5537.   /* If we already need another packet, then try to align the end
  5538.      of this packet to a useful boundary.  */
  5539.   if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
  5540.     todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;

  5541.   /* Append "<memaddr>".  */
  5542.   memaddr = remote_address_masked (memaddr);
  5543.   p += hexnumstr (p, (ULONGEST) memaddr);

  5544.   if (use_length)
  5545.     {
  5546.       /* Append ",".  */
  5547.       *p++ = ',';

  5548.       /* Append <len>.  Retain the location/size of <len>.  It may need to
  5549.          be adjusted once the packet body has been created.  */
  5550.       plen = p;
  5551.       plenlen = hexnumstr (p, (ULONGEST) todo);
  5552.       p += plenlen;
  5553.     }

  5554.   /* Append ":".  */
  5555.   *p++ = ':';
  5556.   *p = '\0';

  5557.   /* Append the packet body.  */
  5558.   if (packet_format == 'X')
  5559.     {
  5560.       /* Binary mode.  Send target system values byte by byte, in
  5561.          increasing byte addresses.  Only escape certain critical
  5562.          characters.  */
  5563.       payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
  5564.                                              &nr_bytes, payload_size);

  5565.       /* If not all TODO bytes fit, then we'll need another packet.  Make
  5566.          a second try to keep the end of the packet aligned.  Don't do
  5567.          this if the packet is tiny.  */
  5568.       if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
  5569.         {
  5570.           int new_nr_bytes;

  5571.           new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
  5572.                           - memaddr);
  5573.           if (new_nr_bytes != nr_bytes)
  5574.             payload_length = remote_escape_output (myaddr, new_nr_bytes,
  5575.                                                    (gdb_byte *) p, &nr_bytes,
  5576.                                                    payload_size);
  5577.         }

  5578.       p += payload_length;
  5579.       if (use_length && nr_bytes < todo)
  5580.         {
  5581.           /* Escape chars have filled up the buffer prematurely,
  5582.              and we have actually sent fewer bytes than planned.
  5583.              Fix-up the length field of the packet.  Use the same
  5584.              number of characters as before.  */
  5585.           plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
  5586.           *plen = ':'/* overwrite \0 from hexnumnstr() */
  5587.         }
  5588.     }
  5589.   else
  5590.     {
  5591.       /* Normal mode: Send target system values byte by byte, in
  5592.          increasing byte addresses.  Each byte is encoded as a two hex
  5593.          value.  */
  5594.       nr_bytes = bin2hex (myaddr, p, todo);
  5595.       p += 2 * nr_bytes;
  5596.     }

  5597.   putpkt_binary (rs->buf, (int) (p - rs->buf));
  5598.   getpkt (&rs->buf, &rs->buf_size, 0);

  5599.   if (rs->buf[0] == 'E')
  5600.     return TARGET_XFER_E_IO;

  5601.   /* Return NR_BYTES, not TODO, in case escape chars caused us to send
  5602.      fewer bytes than we'd planned.  */
  5603.   *xfered_len = (ULONGEST) nr_bytes;
  5604.   return TARGET_XFER_OK;
  5605. }

  5606. /* Write memory data directly to the remote machine.
  5607.    This does not inform the data cache; the data cache uses this.
  5608.    MEMADDR is the address in the remote memory space.
  5609.    MYADDR is the address of the buffer in our space.
  5610.    LEN is the number of bytes.

  5611.    Return the transferred status, error or OK (an
  5612.    'enum target_xfer_status' value).  Save the number of bytes
  5613.    transferred in *XFERED_LEN.  Only transfer a single packet.  */

  5614. static enum target_xfer_status
  5615. remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
  5616.                     ULONGEST *xfered_len)
  5617. {
  5618.   char *packet_format = 0;

  5619.   /* Check whether the target supports binary download.  */
  5620.   check_binary_download (memaddr);

  5621.   switch (packet_support (PACKET_X))
  5622.     {
  5623.     case PACKET_ENABLE:
  5624.       packet_format = "X";
  5625.       break;
  5626.     case PACKET_DISABLE:
  5627.       packet_format = "M";
  5628.       break;
  5629.     case PACKET_SUPPORT_UNKNOWN:
  5630.       internal_error (__FILE__, __LINE__,
  5631.                       _("remote_write_bytes: bad internal state"));
  5632.     default:
  5633.       internal_error (__FILE__, __LINE__, _("bad switch"));
  5634.     }

  5635.   return remote_write_bytes_aux (packet_format,
  5636.                                  memaddr, myaddr, len, xfered_len,
  5637.                                  packet_format[0], 1);
  5638. }

  5639. /* Read memory data directly from the remote machine.
  5640.    This does not use the data cache; the data cache uses this.
  5641.    MEMADDR is the address in the remote memory space.
  5642.    MYADDR is the address of the buffer in our space.
  5643.    LEN is the number of bytes.

  5644.    Return the transferred status, error or OK (an
  5645.    'enum target_xfer_status' value).  Save the number of bytes
  5646.    transferred in *XFERED_LEN.  */

  5647. static enum target_xfer_status
  5648. remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len,
  5649.                      ULONGEST *xfered_len)
  5650. {
  5651.   struct remote_state *rs = get_remote_state ();
  5652.   int max_buf_size;                /* Max size of packet output buffer.  */
  5653.   char *p;
  5654.   int todo;
  5655.   int i;

  5656.   max_buf_size = get_memory_read_packet_size ();
  5657.   /* The packet buffer will be large enough for the payload;
  5658.      get_memory_packet_size ensures this.  */

  5659.   /* Number if bytes that will fit.  */
  5660.   todo = min (len, max_buf_size / 2);

  5661.   /* Construct "m"<memaddr>","<len>".  */
  5662.   memaddr = remote_address_masked (memaddr);
  5663.   p = rs->buf;
  5664.   *p++ = 'm';
  5665.   p += hexnumstr (p, (ULONGEST) memaddr);
  5666.   *p++ = ',';
  5667.   p += hexnumstr (p, (ULONGEST) todo);
  5668.   *p = '\0';
  5669.   putpkt (rs->buf);
  5670.   getpkt (&rs->buf, &rs->buf_size, 0);
  5671.   if (rs->buf[0] == 'E'
  5672.       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
  5673.       && rs->buf[3] == '\0')
  5674.     return TARGET_XFER_E_IO;
  5675.   /* Reply describes memory byte by byte, each byte encoded as two hex
  5676.      characters.  */
  5677.   p = rs->buf;
  5678.   i = hex2bin (p, myaddr, todo);
  5679.   /* Return what we have.  Let higher layers handle partial reads.  */
  5680.   *xfered_len = (ULONGEST) i;
  5681.   return TARGET_XFER_OK;
  5682. }

  5683. /* Using the set of read-only target sections of remote, read live
  5684.    read-only memory.

  5685.    For interface/parameters/return description see target.h,
  5686.    to_xfer_partial.  */

  5687. static enum target_xfer_status
  5688. remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
  5689.                                    ULONGEST memaddr, ULONGEST len,
  5690.                                    ULONGEST *xfered_len)
  5691. {
  5692.   struct target_section *secp;
  5693.   struct target_section_table *table;

  5694.   secp = target_section_by_addr (ops, memaddr);
  5695.   if (secp != NULL
  5696.       && (bfd_get_section_flags (secp->the_bfd_section->owner,
  5697.                                  secp->the_bfd_section)
  5698.           & SEC_READONLY))
  5699.     {
  5700.       struct target_section *p;
  5701.       ULONGEST memend = memaddr + len;

  5702.       table = target_get_section_table (ops);

  5703.       for (p = table->sections; p < table->sections_end; p++)
  5704.         {
  5705.           if (memaddr >= p->addr)
  5706.             {
  5707.               if (memend <= p->endaddr)
  5708.                 {
  5709.                   /* Entire transfer is within this section.  */
  5710.                   return remote_read_bytes_1 (memaddr, readbuf, len,
  5711.                                               xfered_len);
  5712.                 }
  5713.               else if (memaddr >= p->endaddr)
  5714.                 {
  5715.                   /* This section ends before the transfer starts.  */
  5716.                   continue;
  5717.                 }
  5718.               else
  5719.                 {
  5720.                   /* This section overlaps the transfer.  Just do half.  */
  5721.                   len = p->endaddr - memaddr;
  5722.                   return remote_read_bytes_1 (memaddr, readbuf, len,
  5723.                                               xfered_len);
  5724.                 }
  5725.             }
  5726.         }
  5727.     }

  5728.   return TARGET_XFER_EOF;
  5729. }

  5730. /* Similar to remote_read_bytes_1, but it reads from the remote stub
  5731.    first if the requested memory is unavailable in traceframe.
  5732.    Otherwise, fall back to remote_read_bytes_1.  */

  5733. static enum target_xfer_status
  5734. remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
  5735.                    gdb_byte *myaddr, ULONGEST len, ULONGEST *xfered_len)
  5736. {
  5737.   if (len == 0)
  5738.     return TARGET_XFER_EOF;

  5739.   if (get_traceframe_number () != -1)
  5740.     {
  5741.       VEC(mem_range_s) *available;

  5742.       /* If we fail to get the set of available memory, then the
  5743.          target does not support querying traceframe info, and so we
  5744.          attempt reading from the traceframe anyway (assuming the
  5745.          target implements the old QTro packet then).  */
  5746.       if (traceframe_available_memory (&available, memaddr, len))
  5747.         {
  5748.           struct cleanup *old_chain;

  5749.           old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);

  5750.           if (VEC_empty (mem_range_s, available)
  5751.               || VEC_index (mem_range_s, available, 0)->start != memaddr)
  5752.             {
  5753.               enum target_xfer_status res;

  5754.               /* Don't read into the traceframe's available
  5755.                  memory.  */
  5756.               if (!VEC_empty (mem_range_s, available))
  5757.                 {
  5758.                   LONGEST oldlen = len;

  5759.                   len = VEC_index (mem_range_s, available, 0)->start - memaddr;
  5760.                   gdb_assert (len <= oldlen);
  5761.                 }

  5762.               do_cleanups (old_chain);

  5763.               /* This goes through the topmost target again.  */
  5764.               res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
  5765.                                                        len, xfered_len);
  5766.               if (res == TARGET_XFER_OK)
  5767.                 return TARGET_XFER_OK;
  5768.               else
  5769.                 {
  5770.                   /* No use trying further, we know some memory starting
  5771.                      at MEMADDR isn't available.  */
  5772.                   *xfered_len = len;
  5773.                   return TARGET_XFER_UNAVAILABLE;
  5774.                 }
  5775.             }

  5776.           /* Don't try to read more than how much is available, in
  5777.              case the target implements the deprecated QTro packet to
  5778.              cater for older GDBs (the target's knowledge of read-only
  5779.              sections may be outdated by now).  */
  5780.           len = VEC_index (mem_range_s, available, 0)->length;

  5781.           do_cleanups (old_chain);
  5782.         }
  5783.     }

  5784.   return remote_read_bytes_1 (memaddr, myaddr, len, xfered_len);
  5785. }



  5786. /* Sends a packet with content determined by the printf format string
  5787.    FORMAT and the remaining arguments, then gets the reply.  Returns
  5788.    whether the packet was a success, a failure, or unknown.  */

  5789. static enum packet_result
  5790. remote_send_printf (const char *format, ...)
  5791. {
  5792.   struct remote_state *rs = get_remote_state ();
  5793.   int max_size = get_remote_packet_size ();
  5794.   va_list ap;

  5795.   va_start (ap, format);

  5796.   rs->buf[0] = '\0';
  5797.   if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
  5798.     internal_error (__FILE__, __LINE__, _("Too long remote packet."));

  5799.   if (putpkt (rs->buf) < 0)
  5800.     error (_("Communication problem with target."));

  5801.   rs->buf[0] = '\0';
  5802.   getpkt (&rs->buf, &rs->buf_size, 0);

  5803.   return packet_check_result (rs->buf);
  5804. }

  5805. static void
  5806. restore_remote_timeout (void *p)
  5807. {
  5808.   int value = *(int *)p;

  5809.   remote_timeout = value;
  5810. }

  5811. /* Flash writing can take quite some time.  We'll set
  5812.    effectively infinite timeout for flash operations.
  5813.    In future, we'll need to decide on a better approach.  */
  5814. static const int remote_flash_timeout = 1000;

  5815. static void
  5816. remote_flash_erase (struct target_ops *ops,
  5817.                     ULONGEST address, LONGEST length)
  5818. {
  5819.   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
  5820.   int saved_remote_timeout = remote_timeout;
  5821.   enum packet_result ret;
  5822.   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
  5823.                                           &saved_remote_timeout);

  5824.   remote_timeout = remote_flash_timeout;

  5825.   ret = remote_send_printf ("vFlashErase:%s,%s",
  5826.                             phex (address, addr_size),
  5827.                             phex (length, 4));
  5828.   switch (ret)
  5829.     {
  5830.     case PACKET_UNKNOWN:
  5831.       error (_("Remote target does not support flash erase"));
  5832.     case PACKET_ERROR:
  5833.       error (_("Error erasing flash with vFlashErase packet"));
  5834.     default:
  5835.       break;
  5836.     }

  5837.   do_cleanups (back_to);
  5838. }

  5839. static enum target_xfer_status
  5840. remote_flash_write (struct target_ops *ops, ULONGEST address,
  5841.                     ULONGEST length, ULONGEST *xfered_len,
  5842.                     const gdb_byte *data)
  5843. {
  5844.   int saved_remote_timeout = remote_timeout;
  5845.   enum target_xfer_status ret;
  5846.   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
  5847.                                           &saved_remote_timeout);

  5848.   remote_timeout = remote_flash_timeout;
  5849.   ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length,
  5850.                                 xfered_len,'X', 0);
  5851.   do_cleanups (back_to);

  5852.   return ret;
  5853. }

  5854. static void
  5855. remote_flash_done (struct target_ops *ops)
  5856. {
  5857.   int saved_remote_timeout = remote_timeout;
  5858.   int ret;
  5859.   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
  5860.                                           &saved_remote_timeout);

  5861.   remote_timeout = remote_flash_timeout;
  5862.   ret = remote_send_printf ("vFlashDone");
  5863.   do_cleanups (back_to);

  5864.   switch (ret)
  5865.     {
  5866.     case PACKET_UNKNOWN:
  5867.       error (_("Remote target does not support vFlashDone"));
  5868.     case PACKET_ERROR:
  5869.       error (_("Error finishing flash operation"));
  5870.     default:
  5871.       break;
  5872.     }
  5873. }

  5874. static void
  5875. remote_files_info (struct target_ops *ignore)
  5876. {
  5877.   puts_filtered ("Debugging a target over a serial line.\n");
  5878. }

  5879. /* Stuff for dealing with the packets which are part of this protocol.
  5880.    See comment at top of file for details.  */

  5881. /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
  5882.    error to higher layers.  Called when a serial error is detected.
  5883.    The exception message is STRING, followed by a colon and a blank,
  5884.    the system error message for errno at function entry and final dot
  5885.    for output compatibility with throw_perror_with_name.  */

  5886. static void
  5887. unpush_and_perror (const char *string)
  5888. {
  5889.   int saved_errno = errno;

  5890.   remote_unpush_target ();
  5891.   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
  5892.                safe_strerror (saved_errno));
  5893. }

  5894. /* Read a single character from the remote end.  */

  5895. static int
  5896. readchar (int timeout)
  5897. {
  5898.   int ch;
  5899.   struct remote_state *rs = get_remote_state ();

  5900.   ch = serial_readchar (rs->remote_desc, timeout);

  5901.   if (ch >= 0)
  5902.     return ch;

  5903.   switch ((enum serial_rc) ch)
  5904.     {
  5905.     case SERIAL_EOF:
  5906.       remote_unpush_target ();
  5907.       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
  5908.       /* no return */
  5909.     case SERIAL_ERROR:
  5910.       unpush_and_perror (_("Remote communication error.  "
  5911.                            "Target disconnected."));
  5912.       /* no return */
  5913.     case SERIAL_TIMEOUT:
  5914.       break;
  5915.     }
  5916.   return ch;
  5917. }

  5918. /* Wrapper for serial_write that closes the target and throws if
  5919.    writing fails.  */

  5920. static void
  5921. remote_serial_write (const char *str, int len)
  5922. {
  5923.   struct remote_state *rs = get_remote_state ();

  5924.   if (serial_write (rs->remote_desc, str, len))
  5925.     {
  5926.       unpush_and_perror (_("Remote communication error.  "
  5927.                            "Target disconnected."));
  5928.     }
  5929. }

  5930. /* Send the command in *BUF to the remote machine, and read the reply
  5931.    into *BUF.  Report an error if we get an error reply.  Resize
  5932.    *BUF using xrealloc if necessary to hold the result, and update
  5933.    *SIZEOF_BUF.  */

  5934. static void
  5935. remote_send (char **buf,
  5936.              long *sizeof_buf)
  5937. {
  5938.   putpkt (*buf);
  5939.   getpkt (buf, sizeof_buf, 0);

  5940.   if ((*buf)[0] == 'E')
  5941.     error (_("Remote failure reply: %s"), *buf);
  5942. }

  5943. /* Return a pointer to an xmalloc'ed string representing an escaped
  5944.    version of BUF, of len NE.g. \n is converted to \\n, \t to \\t,
  5945.    etc.  The caller is responsible for releasing the returned
  5946.    memory.  */

  5947. static char *
  5948. escape_buffer (const char *buf, int n)
  5949. {
  5950.   struct cleanup *old_chain;
  5951.   struct ui_file *stb;
  5952.   char *str;

  5953.   stb = mem_fileopen ();
  5954.   old_chain = make_cleanup_ui_file_delete (stb);

  5955.   fputstrn_unfiltered (buf, n, '\\', stb);
  5956.   str = ui_file_xstrdup (stb, NULL);
  5957.   do_cleanups (old_chain);
  5958.   return str;
  5959. }

  5960. /* Display a null-terminated packet on stdout, for debugging, using C
  5961.    string notation.  */

  5962. static void
  5963. print_packet (const char *buf)
  5964. {
  5965.   puts_filtered ("\"");
  5966.   fputstr_filtered (buf, '"', gdb_stdout);
  5967.   puts_filtered ("\"");
  5968. }

  5969. int
  5970. putpkt (const char *buf)
  5971. {
  5972.   return putpkt_binary (buf, strlen (buf));
  5973. }

  5974. /* Send a packet to the remote machine, with error checking.  The data
  5975.    of the packet is in BUF.  The string in BUF can be at most
  5976.    get_remote_packet_size () - 5 to account for the $, # and checksum,
  5977.    and for a possible /0 if we are debugging (remote_debug) and want
  5978.    to print the sent packet as a string.  */

  5979. static int
  5980. putpkt_binary (const char *buf, int cnt)
  5981. {
  5982.   struct remote_state *rs = get_remote_state ();
  5983.   int i;
  5984.   unsigned char csum = 0;
  5985.   char *buf2 = alloca (cnt + 6);

  5986.   int ch;
  5987.   int tcount = 0;
  5988.   char *p;
  5989.   char *message;

  5990.   /* Catch cases like trying to read memory or listing threads while
  5991.      we're waiting for a stop reply.  The remote server wouldn't be
  5992.      ready to handle this request, so we'd hang and timeout.  We don't
  5993.      have to worry about this in synchronous mode, because in that
  5994.      case it's not possible to issue a command while the target is
  5995.      running.  This is not a problem in non-stop mode, because in that
  5996.      case, the stub is always ready to process serial input.  */
  5997.   if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
  5998.     {
  5999.       error (_("Cannot execute this command while the target is running.\n"
  6000.                "Use the \"interrupt\" command to stop the target\n"
  6001.                "and then try again."));
  6002.     }

  6003.   /* We're sending out a new packet.  Make sure we don't look at a
  6004.      stale cached response.  */
  6005.   rs->cached_wait_status = 0;

  6006.   /* Copy the packet into buffer BUF2, encapsulating it
  6007.      and giving it a checksum.  */

  6008.   p = buf2;
  6009.   *p++ = '$';

  6010.   for (i = 0; i < cnt; i++)
  6011.     {
  6012.       csum += buf[i];
  6013.       *p++ = buf[i];
  6014.     }
  6015.   *p++ = '#';
  6016.   *p++ = tohex ((csum >> 4) & 0xf);
  6017.   *p++ = tohex (csum & 0xf);

  6018.   /* Send it over and over until we get a positive ack.  */

  6019.   while (1)
  6020.     {
  6021.       int started_error_output = 0;

  6022.       if (remote_debug)
  6023.         {
  6024.           struct cleanup *old_chain;
  6025.           char *str;

  6026.           *p = '\0';
  6027.           str = escape_buffer (buf2, p - buf2);
  6028.           old_chain = make_cleanup (xfree, str);
  6029.           fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
  6030.           gdb_flush (gdb_stdlog);
  6031.           do_cleanups (old_chain);
  6032.         }
  6033.       remote_serial_write (buf2, p - buf2);

  6034.       /* If this is a no acks version of the remote protocol, send the
  6035.          packet and move on.  */
  6036.       if (rs->noack_mode)
  6037.         break;

  6038.       /* Read until either a timeout occurs (-2) or '+' is read.
  6039.          Handle any notification that arrives in the mean time.  */
  6040.       while (1)
  6041.         {
  6042.           ch = readchar (remote_timeout);

  6043.           if (remote_debug)
  6044.             {
  6045.               switch (ch)
  6046.                 {
  6047.                 case '+':
  6048.                 case '-':
  6049.                 case SERIAL_TIMEOUT:
  6050.                 case '$':
  6051.                 case '%':
  6052.                   if (started_error_output)
  6053.                     {
  6054.                       putchar_unfiltered ('\n');
  6055.                       started_error_output = 0;
  6056.                     }
  6057.                 }
  6058.             }

  6059.           switch (ch)
  6060.             {
  6061.             case '+':
  6062.               if (remote_debug)
  6063.                 fprintf_unfiltered (gdb_stdlog, "Ack\n");
  6064.               return 1;
  6065.             case '-':
  6066.               if (remote_debug)
  6067.                 fprintf_unfiltered (gdb_stdlog, "Nak\n");
  6068.               /* FALLTHROUGH */
  6069.             case SERIAL_TIMEOUT:
  6070.               tcount++;
  6071.               if (tcount > 3)
  6072.                 return 0;
  6073.               break;                /* Retransmit buffer.  */
  6074.             case '$':
  6075.               {
  6076.                 if (remote_debug)
  6077.                   fprintf_unfiltered (gdb_stdlog,
  6078.                                       "Packet instead of Ack, ignoring it\n");
  6079.                 /* It's probably an old response sent because an ACK
  6080.                    was lost.  Gobble up the packet and ack it so it
  6081.                    doesn't get retransmitted when we resend this
  6082.                    packet.  */
  6083.                 skip_frame ();
  6084.                 remote_serial_write ("+", 1);
  6085.                 continue;        /* Now, go look for +.  */
  6086.               }

  6087.             case '%':
  6088.               {
  6089.                 int val;

  6090.                 /* If we got a notification, handle it, and go back to looking
  6091.                    for an ack.  */
  6092.                 /* We've found the start of a notification.  Now
  6093.                    collect the data.  */
  6094.                 val = read_frame (&rs->buf, &rs->buf_size);
  6095.                 if (val >= 0)
  6096.                   {
  6097.                     if (remote_debug)
  6098.                       {
  6099.                         struct cleanup *old_chain;
  6100.                         char *str;

  6101.                         str = escape_buffer (rs->buf, val);
  6102.                         old_chain = make_cleanup (xfree, str);
  6103.                         fprintf_unfiltered (gdb_stdlog,
  6104.                                             "  Notification received: %s\n",
  6105.                                             str);
  6106.                         do_cleanups (old_chain);
  6107.                       }
  6108.                     handle_notification (rs->notif_state, rs->buf);
  6109.                     /* We're in sync now, rewait for the ack.  */
  6110.                     tcount = 0;
  6111.                   }
  6112.                 else
  6113.                   {
  6114.                     if (remote_debug)
  6115.                       {
  6116.                         if (!started_error_output)
  6117.                           {
  6118.                             started_error_output = 1;
  6119.                             fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
  6120.                           }
  6121.                         fputc_unfiltered (ch & 0177, gdb_stdlog);
  6122.                         fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
  6123.                       }
  6124.                   }
  6125.                 continue;
  6126.               }
  6127.               /* fall-through */
  6128.             default:
  6129.               if (remote_debug)
  6130.                 {
  6131.                   if (!started_error_output)
  6132.                     {
  6133.                       started_error_output = 1;
  6134.                       fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
  6135.                     }
  6136.                   fputc_unfiltered (ch & 0177, gdb_stdlog);
  6137.                 }
  6138.               continue;
  6139.             }
  6140.           break;                /* Here to retransmit.  */
  6141.         }

  6142. #if 0
  6143.       /* This is wrong.  If doing a long backtrace, the user should be
  6144.          able to get out next time we call QUIT, without anything as
  6145.          violent as interrupt_query.  If we want to provide a way out of
  6146.          here without getting to the next QUIT, it should be based on
  6147.          hitting ^C twice as in remote_wait.  */
  6148.       if (quit_flag)
  6149.         {
  6150.           quit_flag = 0;
  6151.           interrupt_query ();
  6152.         }
  6153. #endif
  6154.     }
  6155.   return 0;
  6156. }

  6157. /* Come here after finding the start of a frame when we expected an
  6158.    ack.  Do our best to discard the rest of this packet.  */

  6159. static void
  6160. skip_frame (void)
  6161. {
  6162.   int c;

  6163.   while (1)
  6164.     {
  6165.       c = readchar (remote_timeout);
  6166.       switch (c)
  6167.         {
  6168.         case SERIAL_TIMEOUT:
  6169.           /* Nothing we can do.  */
  6170.           return;
  6171.         case '#':
  6172.           /* Discard the two bytes of checksum and stop.  */
  6173.           c = readchar (remote_timeout);
  6174.           if (c >= 0)
  6175.             c = readchar (remote_timeout);

  6176.           return;
  6177.         case '*':                /* Run length encoding.  */
  6178.           /* Discard the repeat count.  */
  6179.           c = readchar (remote_timeout);
  6180.           if (c < 0)
  6181.             return;
  6182.           break;
  6183.         default:
  6184.           /* A regular character.  */
  6185.           break;
  6186.         }
  6187.     }
  6188. }

  6189. /* Come here after finding the start of the frame.  Collect the rest
  6190.    into *BUF, verifying the checksum, length, and handling run-length
  6191.    compression.  NUL terminate the buffer.  If there is not enough room,
  6192.    expand *BUF using xrealloc.

  6193.    Returns -1 on error, number of characters in buffer (ignoring the
  6194.    trailing NULL) on success. (could be extended to return one of the
  6195.    SERIAL status indications).  */

  6196. static long
  6197. read_frame (char **buf_p,
  6198.             long *sizeof_buf)
  6199. {
  6200.   unsigned char csum;
  6201.   long bc;
  6202.   int c;
  6203.   char *buf = *buf_p;
  6204.   struct remote_state *rs = get_remote_state ();

  6205.   csum = 0;
  6206.   bc = 0;

  6207.   while (1)
  6208.     {
  6209.       c = readchar (remote_timeout);
  6210.       switch (c)
  6211.         {
  6212.         case SERIAL_TIMEOUT:
  6213.           if (remote_debug)
  6214.             fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
  6215.           return -1;
  6216.         case '$':
  6217.           if (remote_debug)
  6218.             fputs_filtered ("Saw new packet start in middle of old one\n",
  6219.                             gdb_stdlog);
  6220.           return -1;                /* Start a new packet, count retries.  */
  6221.         case '#':
  6222.           {
  6223.             unsigned char pktcsum;
  6224.             int check_0 = 0;
  6225.             int check_1 = 0;

  6226.             buf[bc] = '\0';

  6227.             check_0 = readchar (remote_timeout);
  6228.             if (check_0 >= 0)
  6229.               check_1 = readchar (remote_timeout);

  6230.             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
  6231.               {
  6232.                 if (remote_debug)
  6233.                   fputs_filtered ("Timeout in checksum, retrying\n",
  6234.                                   gdb_stdlog);
  6235.                 return -1;
  6236.               }
  6237.             else if (check_0 < 0 || check_1 < 0)
  6238.               {
  6239.                 if (remote_debug)
  6240.                   fputs_filtered ("Communication error in checksum\n",
  6241.                                   gdb_stdlog);
  6242.                 return -1;
  6243.               }

  6244.             /* Don't recompute the checksum; with no ack packets we
  6245.                don't have any way to indicate a packet retransmission
  6246.                is necessary.  */
  6247.             if (rs->noack_mode)
  6248.               return bc;

  6249.             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
  6250.             if (csum == pktcsum)
  6251.               return bc;

  6252.             if (remote_debug)
  6253.               {
  6254.                 struct cleanup *old_chain;
  6255.                 char *str;

  6256.                 str = escape_buffer (buf, bc);
  6257.                 old_chain = make_cleanup (xfree, str);
  6258.                 fprintf_unfiltered (gdb_stdlog,
  6259.                                     "Bad checksum, sentsum=0x%x, "
  6260.                                     "csum=0x%x, buf=%s\n",
  6261.                                     pktcsum, csum, str);
  6262.                 do_cleanups (old_chain);
  6263.               }
  6264.             /* Number of characters in buffer ignoring trailing
  6265.                NULL.  */
  6266.             return -1;
  6267.           }
  6268.         case '*':                /* Run length encoding.  */
  6269.           {
  6270.             int repeat;

  6271.              csum += c;
  6272.             c = readchar (remote_timeout);
  6273.             csum += c;
  6274.             repeat = c - ' ' + 3;        /* Compute repeat count.  */

  6275.             /* The character before ``*'' is repeated.  */

  6276.             if (repeat > 0 && repeat <= 255 && bc > 0)
  6277.               {
  6278.                 if (bc + repeat - 1 >= *sizeof_buf - 1)
  6279.                   {
  6280.                     /* Make some more room in the buffer.  */
  6281.                     *sizeof_buf += repeat;
  6282.                     *buf_p = xrealloc (*buf_p, *sizeof_buf);
  6283.                     buf = *buf_p;
  6284.                   }

  6285.                 memset (&buf[bc], buf[bc - 1], repeat);
  6286.                 bc += repeat;
  6287.                 continue;
  6288.               }

  6289.             buf[bc] = '\0';
  6290.             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
  6291.             return -1;
  6292.           }
  6293.         default:
  6294.           if (bc >= *sizeof_buf - 1)
  6295.             {
  6296.               /* Make some more room in the buffer.  */
  6297.               *sizeof_buf *= 2;
  6298.               *buf_p = xrealloc (*buf_p, *sizeof_buf);
  6299.               buf = *buf_p;
  6300.             }

  6301.           buf[bc++] = c;
  6302.           csum += c;
  6303.           continue;
  6304.         }
  6305.     }
  6306. }

  6307. /* Read a packet from the remote machine, with error checking, and
  6308.    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
  6309.    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
  6310.    rather than timing out; this is used (in synchronous mode) to wait
  6311.    for a target that is is executing user code to stop.  */
  6312. /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
  6313.    don't have to change all the calls to getpkt to deal with the
  6314.    return value, because at the moment I don't know what the right
  6315.    thing to do it for those.  */
  6316. void
  6317. getpkt (char **buf,
  6318.         long *sizeof_buf,
  6319.         int forever)
  6320. {
  6321.   int timed_out;

  6322.   timed_out = getpkt_sane (buf, sizeof_buf, forever);
  6323. }


  6324. /* Read a packet from the remote machine, with error checking, and
  6325.    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
  6326.    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
  6327.    rather than timing out; this is used (in synchronous mode) to wait
  6328.    for a target that is is executing user code to stop.  If FOREVER ==
  6329.    0, this function is allowed to time out gracefully and return an
  6330.    indication of this to the caller.  Otherwise return the number of
  6331.    bytes read.  If EXPECTING_NOTIF, consider receiving a notification
  6332.    enough reason to return to the caller.  *IS_NOTIF is an output
  6333.    boolean that indicates whether *BUF holds a notification or not
  6334.    (a regular packet).  */

  6335. static int
  6336. getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
  6337.                         int expecting_notif, int *is_notif)
  6338. {
  6339.   struct remote_state *rs = get_remote_state ();
  6340.   int c;
  6341.   int tries;
  6342.   int timeout;
  6343.   int val = -1;

  6344.   /* We're reading a new response.  Make sure we don't look at a
  6345.      previously cached response.  */
  6346.   rs->cached_wait_status = 0;

  6347.   strcpy (*buf, "timeout");

  6348.   if (forever)
  6349.     timeout = watchdog > 0 ? watchdog : -1;
  6350.   else if (expecting_notif)
  6351.     timeout = 0; /* There should already be a char in the buffer.  If
  6352.                     not, bail out.  */
  6353.   else
  6354.     timeout = remote_timeout;

  6355. #define MAX_TRIES 3

  6356.   /* Process any number of notifications, and then return when
  6357.      we get a packet.  */
  6358.   for (;;)
  6359.     {
  6360.       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
  6361.          times.  */
  6362.       for (tries = 1; tries <= MAX_TRIES; tries++)
  6363.         {
  6364.           /* This can loop forever if the remote side sends us
  6365.              characters continuously, but if it pauses, we'll get
  6366.              SERIAL_TIMEOUT from readchar because of timeout.  Then
  6367.              we'll count that as a retry.

  6368.              Note that even when forever is set, we will only wait
  6369.              forever prior to the start of a packet.  After that, we
  6370.              expect characters to arrive at a brisk pace.  They should
  6371.              show up within remote_timeout intervals.  */
  6372.           do
  6373.             c = readchar (timeout);
  6374.           while (c != SERIAL_TIMEOUT && c != '$' && c != '%');

  6375.           if (c == SERIAL_TIMEOUT)
  6376.             {
  6377.               if (expecting_notif)
  6378.                 return -1; /* Don't complain, it's normal to not get
  6379.                               anything in this case.  */

  6380.               if (forever)        /* Watchdog went off?  Kill the target.  */
  6381.                 {
  6382.                   QUIT;
  6383.                   remote_unpush_target ();
  6384.                   throw_error (TARGET_CLOSE_ERROR,
  6385.                                _("Watchdog timeout has expired.  "
  6386.                                  "Target detached."));
  6387.                 }
  6388.               if (remote_debug)
  6389.                 fputs_filtered ("Timed out.\n", gdb_stdlog);
  6390.             }
  6391.           else
  6392.             {
  6393.               /* We've found the start of a packet or notification.
  6394.                  Now collect the data.  */
  6395.               val = read_frame (buf, sizeof_buf);
  6396.               if (val >= 0)
  6397.                 break;
  6398.             }

  6399.           remote_serial_write ("-", 1);
  6400.         }

  6401.       if (tries > MAX_TRIES)
  6402.         {
  6403.           /* We have tried hard enough, and just can't receive the
  6404.              packet/notification.  Give up.  */
  6405.           printf_unfiltered (_("Ignoring packet error, continuing...\n"));

  6406.           /* Skip the ack char if we're in no-ack mode.  */
  6407.           if (!rs->noack_mode)
  6408.             remote_serial_write ("+", 1);
  6409.           return -1;
  6410.         }

  6411.       /* If we got an ordinary packet, return that to our caller.  */
  6412.       if (c == '$')
  6413.         {
  6414.           if (remote_debug)
  6415.             {
  6416.              struct cleanup *old_chain;
  6417.              char *str;

  6418.              str = escape_buffer (*buf, val);
  6419.              old_chain = make_cleanup (xfree, str);
  6420.              fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
  6421.              do_cleanups (old_chain);
  6422.             }

  6423.           /* Skip the ack char if we're in no-ack mode.  */
  6424.           if (!rs->noack_mode)
  6425.             remote_serial_write ("+", 1);
  6426.           if (is_notif != NULL)
  6427.             *is_notif = 0;
  6428.           return val;
  6429.         }

  6430.        /* If we got a notification, handle it, and go back to looking
  6431.          for a packet.  */
  6432.       else
  6433.         {
  6434.           gdb_assert (c == '%');

  6435.           if (remote_debug)
  6436.             {
  6437.               struct cleanup *old_chain;
  6438.               char *str;

  6439.               str = escape_buffer (*buf, val);
  6440.               old_chain = make_cleanup (xfree, str);
  6441.               fprintf_unfiltered (gdb_stdlog,
  6442.                                   "  Notification received: %s\n",
  6443.                                   str);
  6444.               do_cleanups (old_chain);
  6445.             }
  6446.           if (is_notif != NULL)
  6447.             *is_notif = 1;

  6448.           handle_notification (rs->notif_state, *buf);

  6449.           /* Notifications require no acknowledgement.  */

  6450.           if (expecting_notif)
  6451.             return val;
  6452.         }
  6453.     }
  6454. }

  6455. static int
  6456. getpkt_sane (char **buf, long *sizeof_buf, int forever)
  6457. {
  6458.   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
  6459. }

  6460. static int
  6461. getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
  6462.                       int *is_notif)
  6463. {
  6464.   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
  6465.                                  is_notif);
  6466. }


  6467. static void
  6468. remote_kill (struct target_ops *ops)
  6469. {
  6470.   volatile struct gdb_exception ex;

  6471.   /* Catch errors so the user can quit from gdb even when we
  6472.      aren't on speaking terms with the remote system.  */
  6473.   TRY_CATCH (ex, RETURN_MASK_ERROR)
  6474.     {
  6475.       putpkt ("k");
  6476.     }
  6477.   if (ex.reason < 0)
  6478.     {
  6479.       if (ex.error == TARGET_CLOSE_ERROR)
  6480.         {
  6481.           /* If we got an (EOF) error that caused the target
  6482.              to go away, then we're done, that's what we wanted.
  6483.              "k" is susceptible to cause a premature EOF, given
  6484.              that the remote server isn't actually required to
  6485.              reply to "k", and it can happen that it doesn't
  6486.              even get to reply ACK to the "k".  */
  6487.           return;
  6488.         }

  6489.         /* Otherwise, something went wrong.  We didn't actually kill
  6490.            the target.  Just propagate the exception, and let the
  6491.            user or higher layers decide what to do.  */
  6492.         throw_exception (ex);
  6493.     }

  6494.   /* We've killed the remote end, we get to mourn it.  Since this is
  6495.      target remote, single-process, mourning the inferior also
  6496.      unpushes remote_ops.  */
  6497.   target_mourn_inferior ();
  6498. }

  6499. static int
  6500. remote_vkill (int pid, struct remote_state *rs)
  6501. {
  6502.   if (packet_support (PACKET_vKill) == PACKET_DISABLE)
  6503.     return -1;

  6504.   /* Tell the remote target to detach.  */
  6505.   xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
  6506.   putpkt (rs->buf);
  6507.   getpkt (&rs->buf, &rs->buf_size, 0);

  6508.   switch (packet_ok (rs->buf,
  6509.                      &remote_protocol_packets[PACKET_vKill]))
  6510.     {
  6511.     case PACKET_OK:
  6512.       return 0;
  6513.     case PACKET_ERROR:
  6514.       return 1;
  6515.     case PACKET_UNKNOWN:
  6516.       return -1;
  6517.     default:
  6518.       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
  6519.     }
  6520. }

  6521. static void
  6522. extended_remote_kill (struct target_ops *ops)
  6523. {
  6524.   int res;
  6525.   int pid = ptid_get_pid (inferior_ptid);
  6526.   struct remote_state *rs = get_remote_state ();

  6527.   res = remote_vkill (pid, rs);
  6528.   if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
  6529.     {
  6530.       /* Don't try 'k' on a multi-process aware stub -- it has no way
  6531.          to specify the pid.  */

  6532.       putpkt ("k");
  6533. #if 0
  6534.       getpkt (&rs->buf, &rs->buf_size, 0);
  6535.       if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
  6536.         res = 1;
  6537. #else
  6538.       /* Don't wait for it to die.  I'm not really sure it matters whether
  6539.          we do or not.  For the existing stubs, kill is a noop.  */
  6540.       res = 0;
  6541. #endif
  6542.     }

  6543.   if (res != 0)
  6544.     error (_("Can't kill process"));

  6545.   target_mourn_inferior ();
  6546. }

  6547. static void
  6548. remote_mourn (struct target_ops *ops)
  6549. {
  6550.   remote_mourn_1 (ops);
  6551. }

  6552. /* Worker function for remote_mourn.  */
  6553. static void
  6554. remote_mourn_1 (struct target_ops *target)
  6555. {
  6556.   unpush_target (target);

  6557.   /* remote_close takes care of doing most of the clean up.  */
  6558.   generic_mourn_inferior ();
  6559. }

  6560. static void
  6561. extended_remote_mourn_1 (struct target_ops *target)
  6562. {
  6563.   struct remote_state *rs = get_remote_state ();

  6564.   /* In case we got here due to an error, but we're going to stay
  6565.      connected.  */
  6566.   rs->waiting_for_stop_reply = 0;

  6567.   /* If the current general thread belonged to the process we just
  6568.      detached from or has exited, the remote side current general
  6569.      thread becomes undefined.  Considering a case like this:

  6570.      - We just got here due to a detach.
  6571.      - The process that we're detaching from happens to immediately
  6572.        report a global breakpoint being hit in non-stop mode, in the
  6573.        same thread we had selected before.
  6574.      - GDB attaches to this process again.
  6575.      - This event happens to be the next event we handle.

  6576.      GDB would consider that the current general thread didn't need to
  6577.      be set on the stub side (with Hg), since for all it knew,
  6578.      GENERAL_THREAD hadn't changed.

  6579.      Notice that although in all-stop mode, the remote server always
  6580.      sets the current thread to the thread reporting the stop event,
  6581.      that doesn't happen in non-stop mode; in non-stop, the stub *must
  6582.      not* change the current thread when reporting a breakpoint hit,
  6583.      due to the decoupling of event reporting and event handling.

  6584.      To keep things simple, we always invalidate our notion of the
  6585.      current thread.  */
  6586.   record_currthread (rs, minus_one_ptid);

  6587.   /* Unlike "target remote", we do not want to unpush the target; then
  6588.      the next time the user says "run", we won't be connected.  */

  6589.   /* Call common code to mark the inferior as not running.        */
  6590.   generic_mourn_inferior ();

  6591.   if (!have_inferiors ())
  6592.     {
  6593.       if (!remote_multi_process_p (rs))
  6594.         {
  6595.           /* Check whether the target is running now - some remote stubs
  6596.              automatically restart after kill.        */
  6597.           putpkt ("?");
  6598.           getpkt (&rs->buf, &rs->buf_size, 0);

  6599.           if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
  6600.             {
  6601.               /* Assume that the target has been restarted.  Set
  6602.                  inferior_ptid so that bits of core GDB realizes
  6603.                  there's something here, e.g., so that the user can
  6604.                  say "kill" again.  */
  6605.               inferior_ptid = magic_null_ptid;
  6606.             }
  6607.         }
  6608.     }
  6609. }

  6610. static void
  6611. extended_remote_mourn (struct target_ops *ops)
  6612. {
  6613.   extended_remote_mourn_1 (ops);
  6614. }

  6615. static int
  6616. extended_remote_supports_disable_randomization (struct target_ops *self)
  6617. {
  6618.   return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
  6619. }

  6620. static void
  6621. extended_remote_disable_randomization (int val)
  6622. {
  6623.   struct remote_state *rs = get_remote_state ();
  6624.   char *reply;

  6625.   xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
  6626.              val);
  6627.   putpkt (rs->buf);
  6628.   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
  6629.   if (*reply == '\0')
  6630.     error (_("Target does not support QDisableRandomization."));
  6631.   if (strcmp (reply, "OK") != 0)
  6632.     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
  6633. }

  6634. static int
  6635. extended_remote_run (char *args)
  6636. {
  6637.   struct remote_state *rs = get_remote_state ();
  6638.   int len;

  6639.   /* If the user has disabled vRun support, or we have detected that
  6640.      support is not available, do not try it.  */
  6641.   if (packet_support (PACKET_vRun) == PACKET_DISABLE)
  6642.     return -1;

  6643.   strcpy (rs->buf, "vRun;");
  6644.   len = strlen (rs->buf);

  6645.   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
  6646.     error (_("Remote file name too long for run packet"));
  6647.   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
  6648.                       strlen (remote_exec_file));

  6649.   gdb_assert (args != NULL);
  6650.   if (*args)
  6651.     {
  6652.       struct cleanup *back_to;
  6653.       int i;
  6654.       char **argv;

  6655.       argv = gdb_buildargv (args);
  6656.       back_to = make_cleanup_freeargv (argv);
  6657.       for (i = 0; argv[i] != NULL; i++)
  6658.         {
  6659.           if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
  6660.             error (_("Argument list too long for run packet"));
  6661.           rs->buf[len++] = ';';
  6662.           len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
  6663.                               strlen (argv[i]));
  6664.         }
  6665.       do_cleanups (back_to);
  6666.     }

  6667.   rs->buf[len++] = '\0';

  6668.   putpkt (rs->buf);
  6669.   getpkt (&rs->buf, &rs->buf_size, 0);

  6670.   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
  6671.     {
  6672.     case PACKET_OK:
  6673.       /* We have a wait response.  All is well.  */
  6674.       return 0;
  6675.     case PACKET_UNKNOWN:
  6676.       return -1;
  6677.     case PACKET_ERROR:
  6678.       if (remote_exec_file[0] == '\0')
  6679.         error (_("Running the default executable on the remote target failed; "
  6680.                  "try \"set remote exec-file\"?"));
  6681.       else
  6682.         error (_("Running \"%s\" on the remote target failed"),
  6683.                remote_exec_file);
  6684.     default:
  6685.       gdb_assert_not_reached (_("bad switch"));
  6686.     }
  6687. }

  6688. /* In the extended protocol we want to be able to do things like
  6689.    "run" and have them basically work as expected.  So we need
  6690.    a special create_inferior function.  We support changing the
  6691.    executable file and the command line arguments, but not the
  6692.    environment.  */

  6693. static void
  6694. extended_remote_create_inferior (struct target_ops *ops,
  6695.                                  char *exec_file, char *args,
  6696.                                  char **env, int from_tty)
  6697. {
  6698.   int run_worked;
  6699.   char *stop_reply;
  6700.   struct remote_state *rs = get_remote_state ();

  6701.   /* If running asynchronously, register the target file descriptor
  6702.      with the event loop.  */
  6703.   if (target_can_async_p ())
  6704.     target_async (inferior_event_handler, 0);

  6705.   /* Disable address space randomization if requested (and supported).  */
  6706.   if (extended_remote_supports_disable_randomization (ops))
  6707.     extended_remote_disable_randomization (disable_randomization);

  6708.   /* Now restart the remote server.  */
  6709.   run_worked = extended_remote_run (args) != -1;
  6710.   if (!run_worked)
  6711.     {
  6712.       /* vRun was not supported.  Fail if we need it to do what the
  6713.          user requested.  */
  6714.       if (remote_exec_file[0])
  6715.         error (_("Remote target does not support \"set remote exec-file\""));
  6716.       if (args[0])
  6717.         error (_("Remote target does not support \"set args\" or run <ARGS>"));

  6718.       /* Fall back to "R".  */
  6719.       extended_remote_restart ();
  6720.     }

  6721.   if (!have_inferiors ())
  6722.     {
  6723.       /* Clean up from the last time we ran, before we mark the target
  6724.          running again.  This will mark breakpoints uninserted, and
  6725.          get_offsets may insert breakpoints.  */
  6726.       init_thread_list ();
  6727.       init_wait_for_inferior ();
  6728.     }

  6729.   /* vRun's success return is a stop reply.  */
  6730.   stop_reply = run_worked ? rs->buf : NULL;
  6731.   add_current_inferior_and_thread (stop_reply);

  6732.   /* Get updated offsets, if the stub uses qOffsets.  */
  6733.   get_offsets ();
  6734. }


  6735. /* Given a location's target info BP_TGT and the packet buffer BUF,  output
  6736.    the list of conditions (in agent expression bytecode format), if any, the
  6737.    target needs to evaluate.  The output is placed into the packet buffer
  6738.    started from BUF and ended at BUF_END.  */

  6739. static int
  6740. remote_add_target_side_condition (struct gdbarch *gdbarch,
  6741.                                   struct bp_target_info *bp_tgt, char *buf,
  6742.                                   char *buf_end)
  6743. {
  6744.   struct agent_expr *aexpr = NULL;
  6745.   int i, ix;
  6746.   char *pkt;
  6747.   char *buf_start = buf;

  6748.   if (VEC_empty (agent_expr_p, bp_tgt->conditions))
  6749.     return 0;

  6750.   buf += strlen (buf);
  6751.   xsnprintf (buf, buf_end - buf, "%s", ";");
  6752.   buf++;

  6753.   /* Send conditions to the target and free the vector.  */
  6754.   for (ix = 0;
  6755.        VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
  6756.        ix++)
  6757.     {
  6758.       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
  6759.       buf += strlen (buf);
  6760.       for (i = 0; i < aexpr->len; ++i)
  6761.         buf = pack_hex_byte (buf, aexpr->buf[i]);
  6762.       *buf = '\0';
  6763.     }
  6764.   return 0;
  6765. }

  6766. static void
  6767. remote_add_target_side_commands (struct gdbarch *gdbarch,
  6768.                                  struct bp_target_info *bp_tgt, char *buf)
  6769. {
  6770.   struct agent_expr *aexpr = NULL;
  6771.   int i, ix;

  6772.   if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
  6773.     return;

  6774.   buf += strlen (buf);

  6775.   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
  6776.   buf += strlen (buf);

  6777.   /* Concatenate all the agent expressions that are commands into the
  6778.      cmds parameter.  */
  6779.   for (ix = 0;
  6780.        VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
  6781.        ix++)
  6782.     {
  6783.       sprintf (buf, "X%x,", aexpr->len);
  6784.       buf += strlen (buf);
  6785.       for (i = 0; i < aexpr->len; ++i)
  6786.         buf = pack_hex_byte (buf, aexpr->buf[i]);
  6787.       *buf = '\0';
  6788.     }
  6789. }

  6790. /* Insert a breakpoint.  On targets that have software breakpoint
  6791.    support, we ask the remote target to do the work; on targets
  6792.    which don't, we insert a traditional memory breakpoint.  */

  6793. static int
  6794. remote_insert_breakpoint (struct target_ops *ops,
  6795.                           struct gdbarch *gdbarch,
  6796.                           struct bp_target_info *bp_tgt)
  6797. {
  6798.   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
  6799.      If it succeeds, then set the support to PACKET_ENABLE.  If it
  6800.      fails, and the user has explicitly requested the Z support then
  6801.      report an error, otherwise, mark it disabled and go on.  */

  6802.   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
  6803.     {
  6804.       CORE_ADDR addr = bp_tgt->reqstd_address;
  6805.       struct remote_state *rs;
  6806.       char *p, *endbuf;
  6807.       int bpsize;
  6808.       struct condition_list *cond = NULL;

  6809.       /* Make sure the remote is pointing at the right process, if
  6810.          necessary.  */
  6811.       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
  6812.         set_general_process ();

  6813.       gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);

  6814.       rs = get_remote_state ();
  6815.       p = rs->buf;
  6816.       endbuf = rs->buf + get_remote_packet_size ();

  6817.       *(p++) = 'Z';
  6818.       *(p++) = '0';
  6819.       *(p++) = ',';
  6820.       addr = (ULONGEST) remote_address_masked (addr);
  6821.       p += hexnumstr (p, addr);
  6822.       xsnprintf (p, endbuf - p, ",%d", bpsize);

  6823.       if (remote_supports_cond_breakpoints (ops))
  6824.         remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);

  6825.       if (remote_can_run_breakpoint_commands (ops))
  6826.         remote_add_target_side_commands (gdbarch, bp_tgt, p);

  6827.       putpkt (rs->buf);
  6828.       getpkt (&rs->buf, &rs->buf_size, 0);

  6829.       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
  6830.         {
  6831.         case PACKET_ERROR:
  6832.           return -1;
  6833.         case PACKET_OK:
  6834.           bp_tgt->placed_address = addr;
  6835.           bp_tgt->placed_size = bpsize;
  6836.           return 0;
  6837.         case PACKET_UNKNOWN:
  6838.           break;
  6839.         }
  6840.     }

  6841.   /* If this breakpoint has target-side commands but this stub doesn't
  6842.      support Z0 packets, throw error.  */
  6843.   if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
  6844.     throw_error (NOT_SUPPORTED_ERROR, _("\
  6845. Target doesn't support breakpoints that have target side commands."));

  6846.   return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
  6847. }

  6848. static int
  6849. remote_remove_breakpoint (struct target_ops *ops,
  6850.                           struct gdbarch *gdbarch,
  6851.                           struct bp_target_info *bp_tgt)
  6852. {
  6853.   CORE_ADDR addr = bp_tgt->placed_address;
  6854.   struct remote_state *rs = get_remote_state ();

  6855.   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
  6856.     {
  6857.       char *p = rs->buf;
  6858.       char *endbuf = rs->buf + get_remote_packet_size ();

  6859.       /* Make sure the remote is pointing at the right process, if
  6860.          necessary.  */
  6861.       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
  6862.         set_general_process ();

  6863.       *(p++) = 'z';
  6864.       *(p++) = '0';
  6865.       *(p++) = ',';

  6866.       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
  6867.       p += hexnumstr (p, addr);
  6868.       xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);

  6869.       putpkt (rs->buf);
  6870.       getpkt (&rs->buf, &rs->buf_size, 0);

  6871.       return (rs->buf[0] == 'E');
  6872.     }

  6873.   return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
  6874. }

  6875. static int
  6876. watchpoint_to_Z_packet (int type)
  6877. {
  6878.   switch (type)
  6879.     {
  6880.     case hw_write:
  6881.       return Z_PACKET_WRITE_WP;
  6882.       break;
  6883.     case hw_read:
  6884.       return Z_PACKET_READ_WP;
  6885.       break;
  6886.     case hw_access:
  6887.       return Z_PACKET_ACCESS_WP;
  6888.       break;
  6889.     default:
  6890.       internal_error (__FILE__, __LINE__,
  6891.                       _("hw_bp_to_z: bad watchpoint type %d"), type);
  6892.     }
  6893. }

  6894. static int
  6895. remote_insert_watchpoint (struct target_ops *self,
  6896.                           CORE_ADDR addr, int len, int type,
  6897.                           struct expression *cond)
  6898. {
  6899.   struct remote_state *rs = get_remote_state ();
  6900.   char *endbuf = rs->buf + get_remote_packet_size ();
  6901.   char *p;
  6902.   enum Z_packet_type packet = watchpoint_to_Z_packet (type);

  6903.   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
  6904.     return 1;

  6905.   /* Make sure the remote is pointing at the right process, if
  6906.      necessary.  */
  6907.   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
  6908.     set_general_process ();

  6909.   xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
  6910.   p = strchr (rs->buf, '\0');
  6911.   addr = remote_address_masked (addr);
  6912.   p += hexnumstr (p, (ULONGEST) addr);
  6913.   xsnprintf (p, endbuf - p, ",%x", len);

  6914.   putpkt (rs->buf);
  6915.   getpkt (&rs->buf, &rs->buf_size, 0);

  6916.   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
  6917.     {
  6918.     case PACKET_ERROR:
  6919.       return -1;
  6920.     case PACKET_UNKNOWN:
  6921.       return 1;
  6922.     case PACKET_OK:
  6923.       return 0;
  6924.     }
  6925.   internal_error (__FILE__, __LINE__,
  6926.                   _("remote_insert_watchpoint: reached end of function"));
  6927. }

  6928. static int
  6929. remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
  6930.                                      CORE_ADDR start, int length)
  6931. {
  6932.   CORE_ADDR diff = remote_address_masked (addr - start);

  6933.   return diff < length;
  6934. }


  6935. static int
  6936. remote_remove_watchpoint (struct target_ops *self,
  6937.                           CORE_ADDR addr, int len, int type,
  6938.                           struct expression *cond)
  6939. {
  6940.   struct remote_state *rs = get_remote_state ();
  6941.   char *endbuf = rs->buf + get_remote_packet_size ();
  6942.   char *p;
  6943.   enum Z_packet_type packet = watchpoint_to_Z_packet (type);

  6944.   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
  6945.     return -1;

  6946.   /* Make sure the remote is pointing at the right process, if
  6947.      necessary.  */
  6948.   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
  6949.     set_general_process ();

  6950.   xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
  6951.   p = strchr (rs->buf, '\0');
  6952.   addr = remote_address_masked (addr);
  6953.   p += hexnumstr (p, (ULONGEST) addr);
  6954.   xsnprintf (p, endbuf - p, ",%x", len);
  6955.   putpkt (rs->buf);
  6956.   getpkt (&rs->buf, &rs->buf_size, 0);

  6957.   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
  6958.     {
  6959.     case PACKET_ERROR:
  6960.     case PACKET_UNKNOWN:
  6961.       return -1;
  6962.     case PACKET_OK:
  6963.       return 0;
  6964.     }
  6965.   internal_error (__FILE__, __LINE__,
  6966.                   _("remote_remove_watchpoint: reached end of function"));
  6967. }


  6968. int remote_hw_watchpoint_limit = -1;
  6969. int remote_hw_watchpoint_length_limit = -1;
  6970. int remote_hw_breakpoint_limit = -1;

  6971. static int
  6972. remote_region_ok_for_hw_watchpoint (struct target_ops *self,
  6973.                                     CORE_ADDR addr, int len)
  6974. {
  6975.   if (remote_hw_watchpoint_length_limit == 0)
  6976.     return 0;
  6977.   else if (remote_hw_watchpoint_length_limit < 0)
  6978.     return 1;
  6979.   else if (len <= remote_hw_watchpoint_length_limit)
  6980.     return 1;
  6981.   else
  6982.     return 0;
  6983. }

  6984. static int
  6985. remote_check_watch_resources (struct target_ops *self,
  6986.                               int type, int cnt, int ot)
  6987. {
  6988.   if (type == bp_hardware_breakpoint)
  6989.     {
  6990.       if (remote_hw_breakpoint_limit == 0)
  6991.         return 0;
  6992.       else if (remote_hw_breakpoint_limit < 0)
  6993.         return 1;
  6994.       else if (cnt <= remote_hw_breakpoint_limit)
  6995.         return 1;
  6996.     }
  6997.   else
  6998.     {
  6999.       if (remote_hw_watchpoint_limit == 0)
  7000.         return 0;
  7001.       else if (remote_hw_watchpoint_limit < 0)
  7002.         return 1;
  7003.       else if (ot)
  7004.         return -1;
  7005.       else if (cnt <= remote_hw_watchpoint_limit)
  7006.         return 1;
  7007.     }
  7008.   return -1;
  7009. }

  7010. static int
  7011. remote_stopped_by_watchpoint (struct target_ops *ops)
  7012. {
  7013.   struct remote_state *rs = get_remote_state ();

  7014.   return rs->remote_stopped_by_watchpoint_p;
  7015. }

  7016. static int
  7017. remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
  7018. {
  7019.   struct remote_state *rs = get_remote_state ();
  7020.   int rc = 0;

  7021.   if (remote_stopped_by_watchpoint (target))
  7022.     {
  7023.       *addr_p = rs->remote_watch_data_address;
  7024.       rc = 1;
  7025.     }

  7026.   return rc;
  7027. }


  7028. static int
  7029. remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
  7030.                              struct bp_target_info *bp_tgt)
  7031. {
  7032.   CORE_ADDR addr = bp_tgt->reqstd_address;
  7033.   struct remote_state *rs;
  7034.   char *p, *endbuf;
  7035.   char *message;
  7036.   int bpsize;

  7037.   /* The length field should be set to the size of a breakpoint
  7038.      instruction, even though we aren't inserting one ourselves.  */

  7039.   gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);

  7040.   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
  7041.     return -1;

  7042.   /* Make sure the remote is pointing at the right process, if
  7043.      necessary.  */
  7044.   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
  7045.     set_general_process ();

  7046.   rs = get_remote_state ();
  7047.   p = rs->buf;
  7048.   endbuf = rs->buf + get_remote_packet_size ();

  7049.   *(p++) = 'Z';
  7050.   *(p++) = '1';
  7051.   *(p++) = ',';

  7052.   addr = remote_address_masked (addr);
  7053.   p += hexnumstr (p, (ULONGEST) addr);
  7054.   xsnprintf (p, endbuf - p, ",%x", bpsize);

  7055.   if (remote_supports_cond_breakpoints (self))
  7056.     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);

  7057.   if (remote_can_run_breakpoint_commands (self))
  7058.     remote_add_target_side_commands (gdbarch, bp_tgt, p);

  7059.   putpkt (rs->buf);
  7060.   getpkt (&rs->buf, &rs->buf_size, 0);

  7061.   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
  7062.     {
  7063.     case PACKET_ERROR:
  7064.       if (rs->buf[1] == '.')
  7065.         {
  7066.           message = strchr (rs->buf + 2, '.');
  7067.           if (message)
  7068.             error (_("Remote failure reply: %s"), message + 1);
  7069.         }
  7070.       return -1;
  7071.     case PACKET_UNKNOWN:
  7072.       return -1;
  7073.     case PACKET_OK:
  7074.       bp_tgt->placed_address = addr;
  7075.       bp_tgt->placed_size = bpsize;
  7076.       return 0;
  7077.     }
  7078.   internal_error (__FILE__, __LINE__,
  7079.                   _("remote_insert_hw_breakpoint: reached end of function"));
  7080. }


  7081. static int
  7082. remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
  7083.                              struct bp_target_info *bp_tgt)
  7084. {
  7085.   CORE_ADDR addr;
  7086.   struct remote_state *rs = get_remote_state ();
  7087.   char *p = rs->buf;
  7088.   char *endbuf = rs->buf + get_remote_packet_size ();

  7089.   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
  7090.     return -1;

  7091.   /* Make sure the remote is pointing at the right process, if
  7092.      necessary.  */
  7093.   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
  7094.     set_general_process ();

  7095.   *(p++) = 'z';
  7096.   *(p++) = '1';
  7097.   *(p++) = ',';

  7098.   addr = remote_address_masked (bp_tgt->placed_address);
  7099.   p += hexnumstr (p, (ULONGEST) addr);
  7100.   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->placed_size);

  7101.   putpkt (rs->buf);
  7102.   getpkt (&rs->buf, &rs->buf_size, 0);

  7103.   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
  7104.     {
  7105.     case PACKET_ERROR:
  7106.     case PACKET_UNKNOWN:
  7107.       return -1;
  7108.     case PACKET_OK:
  7109.       return 0;
  7110.     }
  7111.   internal_error (__FILE__, __LINE__,
  7112.                   _("remote_remove_hw_breakpoint: reached end of function"));
  7113. }

  7114. /* Verify memory using the "qCRC:" request.  */

  7115. static int
  7116. remote_verify_memory (struct target_ops *ops,
  7117.                       const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
  7118. {
  7119.   struct remote_state *rs = get_remote_state ();
  7120.   unsigned long host_crc, target_crc;
  7121.   char *tmp;

  7122.   /* It doesn't make sense to use qCRC if the remote target is
  7123.      connected but not running.  */
  7124.   if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
  7125.     {
  7126.       enum packet_result result;

  7127.       /* Make sure the remote is pointing at the right process.  */
  7128.       set_general_process ();

  7129.       /* FIXME: assumes lma can fit into long.  */
  7130.       xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
  7131.                  (long) lma, (long) size);
  7132.       putpkt (rs->buf);

  7133.       /* Be clever; compute the host_crc before waiting for target
  7134.          reply.  */
  7135.       host_crc = xcrc32 (data, size, 0xffffffff);

  7136.       getpkt (&rs->buf, &rs->buf_size, 0);

  7137.       result = packet_ok (rs->buf,
  7138.                           &remote_protocol_packets[PACKET_qCRC]);
  7139.       if (result == PACKET_ERROR)
  7140.         return -1;
  7141.       else if (result == PACKET_OK)
  7142.         {
  7143.           for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
  7144.             target_crc = target_crc * 16 + fromhex (*tmp);

  7145.           return (host_crc == target_crc);
  7146.         }
  7147.     }

  7148.   return simple_verify_memory (ops, data, lma, size);
  7149. }

  7150. /* compare-sections command

  7151.    With no arguments, compares each loadable section in the exec bfd
  7152.    with the same memory range on the target, and reports mismatches.
  7153.    Useful for verifying the image on the target against the exec file.  */

  7154. static void
  7155. compare_sections_command (char *args, int from_tty)
  7156. {
  7157.   asection *s;
  7158.   struct cleanup *old_chain;
  7159.   gdb_byte *sectdata;
  7160.   const char *sectname;
  7161.   bfd_size_type size;
  7162.   bfd_vma lma;
  7163.   int matched = 0;
  7164.   int mismatched = 0;
  7165.   int res;
  7166.   int read_only = 0;

  7167.   if (!exec_bfd)
  7168.     error (_("command cannot be used without an exec file"));

  7169.   /* Make sure the remote is pointing at the right process.  */
  7170.   set_general_process ();

  7171.   if (args != NULL && strcmp (args, "-r") == 0)
  7172.     {
  7173.       read_only = 1;
  7174.       args = NULL;
  7175.     }

  7176.   for (s = exec_bfd->sections; s; s = s->next)
  7177.     {
  7178.       if (!(s->flags & SEC_LOAD))
  7179.         continue;                /* Skip non-loadable section.  */

  7180.       if (read_only && (s->flags & SEC_READONLY) == 0)
  7181.         continue;                /* Skip writeable sections */

  7182.       size = bfd_get_section_size (s);
  7183.       if (size == 0)
  7184.         continue;                /* Skip zero-length section.  */

  7185.       sectname = bfd_get_section_name (exec_bfd, s);
  7186.       if (args && strcmp (args, sectname) != 0)
  7187.         continue;                /* Not the section selected by user.  */

  7188.       matched = 1;                /* Do this section.  */
  7189.       lma = s->lma;

  7190.       sectdata = xmalloc (size);
  7191.       old_chain = make_cleanup (xfree, sectdata);
  7192.       bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);

  7193.       res = target_verify_memory (sectdata, lma, size);

  7194.       if (res == -1)
  7195.         error (_("target memory fault, section %s, range %s -- %s"), sectname,
  7196.                paddress (target_gdbarch (), lma),
  7197.                paddress (target_gdbarch (), lma + size));

  7198.       printf_filtered ("Section %s, range %s -- %s: ", sectname,
  7199.                        paddress (target_gdbarch (), lma),
  7200.                        paddress (target_gdbarch (), lma + size));
  7201.       if (res)
  7202.         printf_filtered ("matched.\n");
  7203.       else
  7204.         {
  7205.           printf_filtered ("MIS-MATCHED!\n");
  7206.           mismatched++;
  7207.         }

  7208.       do_cleanups (old_chain);
  7209.     }
  7210.   if (mismatched > 0)
  7211.     warning (_("One or more sections of the target image does not match\n\
  7212. the loaded file\n"));
  7213.   if (args && !matched)
  7214.     printf_filtered (_("No loaded section named '%s'.\n"), args);
  7215. }

  7216. /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
  7217.    into remote target.  The number of bytes written to the remote
  7218.    target is returned, or -1 for error.  */

  7219. static enum target_xfer_status
  7220. remote_write_qxfer (struct target_ops *ops, const char *object_name,
  7221.                     const char *annex, const gdb_byte *writebuf,
  7222.                     ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
  7223.                     struct packet_config *packet)
  7224. {
  7225.   int i, buf_len;
  7226.   ULONGEST n;
  7227.   struct remote_state *rs = get_remote_state ();
  7228.   int max_size = get_memory_write_packet_size ();

  7229.   if (packet->support == PACKET_DISABLE)
  7230.     return TARGET_XFER_E_IO;

  7231.   /* Insert header.  */
  7232.   i = snprintf (rs->buf, max_size,
  7233.                 "qXfer:%s:write:%s:%s:",
  7234.                 object_name, annex ? annex : "",
  7235.                 phex_nz (offset, sizeof offset));
  7236.   max_size -= (i + 1);

  7237.   /* Escape as much data as fits into rs->buf.  */
  7238.   buf_len = remote_escape_output
  7239.     (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);

  7240.   if (putpkt_binary (rs->buf, i + buf_len) < 0
  7241.       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
  7242.       || packet_ok (rs->buf, packet) != PACKET_OK)
  7243.     return TARGET_XFER_E_IO;

  7244.   unpack_varlen_hex (rs->buf, &n);

  7245.   *xfered_len = n;
  7246.   return TARGET_XFER_OK;
  7247. }

  7248. /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
  7249.    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
  7250.    number of bytes read is returned, or 0 for EOF, or -1 for error.
  7251.    The number of bytes read may be less than LEN without indicating an
  7252.    EOF.  PACKET is checked and updated to indicate whether the remote
  7253.    target supports this object.  */

  7254. static enum target_xfer_status
  7255. remote_read_qxfer (struct target_ops *ops, const char *object_name,
  7256.                    const char *annex,
  7257.                    gdb_byte *readbuf, ULONGEST offset, LONGEST len,
  7258.                    ULONGEST *xfered_len,
  7259.                    struct packet_config *packet)
  7260. {
  7261.   struct remote_state *rs = get_remote_state ();
  7262.   LONGEST i, n, packet_len;

  7263.   if (packet->support == PACKET_DISABLE)
  7264.     return TARGET_XFER_E_IO;

  7265.   /* Check whether we've cached an end-of-object packet that matches
  7266.      this request.  */
  7267.   if (rs->finished_object)
  7268.     {
  7269.       if (strcmp (object_name, rs->finished_object) == 0
  7270.           && strcmp (annex ? annex : "", rs->finished_annex) == 0
  7271.           && offset == rs->finished_offset)
  7272.         return TARGET_XFER_EOF;


  7273.       /* Otherwise, we're now reading something different.  Discard
  7274.          the cache.  */
  7275.       xfree (rs->finished_object);
  7276.       xfree (rs->finished_annex);
  7277.       rs->finished_object = NULL;
  7278.       rs->finished_annex = NULL;
  7279.     }

  7280.   /* Request only enough to fit in a single packet.  The actual data
  7281.      may not, since we don't know how much of it will need to be escaped;
  7282.      the target is free to respond with slightly less data.  We subtract
  7283.      five to account for the response type and the protocol frame.  */
  7284.   n = min (get_remote_packet_size () - 5, len);
  7285.   snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
  7286.             object_name, annex ? annex : "",
  7287.             phex_nz (offset, sizeof offset),
  7288.             phex_nz (n, sizeof n));
  7289.   i = putpkt (rs->buf);
  7290.   if (i < 0)
  7291.     return TARGET_XFER_E_IO;

  7292.   rs->buf[0] = '\0';
  7293.   packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
  7294.   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
  7295.     return TARGET_XFER_E_IO;

  7296.   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
  7297.     error (_("Unknown remote qXfer reply: %s"), rs->buf);

  7298.   /* 'm' means there is (or at least might be) more data after this
  7299.      batch.  That does not make sense unless there's at least one byte
  7300.      of data in this reply.  */
  7301.   if (rs->buf[0] == 'm' && packet_len == 1)
  7302.     error (_("Remote qXfer reply contained no data."));

  7303.   /* Got some data.  */
  7304.   i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
  7305.                              packet_len - 1, readbuf, n);

  7306.   /* 'l' is an EOF marker, possibly including a final block of data,
  7307.      or possibly empty.  If we have the final block of a non-empty
  7308.      object, record this fact to bypass a subsequent partial read.  */
  7309.   if (rs->buf[0] == 'l' && offset + i > 0)
  7310.     {
  7311.       rs->finished_object = xstrdup (object_name);
  7312.       rs->finished_annex = xstrdup (annex ? annex : "");
  7313.       rs->finished_offset = offset + i;
  7314.     }

  7315.   if (i == 0)
  7316.     return TARGET_XFER_EOF;
  7317.   else
  7318.     {
  7319.       *xfered_len = i;
  7320.       return TARGET_XFER_OK;
  7321.     }
  7322. }

  7323. static enum target_xfer_status
  7324. remote_xfer_partial (struct target_ops *ops, enum target_object object,
  7325.                      const char *annex, gdb_byte *readbuf,
  7326.                      const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
  7327.                      ULONGEST *xfered_len)
  7328. {
  7329.   struct remote_state *rs;
  7330.   int i;
  7331.   char *p2;
  7332.   char query_type;

  7333.   set_remote_traceframe ();
  7334.   set_general_thread (inferior_ptid);

  7335.   rs = get_remote_state ();

  7336.   /* Handle memory using the standard memory routines.  */
  7337.   if (object == TARGET_OBJECT_MEMORY)
  7338.     {
  7339.       /* If the remote target is connected but not running, we should
  7340.          pass this request down to a lower stratum (e.g. the executable
  7341.          file).  */
  7342.       if (!target_has_execution)
  7343.         return TARGET_XFER_EOF;

  7344.       if (writebuf != NULL)
  7345.         return remote_write_bytes (offset, writebuf, len, xfered_len);
  7346.       else
  7347.         return remote_read_bytes (ops, offset, readbuf, len, xfered_len);
  7348.     }

  7349.   /* Handle SPU memory using qxfer packets.  */
  7350.   if (object == TARGET_OBJECT_SPU)
  7351.     {
  7352.       if (readbuf)
  7353.         return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
  7354.                                   xfered_len, &remote_protocol_packets
  7355.                                   [PACKET_qXfer_spu_read]);
  7356.       else
  7357.         return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
  7358.                                    xfered_len, &remote_protocol_packets
  7359.                                    [PACKET_qXfer_spu_write]);
  7360.     }

  7361.   /* Handle extra signal info using qxfer packets.  */
  7362.   if (object == TARGET_OBJECT_SIGNAL_INFO)
  7363.     {
  7364.       if (readbuf)
  7365.         return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
  7366.                                   xfered_len, &remote_protocol_packets
  7367.                                   [PACKET_qXfer_siginfo_read]);
  7368.       else
  7369.         return remote_write_qxfer (ops, "siginfo", annex,
  7370.                                    writebuf, offset, len, xfered_len,
  7371.                                    &remote_protocol_packets
  7372.                                    [PACKET_qXfer_siginfo_write]);
  7373.     }

  7374.   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
  7375.     {
  7376.       if (readbuf)
  7377.         return remote_read_qxfer (ops, "statictrace", annex,
  7378.                                   readbuf, offset, len, xfered_len,
  7379.                                   &remote_protocol_packets
  7380.                                   [PACKET_qXfer_statictrace_read]);
  7381.       else
  7382.         return TARGET_XFER_E_IO;
  7383.     }

  7384.   /* Only handle flash writes.  */
  7385.   if (writebuf != NULL)
  7386.     {
  7387.       LONGEST xfered;

  7388.       switch (object)
  7389.         {
  7390.         case TARGET_OBJECT_FLASH:
  7391.           return remote_flash_write (ops, offset, len, xfered_len,
  7392.                                      writebuf);

  7393.         default:
  7394.           return TARGET_XFER_E_IO;
  7395.         }
  7396.     }

  7397.   /* Map pre-existing objects onto letters.  DO NOT do this for new
  7398.      objects!!!  Instead specify new query packets.  */
  7399.   switch (object)
  7400.     {
  7401.     case TARGET_OBJECT_AVR:
  7402.       query_type = 'R';
  7403.       break;

  7404.     case TARGET_OBJECT_AUXV:
  7405.       gdb_assert (annex == NULL);
  7406.       return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
  7407.                                 xfered_len,
  7408.                                 &remote_protocol_packets[PACKET_qXfer_auxv]);

  7409.     case TARGET_OBJECT_AVAILABLE_FEATURES:
  7410.       return remote_read_qxfer
  7411.         (ops, "features", annex, readbuf, offset, len, xfered_len,
  7412.          &remote_protocol_packets[PACKET_qXfer_features]);

  7413.     case TARGET_OBJECT_LIBRARIES:
  7414.       return remote_read_qxfer
  7415.         (ops, "libraries", annex, readbuf, offset, len, xfered_len,
  7416.          &remote_protocol_packets[PACKET_qXfer_libraries]);

  7417.     case TARGET_OBJECT_LIBRARIES_SVR4:
  7418.       return remote_read_qxfer
  7419.         (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
  7420.          &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);

  7421.     case TARGET_OBJECT_MEMORY_MAP:
  7422.       gdb_assert (annex == NULL);
  7423.       return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
  7424.                                  xfered_len,
  7425.                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);

  7426.     case TARGET_OBJECT_OSDATA:
  7427.       /* Should only get here if we're connected.  */
  7428.       gdb_assert (rs->remote_desc);
  7429.       return remote_read_qxfer
  7430.         (ops, "osdata", annex, readbuf, offset, len, xfered_len,
  7431.         &remote_protocol_packets[PACKET_qXfer_osdata]);

  7432.     case TARGET_OBJECT_THREADS:
  7433.       gdb_assert (annex == NULL);
  7434.       return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
  7435.                                 xfered_len,
  7436.                                 &remote_protocol_packets[PACKET_qXfer_threads]);

  7437.     case TARGET_OBJECT_TRACEFRAME_INFO:
  7438.       gdb_assert (annex == NULL);
  7439.       return remote_read_qxfer
  7440.         (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
  7441.          &remote_protocol_packets[PACKET_qXfer_traceframe_info]);

  7442.     case TARGET_OBJECT_FDPIC:
  7443.       return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
  7444.                                 xfered_len,
  7445.                                 &remote_protocol_packets[PACKET_qXfer_fdpic]);

  7446.     case TARGET_OBJECT_OPENVMS_UIB:
  7447.       return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
  7448.                                 xfered_len,
  7449.                                 &remote_protocol_packets[PACKET_qXfer_uib]);

  7450.     case TARGET_OBJECT_BTRACE:
  7451.       return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
  7452.                                 xfered_len,
  7453.         &remote_protocol_packets[PACKET_qXfer_btrace]);

  7454.     default:
  7455.       return TARGET_XFER_E_IO;
  7456.     }

  7457.   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
  7458.      large enough let the caller deal with it.  */
  7459.   if (len < get_remote_packet_size ())
  7460.     return TARGET_XFER_E_IO;
  7461.   len = get_remote_packet_size ();

  7462.   /* Except for querying the minimum buffer size, target must be open.  */
  7463.   if (!rs->remote_desc)
  7464.     error (_("remote query is only available after target open"));

  7465.   gdb_assert (annex != NULL);
  7466.   gdb_assert (readbuf != NULL);

  7467.   p2 = rs->buf;
  7468.   *p2++ = 'q';
  7469.   *p2++ = query_type;

  7470.   /* We used one buffer char for the remote protocol q command and
  7471.      another for the query type.  As the remote protocol encapsulation
  7472.      uses 4 chars plus one extra in case we are debugging
  7473.      (remote_debug), we have PBUFZIZ - 7 left to pack the query
  7474.      string.  */
  7475.   i = 0;
  7476.   while (annex[i] && (i < (get_remote_packet_size () - 8)))
  7477.     {
  7478.       /* Bad caller may have sent forbidden characters.  */
  7479.       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
  7480.       *p2++ = annex[i];
  7481.       i++;
  7482.     }
  7483.   *p2 = '\0';
  7484.   gdb_assert (annex[i] == '\0');

  7485.   i = putpkt (rs->buf);
  7486.   if (i < 0)
  7487.     return TARGET_XFER_E_IO;

  7488.   getpkt (&rs->buf, &rs->buf_size, 0);
  7489.   strcpy ((char *) readbuf, rs->buf);

  7490.   *xfered_len = strlen ((char *) readbuf);
  7491.   return TARGET_XFER_OK;
  7492. }

  7493. static int
  7494. remote_search_memory (struct target_ops* ops,
  7495.                       CORE_ADDR start_addr, ULONGEST search_space_len,
  7496.                       const gdb_byte *pattern, ULONGEST pattern_len,
  7497.                       CORE_ADDR *found_addrp)
  7498. {
  7499.   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
  7500.   struct remote_state *rs = get_remote_state ();
  7501.   int max_size = get_memory_write_packet_size ();
  7502.   struct packet_config *packet =
  7503.     &remote_protocol_packets[PACKET_qSearch_memory];
  7504.   /* Number of packet bytes used to encode the pattern;
  7505.      this could be more than PATTERN_LEN due to escape characters.  */
  7506.   int escaped_pattern_len;
  7507.   /* Amount of pattern that was encodable in the packet.  */
  7508.   int used_pattern_len;
  7509.   int i;
  7510.   int found;
  7511.   ULONGEST found_addr;

  7512.   /* Don't go to the target if we don't have to.
  7513.      This is done before checking packet->support to avoid the possibility that
  7514.      a success for this edge case means the facility works in general.  */
  7515.   if (pattern_len > search_space_len)
  7516.     return 0;
  7517.   if (pattern_len == 0)
  7518.     {
  7519.       *found_addrp = start_addr;
  7520.       return 1;
  7521.     }

  7522.   /* If we already know the packet isn't supported, fall back to the simple
  7523.      way of searching memory.  */

  7524.   if (packet_config_support (packet) == PACKET_DISABLE)
  7525.     {
  7526.       /* Target doesn't provided special support, fall back and use the
  7527.          standard support (copy memory and do the search here).  */
  7528.       return simple_search_memory (ops, start_addr, search_space_len,
  7529.                                    pattern, pattern_len, found_addrp);
  7530.     }

  7531.   /* Make sure the remote is pointing at the right process.  */
  7532.   set_general_process ();

  7533.   /* Insert header.  */
  7534.   i = snprintf (rs->buf, max_size,
  7535.                 "qSearch:memory:%s;%s;",
  7536.                 phex_nz (start_addr, addr_size),
  7537.                 phex_nz (search_space_len, sizeof (search_space_len)));
  7538.   max_size -= (i + 1);

  7539.   /* Escape as much data as fits into rs->buf.  */
  7540.   escaped_pattern_len =
  7541.     remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
  7542.                           &used_pattern_len, max_size);

  7543.   /* Bail if the pattern is too large.  */
  7544.   if (used_pattern_len != pattern_len)
  7545.     error (_("Pattern is too large to transmit to remote target."));

  7546.   if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
  7547.       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
  7548.       || packet_ok (rs->buf, packet) != PACKET_OK)
  7549.     {
  7550.       /* The request may not have worked because the command is not
  7551.          supported.  If so, fall back to the simple way.  */
  7552.       if (packet->support == PACKET_DISABLE)
  7553.         {
  7554.           return simple_search_memory (ops, start_addr, search_space_len,
  7555.                                        pattern, pattern_len, found_addrp);
  7556.         }
  7557.       return -1;
  7558.     }

  7559.   if (rs->buf[0] == '0')
  7560.     found = 0;
  7561.   else if (rs->buf[0] == '1')
  7562.     {
  7563.       found = 1;
  7564.       if (rs->buf[1] != ',')
  7565.         error (_("Unknown qSearch:memory reply: %s"), rs->buf);
  7566.       unpack_varlen_hex (rs->buf + 2, &found_addr);
  7567.       *found_addrp = found_addr;
  7568.     }
  7569.   else
  7570.     error (_("Unknown qSearch:memory reply: %s"), rs->buf);

  7571.   return found;
  7572. }

  7573. static void
  7574. remote_rcmd (struct target_ops *self, const char *command,
  7575.              struct ui_file *outbuf)
  7576. {
  7577.   struct remote_state *rs = get_remote_state ();
  7578.   char *p = rs->buf;

  7579.   if (!rs->remote_desc)
  7580.     error (_("remote rcmd is only available after target open"));

  7581.   /* Send a NULL command across as an empty command.  */
  7582.   if (command == NULL)
  7583.     command = "";

  7584.   /* The query prefix.  */
  7585.   strcpy (rs->buf, "qRcmd,");
  7586.   p = strchr (rs->buf, '\0');

  7587.   if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
  7588.       > get_remote_packet_size ())
  7589.     error (_("\"monitor\" command ``%s'' is too long."), command);

  7590.   /* Encode the actual command.  */
  7591.   bin2hex ((const gdb_byte *) command, p, strlen (command));

  7592.   if (putpkt (rs->buf) < 0)
  7593.     error (_("Communication problem with target."));

  7594.   /* get/display the response */
  7595.   while (1)
  7596.     {
  7597.       char *buf;

  7598.       /* XXX - see also remote_get_noisy_reply().  */
  7599.       QUIT;                        /* Allow user to bail out with ^C.  */
  7600.       rs->buf[0] = '\0';
  7601.       if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
  7602.         {
  7603.           /* Timeout.  Continue to (try to) read responses.
  7604.              This is better than stopping with an error, assuming the stub
  7605.              is still executing the (long) monitor command.
  7606.              If needed, the user can interrupt gdb using C-c, obtaining
  7607.              an effect similar to stop on timeout.  */
  7608.           continue;
  7609.         }
  7610.       buf = rs->buf;
  7611.       if (buf[0] == '\0')
  7612.         error (_("Target does not support this command."));
  7613.       if (buf[0] == 'O' && buf[1] != 'K')
  7614.         {
  7615.           remote_console_output (buf + 1); /* 'O' message from stub.  */
  7616.           continue;
  7617.         }
  7618.       if (strcmp (buf, "OK") == 0)
  7619.         break;
  7620.       if (strlen (buf) == 3 && buf[0] == 'E'
  7621.           && isdigit (buf[1]) && isdigit (buf[2]))
  7622.         {
  7623.           error (_("Protocol error with Rcmd"));
  7624.         }
  7625.       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
  7626.         {
  7627.           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);

  7628.           fputc_unfiltered (c, outbuf);
  7629.         }
  7630.       break;
  7631.     }
  7632. }

  7633. static VEC(mem_region_s) *
  7634. remote_memory_map (struct target_ops *ops)
  7635. {
  7636.   VEC(mem_region_s) *result = NULL;
  7637.   char *text = target_read_stralloc (&current_target,
  7638.                                      TARGET_OBJECT_MEMORY_MAP, NULL);

  7639.   if (text)
  7640.     {
  7641.       struct cleanup *back_to = make_cleanup (xfree, text);

  7642.       result = parse_memory_map (text);
  7643.       do_cleanups (back_to);
  7644.     }

  7645.   return result;
  7646. }

  7647. static void
  7648. packet_command (char *args, int from_tty)
  7649. {
  7650.   struct remote_state *rs = get_remote_state ();

  7651.   if (!rs->remote_desc)
  7652.     error (_("command can only be used with remote target"));

  7653.   if (!args)
  7654.     error (_("remote-packet command requires packet text as argument"));

  7655.   puts_filtered ("sending: ");
  7656.   print_packet (args);
  7657.   puts_filtered ("\n");
  7658.   putpkt (args);

  7659.   getpkt (&rs->buf, &rs->buf_size, 0);
  7660.   puts_filtered ("received: ");
  7661.   print_packet (rs->buf);
  7662.   puts_filtered ("\n");
  7663. }

  7664. #if 0
  7665. /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */

  7666. static void display_thread_info (struct gdb_ext_thread_info *info);

  7667. static void threadset_test_cmd (char *cmd, int tty);

  7668. static void threadalive_test (char *cmd, int tty);

  7669. static void threadlist_test_cmd (char *cmd, int tty);

  7670. int get_and_display_threadinfo (threadref *ref);

  7671. static void threadinfo_test_cmd (char *cmd, int tty);

  7672. static int thread_display_step (threadref *ref, void *context);

  7673. static void threadlist_update_test_cmd (char *cmd, int tty);

  7674. static void init_remote_threadtests (void);

  7675. #define SAMPLE_THREAD  0x05060708        /* Truncated 64 bit threadid.  */

  7676. static void
  7677. threadset_test_cmd (char *cmd, int tty)
  7678. {
  7679.   int sample_thread = SAMPLE_THREAD;

  7680.   printf_filtered (_("Remote threadset test\n"));
  7681.   set_general_thread (sample_thread);
  7682. }


  7683. static void
  7684. threadalive_test (char *cmd, int tty)
  7685. {
  7686.   int sample_thread = SAMPLE_THREAD;
  7687.   int pid = ptid_get_pid (inferior_ptid);
  7688.   ptid_t ptid = ptid_build (pid, sample_thread, 0);

  7689.   if (remote_thread_alive (ptid))
  7690.     printf_filtered ("PASS: Thread alive test\n");
  7691.   else
  7692.     printf_filtered ("FAIL: Thread alive test\n");
  7693. }

  7694. void output_threadid (char *title, threadref *ref);

  7695. void
  7696. output_threadid (char *title, threadref *ref)
  7697. {
  7698.   char hexid[20];

  7699.   pack_threadid (&hexid[0], ref);        /* Convert threead id into hex.  */
  7700.   hexid[16] = 0;
  7701.   printf_filtered ("%s  %s\n", title, (&hexid[0]));
  7702. }

  7703. static void
  7704. threadlist_test_cmd (char *cmd, int tty)
  7705. {
  7706.   int startflag = 1;
  7707.   threadref nextthread;
  7708.   int done, result_count;
  7709.   threadref threadlist[3];

  7710.   printf_filtered ("Remote Threadlist test\n");
  7711.   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
  7712.                               &result_count, &threadlist[0]))
  7713.     printf_filtered ("FAIL: threadlist test\n");
  7714.   else
  7715.     {
  7716.       threadref *scan = threadlist;
  7717.       threadref *limit = scan + result_count;

  7718.       while (scan < limit)
  7719.         output_threadid (" thread ", scan++);
  7720.     }
  7721. }

  7722. void
  7723. display_thread_info (struct gdb_ext_thread_info *info)
  7724. {
  7725.   output_threadid ("Threadid: ", &info->threadid);
  7726.   printf_filtered ("Name: %s\n ", info->shortname);
  7727.   printf_filtered ("State: %s\n", info->display);
  7728.   printf_filtered ("other: %s\n\n", info->more_display);
  7729. }

  7730. int
  7731. get_and_display_threadinfo (threadref *ref)
  7732. {
  7733.   int result;
  7734.   int set;
  7735.   struct gdb_ext_thread_info threadinfo;

  7736.   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
  7737.     | TAG_MOREDISPLAY | TAG_DISPLAY;
  7738.   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
  7739.     display_thread_info (&threadinfo);
  7740.   return result;
  7741. }

  7742. static void
  7743. threadinfo_test_cmd (char *cmd, int tty)
  7744. {
  7745.   int athread = SAMPLE_THREAD;
  7746.   threadref thread;
  7747.   int set;

  7748.   int_to_threadref (&thread, athread);
  7749.   printf_filtered ("Remote Threadinfo test\n");
  7750.   if (!get_and_display_threadinfo (&thread))
  7751.     printf_filtered ("FAIL cannot get thread info\n");
  7752. }

  7753. static int
  7754. thread_display_step (threadref *ref, void *context)
  7755. {
  7756.   /* output_threadid(" threadstep ",ref); *//* simple test */
  7757.   return get_and_display_threadinfo (ref);
  7758. }

  7759. static void
  7760. threadlist_update_test_cmd (char *cmd, int tty)
  7761. {
  7762.   printf_filtered ("Remote Threadlist update test\n");
  7763.   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
  7764. }

  7765. static void
  7766. init_remote_threadtests (void)
  7767. {
  7768.   add_com ("tlist", class_obscure, threadlist_test_cmd,
  7769.            _("Fetch and print the remote list of "
  7770.              "thread identifiers, one pkt only"));
  7771.   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
  7772.            _("Fetch and display info about one thread"));
  7773.   add_com ("tset", class_obscure, threadset_test_cmd,
  7774.            _("Test setting to a different thread"));
  7775.   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
  7776.            _("Iterate through updating all remote thread info"));
  7777.   add_com ("talive", class_obscure, threadalive_test,
  7778.            _(" Remote thread alive test "));
  7779. }

  7780. #endif /* 0 */

  7781. /* Convert a thread ID to a string.  Returns the string in a static
  7782.    buffer.  */

  7783. static char *
  7784. remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
  7785. {
  7786.   static char buf[64];
  7787.   struct remote_state *rs = get_remote_state ();

  7788.   if (ptid_equal (ptid, null_ptid))
  7789.     return normal_pid_to_str (ptid);
  7790.   else if (ptid_is_pid (ptid))
  7791.     {
  7792.       /* Printing an inferior target id.  */

  7793.       /* When multi-process extensions are off, there's no way in the
  7794.          remote protocol to know the remote process id, if there's any
  7795.          at all.  There's one exception --- when we're connected with
  7796.          target extended-remote, and we manually attached to a process
  7797.          with "attach PID".  We don't record anywhere a flag that
  7798.          allows us to distinguish that case from the case of
  7799.          connecting with extended-remote and the stub already being
  7800.          attached to a process, and reporting yes to qAttached, hence
  7801.          no smart special casing here.  */
  7802.       if (!remote_multi_process_p (rs))
  7803.         {
  7804.           xsnprintf (buf, sizeof buf, "Remote target");
  7805.           return buf;
  7806.         }

  7807.       return normal_pid_to_str (ptid);
  7808.     }
  7809.   else
  7810.     {
  7811.       if (ptid_equal (magic_null_ptid, ptid))
  7812.         xsnprintf (buf, sizeof buf, "Thread <main>");
  7813.       else if (rs->extended && remote_multi_process_p (rs))
  7814.         xsnprintf (buf, sizeof buf, "Thread %d.%ld",
  7815.                    ptid_get_pid (ptid), ptid_get_lwp (ptid));
  7816.       else
  7817.         xsnprintf (buf, sizeof buf, "Thread %ld",
  7818.                    ptid_get_lwp (ptid));
  7819.       return buf;
  7820.     }
  7821. }

  7822. /* Get the address of the thread local variable in OBJFILE which is
  7823.    stored at OFFSET within the thread local storage for thread PTID.  */

  7824. static CORE_ADDR
  7825. remote_get_thread_local_address (struct target_ops *ops,
  7826.                                  ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
  7827. {
  7828.   if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
  7829.     {
  7830.       struct remote_state *rs = get_remote_state ();
  7831.       char *p = rs->buf;
  7832.       char *endp = rs->buf + get_remote_packet_size ();
  7833.       enum packet_result result;

  7834.       strcpy (p, "qGetTLSAddr:");
  7835.       p += strlen (p);
  7836.       p = write_ptid (p, endp, ptid);
  7837.       *p++ = ',';
  7838.       p += hexnumstr (p, offset);
  7839.       *p++ = ',';
  7840.       p += hexnumstr (p, lm);
  7841.       *p++ = '\0';

  7842.       putpkt (rs->buf);
  7843.       getpkt (&rs->buf, &rs->buf_size, 0);
  7844.       result = packet_ok (rs->buf,
  7845.                           &remote_protocol_packets[PACKET_qGetTLSAddr]);
  7846.       if (result == PACKET_OK)
  7847.         {
  7848.           ULONGEST result;

  7849.           unpack_varlen_hex (rs->buf, &result);
  7850.           return result;
  7851.         }
  7852.       else if (result == PACKET_UNKNOWN)
  7853.         throw_error (TLS_GENERIC_ERROR,
  7854.                      _("Remote target doesn't support qGetTLSAddr packet"));
  7855.       else
  7856.         throw_error (TLS_GENERIC_ERROR,
  7857.                      _("Remote target failed to process qGetTLSAddr request"));
  7858.     }
  7859.   else
  7860.     throw_error (TLS_GENERIC_ERROR,
  7861.                  _("TLS not supported or disabled on this target"));
  7862.   /* Not reached.  */
  7863.   return 0;
  7864. }

  7865. /* Provide thread local base, i.e. Thread Information Block address.
  7866.    Returns 1 if ptid is found and thread_local_base is non zero.  */

  7867. static int
  7868. remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
  7869. {
  7870.   if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
  7871.     {
  7872.       struct remote_state *rs = get_remote_state ();
  7873.       char *p = rs->buf;
  7874.       char *endp = rs->buf + get_remote_packet_size ();
  7875.       enum packet_result result;

  7876.       strcpy (p, "qGetTIBAddr:");
  7877.       p += strlen (p);
  7878.       p = write_ptid (p, endp, ptid);
  7879.       *p++ = '\0';

  7880.       putpkt (rs->buf);
  7881.       getpkt (&rs->buf, &rs->buf_size, 0);
  7882.       result = packet_ok (rs->buf,
  7883.                           &remote_protocol_packets[PACKET_qGetTIBAddr]);
  7884.       if (result == PACKET_OK)
  7885.         {
  7886.           ULONGEST result;

  7887.           unpack_varlen_hex (rs->buf, &result);
  7888.           if (addr)
  7889.             *addr = (CORE_ADDR) result;
  7890.           return 1;
  7891.         }
  7892.       else if (result == PACKET_UNKNOWN)
  7893.         error (_("Remote target doesn't support qGetTIBAddr packet"));
  7894.       else
  7895.         error (_("Remote target failed to process qGetTIBAddr request"));
  7896.     }
  7897.   else
  7898.     error (_("qGetTIBAddr not supported or disabled on this target"));
  7899.   /* Not reached.  */
  7900.   return 0;
  7901. }

  7902. /* Support for inferring a target description based on the current
  7903.    architecture and the size of a 'g' packet.  While the 'g' packet
  7904.    can have any size (since optional registers can be left off the
  7905.    end), some sizes are easily recognizable given knowledge of the
  7906.    approximate architecture.  */

  7907. struct remote_g_packet_guess
  7908. {
  7909.   int bytes;
  7910.   const struct target_desc *tdesc;
  7911. };
  7912. typedef struct remote_g_packet_guess remote_g_packet_guess_s;
  7913. DEF_VEC_O(remote_g_packet_guess_s);

  7914. struct remote_g_packet_data
  7915. {
  7916.   VEC(remote_g_packet_guess_s) *guesses;
  7917. };

  7918. static struct gdbarch_data *remote_g_packet_data_handle;

  7919. static void *
  7920. remote_g_packet_data_init (struct obstack *obstack)
  7921. {
  7922.   return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
  7923. }

  7924. void
  7925. register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
  7926.                                 const struct target_desc *tdesc)
  7927. {
  7928.   struct remote_g_packet_data *data
  7929.     = gdbarch_data (gdbarch, remote_g_packet_data_handle);
  7930.   struct remote_g_packet_guess new_guess, *guess;
  7931.   int ix;

  7932.   gdb_assert (tdesc != NULL);

  7933.   for (ix = 0;
  7934.        VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
  7935.        ix++)
  7936.     if (guess->bytes == bytes)
  7937.       internal_error (__FILE__, __LINE__,
  7938.                       _("Duplicate g packet description added for size %d"),
  7939.                       bytes);

  7940.   new_guess.bytes = bytes;
  7941.   new_guess.tdesc = tdesc;
  7942.   VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
  7943. }

  7944. /* Return 1 if remote_read_description would do anything on this target
  7945.    and architecture, 0 otherwise.  */

  7946. static int
  7947. remote_read_description_p (struct target_ops *target)
  7948. {
  7949.   struct remote_g_packet_data *data
  7950.     = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);

  7951.   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
  7952.     return 1;

  7953.   return 0;
  7954. }

  7955. static const struct target_desc *
  7956. remote_read_description (struct target_ops *target)
  7957. {
  7958.   struct remote_g_packet_data *data
  7959.     = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);

  7960.   /* Do not try this during initial connection, when we do not know
  7961.      whether there is a running but stopped thread.  */
  7962.   if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
  7963.     return target->beneath->to_read_description (target->beneath);

  7964.   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
  7965.     {
  7966.       struct remote_g_packet_guess *guess;
  7967.       int ix;
  7968.       int bytes = send_g_packet ();

  7969.       for (ix = 0;
  7970.            VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
  7971.            ix++)
  7972.         if (guess->bytes == bytes)
  7973.           return guess->tdesc;

  7974.       /* We discard the g packet.  A minor optimization would be to
  7975.          hold on to it, and fill the register cache once we have selected
  7976.          an architecture, but it's too tricky to do safely.  */
  7977.     }

  7978.   return target->beneath->to_read_description (target->beneath);
  7979. }

  7980. /* Remote file transfer support.  This is host-initiated I/O, not
  7981.    target-initiated; for target-initiated, see remote-fileio.c.  */

  7982. /* If *LEFT is at least the length of STRING, copy STRING to
  7983.    *BUFFER, update *BUFFER to point to the new end of the buffer, and
  7984.    decrease *LEFT.  Otherwise raise an error.  */

  7985. static void
  7986. remote_buffer_add_string (char **buffer, int *left, char *string)
  7987. {
  7988.   int len = strlen (string);

  7989.   if (len > *left)
  7990.     error (_("Packet too long for target."));

  7991.   memcpy (*buffer, string, len);
  7992.   *buffer += len;
  7993.   *left -= len;

  7994.   /* NUL-terminate the buffer as a convenience, if there is
  7995.      room.  */
  7996.   if (*left)
  7997.     **buffer = '\0';
  7998. }

  7999. /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
  8000.    *BUFFER, update *BUFFER to point to the new end of the buffer, and
  8001.    decrease *LEFT.  Otherwise raise an error.  */

  8002. static void
  8003. remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
  8004.                          int len)
  8005. {
  8006.   if (2 * len > *left)
  8007.     error (_("Packet too long for target."));

  8008.   bin2hex (bytes, *buffer, len);
  8009.   *buffer += 2 * len;
  8010.   *left -= 2 * len;

  8011.   /* NUL-terminate the buffer as a convenience, if there is
  8012.      room.  */
  8013.   if (*left)
  8014.     **buffer = '\0';
  8015. }

  8016. /* If *LEFT is large enough, convert VALUE to hex and add it to
  8017.    *BUFFER, update *BUFFER to point to the new end of the buffer, and
  8018.    decrease *LEFT.  Otherwise raise an error.  */

  8019. static void
  8020. remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
  8021. {
  8022.   int len = hexnumlen (value);

  8023.   if (len > *left)
  8024.     error (_("Packet too long for target."));

  8025.   hexnumstr (*buffer, value);
  8026.   *buffer += len;
  8027.   *left -= len;

  8028.   /* NUL-terminate the buffer as a convenience, if there is
  8029.      room.  */
  8030.   if (*left)
  8031.     **buffer = '\0';
  8032. }

  8033. /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
  8034.    value, *REMOTE_ERRNO to the remote error number or zero if none
  8035.    was included, and *ATTACHMENT to point to the start of the annex
  8036.    if any.  The length of the packet isn't needed here; there may
  8037.    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.

  8038.    Return 0 if the packet could be parsed, -1 if it could not.  If
  8039.    -1 is returned, the other variables may not be initialized.  */

  8040. static int
  8041. remote_hostio_parse_result (char *buffer, int *retcode,
  8042.                             int *remote_errno, char **attachment)
  8043. {
  8044.   char *p, *p2;

  8045.   *remote_errno = 0;
  8046.   *attachment = NULL;

  8047.   if (buffer[0] != 'F')
  8048.     return -1;

  8049.   errno = 0;
  8050.   *retcode = strtol (&buffer[1], &p, 16);
  8051.   if (errno != 0 || p == &buffer[1])
  8052.     return -1;

  8053.   /* Check for ",errno".  */
  8054.   if (*p == ',')
  8055.     {
  8056.       errno = 0;
  8057.       *remote_errno = strtol (p + 1, &p2, 16);
  8058.       if (errno != 0 || p + 1 == p2)
  8059.         return -1;
  8060.       p = p2;
  8061.     }

  8062.   /* Check for ";attachment".  If there is no attachment, the
  8063.      packet should end here.  */
  8064.   if (*p == ';')
  8065.     {
  8066.       *attachment = p + 1;
  8067.       return 0;
  8068.     }
  8069.   else if (*p == '\0')
  8070.     return 0;
  8071.   else
  8072.     return -1;
  8073. }

  8074. /* Send a prepared I/O packet to the target and read its response.
  8075.    The prepared packet is in the global RS->BUF before this function
  8076.    is called, and the answer is there when we return.

  8077.    COMMAND_BYTES is the length of the request to send, which may include
  8078.    binary data.  WHICH_PACKET is the packet configuration to check
  8079.    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
  8080.    is set to the error number and -1 is returned.  Otherwise the value
  8081.    returned by the function is returned.

  8082.    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
  8083.    attachment is expected; an error will be reported if there's a
  8084.    mismatch.  If one is found, *ATTACHMENT will be set to point into
  8085.    the packet buffer and *ATTACHMENT_LEN will be set to the
  8086.    attachment's length.  */

  8087. static int
  8088. remote_hostio_send_command (int command_bytes, int which_packet,
  8089.                             int *remote_errno, char **attachment,
  8090.                             int *attachment_len)
  8091. {
  8092.   struct remote_state *rs = get_remote_state ();
  8093.   int ret, bytes_read;
  8094.   char *attachment_tmp;

  8095.   if (!rs->remote_desc
  8096.       || packet_support (which_packet) == PACKET_DISABLE)
  8097.     {
  8098.       *remote_errno = FILEIO_ENOSYS;
  8099.       return -1;
  8100.     }

  8101.   putpkt_binary (rs->buf, command_bytes);
  8102.   bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);

  8103.   /* If it timed out, something is wrong.  Don't try to parse the
  8104.      buffer.  */
  8105.   if (bytes_read < 0)
  8106.     {
  8107.       *remote_errno = FILEIO_EINVAL;
  8108.       return -1;
  8109.     }

  8110.   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
  8111.     {
  8112.     case PACKET_ERROR:
  8113.       *remote_errno = FILEIO_EINVAL;
  8114.       return -1;
  8115.     case PACKET_UNKNOWN:
  8116.       *remote_errno = FILEIO_ENOSYS;
  8117.       return -1;
  8118.     case PACKET_OK:
  8119.       break;
  8120.     }

  8121.   if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
  8122.                                   &attachment_tmp))
  8123.     {
  8124.       *remote_errno = FILEIO_EINVAL;
  8125.       return -1;
  8126.     }

  8127.   /* Make sure we saw an attachment if and only if we expected one.  */
  8128.   if ((attachment_tmp == NULL && attachment != NULL)
  8129.       || (attachment_tmp != NULL && attachment == NULL))
  8130.     {
  8131.       *remote_errno = FILEIO_EINVAL;
  8132.       return -1;
  8133.     }

  8134.   /* If an attachment was found, it must point into the packet buffer;
  8135.      work out how many bytes there were.  */
  8136.   if (attachment_tmp != NULL)
  8137.     {
  8138.       *attachment = attachment_tmp;
  8139.       *attachment_len = bytes_read - (*attachment - rs->buf);
  8140.     }

  8141.   return ret;
  8142. }

  8143. /* Open FILENAME on the remote target, using FLAGS and MODE.  Return a
  8144.    remote file descriptor, or -1 if an error occurs (and set
  8145.    *REMOTE_ERRNO).  */

  8146. static int
  8147. remote_hostio_open (struct target_ops *self,
  8148.                     const char *filename, int flags, int mode,
  8149.                     int *remote_errno)
  8150. {
  8151.   struct remote_state *rs = get_remote_state ();
  8152.   char *p = rs->buf;
  8153.   int left = get_remote_packet_size () - 1;

  8154.   remote_buffer_add_string (&p, &left, "vFile:open:");

  8155.   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
  8156.                            strlen (filename));
  8157.   remote_buffer_add_string (&p, &left, ",");

  8158.   remote_buffer_add_int (&p, &left, flags);
  8159.   remote_buffer_add_string (&p, &left, ",");

  8160.   remote_buffer_add_int (&p, &left, mode);

  8161.   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
  8162.                                      remote_errno, NULL, NULL);
  8163. }

  8164. /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
  8165.    Return the number of bytes written, or -1 if an error occurs (and
  8166.    set *REMOTE_ERRNO).  */

  8167. static int
  8168. remote_hostio_pwrite (struct target_ops *self,
  8169.                       int fd, const gdb_byte *write_buf, int len,
  8170.                       ULONGEST offset, int *remote_errno)
  8171. {
  8172.   struct remote_state *rs = get_remote_state ();
  8173.   char *p = rs->buf;
  8174.   int left = get_remote_packet_size ();
  8175.   int out_len;

  8176.   remote_buffer_add_string (&p, &left, "vFile:pwrite:");

  8177.   remote_buffer_add_int (&p, &left, fd);
  8178.   remote_buffer_add_string (&p, &left, ",");

  8179.   remote_buffer_add_int (&p, &left, offset);
  8180.   remote_buffer_add_string (&p, &left, ",");

  8181.   p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
  8182.                              get_remote_packet_size () - (p - rs->buf));

  8183.   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
  8184.                                      remote_errno, NULL, NULL);
  8185. }

  8186. /* Read up to LEN bytes FD on the remote target into READ_BUF
  8187.    Return the number of bytes read, or -1 if an error occurs (and
  8188.    set *REMOTE_ERRNO).  */

  8189. static int
  8190. remote_hostio_pread (struct target_ops *self,
  8191.                      int fd, gdb_byte *read_buf, int len,
  8192.                      ULONGEST offset, int *remote_errno)
  8193. {
  8194.   struct remote_state *rs = get_remote_state ();
  8195.   char *p = rs->buf;
  8196.   char *attachment;
  8197.   int left = get_remote_packet_size ();
  8198.   int ret, attachment_len;
  8199.   int read_len;

  8200.   remote_buffer_add_string (&p, &left, "vFile:pread:");

  8201.   remote_buffer_add_int (&p, &left, fd);
  8202.   remote_buffer_add_string (&p, &left, ",");

  8203.   remote_buffer_add_int (&p, &left, len);
  8204.   remote_buffer_add_string (&p, &left, ",");

  8205.   remote_buffer_add_int (&p, &left, offset);

  8206.   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
  8207.                                     remote_errno, &attachment,
  8208.                                     &attachment_len);

  8209.   if (ret < 0)
  8210.     return ret;

  8211.   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
  8212.                                     read_buf, len);
  8213.   if (read_len != ret)
  8214.     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);

  8215.   return ret;
  8216. }

  8217. /* Close FD on the remote target.  Return 0, or -1 if an error occurs
  8218.    (and set *REMOTE_ERRNO).  */

  8219. static int
  8220. remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
  8221. {
  8222.   struct remote_state *rs = get_remote_state ();
  8223.   char *p = rs->buf;
  8224.   int left = get_remote_packet_size () - 1;

  8225.   remote_buffer_add_string (&p, &left, "vFile:close:");

  8226.   remote_buffer_add_int (&p, &left, fd);

  8227.   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
  8228.                                      remote_errno, NULL, NULL);
  8229. }

  8230. /* Unlink FILENAME on the remote target.  Return 0, or -1 if an error
  8231.    occurs (and set *REMOTE_ERRNO).  */

  8232. static int
  8233. remote_hostio_unlink (struct target_ops *self,
  8234.                       const char *filename, int *remote_errno)
  8235. {
  8236.   struct remote_state *rs = get_remote_state ();
  8237.   char *p = rs->buf;
  8238.   int left = get_remote_packet_size () - 1;

  8239.   remote_buffer_add_string (&p, &left, "vFile:unlink:");

  8240.   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
  8241.                            strlen (filename));

  8242.   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
  8243.                                      remote_errno, NULL, NULL);
  8244. }

  8245. /* Read value of symbolic link FILENAME on the remote target.  Return
  8246.    a null-terminated string allocated via xmalloc, or NULL if an error
  8247.    occurs (and set *REMOTE_ERRNO).  */

  8248. static char *
  8249. remote_hostio_readlink (struct target_ops *self,
  8250.                         const char *filename, int *remote_errno)
  8251. {
  8252.   struct remote_state *rs = get_remote_state ();
  8253.   char *p = rs->buf;
  8254.   char *attachment;
  8255.   int left = get_remote_packet_size ();
  8256.   int len, attachment_len;
  8257.   int read_len;
  8258.   char *ret;

  8259.   remote_buffer_add_string (&p, &left, "vFile:readlink:");

  8260.   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
  8261.                            strlen (filename));

  8262.   len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
  8263.                                     remote_errno, &attachment,
  8264.                                     &attachment_len);

  8265.   if (len < 0)
  8266.     return NULL;

  8267.   ret = xmalloc (len + 1);

  8268.   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
  8269.                                     (gdb_byte *) ret, len);
  8270.   if (read_len != len)
  8271.     error (_("Readlink returned %d, but %d bytes."), len, read_len);

  8272.   ret[len] = '\0';
  8273.   return ret;
  8274. }

  8275. static int
  8276. remote_fileio_errno_to_host (int errnum)
  8277. {
  8278.   switch (errnum)
  8279.     {
  8280.       case FILEIO_EPERM:
  8281.         return EPERM;
  8282.       case FILEIO_ENOENT:
  8283.         return ENOENT;
  8284.       case FILEIO_EINTR:
  8285.         return EINTR;
  8286.       case FILEIO_EIO:
  8287.         return EIO;
  8288.       case FILEIO_EBADF:
  8289.         return EBADF;
  8290.       case FILEIO_EACCES:
  8291.         return EACCES;
  8292.       case FILEIO_EFAULT:
  8293.         return EFAULT;
  8294.       case FILEIO_EBUSY:
  8295.         return EBUSY;
  8296.       case FILEIO_EEXIST:
  8297.         return EEXIST;
  8298.       case FILEIO_ENODEV:
  8299.         return ENODEV;
  8300.       case FILEIO_ENOTDIR:
  8301.         return ENOTDIR;
  8302.       case FILEIO_EISDIR:
  8303.         return EISDIR;
  8304.       case FILEIO_EINVAL:
  8305.         return EINVAL;
  8306.       case FILEIO_ENFILE:
  8307.         return ENFILE;
  8308.       case FILEIO_EMFILE:
  8309.         return EMFILE;
  8310.       case FILEIO_EFBIG:
  8311.         return EFBIG;
  8312.       case FILEIO_ENOSPC:
  8313.         return ENOSPC;
  8314.       case FILEIO_ESPIPE:
  8315.         return ESPIPE;
  8316.       case FILEIO_EROFS:
  8317.         return EROFS;
  8318.       case FILEIO_ENOSYS:
  8319.         return ENOSYS;
  8320.       case FILEIO_ENAMETOOLONG:
  8321.         return ENAMETOOLONG;
  8322.     }
  8323.   return -1;
  8324. }

  8325. static char *
  8326. remote_hostio_error (int errnum)
  8327. {
  8328.   int host_error = remote_fileio_errno_to_host (errnum);

  8329.   if (host_error == -1)
  8330.     error (_("Unknown remote I/O error %d"), errnum);
  8331.   else
  8332.     error (_("Remote I/O error: %s"), safe_strerror (host_error));
  8333. }

  8334. static void
  8335. remote_hostio_close_cleanup (void *opaque)
  8336. {
  8337.   int fd = *(int *) opaque;
  8338.   int remote_errno;

  8339.   remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
  8340. }


  8341. static void *
  8342. remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
  8343. {
  8344.   const char *filename = bfd_get_filename (abfd);
  8345.   int fd, remote_errno;
  8346.   int *stream;

  8347.   gdb_assert (remote_filename_p (filename));

  8348.   fd = remote_hostio_open (find_target_at (process_stratum),
  8349.                            filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
  8350.   if (fd == -1)
  8351.     {
  8352.       errno = remote_fileio_errno_to_host (remote_errno);
  8353.       bfd_set_error (bfd_error_system_call);
  8354.       return NULL;
  8355.     }

  8356.   stream = xmalloc (sizeof (int));
  8357.   *stream = fd;
  8358.   return stream;
  8359. }

  8360. static int
  8361. remote_bfd_iovec_close (struct bfd *abfd, void *stream)
  8362. {
  8363.   int fd = *(int *)stream;
  8364.   int remote_errno;

  8365.   xfree (stream);

  8366.   /* Ignore errors on close; these may happen if the remote
  8367.      connection was already torn down.  */
  8368.   remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);

  8369.   /* Zero means success.  */
  8370.   return 0;
  8371. }

  8372. static file_ptr
  8373. remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
  8374.                         file_ptr nbytes, file_ptr offset)
  8375. {
  8376.   int fd = *(int *)stream;
  8377.   int remote_errno;
  8378.   file_ptr pos, bytes;

  8379.   pos = 0;
  8380.   while (nbytes > pos)
  8381.     {
  8382.       bytes = remote_hostio_pread (find_target_at (process_stratum),
  8383.                                    fd, (gdb_byte *) buf + pos, nbytes - pos,
  8384.                                    offset + pos, &remote_errno);
  8385.       if (bytes == 0)
  8386.         /* Success, but no bytes, means end-of-file.  */
  8387.         break;
  8388.       if (bytes == -1)
  8389.         {
  8390.           errno = remote_fileio_errno_to_host (remote_errno);
  8391.           bfd_set_error (bfd_error_system_call);
  8392.           return -1;
  8393.         }

  8394.       pos += bytes;
  8395.     }

  8396.   return pos;
  8397. }

  8398. static int
  8399. remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
  8400. {
  8401.   /* FIXME: We should probably implement remote_hostio_stat.  */
  8402.   sb->st_size = INT_MAX;
  8403.   return 0;
  8404. }

  8405. int
  8406. remote_filename_p (const char *filename)
  8407. {
  8408.   return strncmp (filename,
  8409.                   REMOTE_SYSROOT_PREFIX,
  8410.                   sizeof (REMOTE_SYSROOT_PREFIX) - 1) == 0;
  8411. }

  8412. bfd *
  8413. remote_bfd_open (const char *remote_file, const char *target)
  8414. {
  8415.   bfd *abfd = gdb_bfd_openr_iovec (remote_file, target,
  8416.                                    remote_bfd_iovec_open, NULL,
  8417.                                    remote_bfd_iovec_pread,
  8418.                                    remote_bfd_iovec_close,
  8419.                                    remote_bfd_iovec_stat);

  8420.   return abfd;
  8421. }

  8422. void
  8423. remote_file_put (const char *local_file, const char *remote_file, int from_tty)
  8424. {
  8425.   struct cleanup *back_to, *close_cleanup;
  8426.   int retcode, fd, remote_errno, bytes, io_size;
  8427.   FILE *file;
  8428.   gdb_byte *buffer;
  8429.   int bytes_in_buffer;
  8430.   int saw_eof;
  8431.   ULONGEST offset;
  8432.   struct remote_state *rs = get_remote_state ();

  8433.   if (!rs->remote_desc)
  8434.     error (_("command can only be used with remote target"));

  8435.   file = gdb_fopen_cloexec (local_file, "rb");
  8436.   if (file == NULL)
  8437.     perror_with_name (local_file);
  8438.   back_to = make_cleanup_fclose (file);

  8439.   fd = remote_hostio_open (find_target_at (process_stratum),
  8440.                            remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
  8441.                                          | FILEIO_O_TRUNC),
  8442.                            0700, &remote_errno);
  8443.   if (fd == -1)
  8444.     remote_hostio_error (remote_errno);

  8445.   /* Send up to this many bytes at once.  They won't all fit in the
  8446.      remote packet limit, so we'll transfer slightly fewer.  */
  8447.   io_size = get_remote_packet_size ();
  8448.   buffer = xmalloc (io_size);
  8449.   make_cleanup (xfree, buffer);

  8450.   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);

  8451.   bytes_in_buffer = 0;
  8452.   saw_eof = 0;
  8453.   offset = 0;
  8454.   while (bytes_in_buffer || !saw_eof)
  8455.     {
  8456.       if (!saw_eof)
  8457.         {
  8458.           bytes = fread (buffer + bytes_in_buffer, 1,
  8459.                          io_size - bytes_in_buffer,
  8460.                          file);
  8461.           if (bytes == 0)
  8462.             {
  8463.               if (ferror (file))
  8464.                 error (_("Error reading %s."), local_file);
  8465.               else
  8466.                 {
  8467.                   /* EOF.  Unless there is something still in the
  8468.                      buffer from the last iteration, we are done.  */
  8469.                   saw_eof = 1;
  8470.                   if (bytes_in_buffer == 0)
  8471.                     break;
  8472.                 }
  8473.             }
  8474.         }
  8475.       else
  8476.         bytes = 0;

  8477.       bytes += bytes_in_buffer;
  8478.       bytes_in_buffer = 0;

  8479.       retcode = remote_hostio_pwrite (find_target_at (process_stratum),
  8480.                                       fd, buffer, bytes,
  8481.                                       offset, &remote_errno);

  8482.       if (retcode < 0)
  8483.         remote_hostio_error (remote_errno);
  8484.       else if (retcode == 0)
  8485.         error (_("Remote write of %d bytes returned 0!"), bytes);
  8486.       else if (retcode < bytes)
  8487.         {
  8488.           /* Short write.  Save the rest of the read data for the next
  8489.              write.  */
  8490.           bytes_in_buffer = bytes - retcode;
  8491.           memmove (buffer, buffer + retcode, bytes_in_buffer);
  8492.         }

  8493.       offset += retcode;
  8494.     }

  8495.   discard_cleanups (close_cleanup);
  8496.   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
  8497.     remote_hostio_error (remote_errno);

  8498.   if (from_tty)
  8499.     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
  8500.   do_cleanups (back_to);
  8501. }

  8502. void
  8503. remote_file_get (const char *remote_file, const char *local_file, int from_tty)
  8504. {
  8505.   struct cleanup *back_to, *close_cleanup;
  8506.   int fd, remote_errno, bytes, io_size;
  8507.   FILE *file;
  8508.   gdb_byte *buffer;
  8509.   ULONGEST offset;
  8510.   struct remote_state *rs = get_remote_state ();

  8511.   if (!rs->remote_desc)
  8512.     error (_("command can only be used with remote target"));

  8513.   fd = remote_hostio_open (find_target_at (process_stratum),
  8514.                            remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
  8515.   if (fd == -1)
  8516.     remote_hostio_error (remote_errno);

  8517.   file = gdb_fopen_cloexec (local_file, "wb");
  8518.   if (file == NULL)
  8519.     perror_with_name (local_file);
  8520.   back_to = make_cleanup_fclose (file);

  8521.   /* Send up to this many bytes at once.  They won't all fit in the
  8522.      remote packet limit, so we'll transfer slightly fewer.  */
  8523.   io_size = get_remote_packet_size ();
  8524.   buffer = xmalloc (io_size);
  8525.   make_cleanup (xfree, buffer);

  8526.   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);

  8527.   offset = 0;
  8528.   while (1)
  8529.     {
  8530.       bytes = remote_hostio_pread (find_target_at (process_stratum),
  8531.                                    fd, buffer, io_size, offset, &remote_errno);
  8532.       if (bytes == 0)
  8533.         /* Success, but no bytes, means end-of-file.  */
  8534.         break;
  8535.       if (bytes == -1)
  8536.         remote_hostio_error (remote_errno);

  8537.       offset += bytes;

  8538.       bytes = fwrite (buffer, 1, bytes, file);
  8539.       if (bytes == 0)
  8540.         perror_with_name (local_file);
  8541.     }

  8542.   discard_cleanups (close_cleanup);
  8543.   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
  8544.     remote_hostio_error (remote_errno);

  8545.   if (from_tty)
  8546.     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
  8547.   do_cleanups (back_to);
  8548. }

  8549. void
  8550. remote_file_delete (const char *remote_file, int from_tty)
  8551. {
  8552.   int retcode, remote_errno;
  8553.   struct remote_state *rs = get_remote_state ();

  8554.   if (!rs->remote_desc)
  8555.     error (_("command can only be used with remote target"));

  8556.   retcode = remote_hostio_unlink (find_target_at (process_stratum),
  8557.                                   remote_file, &remote_errno);
  8558.   if (retcode == -1)
  8559.     remote_hostio_error (remote_errno);

  8560.   if (from_tty)
  8561.     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
  8562. }

  8563. static void
  8564. remote_put_command (char *args, int from_tty)
  8565. {
  8566.   struct cleanup *back_to;
  8567.   char **argv;

  8568.   if (args == NULL)
  8569.     error_no_arg (_("file to put"));

  8570.   argv = gdb_buildargv (args);
  8571.   back_to = make_cleanup_freeargv (argv);
  8572.   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
  8573.     error (_("Invalid parameters to remote put"));

  8574.   remote_file_put (argv[0], argv[1], from_tty);

  8575.   do_cleanups (back_to);
  8576. }

  8577. static void
  8578. remote_get_command (char *args, int from_tty)
  8579. {
  8580.   struct cleanup *back_to;
  8581.   char **argv;

  8582.   if (args == NULL)
  8583.     error_no_arg (_("file to get"));

  8584.   argv = gdb_buildargv (args);
  8585.   back_to = make_cleanup_freeargv (argv);
  8586.   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
  8587.     error (_("Invalid parameters to remote get"));

  8588.   remote_file_get (argv[0], argv[1], from_tty);

  8589.   do_cleanups (back_to);
  8590. }

  8591. static void
  8592. remote_delete_command (char *args, int from_tty)
  8593. {
  8594.   struct cleanup *back_to;
  8595.   char **argv;

  8596.   if (args == NULL)
  8597.     error_no_arg (_("file to delete"));

  8598.   argv = gdb_buildargv (args);
  8599.   back_to = make_cleanup_freeargv (argv);
  8600.   if (argv[0] == NULL || argv[1] != NULL)
  8601.     error (_("Invalid parameters to remote delete"));

  8602.   remote_file_delete (argv[0], from_tty);

  8603.   do_cleanups (back_to);
  8604. }

  8605. static void
  8606. remote_command (char *args, int from_tty)
  8607. {
  8608.   help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
  8609. }

  8610. static int
  8611. remote_can_execute_reverse (struct target_ops *self)
  8612. {
  8613.   if (packet_support (PACKET_bs) == PACKET_ENABLE
  8614.       || packet_support (PACKET_bc) == PACKET_ENABLE)
  8615.     return 1;
  8616.   else
  8617.     return 0;
  8618. }

  8619. static int
  8620. remote_supports_non_stop (struct target_ops *self)
  8621. {
  8622.   return 1;
  8623. }

  8624. static int
  8625. remote_supports_disable_randomization (struct target_ops *self)
  8626. {
  8627.   /* Only supported in extended mode.  */
  8628.   return 0;
  8629. }

  8630. static int
  8631. remote_supports_multi_process (struct target_ops *self)
  8632. {
  8633.   struct remote_state *rs = get_remote_state ();

  8634.   /* Only extended-remote handles being attached to multiple
  8635.      processes, even though plain remote can use the multi-process
  8636.      thread id extensions, so that GDB knows the target process's
  8637.      PID.  */
  8638.   return rs->extended && remote_multi_process_p (rs);
  8639. }

  8640. static int
  8641. remote_supports_cond_tracepoints (void)
  8642. {
  8643.   return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
  8644. }

  8645. static int
  8646. remote_supports_cond_breakpoints (struct target_ops *self)
  8647. {
  8648.   return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
  8649. }

  8650. static int
  8651. remote_supports_fast_tracepoints (void)
  8652. {
  8653.   return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
  8654. }

  8655. static int
  8656. remote_supports_static_tracepoints (void)
  8657. {
  8658.   return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
  8659. }

  8660. static int
  8661. remote_supports_install_in_trace (void)
  8662. {
  8663.   return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
  8664. }

  8665. static int
  8666. remote_supports_enable_disable_tracepoint (struct target_ops *self)
  8667. {
  8668.   return (packet_support (PACKET_EnableDisableTracepoints_feature)
  8669.           == PACKET_ENABLE);
  8670. }

  8671. static int
  8672. remote_supports_string_tracing (struct target_ops *self)
  8673. {
  8674.   return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
  8675. }

  8676. static int
  8677. remote_can_run_breakpoint_commands (struct target_ops *self)
  8678. {
  8679.   return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
  8680. }

  8681. static void
  8682. remote_trace_init (struct target_ops *self)
  8683. {
  8684.   putpkt ("QTinit");
  8685.   remote_get_noisy_reply (&target_buf, &target_buf_size);
  8686.   if (strcmp (target_buf, "OK") != 0)
  8687.     error (_("Target does not support this command."));
  8688. }

  8689. static void free_actions_list (char **actions_list);
  8690. static void free_actions_list_cleanup_wrapper (void *);
  8691. static void
  8692. free_actions_list_cleanup_wrapper (void *al)
  8693. {
  8694.   free_actions_list (al);
  8695. }

  8696. static void
  8697. free_actions_list (char **actions_list)
  8698. {
  8699.   int ndx;

  8700.   if (actions_list == 0)
  8701.     return;

  8702.   for (ndx = 0; actions_list[ndx]; ndx++)
  8703.     xfree (actions_list[ndx]);

  8704.   xfree (actions_list);
  8705. }

  8706. /* Recursive routine to walk through command list including loops, and
  8707.    download packets for each command.  */

  8708. static void
  8709. remote_download_command_source (int num, ULONGEST addr,
  8710.                                 struct command_line *cmds)
  8711. {
  8712.   struct remote_state *rs = get_remote_state ();
  8713.   struct command_line *cmd;

  8714.   for (cmd = cmds; cmd; cmd = cmd->next)
  8715.     {
  8716.       QUIT;        /* Allow user to bail out with ^C.  */
  8717.       strcpy (rs->buf, "QTDPsrc:");
  8718.       encode_source_string (num, addr, "cmd", cmd->line,
  8719.                             rs->buf + strlen (rs->buf),
  8720.                             rs->buf_size - strlen (rs->buf));
  8721.       putpkt (rs->buf);
  8722.       remote_get_noisy_reply (&target_buf, &target_buf_size);
  8723.       if (strcmp (target_buf, "OK"))
  8724.         warning (_("Target does not support source download."));

  8725.       if (cmd->control_type == while_control
  8726.           || cmd->control_type == while_stepping_control)
  8727.         {
  8728.           remote_download_command_source (num, addr, *cmd->body_list);

  8729.           QUIT;        /* Allow user to bail out with ^C.  */
  8730.           strcpy (rs->buf, "QTDPsrc:");
  8731.           encode_source_string (num, addr, "cmd", "end",
  8732.                                 rs->buf + strlen (rs->buf),
  8733.                                 rs->buf_size - strlen (rs->buf));
  8734.           putpkt (rs->buf);
  8735.           remote_get_noisy_reply (&target_buf, &target_buf_size);
  8736.           if (strcmp (target_buf, "OK"))
  8737.             warning (_("Target does not support source download."));
  8738.         }
  8739.     }
  8740. }

  8741. static void
  8742. remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
  8743. {
  8744. #define BUF_SIZE 2048

  8745.   CORE_ADDR tpaddr;
  8746.   char addrbuf[40];
  8747.   char buf[BUF_SIZE];
  8748.   char **tdp_actions;
  8749.   char **stepping_actions;
  8750.   int ndx;
  8751.   struct cleanup *old_chain = NULL;
  8752.   struct agent_expr *aexpr;
  8753.   struct cleanup *aexpr_chain = NULL;
  8754.   char *pkt;
  8755.   struct breakpoint *b = loc->owner;
  8756.   struct tracepoint *t = (struct tracepoint *) b;

  8757.   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
  8758.   old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
  8759.                             tdp_actions);
  8760.   (void) make_cleanup (free_actions_list_cleanup_wrapper,
  8761.                        stepping_actions);

  8762.   tpaddr = loc->address;
  8763.   sprintf_vma (addrbuf, tpaddr);
  8764.   xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
  8765.              addrbuf, /* address */
  8766.              (b->enable_state == bp_enabled ? 'E' : 'D'),
  8767.              t->step_count, t->pass_count);
  8768.   /* Fast tracepoints are mostly handled by the target, but we can
  8769.      tell the target how big of an instruction block should be moved
  8770.      around.  */
  8771.   if (b->type == bp_fast_tracepoint)
  8772.     {
  8773.       /* Only test for support at download time; we may not know
  8774.          target capabilities at definition time.  */
  8775.       if (remote_supports_fast_tracepoints ())
  8776.         {
  8777.           int isize;

  8778.           if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
  8779.                                                 tpaddr, &isize, NULL))
  8780.             xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
  8781.                        isize);
  8782.           else
  8783.             /* If it passed validation at definition but fails now,
  8784.                something is very wrong.  */
  8785.             internal_error (__FILE__, __LINE__,
  8786.                             _("Fast tracepoint not "
  8787.                               "valid during download"));
  8788.         }
  8789.       else
  8790.         /* Fast tracepoints are functionally identical to regular
  8791.            tracepoints, so don't take lack of support as a reason to
  8792.            give up on the trace run.  */
  8793.         warning (_("Target does not support fast tracepoints, "
  8794.                    "downloading %d as regular tracepoint"), b->number);
  8795.     }
  8796.   else if (b->type == bp_static_tracepoint)
  8797.     {
  8798.       /* Only test for support at download time; we may not know
  8799.          target capabilities at definition time.  */
  8800.       if (remote_supports_static_tracepoints ())
  8801.         {
  8802.           struct static_tracepoint_marker marker;

  8803.           if (target_static_tracepoint_marker_at (tpaddr, &marker))
  8804.             strcat (buf, ":S");
  8805.           else
  8806.             error (_("Static tracepoint not valid during download"));
  8807.         }
  8808.       else
  8809.         /* Fast tracepoints are functionally identical to regular
  8810.            tracepoints, so don't take lack of support as a reason
  8811.            to give up on the trace run.  */
  8812.         error (_("Target does not support static tracepoints"));
  8813.     }
  8814.   /* If the tracepoint has a conditional, make it into an agent
  8815.      expression and append to the definition.  */
  8816.   if (loc->cond)
  8817.     {
  8818.       /* Only test support at download time, we may not know target
  8819.          capabilities at definition time.  */
  8820.       if (remote_supports_cond_tracepoints ())
  8821.         {
  8822.           aexpr = gen_eval_for_expr (tpaddr, loc->cond);
  8823.           aexpr_chain = make_cleanup_free_agent_expr (aexpr);
  8824.           xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
  8825.                      aexpr->len);
  8826.           pkt = buf + strlen (buf);
  8827.           for (ndx = 0; ndx < aexpr->len; ++ndx)
  8828.             pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
  8829.           *pkt = '\0';
  8830.           do_cleanups (aexpr_chain);
  8831.         }
  8832.       else
  8833.         warning (_("Target does not support conditional tracepoints, "
  8834.                    "ignoring tp %d cond"), b->number);
  8835.     }

  8836.   if (b->commands || *default_collect)
  8837.     strcat (buf, "-");
  8838.   putpkt (buf);
  8839.   remote_get_noisy_reply (&target_buf, &target_buf_size);
  8840.   if (strcmp (target_buf, "OK"))
  8841.     error (_("Target does not support tracepoints."));

  8842.   /* do_single_steps (t); */
  8843.   if (tdp_actions)
  8844.     {
  8845.       for (ndx = 0; tdp_actions[ndx]; ndx++)
  8846.         {
  8847.           QUIT;        /* Allow user to bail out with ^C.  */
  8848.           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
  8849.                      b->number, addrbuf, /* address */
  8850.                      tdp_actions[ndx],
  8851.                      ((tdp_actions[ndx + 1] || stepping_actions)
  8852.                       ? '-' : 0));
  8853.           putpkt (buf);
  8854.           remote_get_noisy_reply (&target_buf,
  8855.                                   &target_buf_size);
  8856.           if (strcmp (target_buf, "OK"))
  8857.             error (_("Error on target while setting tracepoints."));
  8858.         }
  8859.     }
  8860.   if (stepping_actions)
  8861.     {
  8862.       for (ndx = 0; stepping_actions[ndx]; ndx++)
  8863.         {
  8864.           QUIT;        /* Allow user to bail out with ^C.  */
  8865.           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
  8866.                      b->number, addrbuf, /* address */
  8867.                      ((ndx == 0) ? "S" : ""),
  8868.                      stepping_actions[ndx],
  8869.                      (stepping_actions[ndx + 1] ? "-" : ""));
  8870.           putpkt (buf);
  8871.           remote_get_noisy_reply (&target_buf,
  8872.                                   &target_buf_size);
  8873.           if (strcmp (target_buf, "OK"))
  8874.             error (_("Error on target while setting tracepoints."));
  8875.         }
  8876.     }

  8877.   if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
  8878.     {
  8879.       if (b->addr_string)
  8880.         {
  8881.           strcpy (buf, "QTDPsrc:");
  8882.           encode_source_string (b->number, loc->address,
  8883.                                 "at", b->addr_string, buf + strlen (buf),
  8884.                                 2048 - strlen (buf));

  8885.           putpkt (buf);
  8886.           remote_get_noisy_reply (&target_buf, &target_buf_size);
  8887.           if (strcmp (target_buf, "OK"))
  8888.             warning (_("Target does not support source download."));
  8889.         }
  8890.       if (b->cond_string)
  8891.         {
  8892.           strcpy (buf, "QTDPsrc:");
  8893.           encode_source_string (b->number, loc->address,
  8894.                                 "cond", b->cond_string, buf + strlen (buf),
  8895.                                 2048 - strlen (buf));
  8896.           putpkt (buf);
  8897.           remote_get_noisy_reply (&target_buf, &target_buf_size);
  8898.           if (strcmp (target_buf, "OK"))
  8899.             warning (_("Target does not support source download."));
  8900.         }
  8901.       remote_download_command_source (b->number, loc->address,
  8902.                                       breakpoint_commands (b));
  8903.     }

  8904.   do_cleanups (old_chain);
  8905. }

  8906. static int
  8907. remote_can_download_tracepoint (struct target_ops *self)
  8908. {
  8909.   struct remote_state *rs = get_remote_state ();
  8910.   struct trace_status *ts;
  8911.   int status;

  8912.   /* Don't try to install tracepoints until we've relocated our
  8913.      symbols, and fetched and merged the target's tracepoint list with
  8914.      ours.  */
  8915.   if (rs->starting_up)
  8916.     return 0;

  8917.   ts = current_trace_status ();
  8918.   status = remote_get_trace_status (self, ts);

  8919.   if (status == -1 || !ts->running_known || !ts->running)
  8920.     return 0;

  8921.   /* If we are in a tracing experiment, but remote stub doesn't support
  8922.      installing tracepoint in trace, we have to return.  */
  8923.   if (!remote_supports_install_in_trace ())
  8924.     return 0;

  8925.   return 1;
  8926. }


  8927. static void
  8928. remote_download_trace_state_variable (struct target_ops *self,
  8929.                                       struct trace_state_variable *tsv)
  8930. {
  8931.   struct remote_state *rs = get_remote_state ();
  8932.   char *p;

  8933.   xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
  8934.              tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
  8935.              tsv->builtin);
  8936.   p = rs->buf + strlen (rs->buf);
  8937.   if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
  8938.     error (_("Trace state variable name too long for tsv definition packet"));
  8939.   p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
  8940.   *p++ = '\0';
  8941.   putpkt (rs->buf);
  8942.   remote_get_noisy_reply (&target_buf, &target_buf_size);
  8943.   if (*target_buf == '\0')
  8944.     error (_("Target does not support this command."));
  8945.   if (strcmp (target_buf, "OK") != 0)
  8946.     error (_("Error on target while downloading trace state variable."));
  8947. }

  8948. static void
  8949. remote_enable_tracepoint (struct target_ops *self,
  8950.                           struct bp_location *location)
  8951. {
  8952.   struct remote_state *rs = get_remote_state ();
  8953.   char addr_buf[40];

  8954.   sprintf_vma (addr_buf, location->address);
  8955.   xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
  8956.              location->owner->number, addr_buf);
  8957.   putpkt (rs->buf);
  8958.   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
  8959.   if (*rs->buf == '\0')
  8960.     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
  8961.   if (strcmp (rs->buf, "OK") != 0)
  8962.     error (_("Error on target while enabling tracepoint."));
  8963. }

  8964. static void
  8965. remote_disable_tracepoint (struct target_ops *self,
  8966.                            struct bp_location *location)
  8967. {
  8968.   struct remote_state *rs = get_remote_state ();
  8969.   char addr_buf[40];

  8970.   sprintf_vma (addr_buf, location->address);
  8971.   xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
  8972.              location->owner->number, addr_buf);
  8973.   putpkt (rs->buf);
  8974.   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
  8975.   if (*rs->buf == '\0')
  8976.     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
  8977.   if (strcmp (rs->buf, "OK") != 0)
  8978.     error (_("Error on target while disabling tracepoint."));
  8979. }

  8980. static void
  8981. remote_trace_set_readonly_regions (struct target_ops *self)
  8982. {
  8983.   asection *s;
  8984.   bfd *abfd = NULL;
  8985.   bfd_size_type size;
  8986.   bfd_vma vma;
  8987.   int anysecs = 0;
  8988.   int offset = 0;

  8989.   if (!exec_bfd)
  8990.     return;                        /* No information to give.  */

  8991.   strcpy (target_buf, "QTro");
  8992.   offset = strlen (target_buf);
  8993.   for (s = exec_bfd->sections; s; s = s->next)
  8994.     {
  8995.       char tmp1[40], tmp2[40];
  8996.       int sec_length;

  8997.       if ((s->flags & SEC_LOAD) == 0 ||
  8998.       /*  (s->flags & SEC_CODE) == 0 || */
  8999.           (s->flags & SEC_READONLY) == 0)
  9000.         continue;

  9001.       anysecs = 1;
  9002.       vma = bfd_get_section_vma (abfd, s);
  9003.       size = bfd_get_section_size (s);
  9004.       sprintf_vma (tmp1, vma);
  9005.       sprintf_vma (tmp2, vma + size);
  9006.       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
  9007.       if (offset + sec_length + 1 > target_buf_size)
  9008.         {
  9009.           if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
  9010.             warning (_("\
  9011. Too many sections for read-only sections definition packet."));
  9012.           break;
  9013.         }
  9014.       xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
  9015.                  tmp1, tmp2);
  9016.       offset += sec_length;
  9017.     }
  9018.   if (anysecs)
  9019.     {
  9020.       putpkt (target_buf);
  9021.       getpkt (&target_buf, &target_buf_size, 0);
  9022.     }
  9023. }

  9024. static void
  9025. remote_trace_start (struct target_ops *self)
  9026. {
  9027.   putpkt ("QTStart");
  9028.   remote_get_noisy_reply (&target_buf, &target_buf_size);
  9029.   if (*target_buf == '\0')
  9030.     error (_("Target does not support this command."));
  9031.   if (strcmp (target_buf, "OK") != 0)
  9032.     error (_("Bogus reply from target: %s"), target_buf);
  9033. }

  9034. static int
  9035. remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
  9036. {
  9037.   /* Initialize it just to avoid a GCC false warning.  */
  9038.   char *p = NULL;
  9039.   /* FIXME we need to get register block size some other way.  */
  9040.   extern int trace_regblock_size;
  9041.   volatile struct gdb_exception ex;
  9042.   enum packet_result result;

  9043.   if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
  9044.     return -1;

  9045.   trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;

  9046.   putpkt ("qTStatus");

  9047.   TRY_CATCH (ex, RETURN_MASK_ERROR)
  9048.     {
  9049.       p = remote_get_noisy_reply (&target_buf, &target_buf_size);
  9050.     }
  9051.   if (ex.reason < 0)
  9052.     {
  9053.       if (ex.error != TARGET_CLOSE_ERROR)
  9054.         {
  9055.           exception_fprintf (gdb_stderr, ex, "qTStatus: ");
  9056.           return -1;
  9057.         }
  9058.       throw_exception (ex);
  9059.     }

  9060.   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);

  9061.   /* If the remote target doesn't do tracing, flag it.  */
  9062.   if (result == PACKET_UNKNOWN)
  9063.     return -1;

  9064.   /* We're working with a live target.  */
  9065.   ts->filename = NULL;

  9066.   if (*p++ != 'T')
  9067.     error (_("Bogus trace status reply from target: %s"), target_buf);

  9068.   /* Function 'parse_trace_status' sets default value of each field of
  9069.      'ts' at first, so we don't have to do it here.  */
  9070.   parse_trace_status (p, ts);

  9071.   return ts->running;
  9072. }

  9073. static void
  9074. remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
  9075.                               struct uploaded_tp *utp)
  9076. {
  9077.   struct remote_state *rs = get_remote_state ();
  9078.   char *reply;
  9079.   struct bp_location *loc;
  9080.   struct tracepoint *tp = (struct tracepoint *) bp;
  9081.   size_t size = get_remote_packet_size ();

  9082.   if (tp)
  9083.     {
  9084.       tp->base.hit_count = 0;
  9085.       tp->traceframe_usage = 0;
  9086.       for (loc = tp->base.loc; loc; loc = loc->next)
  9087.         {
  9088.           /* If the tracepoint was never downloaded, don't go asking for
  9089.              any status.  */
  9090.           if (tp->number_on_target == 0)
  9091.             continue;
  9092.           xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
  9093.                      phex_nz (loc->address, 0));
  9094.           putpkt (rs->buf);
  9095.           reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
  9096.           if (reply && *reply)
  9097.             {
  9098.               if (*reply == 'V')
  9099.                 parse_tracepoint_status (reply + 1, bp, utp);
  9100.             }
  9101.         }
  9102.     }
  9103.   else if (utp)
  9104.     {
  9105.       utp->hit_count = 0;
  9106.       utp->traceframe_usage = 0;
  9107.       xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
  9108.                  phex_nz (utp->addr, 0));
  9109.       putpkt (rs->buf);
  9110.       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
  9111.       if (reply && *reply)
  9112.         {
  9113.           if (*reply == 'V')
  9114.             parse_tracepoint_status (reply + 1, bp, utp);
  9115.         }
  9116.     }
  9117. }

  9118. static void
  9119. remote_trace_stop (struct target_ops *self)
  9120. {
  9121.   putpkt ("QTStop");
  9122.   remote_get_noisy_reply (&target_buf, &target_buf_size);
  9123.   if (*target_buf == '\0')
  9124.     error (_("Target does not support this command."));
  9125.   if (strcmp (target_buf, "OK") != 0)
  9126.     error (_("Bogus reply from target: %s"), target_buf);
  9127. }

  9128. static int
  9129. remote_trace_find (struct target_ops *self,
  9130.                    enum trace_find_type type, int num,
  9131.                    CORE_ADDR addr1, CORE_ADDR addr2,
  9132.                    int *tpp)
  9133. {
  9134.   struct remote_state *rs = get_remote_state ();
  9135.   char *endbuf = rs->buf + get_remote_packet_size ();
  9136.   char *p, *reply;
  9137.   int target_frameno = -1, target_tracept = -1;

  9138.   /* Lookups other than by absolute frame number depend on the current
  9139.      trace selected, so make sure it is correct on the remote end
  9140.      first.  */
  9141.   if (type != tfind_number)
  9142.     set_remote_traceframe ();

  9143.   p = rs->buf;
  9144.   strcpy (p, "QTFrame:");
  9145.   p = strchr (p, '\0');
  9146.   switch (type)
  9147.     {
  9148.     case tfind_number:
  9149.       xsnprintf (p, endbuf - p, "%x", num);
  9150.       break;
  9151.     case tfind_pc:
  9152.       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
  9153.       break;
  9154.     case tfind_tp:
  9155.       xsnprintf (p, endbuf - p, "tdp:%x", num);
  9156.       break;
  9157.     case tfind_range:
  9158.       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
  9159.                  phex_nz (addr2, 0));
  9160.       break;
  9161.     case tfind_outside:
  9162.       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
  9163.                  phex_nz (addr2, 0));
  9164.       break;
  9165.     default:
  9166.       error (_("Unknown trace find type %d"), type);
  9167.     }

  9168.   putpkt (rs->buf);
  9169.   reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
  9170.   if (*reply == '\0')
  9171.     error (_("Target does not support this command."));

  9172.   while (reply && *reply)
  9173.     switch (*reply)
  9174.       {
  9175.       case 'F':
  9176.         p = ++reply;
  9177.         target_frameno = (int) strtol (p, &reply, 16);
  9178.         if (reply == p)
  9179.           error (_("Unable to parse trace frame number"));
  9180.         /* Don't update our remote traceframe number cache on failure
  9181.            to select a remote traceframe.  */
  9182.         if (target_frameno == -1)
  9183.           return -1;
  9184.         break;
  9185.       case 'T':
  9186.         p = ++reply;
  9187.         target_tracept = (int) strtol (p, &reply, 16);
  9188.         if (reply == p)
  9189.           error (_("Unable to parse tracepoint number"));
  9190.         break;
  9191.       case 'O':                /* "OK"? */
  9192.         if (reply[1] == 'K' && reply[2] == '\0')
  9193.           reply += 2;
  9194.         else
  9195.           error (_("Bogus reply from target: %s"), reply);
  9196.         break;
  9197.       default:
  9198.         error (_("Bogus reply from target: %s"), reply);
  9199.       }
  9200.   if (tpp)
  9201.     *tpp = target_tracept;

  9202.   rs->remote_traceframe_number = target_frameno;
  9203.   return target_frameno;
  9204. }

  9205. static int
  9206. remote_get_trace_state_variable_value (struct target_ops *self,
  9207.                                        int tsvnum, LONGEST *val)
  9208. {
  9209.   struct remote_state *rs = get_remote_state ();
  9210.   char *reply;
  9211.   ULONGEST uval;

  9212.   set_remote_traceframe ();

  9213.   xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
  9214.   putpkt (rs->buf);
  9215.   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
  9216.   if (reply && *reply)
  9217.     {
  9218.       if (*reply == 'V')
  9219.         {
  9220.           unpack_varlen_hex (reply + 1, &uval);
  9221.           *val = (LONGEST) uval;
  9222.           return 1;
  9223.         }
  9224.     }
  9225.   return 0;
  9226. }

  9227. static int
  9228. remote_save_trace_data (struct target_ops *self, const char *filename)
  9229. {
  9230.   struct remote_state *rs = get_remote_state ();
  9231.   char *p, *reply;

  9232.   p = rs->buf;
  9233.   strcpy (p, "QTSave:");
  9234.   p += strlen (p);
  9235.   if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
  9236.     error (_("Remote file name too long for trace save packet"));
  9237.   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
  9238.   *p++ = '\0';
  9239.   putpkt (rs->buf);
  9240.   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
  9241.   if (*reply == '\0')
  9242.     error (_("Target does not support this command."));
  9243.   if (strcmp (reply, "OK") != 0)
  9244.     error (_("Bogus reply from target: %s"), reply);
  9245.   return 0;
  9246. }

  9247. /* This is basically a memory transfer, but needs to be its own packet
  9248.    because we don't know how the target actually organizes its trace
  9249.    memory, plus we want to be able to ask for as much as possible, but
  9250.    not be unhappy if we don't get as much as we ask for.  */

  9251. static LONGEST
  9252. remote_get_raw_trace_data (struct target_ops *self,
  9253.                            gdb_byte *buf, ULONGEST offset, LONGEST len)
  9254. {
  9255.   struct remote_state *rs = get_remote_state ();
  9256.   char *reply;
  9257.   char *p;
  9258.   int rslt;

  9259.   p = rs->buf;
  9260.   strcpy (p, "qTBuffer:");
  9261.   p += strlen (p);
  9262.   p += hexnumstr (p, offset);
  9263.   *p++ = ',';
  9264.   p += hexnumstr (p, len);
  9265.   *p++ = '\0';

  9266.   putpkt (rs->buf);
  9267.   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
  9268.   if (reply && *reply)
  9269.     {
  9270.       /* 'l' by itself means we're at the end of the buffer and
  9271.          there is nothing more to get.  */
  9272.       if (*reply == 'l')
  9273.         return 0;

  9274.       /* Convert the reply into binary.  Limit the number of bytes to
  9275.          convert according to our passed-in buffer size, rather than
  9276.          what was returned in the packet; if the target is
  9277.          unexpectedly generous and gives us a bigger reply than we
  9278.          asked for, we don't want to crash.  */
  9279.       rslt = hex2bin (target_buf, buf, len);
  9280.       return rslt;
  9281.     }

  9282.   /* Something went wrong, flag as an error.  */
  9283.   return -1;
  9284. }

  9285. static void
  9286. remote_set_disconnected_tracing (struct target_ops *self, int val)
  9287. {
  9288.   struct remote_state *rs = get_remote_state ();

  9289.   if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
  9290.     {
  9291.       char *reply;

  9292.       xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
  9293.       putpkt (rs->buf);
  9294.       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
  9295.       if (*reply == '\0')
  9296.         error (_("Target does not support this command."));
  9297.       if (strcmp (reply, "OK") != 0)
  9298.         error (_("Bogus reply from target: %s"), reply);
  9299.     }
  9300.   else if (val)
  9301.     warning (_("Target does not support disconnected tracing."));
  9302. }

  9303. static int
  9304. remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
  9305. {
  9306.   struct thread_info *info = find_thread_ptid (ptid);

  9307.   if (info && info->private)
  9308.     return info->private->core;
  9309.   return -1;
  9310. }

  9311. static void
  9312. remote_set_circular_trace_buffer (struct target_ops *self, int val)
  9313. {
  9314.   struct remote_state *rs = get_remote_state ();
  9315.   char *reply;

  9316.   xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
  9317.   putpkt (rs->buf);
  9318.   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
  9319.   if (*reply == '\0')
  9320.     error (_("Target does not support this command."));
  9321.   if (strcmp (reply, "OK") != 0)
  9322.     error (_("Bogus reply from target: %s"), reply);
  9323. }

  9324. static struct traceframe_info *
  9325. remote_traceframe_info (struct target_ops *self)
  9326. {
  9327.   char *text;

  9328.   text = target_read_stralloc (&current_target,
  9329.                                TARGET_OBJECT_TRACEFRAME_INFO, NULL);
  9330.   if (text != NULL)
  9331.     {
  9332.       struct traceframe_info *info;
  9333.       struct cleanup *back_to = make_cleanup (xfree, text);

  9334.       info = parse_traceframe_info (text);
  9335.       do_cleanups (back_to);
  9336.       return info;
  9337.     }

  9338.   return NULL;
  9339. }

  9340. /* Handle the qTMinFTPILen packet.  Returns the minimum length of
  9341.    instruction on which a fast tracepoint may be placed.  Returns -1
  9342.    if the packet is not supported, and 0 if the minimum instruction
  9343.    length is unknown.  */

  9344. static int
  9345. remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
  9346. {
  9347.   struct remote_state *rs = get_remote_state ();
  9348.   char *reply;

  9349.   /* If we're not debugging a process yet, the IPA can't be
  9350.      loaded.  */
  9351.   if (!target_has_execution)
  9352.     return 0;

  9353.   /* Make sure the remote is pointing at the right process.  */
  9354.   set_general_process ();

  9355.   xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
  9356.   putpkt (rs->buf);
  9357.   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
  9358.   if (*reply == '\0')
  9359.     return -1;
  9360.   else
  9361.     {
  9362.       ULONGEST min_insn_len;

  9363.       unpack_varlen_hex (reply, &min_insn_len);

  9364.       return (int) min_insn_len;
  9365.     }
  9366. }

  9367. static void
  9368. remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
  9369. {
  9370.   if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
  9371.     {
  9372.       struct remote_state *rs = get_remote_state ();
  9373.       char *buf = rs->buf;
  9374.       char *endbuf = rs->buf + get_remote_packet_size ();
  9375.       enum packet_result result;

  9376.       gdb_assert (val >= 0 || val == -1);
  9377.       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
  9378.       /* Send -1 as literal "-1" to avoid host size dependency.  */
  9379.       if (val < 0)
  9380.         {
  9381.           *buf++ = '-';
  9382.           buf += hexnumstr (buf, (ULONGEST) -val);
  9383.         }
  9384.       else
  9385.         buf += hexnumstr (buf, (ULONGEST) val);

  9386.       putpkt (rs->buf);
  9387.       remote_get_noisy_reply (&rs->buf, &rs->buf_size);
  9388.       result = packet_ok (rs->buf,
  9389.                   &remote_protocol_packets[PACKET_QTBuffer_size]);

  9390.       if (result != PACKET_OK)
  9391.         warning (_("Bogus reply from target: %s"), rs->buf);
  9392.     }
  9393. }

  9394. static int
  9395. remote_set_trace_notes (struct target_ops *self,
  9396.                         const char *user, const char *notes,
  9397.                         const char *stop_notes)
  9398. {
  9399.   struct remote_state *rs = get_remote_state ();
  9400.   char *reply;
  9401.   char *buf = rs->buf;
  9402.   char *endbuf = rs->buf + get_remote_packet_size ();
  9403.   int nbytes;

  9404.   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
  9405.   if (user)
  9406.     {
  9407.       buf += xsnprintf (buf, endbuf - buf, "user:");
  9408.       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
  9409.       buf += 2 * nbytes;
  9410.       *buf++ = ';';
  9411.     }
  9412.   if (notes)
  9413.     {
  9414.       buf += xsnprintf (buf, endbuf - buf, "notes:");
  9415.       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
  9416.       buf += 2 * nbytes;
  9417.       *buf++ = ';';
  9418.     }
  9419.   if (stop_notes)
  9420.     {
  9421.       buf += xsnprintf (buf, endbuf - buf, "tstop:");
  9422.       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
  9423.       buf += 2 * nbytes;
  9424.       *buf++ = ';';
  9425.     }
  9426.   /* Ensure the buffer is terminated.  */
  9427.   *buf = '\0';

  9428.   putpkt (rs->buf);
  9429.   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
  9430.   if (*reply == '\0')
  9431.     return 0;

  9432.   if (strcmp (reply, "OK") != 0)
  9433.     error (_("Bogus reply from target: %s"), reply);

  9434.   return 1;
  9435. }

  9436. static int
  9437. remote_use_agent (struct target_ops *self, int use)
  9438. {
  9439.   if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
  9440.     {
  9441.       struct remote_state *rs = get_remote_state ();

  9442.       /* If the stub supports QAgent.  */
  9443.       xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
  9444.       putpkt (rs->buf);
  9445.       getpkt (&rs->buf, &rs->buf_size, 0);

  9446.       if (strcmp (rs->buf, "OK") == 0)
  9447.         {
  9448.           use_agent = use;
  9449.           return 1;
  9450.         }
  9451.     }

  9452.   return 0;
  9453. }

  9454. static int
  9455. remote_can_use_agent (struct target_ops *self)
  9456. {
  9457.   return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
  9458. }

  9459. struct btrace_target_info
  9460. {
  9461.   /* The ptid of the traced thread.  */
  9462.   ptid_t ptid;
  9463. };

  9464. /* Check whether the target supports branch tracing.  */

  9465. static int
  9466. remote_supports_btrace (struct target_ops *self)
  9467. {
  9468.   if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
  9469.     return 0;
  9470.   if (packet_support (PACKET_Qbtrace_bts) != PACKET_ENABLE)
  9471.     return 0;
  9472.   if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
  9473.     return 0;

  9474.   return 1;
  9475. }

  9476. /* Enable branch tracing.  */

  9477. static struct btrace_target_info *
  9478. remote_enable_btrace (struct target_ops *self, ptid_t ptid)
  9479. {
  9480.   struct btrace_target_info *tinfo = NULL;
  9481.   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
  9482.   struct remote_state *rs = get_remote_state ();
  9483.   char *buf = rs->buf;
  9484.   char *endbuf = rs->buf + get_remote_packet_size ();

  9485.   if (packet_config_support (packet) != PACKET_ENABLE)
  9486.     error (_("Target does not support branch tracing."));

  9487.   set_general_thread (ptid);

  9488.   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
  9489.   putpkt (rs->buf);
  9490.   getpkt (&rs->buf, &rs->buf_size, 0);

  9491.   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
  9492.     {
  9493.       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
  9494.         error (_("Could not enable branch tracing for %s: %s"),
  9495.                target_pid_to_str (ptid), rs->buf + 2);
  9496.       else
  9497.         error (_("Could not enable branch tracing for %s."),
  9498.                target_pid_to_str (ptid));
  9499.     }

  9500.   tinfo = xzalloc (sizeof (*tinfo));
  9501.   tinfo->ptid = ptid;

  9502.   return tinfo;
  9503. }

  9504. /* Disable branch tracing.  */

  9505. static void
  9506. remote_disable_btrace (struct target_ops *self,
  9507.                        struct btrace_target_info *tinfo)
  9508. {
  9509.   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
  9510.   struct remote_state *rs = get_remote_state ();
  9511.   char *buf = rs->buf;
  9512.   char *endbuf = rs->buf + get_remote_packet_size ();

  9513.   if (packet_config_support (packet) != PACKET_ENABLE)
  9514.     error (_("Target does not support branch tracing."));

  9515.   set_general_thread (tinfo->ptid);

  9516.   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
  9517.   putpkt (rs->buf);
  9518.   getpkt (&rs->buf, &rs->buf_size, 0);

  9519.   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
  9520.     {
  9521.       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
  9522.         error (_("Could not disable branch tracing for %s: %s"),
  9523.                target_pid_to_str (tinfo->ptid), rs->buf + 2);
  9524.       else
  9525.         error (_("Could not disable branch tracing for %s."),
  9526.                target_pid_to_str (tinfo->ptid));
  9527.     }

  9528.   xfree (tinfo);
  9529. }

  9530. /* Teardown branch tracing.  */

  9531. static void
  9532. remote_teardown_btrace (struct target_ops *self,
  9533.                         struct btrace_target_info *tinfo)
  9534. {
  9535.   /* We must not talk to the target during teardown.  */
  9536.   xfree (tinfo);
  9537. }

  9538. /* Read the branch trace.  */

  9539. static enum btrace_error
  9540. remote_read_btrace (struct target_ops *self,
  9541.                     VEC (btrace_block_s) **btrace,
  9542.                     struct btrace_target_info *tinfo,
  9543.                     enum btrace_read_type type)
  9544. {
  9545.   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
  9546.   struct remote_state *rs = get_remote_state ();
  9547.   struct cleanup *cleanup;
  9548.   const char *annex;
  9549.   char *xml;

  9550.   if (packet_config_support (packet) != PACKET_ENABLE)
  9551.     error (_("Target does not support branch tracing."));

  9552. #if !defined(HAVE_LIBEXPAT)
  9553.   error (_("Cannot process branch tracing result. XML parsing not supported."));
  9554. #endif

  9555.   switch (type)
  9556.     {
  9557.     case BTRACE_READ_ALL:
  9558.       annex = "all";
  9559.       break;
  9560.     case BTRACE_READ_NEW:
  9561.       annex = "new";
  9562.       break;
  9563.     case BTRACE_READ_DELTA:
  9564.       annex = "delta";
  9565.       break;
  9566.     default:
  9567.       internal_error (__FILE__, __LINE__,
  9568.                       _("Bad branch tracing read type: %u."),
  9569.                       (unsigned int) type);
  9570.     }

  9571.   xml = target_read_stralloc (&current_target,
  9572.                               TARGET_OBJECT_BTRACE, annex);
  9573.   if (xml == NULL)
  9574.     return BTRACE_ERR_UNKNOWN;

  9575.   cleanup = make_cleanup (xfree, xml);
  9576.   *btrace = parse_xml_btrace (xml);
  9577.   do_cleanups (cleanup);

  9578.   return BTRACE_ERR_NONE;
  9579. }

  9580. static int
  9581. remote_augmented_libraries_svr4_read (struct target_ops *self)
  9582. {
  9583.   return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
  9584.           == PACKET_ENABLE);
  9585. }

  9586. /* Implementation of to_load.  */

  9587. static void
  9588. remote_load (struct target_ops *self, const char *name, int from_tty)
  9589. {
  9590.   generic_load (name, from_tty);
  9591. }

  9592. static void
  9593. init_remote_ops (void)
  9594. {
  9595.   remote_ops.to_shortname = "remote";
  9596.   remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
  9597.   remote_ops.to_doc =
  9598.     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
  9599. Specify the serial device it is connected to\n\
  9600. (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
  9601.   remote_ops.to_open = remote_open;
  9602.   remote_ops.to_close = remote_close;
  9603.   remote_ops.to_detach = remote_detach;
  9604.   remote_ops.to_disconnect = remote_disconnect;
  9605.   remote_ops.to_resume = remote_resume;
  9606.   remote_ops.to_wait = remote_wait;
  9607.   remote_ops.to_fetch_registers = remote_fetch_registers;
  9608.   remote_ops.to_store_registers = remote_store_registers;
  9609.   remote_ops.to_prepare_to_store = remote_prepare_to_store;
  9610.   remote_ops.to_files_info = remote_files_info;
  9611.   remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
  9612.   remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
  9613.   remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
  9614.   remote_ops.to_stopped_data_address = remote_stopped_data_address;
  9615.   remote_ops.to_watchpoint_addr_within_range =
  9616.     remote_watchpoint_addr_within_range;
  9617.   remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
  9618.   remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
  9619.   remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
  9620.   remote_ops.to_region_ok_for_hw_watchpoint
  9621.      = remote_region_ok_for_hw_watchpoint;
  9622.   remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
  9623.   remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
  9624.   remote_ops.to_kill = remote_kill;
  9625.   remote_ops.to_load = remote_load;
  9626.   remote_ops.to_mourn_inferior = remote_mourn;
  9627.   remote_ops.to_pass_signals = remote_pass_signals;
  9628.   remote_ops.to_program_signals = remote_program_signals;
  9629.   remote_ops.to_thread_alive = remote_thread_alive;
  9630.   remote_ops.to_update_thread_list = remote_update_thread_list;
  9631.   remote_ops.to_pid_to_str = remote_pid_to_str;
  9632.   remote_ops.to_extra_thread_info = remote_threads_extra_info;
  9633.   remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
  9634.   remote_ops.to_stop = remote_stop;
  9635.   remote_ops.to_xfer_partial = remote_xfer_partial;
  9636.   remote_ops.to_rcmd = remote_rcmd;
  9637.   remote_ops.to_log_command = serial_log_command;
  9638.   remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
  9639.   remote_ops.to_stratum = process_stratum;
  9640.   remote_ops.to_has_all_memory = default_child_has_all_memory;
  9641.   remote_ops.to_has_memory = default_child_has_memory;
  9642.   remote_ops.to_has_stack = default_child_has_stack;
  9643.   remote_ops.to_has_registers = default_child_has_registers;
  9644.   remote_ops.to_has_execution = default_child_has_execution;
  9645.   remote_ops.to_has_thread_control = tc_schedlock;    /* can lock scheduler */
  9646.   remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
  9647.   remote_ops.to_magic = OPS_MAGIC;
  9648.   remote_ops.to_memory_map = remote_memory_map;
  9649.   remote_ops.to_flash_erase = remote_flash_erase;
  9650.   remote_ops.to_flash_done = remote_flash_done;
  9651.   remote_ops.to_read_description = remote_read_description;
  9652.   remote_ops.to_search_memory = remote_search_memory;
  9653.   remote_ops.to_can_async_p = remote_can_async_p;
  9654.   remote_ops.to_is_async_p = remote_is_async_p;
  9655.   remote_ops.to_async = remote_async;
  9656.   remote_ops.to_terminal_inferior = remote_terminal_inferior;
  9657.   remote_ops.to_terminal_ours = remote_terminal_ours;
  9658.   remote_ops.to_supports_non_stop = remote_supports_non_stop;
  9659.   remote_ops.to_supports_multi_process = remote_supports_multi_process;
  9660.   remote_ops.to_supports_disable_randomization
  9661.     = remote_supports_disable_randomization;
  9662.   remote_ops.to_fileio_open = remote_hostio_open;
  9663.   remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
  9664.   remote_ops.to_fileio_pread = remote_hostio_pread;
  9665.   remote_ops.to_fileio_close = remote_hostio_close;
  9666.   remote_ops.to_fileio_unlink = remote_hostio_unlink;
  9667.   remote_ops.to_fileio_readlink = remote_hostio_readlink;
  9668.   remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
  9669.   remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
  9670.   remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
  9671.   remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
  9672.   remote_ops.to_trace_init = remote_trace_init;
  9673.   remote_ops.to_download_tracepoint = remote_download_tracepoint;
  9674.   remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
  9675.   remote_ops.to_download_trace_state_variable
  9676.     = remote_download_trace_state_variable;
  9677.   remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
  9678.   remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
  9679.   remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
  9680.   remote_ops.to_trace_start = remote_trace_start;
  9681.   remote_ops.to_get_trace_status = remote_get_trace_status;
  9682.   remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
  9683.   remote_ops.to_trace_stop = remote_trace_stop;
  9684.   remote_ops.to_trace_find = remote_trace_find;
  9685.   remote_ops.to_get_trace_state_variable_value
  9686.     = remote_get_trace_state_variable_value;
  9687.   remote_ops.to_save_trace_data = remote_save_trace_data;
  9688.   remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
  9689.   remote_ops.to_upload_trace_state_variables
  9690.     = remote_upload_trace_state_variables;
  9691.   remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
  9692.   remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
  9693.   remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
  9694.   remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
  9695.   remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
  9696.   remote_ops.to_set_trace_notes = remote_set_trace_notes;
  9697.   remote_ops.to_core_of_thread = remote_core_of_thread;
  9698.   remote_ops.to_verify_memory = remote_verify_memory;
  9699.   remote_ops.to_get_tib_address = remote_get_tib_address;
  9700.   remote_ops.to_set_permissions = remote_set_permissions;
  9701.   remote_ops.to_static_tracepoint_marker_at
  9702.     = remote_static_tracepoint_marker_at;
  9703.   remote_ops.to_static_tracepoint_markers_by_strid
  9704.     = remote_static_tracepoint_markers_by_strid;
  9705.   remote_ops.to_traceframe_info = remote_traceframe_info;
  9706.   remote_ops.to_use_agent = remote_use_agent;
  9707.   remote_ops.to_can_use_agent = remote_can_use_agent;
  9708.   remote_ops.to_supports_btrace = remote_supports_btrace;
  9709.   remote_ops.to_enable_btrace = remote_enable_btrace;
  9710.   remote_ops.to_disable_btrace = remote_disable_btrace;
  9711.   remote_ops.to_teardown_btrace = remote_teardown_btrace;
  9712.   remote_ops.to_read_btrace = remote_read_btrace;
  9713.   remote_ops.to_augmented_libraries_svr4_read =
  9714.     remote_augmented_libraries_svr4_read;
  9715. }

  9716. /* Set up the extended remote vector by making a copy of the standard
  9717.    remote vector and adding to it.  */

  9718. static void
  9719. init_extended_remote_ops (void)
  9720. {
  9721.   extended_remote_ops = remote_ops;

  9722.   extended_remote_ops.to_shortname = "extended-remote";
  9723.   extended_remote_ops.to_longname =
  9724.     "Extended remote serial target in gdb-specific protocol";
  9725.   extended_remote_ops.to_doc =
  9726.     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
  9727. Specify the serial device it is connected to (e.g. /dev/ttya).";
  9728.   extended_remote_ops.to_open = extended_remote_open;
  9729.   extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
  9730.   extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
  9731.   extended_remote_ops.to_detach = extended_remote_detach;
  9732.   extended_remote_ops.to_attach = extended_remote_attach;
  9733.   extended_remote_ops.to_post_attach = extended_remote_post_attach;
  9734.   extended_remote_ops.to_kill = extended_remote_kill;
  9735.   extended_remote_ops.to_supports_disable_randomization
  9736.     = extended_remote_supports_disable_randomization;
  9737. }

  9738. static int
  9739. remote_can_async_p (struct target_ops *ops)
  9740. {
  9741.   struct remote_state *rs = get_remote_state ();

  9742.   if (!target_async_permitted)
  9743.     /* We only enable async when the user specifically asks for it.  */
  9744.     return 0;

  9745.   /* We're async whenever the serial device is.  */
  9746.   return serial_can_async_p (rs->remote_desc);
  9747. }

  9748. static int
  9749. remote_is_async_p (struct target_ops *ops)
  9750. {
  9751.   struct remote_state *rs = get_remote_state ();

  9752.   if (!target_async_permitted)
  9753.     /* We only enable async when the user specifically asks for it.  */
  9754.     return 0;

  9755.   /* We're async whenever the serial device is.  */
  9756.   return serial_is_async_p (rs->remote_desc);
  9757. }

  9758. /* Pass the SERIAL event on and up to the client.  One day this code
  9759.    will be able to delay notifying the client of an event until the
  9760.    point where an entire packet has been received.  */

  9761. static serial_event_ftype remote_async_serial_handler;

  9762. static void
  9763. remote_async_serial_handler (struct serial *scb, void *context)
  9764. {
  9765.   struct remote_state *rs = context;

  9766.   /* Don't propogate error information up to the client.  Instead let
  9767.      the client find out about the error by querying the target.  */
  9768.   rs->async_client_callback (INF_REG_EVENT, rs->async_client_context);
  9769. }

  9770. static void
  9771. remote_async_inferior_event_handler (gdb_client_data data)
  9772. {
  9773.   inferior_event_handler (INF_REG_EVENT, NULL);
  9774. }

  9775. static void
  9776. remote_async (struct target_ops *ops,
  9777.               void (*callback) (enum inferior_event_type event_type,
  9778.                                 void *context),
  9779.               void *context)
  9780. {
  9781.   struct remote_state *rs = get_remote_state ();

  9782.   if (callback != NULL)
  9783.     {
  9784.       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
  9785.       rs->async_client_callback = callback;
  9786.       rs->async_client_context = context;
  9787.     }
  9788.   else
  9789.     serial_async (rs->remote_desc, NULL, NULL);
  9790. }

  9791. static void
  9792. set_remote_cmd (char *args, int from_tty)
  9793. {
  9794.   help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
  9795. }

  9796. static void
  9797. show_remote_cmd (char *args, int from_tty)
  9798. {
  9799.   /* We can't just use cmd_show_list here, because we want to skip
  9800.      the redundant "show remote Z-packet" and the legacy aliases.  */
  9801.   struct cleanup *showlist_chain;
  9802.   struct cmd_list_element *list = remote_show_cmdlist;
  9803.   struct ui_out *uiout = current_uiout;

  9804.   showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
  9805.   for (; list != NULL; list = list->next)
  9806.     if (strcmp (list->name, "Z-packet") == 0)
  9807.       continue;
  9808.     else if (list->type == not_set_cmd)
  9809.       /* Alias commands are exactly like the original, except they
  9810.          don't have the normal type.  */
  9811.       continue;
  9812.     else
  9813.       {
  9814.         struct cleanup *option_chain
  9815.           = make_cleanup_ui_out_tuple_begin_end (uiout, "option");

  9816.         ui_out_field_string (uiout, "name", list->name);
  9817.         ui_out_text (uiout, ":  ");
  9818.         if (list->type == show_cmd)
  9819.           do_show_command ((char *) NULL, from_tty, list);
  9820.         else
  9821.           cmd_func (list, NULL, from_tty);
  9822.         /* Close the tuple.  */
  9823.         do_cleanups (option_chain);
  9824.       }

  9825.   /* Close the tuple.  */
  9826.   do_cleanups (showlist_chain);
  9827. }


  9828. /* Function to be called whenever a new objfile (shlib) is detected.  */
  9829. static void
  9830. remote_new_objfile (struct objfile *objfile)
  9831. {
  9832.   struct remote_state *rs = get_remote_state ();

  9833.   if (rs->remote_desc != 0)                /* Have a remote connection.  */
  9834.     remote_check_symbols ();
  9835. }

  9836. /* Pull all the tracepoints defined on the target and create local
  9837.    data structures representing them.  We don't want to create real
  9838.    tracepoints yet, we don't want to mess up the user's existing
  9839.    collection.  */

  9840. static int
  9841. remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
  9842. {
  9843.   struct remote_state *rs = get_remote_state ();
  9844.   char *p;

  9845.   /* Ask for a first packet of tracepoint definition.  */
  9846.   putpkt ("qTfP");
  9847.   getpkt (&rs->buf, &rs->buf_size, 0);
  9848.   p = rs->buf;
  9849.   while (*p && *p != 'l')
  9850.     {
  9851.       parse_tracepoint_definition (p, utpp);
  9852.       /* Ask for another packet of tracepoint definition.  */
  9853.       putpkt ("qTsP");
  9854.       getpkt (&rs->buf, &rs->buf_size, 0);
  9855.       p = rs->buf;
  9856.     }
  9857.   return 0;
  9858. }

  9859. static int
  9860. remote_upload_trace_state_variables (struct target_ops *self,
  9861.                                      struct uploaded_tsv **utsvp)
  9862. {
  9863.   struct remote_state *rs = get_remote_state ();
  9864.   char *p;

  9865.   /* Ask for a first packet of variable definition.  */
  9866.   putpkt ("qTfV");
  9867.   getpkt (&rs->buf, &rs->buf_size, 0);
  9868.   p = rs->buf;
  9869.   while (*p && *p != 'l')
  9870.     {
  9871.       parse_tsv_definition (p, utsvp);
  9872.       /* Ask for another packet of variable definition.  */
  9873.       putpkt ("qTsV");
  9874.       getpkt (&rs->buf, &rs->buf_size, 0);
  9875.       p = rs->buf;
  9876.     }
  9877.   return 0;
  9878. }

  9879. /* The "set/show range-stepping" show hook.  */

  9880. static void
  9881. show_range_stepping (struct ui_file *file, int from_tty,
  9882.                      struct cmd_list_element *c,
  9883.                      const char *value)
  9884. {
  9885.   fprintf_filtered (file,
  9886.                     _("Debugger's willingness to use range stepping "
  9887.                       "is %s.\n"), value);
  9888. }

  9889. /* The "set/show range-stepping" set hook.  */

  9890. static void
  9891. set_range_stepping (char *ignore_args, int from_tty,
  9892.                     struct cmd_list_element *c)
  9893. {
  9894.   struct remote_state *rs = get_remote_state ();

  9895.   /* Whene enabling, check whether range stepping is actually
  9896.      supported by the target, and warn if not.  */
  9897.   if (use_range_stepping)
  9898.     {
  9899.       if (rs->remote_desc != NULL)
  9900.         {
  9901.           if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
  9902.             remote_vcont_probe (rs);

  9903.           if (packet_support (PACKET_vCont) == PACKET_ENABLE
  9904.               && rs->supports_vCont.r)
  9905.             return;
  9906.         }

  9907.       warning (_("Range stepping is not supported by the current target"));
  9908.     }
  9909. }

  9910. void
  9911. _initialize_remote (void)
  9912. {
  9913.   struct remote_state *rs;
  9914.   struct cmd_list_element *cmd;
  9915.   const char *cmd_name;

  9916.   /* architecture specific data */
  9917.   remote_gdbarch_data_handle =
  9918.     gdbarch_data_register_post_init (init_remote_state);
  9919.   remote_g_packet_data_handle =
  9920.     gdbarch_data_register_pre_init (remote_g_packet_data_init);

  9921.   /* Initialize the per-target state.  At the moment there is only one
  9922.      of these, not one per target.  Only one target is active at a
  9923.      time.  */
  9924.   remote_state = new_remote_state ();

  9925.   init_remote_ops ();
  9926.   add_target (&remote_ops);

  9927.   init_extended_remote_ops ();
  9928.   add_target (&extended_remote_ops);

  9929.   /* Hook into new objfile notification.  */
  9930.   observer_attach_new_objfile (remote_new_objfile);
  9931.   /* We're no longer interested in notification events of an inferior
  9932.      when it exits.  */
  9933.   observer_attach_inferior_exit (discard_pending_stop_replies);

  9934.   /* Set up signal handlers.  */
  9935.   async_sigint_remote_token =
  9936.     create_async_signal_handler (async_remote_interrupt, NULL);
  9937.   async_sigint_remote_twice_token =
  9938.     create_async_signal_handler (async_remote_interrupt_twice, NULL);

  9939. #if 0
  9940.   init_remote_threadtests ();
  9941. #endif

  9942.   stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
  9943.   /* set/show remote ...  */

  9944.   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
  9945. Remote protocol specific variables\n\
  9946. Configure various remote-protocol specific variables such as\n\
  9947. the packets being used"),
  9948.                   &remote_set_cmdlist, "set remote ",
  9949.                   0 /* allow-unknown */, &setlist);
  9950.   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
  9951. Remote protocol specific variables\n\
  9952. Configure various remote-protocol specific variables such as\n\
  9953. the packets being used"),
  9954.                   &remote_show_cmdlist, "show remote ",
  9955.                   0 /* allow-unknown */, &showlist);

  9956.   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
  9957. Compare section data on target to the exec file.\n\
  9958. Argument is a single section name (default: all loaded sections).\n\
  9959. To compare only read-only loaded sections, specify the -r option."),
  9960.            &cmdlist);

  9961.   add_cmd ("packet", class_maintenance, packet_command, _("\
  9962. Send an arbitrary packet to a remote target.\n\
  9963.    maintenance packet TEXT\n\
  9964. If GDB is talking to an inferior via the GDB serial protocol, then\n\
  9965. this command sends the string TEXT to the inferior, and displays the\n\
  9966. response packet.  GDB supplies the initial `$' character, and the\n\
  9967. terminating `#' character and checksum."),
  9968.            &maintenancelist);

  9969.   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
  9970. Set whether to send break if interrupted."), _("\
  9971. Show whether to send break if interrupted."), _("\
  9972. If set, a break, instead of a cntrl-c, is sent to the remote target."),
  9973.                            set_remotebreak, show_remotebreak,
  9974.                            &setlist, &showlist);
  9975.   cmd_name = "remotebreak";
  9976.   cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
  9977.   deprecate_cmd (cmd, "set remote interrupt-sequence");
  9978.   cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
  9979.   cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
  9980.   deprecate_cmd (cmd, "show remote interrupt-sequence");

  9981.   add_setshow_enum_cmd ("interrupt-sequence", class_support,
  9982.                         interrupt_sequence_modes, &interrupt_sequence_mode,
  9983.                         _("\
  9984. Set interrupt sequence to remote target."), _("\
  9985. Show interrupt sequence to remote target."), _("\
  9986. Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
  9987.                         NULL, show_interrupt_sequence,
  9988.                         &remote_set_cmdlist,
  9989.                         &remote_show_cmdlist);

  9990.   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
  9991.                            &interrupt_on_connect, _("\
  9992. Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("                \
  9993. Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("                \
  9994. If set, interrupt sequence is sent to remote target."),
  9995.                            NULL, NULL,
  9996.                            &remote_set_cmdlist, &remote_show_cmdlist);

  9997.   /* Install commands for configuring memory read/write packets.  */

  9998.   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
  9999. Set the maximum number of bytes per memory write packet (deprecated)."),
  10000.            &setlist);
  10001.   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
  10002. Show the maximum number of bytes per memory write packet (deprecated)."),
  10003.            &showlist);
  10004.   add_cmd ("memory-write-packet-size", no_class,
  10005.            set_memory_write_packet_size, _("\
  10006. Set the maximum number of bytes per memory-write packet.\n\
  10007. Specify the number of bytes in a packet or 0 (zero) for the\n\
  10008. default packet size.  The actual limit is further reduced\n\
  10009. dependent on the target.  Specify ``fixed'' to disable the\n\
  10010. further restriction and ``limit'' to enable that restriction."),
  10011.            &remote_set_cmdlist);
  10012.   add_cmd ("memory-read-packet-size", no_class,
  10013.            set_memory_read_packet_size, _("\
  10014. Set the maximum number of bytes per memory-read packet.\n\
  10015. Specify the number of bytes in a packet or 0 (zero) for the\n\
  10016. default packet size.  The actual limit is further reduced\n\
  10017. dependent on the target.  Specify ``fixed'' to disable the\n\
  10018. further restriction and ``limit'' to enable that restriction."),
  10019.            &remote_set_cmdlist);
  10020.   add_cmd ("memory-write-packet-size", no_class,
  10021.            show_memory_write_packet_size,
  10022.            _("Show the maximum number of bytes per memory-write packet."),
  10023.            &remote_show_cmdlist);
  10024.   add_cmd ("memory-read-packet-size", no_class,
  10025.            show_memory_read_packet_size,
  10026.            _("Show the maximum number of bytes per memory-read packet."),
  10027.            &remote_show_cmdlist);

  10028.   add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
  10029.                             &remote_hw_watchpoint_limit, _("\
  10030. Set the maximum number of target hardware watchpoints."), _("\
  10031. Show the maximum number of target hardware watchpoints."), _("\
  10032. Specify a negative limit for unlimited."),
  10033.                             NULL, NULL, /* FIXME: i18n: The maximum
  10034.                                            number of target hardware
  10035.                                            watchpoints is %s.  */
  10036.                             &remote_set_cmdlist, &remote_show_cmdlist);
  10037.   add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
  10038.                             &remote_hw_watchpoint_length_limit, _("\
  10039. Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
  10040. Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
  10041. Specify a negative limit for unlimited."),
  10042.                             NULL, NULL, /* FIXME: i18n: The maximum
  10043.                                            length (in bytes) of a target
  10044.                                            hardware watchpoint is %s.  */
  10045.                             &remote_set_cmdlist, &remote_show_cmdlist);
  10046.   add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
  10047.                             &remote_hw_breakpoint_limit, _("\
  10048. Set the maximum number of target hardware breakpoints."), _("\
  10049. Show the maximum number of target hardware breakpoints."), _("\
  10050. Specify a negative limit for unlimited."),
  10051.                             NULL, NULL, /* FIXME: i18n: The maximum
  10052.                                            number of target hardware
  10053.                                            breakpoints is %s.  */
  10054.                             &remote_set_cmdlist, &remote_show_cmdlist);

  10055.   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
  10056.                              &remote_address_size, _("\
  10057. Set the maximum size of the address (in bits) in a memory packet."), _("\
  10058. Show the maximum size of the address (in bits) in a memory packet."), NULL,
  10059.                              NULL,
  10060.                              NULL, /* FIXME: i18n: */
  10061.                              &setlist, &showlist);

  10062.   init_all_packet_configs ();

  10063.   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
  10064.                          "X", "binary-download", 1);

  10065.   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
  10066.                          "vCont", "verbose-resume", 0);

  10067.   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
  10068.                          "QPassSignals", "pass-signals", 0);

  10069.   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
  10070.                          "QProgramSignals", "program-signals", 0);

  10071.   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
  10072.                          "qSymbol", "symbol-lookup", 0);

  10073.   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
  10074.                          "P", "set-register", 1);

  10075.   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
  10076.                          "p", "fetch-register", 1);

  10077.   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
  10078.                          "Z0", "software-breakpoint", 0);

  10079.   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
  10080.                          "Z1", "hardware-breakpoint", 0);

  10081.   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
  10082.                          "Z2", "write-watchpoint", 0);

  10083.   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
  10084.                          "Z3", "read-watchpoint", 0);

  10085.   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
  10086.                          "Z4", "access-watchpoint", 0);

  10087.   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
  10088.                          "qXfer:auxv:read", "read-aux-vector", 0);

  10089.   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
  10090.                          "qXfer:features:read", "target-features", 0);

  10091.   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
  10092.                          "qXfer:libraries:read", "library-info", 0);

  10093.   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
  10094.                          "qXfer:libraries-svr4:read", "library-info-svr4", 0);

  10095.   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
  10096.                          "qXfer:memory-map:read", "memory-map", 0);

  10097.   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
  10098.                          "qXfer:spu:read", "read-spu-object", 0);

  10099.   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
  10100.                          "qXfer:spu:write", "write-spu-object", 0);

  10101.   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
  10102.                         "qXfer:osdata:read", "osdata", 0);

  10103.   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
  10104.                          "qXfer:threads:read", "threads", 0);

  10105.   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
  10106.                          "qXfer:siginfo:read", "read-siginfo-object", 0);

  10107.   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
  10108.                          "qXfer:siginfo:write", "write-siginfo-object", 0);

  10109.   add_packet_config_cmd
  10110.     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
  10111.      "qXfer:traceframe-info:read", "traceframe-info", 0);

  10112.   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
  10113.                          "qXfer:uib:read", "unwind-info-block", 0);

  10114.   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
  10115.                          "qGetTLSAddr", "get-thread-local-storage-address",
  10116.                          0);

  10117.   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
  10118.                          "qGetTIBAddr", "get-thread-information-block-address",
  10119.                          0);

  10120.   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
  10121.                          "bc", "reverse-continue", 0);

  10122.   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
  10123.                          "bs", "reverse-step", 0);

  10124.   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
  10125.                          "qSupported", "supported-packets", 0);

  10126.   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
  10127.                          "qSearch:memory", "search-memory", 0);

  10128.   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
  10129.                          "qTStatus", "trace-status", 0);

  10130.   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
  10131.                          "vFile:open", "hostio-open", 0);

  10132.   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
  10133.                          "vFile:pread", "hostio-pread", 0);

  10134.   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
  10135.                          "vFile:pwrite", "hostio-pwrite", 0);

  10136.   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
  10137.                          "vFile:close", "hostio-close", 0);

  10138.   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
  10139.                          "vFile:unlink", "hostio-unlink", 0);

  10140.   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
  10141.                          "vFile:readlink", "hostio-readlink", 0);

  10142.   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
  10143.                          "vAttach", "attach", 0);

  10144.   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
  10145.                          "vRun", "run", 0);

  10146.   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
  10147.                          "QStartNoAckMode", "noack", 0);

  10148.   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
  10149.                          "vKill", "kill", 0);

  10150.   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
  10151.                          "qAttached", "query-attached", 0);

  10152.   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
  10153.                          "ConditionalTracepoints",
  10154.                          "conditional-tracepoints", 0);

  10155.   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
  10156.                          "ConditionalBreakpoints",
  10157.                          "conditional-breakpoints", 0);

  10158.   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
  10159.                          "BreakpointCommands",
  10160.                          "breakpoint-commands", 0);

  10161.   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
  10162.                          "FastTracepoints", "fast-tracepoints", 0);

  10163.   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
  10164.                          "TracepointSource", "TracepointSource", 0);

  10165.   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
  10166.                          "QAllow", "allow", 0);

  10167.   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
  10168.                          "StaticTracepoints", "static-tracepoints", 0);

  10169.   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
  10170.                          "InstallInTrace", "install-in-trace", 0);

  10171.   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
  10172.                          "qXfer:statictrace:read", "read-sdata-object", 0);

  10173.   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
  10174.                          "qXfer:fdpic:read", "read-fdpic-loadmap", 0);

  10175.   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
  10176.                          "QDisableRandomization", "disable-randomization", 0);

  10177.   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
  10178.                          "QAgent", "agent", 0);

  10179.   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
  10180.                          "QTBuffer:size", "trace-buffer-size", 0);

  10181.   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
  10182.        "Qbtrace:off", "disable-btrace", 0);

  10183.   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
  10184.        "Qbtrace:bts", "enable-btrace", 0);

  10185.   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
  10186.        "qXfer:btrace", "read-btrace", 0);

  10187.   /* Assert that we've registered commands for all packet configs.  */
  10188.   {
  10189.     int i;

  10190.     for (i = 0; i < PACKET_MAX; i++)
  10191.       {
  10192.         /* Ideally all configs would have a command associated.  Some
  10193.            still don't though.  */
  10194.         int excepted;

  10195.         switch (i)
  10196.           {
  10197.           case PACKET_QNonStop:
  10198.           case PACKET_multiprocess_feature:
  10199.           case PACKET_EnableDisableTracepoints_feature:
  10200.           case PACKET_tracenz_feature:
  10201.           case PACKET_DisconnectedTracing_feature:
  10202.           case PACKET_augmented_libraries_svr4_read_feature:
  10203.           case PACKET_qCRC:
  10204.             /* Additions to this list need to be well justified:
  10205.                pre-existing packets are OK; new packets are not.  */
  10206.             excepted = 1;
  10207.             break;
  10208.           default:
  10209.             excepted = 0;
  10210.             break;
  10211.           }

  10212.         /* This catches both forgetting to add a config command, and
  10213.            forgetting to remove a packet from the exception list.  */
  10214.         gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
  10215.       }
  10216.   }

  10217.   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
  10218.      Z sub-packet has its own set and show commands, but users may
  10219.      have sets to this variable in their .gdbinit files (or in their
  10220.      documentation).  */
  10221.   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
  10222.                                 &remote_Z_packet_detect, _("\
  10223. Set use of remote protocol `Z' packets"), _("\
  10224. Show use of remote protocol `Z' packets "), _("\
  10225. When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
  10226. packets."),
  10227.                                 set_remote_protocol_Z_packet_cmd,
  10228.                                 show_remote_protocol_Z_packet_cmd,
  10229.                                 /* FIXME: i18n: Use of remote protocol
  10230.                                    `Z' packets is %s.  */
  10231.                                 &remote_set_cmdlist, &remote_show_cmdlist);

  10232.   add_prefix_cmd ("remote", class_files, remote_command, _("\
  10233. Manipulate files on the remote system\n\
  10234. Transfer files to and from the remote target system."),
  10235.                   &remote_cmdlist, "remote ",
  10236.                   0 /* allow-unknown */, &cmdlist);

  10237.   add_cmd ("put", class_files, remote_put_command,
  10238.            _("Copy a local file to the remote system."),
  10239.            &remote_cmdlist);

  10240.   add_cmd ("get", class_files, remote_get_command,
  10241.            _("Copy a remote file to the local system."),
  10242.            &remote_cmdlist);

  10243.   add_cmd ("delete", class_files, remote_delete_command,
  10244.            _("Delete a remote file."),
  10245.            &remote_cmdlist);

  10246.   remote_exec_file = xstrdup ("");
  10247.   add_setshow_string_noescape_cmd ("exec-file", class_files,
  10248.                                    &remote_exec_file, _("\
  10249. Set the remote pathname for \"run\""), _("\
  10250. Show the remote pathname for \"run\""), NULL, NULL, NULL,
  10251.                                    &remote_set_cmdlist, &remote_show_cmdlist);

  10252.   add_setshow_boolean_cmd ("range-stepping", class_run,
  10253.                            &use_range_stepping, _("\
  10254. Enable or disable range stepping."), _("\
  10255. Show whether target-assisted range stepping is enabled."), _("\
  10256. If on, and the target supports it, when stepping a source line, GDB\n\
  10257. tells the target to step the corresponding range of addresses itself instead\n\
  10258. of issuing multiple single-steps.  This speeds up source level\n\
  10259. stepping.  If off, GDB always issues single-steps, even if range\n\
  10260. stepping is supported by the target.  The default is on."),
  10261.                            set_range_stepping,
  10262.                            show_range_stepping,
  10263.                            &setlist,
  10264.                            &showlist);

  10265.   /* Eventually initialize fileio.  See fileio.c */
  10266.   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);

  10267.   /* Take advantage of the fact that the TID field is not used, to tag
  10268.      special ptids with it set to != 0.  */
  10269.   magic_null_ptid = ptid_build (42000, -1, 1);
  10270.   not_sent_ptid = ptid_build (42000, -2, 1);
  10271.   any_thread_ptid = ptid_build (42000, 0, 1);

  10272.   target_buf_size = 2048;
  10273.   target_buf = xmalloc (target_buf_size);
  10274. }