GDB (API)
/home/stan/gdb/src/gdb/remote.c
Go to the documentation of this file.
00001 /* Remote target communications for serial-line targets in custom GDB protocol
00002 
00003    Copyright (C) 1988-2013 Free Software Foundation, Inc.
00004 
00005    This file is part of GDB.
00006 
00007    This program is free software; you can redistribute it and/or modify
00008    it under the terms of the GNU General Public License as published by
00009    the Free Software Foundation; either version 3 of the License, or
00010    (at your option) any later version.
00011 
00012    This program is distributed in the hope that it will be useful,
00013    but WITHOUT ANY WARRANTY; without even the implied warranty of
00014    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00015    GNU General Public License for more details.
00016 
00017    You should have received a copy of the GNU General Public License
00018    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
00019 
00020 /* See the GDB User Guide for details of the GDB remote protocol.  */
00021 
00022 #include "defs.h"
00023 #include "gdb_string.h"
00024 #include <ctype.h>
00025 #include <fcntl.h>
00026 #include "inferior.h"
00027 #include "bfd.h"
00028 #include "symfile.h"
00029 #include "exceptions.h"
00030 #include "target.h"
00031 /*#include "terminal.h" */
00032 #include "gdbcmd.h"
00033 #include "objfiles.h"
00034 #include "gdb-stabs.h"
00035 #include "gdbthread.h"
00036 #include "remote.h"
00037 #include "remote-notif.h"
00038 #include "regcache.h"
00039 #include "value.h"
00040 #include "gdb_assert.h"
00041 #include "observer.h"
00042 #include "solib.h"
00043 #include "cli/cli-decode.h"
00044 #include "cli/cli-setshow.h"
00045 #include "target-descriptions.h"
00046 #include "gdb_bfd.h"
00047 #include "filestuff.h"
00048 
00049 #include <ctype.h>
00050 #include <sys/time.h>
00051 
00052 #include "event-loop.h"
00053 #include "event-top.h"
00054 #include "inf-loop.h"
00055 
00056 #include <signal.h>
00057 #include "serial.h"
00058 
00059 #include "gdbcore.h" /* for exec_bfd */
00060 
00061 #include "remote-fileio.h"
00062 #include "gdb/fileio.h"
00063 #include "gdb_stat.h"
00064 #include "xml-support.h"
00065 
00066 #include "memory-map.h"
00067 
00068 #include "tracepoint.h"
00069 #include "ax.h"
00070 #include "ax-gdb.h"
00071 #include "agent.h"
00072 #include "btrace.h"
00073 
00074 /* Temp hacks for tracepoint encoding migration.  */
00075 static char *target_buf;
00076 static long target_buf_size;
00077 
00078 /* The size to align memory write packets, when practical.  The protocol
00079    does not guarantee any alignment, and gdb will generate short
00080    writes and unaligned writes, but even as a best-effort attempt this
00081    can improve bulk transfers.  For instance, if a write is misaligned
00082    relative to the target's data bus, the stub may need to make an extra
00083    round trip fetching data from the target.  This doesn't make a
00084    huge difference, but it's easy to do, so we try to be helpful.
00085 
00086    The alignment chosen is arbitrary; usually data bus width is
00087    important here, not the possibly larger cache line size.  */
00088 enum { REMOTE_ALIGN_WRITES = 16 };
00089 
00090 /* Prototypes for local functions.  */
00091 static void async_cleanup_sigint_signal_handler (void *dummy);
00092 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
00093 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
00094                                  int forever, int *is_notif);
00095 
00096 static void async_handle_remote_sigint (int);
00097 static void async_handle_remote_sigint_twice (int);
00098 
00099 static void remote_files_info (struct target_ops *ignore);
00100 
00101 static void remote_prepare_to_store (struct regcache *regcache);
00102 
00103 static void remote_open (char *name, int from_tty);
00104 
00105 static void extended_remote_open (char *name, int from_tty);
00106 
00107 static void remote_open_1 (char *, int, struct target_ops *, int extended_p);
00108 
00109 static void remote_close (void);
00110 
00111 static void remote_mourn (struct target_ops *ops);
00112 
00113 static void extended_remote_restart (void);
00114 
00115 static void extended_remote_mourn (struct target_ops *);
00116 
00117 static void remote_mourn_1 (struct target_ops *);
00118 
00119 static void remote_send (char **buf, long *sizeof_buf_p);
00120 
00121 static int readchar (int timeout);
00122 
00123 static void remote_serial_write (const char *str, int len);
00124 
00125 static void remote_kill (struct target_ops *ops);
00126 
00127 static int tohex (int nib);
00128 
00129 static int remote_can_async_p (void);
00130 
00131 static int remote_is_async_p (void);
00132 
00133 static void remote_async (void (*callback) (enum inferior_event_type event_type,
00134                                             void *context), void *context);
00135 
00136 static void remote_detach (struct target_ops *ops, char *args, int from_tty);
00137 
00138 static void sync_remote_interrupt_twice (int signo);
00139 
00140 static void interrupt_query (void);
00141 
00142 static void set_general_thread (struct ptid ptid);
00143 static void set_continue_thread (struct ptid ptid);
00144 
00145 static void get_offsets (void);
00146 
00147 static void skip_frame (void);
00148 
00149 static long read_frame (char **buf_p, long *sizeof_buf);
00150 
00151 static int hexnumlen (ULONGEST num);
00152 
00153 static void init_remote_ops (void);
00154 
00155 static void init_extended_remote_ops (void);
00156 
00157 static void remote_stop (ptid_t);
00158 
00159 static int ishex (int ch, int *val);
00160 
00161 static int stubhex (int ch);
00162 
00163 static int hexnumstr (char *, ULONGEST);
00164 
00165 static int hexnumnstr (char *, ULONGEST, int);
00166 
00167 static CORE_ADDR remote_address_masked (CORE_ADDR);
00168 
00169 static void print_packet (char *);
00170 
00171 static void compare_sections_command (char *, int);
00172 
00173 static void packet_command (char *, int);
00174 
00175 static int stub_unpack_int (char *buff, int fieldlength);
00176 
00177 static ptid_t remote_current_thread (ptid_t oldptid);
00178 
00179 static void remote_find_new_threads (void);
00180 
00181 static int fromhex (int a);
00182 
00183 static int putpkt_binary (char *buf, int cnt);
00184 
00185 static void check_binary_download (CORE_ADDR addr);
00186 
00187 struct packet_config;
00188 
00189 static void show_packet_config_cmd (struct packet_config *config);
00190 
00191 static void update_packet_config (struct packet_config *config);
00192 
00193 static void set_remote_protocol_packet_cmd (char *args, int from_tty,
00194                                             struct cmd_list_element *c);
00195 
00196 static void show_remote_protocol_packet_cmd (struct ui_file *file,
00197                                              int from_tty,
00198                                              struct cmd_list_element *c,
00199                                              const char *value);
00200 
00201 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
00202 static ptid_t read_ptid (char *buf, char **obuf);
00203 
00204 static void remote_set_permissions (void);
00205 
00206 struct remote_state;
00207 static int remote_get_trace_status (struct trace_status *ts);
00208 
00209 static int remote_upload_tracepoints (struct uploaded_tp **utpp);
00210 
00211 static int remote_upload_trace_state_variables (struct uploaded_tsv **utsvp);
00212   
00213 static void remote_query_supported (void);
00214 
00215 static void remote_check_symbols (void);
00216 
00217 void _initialize_remote (void);
00218 
00219 struct stop_reply;
00220 static void stop_reply_xfree (struct stop_reply *);
00221 static void remote_parse_stop_reply (char *, struct stop_reply *);
00222 static void push_stop_reply (struct stop_reply *);
00223 static void discard_pending_stop_replies_in_queue (struct remote_state *);
00224 static int peek_stop_reply (ptid_t ptid);
00225 
00226 static void remote_async_inferior_event_handler (gdb_client_data);
00227 
00228 static void remote_terminal_ours (void);
00229 
00230 static int remote_read_description_p (struct target_ops *target);
00231 
00232 static void remote_console_output (char *msg);
00233 
00234 static int remote_supports_cond_breakpoints (void);
00235 
00236 static int remote_can_run_breakpoint_commands (void);
00237 
00238 /* For "remote".  */
00239 
00240 static struct cmd_list_element *remote_cmdlist;
00241 
00242 /* For "set remote" and "show remote".  */
00243 
00244 static struct cmd_list_element *remote_set_cmdlist;
00245 static struct cmd_list_element *remote_show_cmdlist;
00246 
00247 /* Stub vCont actions support.
00248 
00249    Each field is a boolean flag indicating whether the stub reports
00250    support for the corresponding action.  */
00251 
00252 struct vCont_action_support
00253 {
00254   /* vCont;t */
00255   int t;
00256 
00257   /* vCont;r */
00258   int r;
00259 };
00260 
00261 /* Controls whether GDB is willing to use range stepping.  */
00262 
00263 static int use_range_stepping = 1;
00264 
00265 #define OPAQUETHREADBYTES 8
00266 
00267 /* a 64 bit opaque identifier */
00268 typedef unsigned char threadref[OPAQUETHREADBYTES];
00269 
00270 /* About this many threadisds fit in a packet.  */
00271 
00272 #define MAXTHREADLISTRESULTS 32
00273 
00274 /* Description of the remote protocol state for the currently
00275    connected target.  This is per-target state, and independent of the
00276    selected architecture.  */
00277 
00278 struct remote_state
00279 {
00280   /* A buffer to use for incoming packets, and its current size.  The
00281      buffer is grown dynamically for larger incoming packets.
00282      Outgoing packets may also be constructed in this buffer.
00283      BUF_SIZE is always at least REMOTE_PACKET_SIZE;
00284      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
00285      packets.  */
00286   char *buf;
00287   long buf_size;
00288 
00289   /* True if we're going through initial connection setup (finding out
00290      about the remote side's threads, relocating symbols, etc.).  */
00291   int starting_up;
00292 
00293   /* If we negotiated packet size explicitly (and thus can bypass
00294      heuristics for the largest packet size that will not overflow
00295      a buffer in the stub), this will be set to that packet size.
00296      Otherwise zero, meaning to use the guessed size.  */
00297   long explicit_packet_size;
00298 
00299   /* remote_wait is normally called when the target is running and
00300      waits for a stop reply packet.  But sometimes we need to call it
00301      when the target is already stopped.  We can send a "?" packet
00302      and have remote_wait read the response.  Or, if we already have
00303      the response, we can stash it in BUF and tell remote_wait to
00304      skip calling getpkt.  This flag is set when BUF contains a
00305      stop reply packet and the target is not waiting.  */
00306   int cached_wait_status;
00307 
00308   /* True, if in no ack mode.  That is, neither GDB nor the stub will
00309      expect acks from each other.  The connection is assumed to be
00310      reliable.  */
00311   int noack_mode;
00312 
00313   /* True if we're connected in extended remote mode.  */
00314   int extended;
00315 
00316   /* True if the stub reported support for multi-process
00317      extensions.  */
00318   int multi_process_aware;
00319 
00320   /* True if we resumed the target and we're waiting for the target to
00321      stop.  In the mean time, we can't start another command/query.
00322      The remote server wouldn't be ready to process it, so we'd
00323      timeout waiting for a reply that would never come and eventually
00324      we'd close the connection.  This can happen in asynchronous mode
00325      because we allow GDB commands while the target is running.  */
00326   int waiting_for_stop_reply;
00327 
00328   /* True if the stub reports support for non-stop mode.  */
00329   int non_stop_aware;
00330 
00331   /* The status of the stub support for the various vCont actions.  */
00332   struct vCont_action_support supports_vCont;
00333 
00334   /* True if the stub reports support for conditional tracepoints.  */
00335   int cond_tracepoints;
00336 
00337   /* True if the stub reports support for target-side breakpoint
00338      conditions.  */
00339   int cond_breakpoints;
00340 
00341   /* True if the stub reports support for target-side breakpoint
00342      commands.  */
00343   int breakpoint_commands;
00344 
00345   /* True if the stub reports support for fast tracepoints.  */
00346   int fast_tracepoints;
00347 
00348   /* True if the stub reports support for static tracepoints.  */
00349   int static_tracepoints;
00350 
00351   /* True if the stub reports support for installing tracepoint while
00352      tracing.  */
00353   int install_in_trace;
00354 
00355   /* True if the stub can continue running a trace while GDB is
00356      disconnected.  */
00357   int disconnected_tracing;
00358 
00359   /* True if the stub reports support for enabling and disabling
00360      tracepoints while a trace experiment is running.  */
00361   int enable_disable_tracepoints;
00362 
00363   /* True if the stub can collect strings using tracenz bytecode.  */
00364   int string_tracing;
00365 
00366   /* True if the stub supports qXfer:libraries-svr4:read with a
00367      non-empty annex.  */
00368   int augmented_libraries_svr4_read;
00369 
00370   /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
00371      responded to that.  */
00372   int ctrlc_pending_p;
00373 
00374   /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
00375      remote_open knows that we don't have a file open when the program
00376      starts.  */
00377   struct serial *remote_desc;
00378 
00379   /* These are the threads which we last sent to the remote system.  The
00380      TID member will be -1 for all or -2 for not sent yet.  */
00381   ptid_t general_thread;
00382   ptid_t continue_thread;
00383 
00384   /* This is the traceframe which we last selected on the remote system.
00385      It will be -1 if no traceframe is selected.  */
00386   int remote_traceframe_number;
00387 
00388   char *last_pass_packet;
00389 
00390   /* The last QProgramSignals packet sent to the target.  We bypass
00391      sending a new program signals list down to the target if the new
00392      packet is exactly the same as the last we sent.  IOW, we only let
00393      the target know about program signals list changes.  */
00394   char *last_program_signals_packet;
00395 
00396   enum gdb_signal last_sent_signal;
00397 
00398   int last_sent_step;
00399 
00400   char *finished_object;
00401   char *finished_annex;
00402   ULONGEST finished_offset;
00403 
00404   /* Should we try the 'ThreadInfo' query packet?
00405 
00406      This variable (NOT available to the user: auto-detect only!)
00407      determines whether GDB will use the new, simpler "ThreadInfo"
00408      query or the older, more complex syntax for thread queries.
00409      This is an auto-detect variable (set to true at each connect,
00410      and set to false when the target fails to recognize it).  */
00411   int use_threadinfo_query;
00412   int use_threadextra_query;
00413 
00414   void (*async_client_callback) (enum inferior_event_type event_type,
00415                                  void *context);
00416   void *async_client_context;
00417 
00418   /* This is set to the data address of the access causing the target
00419      to stop for a watchpoint.  */
00420   CORE_ADDR remote_watch_data_address;
00421 
00422   /* This is non-zero if target stopped for a watchpoint.  */
00423   int remote_stopped_by_watchpoint_p;
00424 
00425   threadref echo_nextthread;
00426   threadref nextthread;
00427   threadref resultthreadlist[MAXTHREADLISTRESULTS];
00428 
00429   /* The state of remote notification.  */
00430   struct remote_notif_state *notif_state;
00431 };
00432 
00433 /* Private data that we'll store in (struct thread_info)->private.  */
00434 struct private_thread_info
00435 {
00436   char *extra;
00437   int core;
00438 };
00439 
00440 static void
00441 free_private_thread_info (struct private_thread_info *info)
00442 {
00443   xfree (info->extra);
00444   xfree (info);
00445 }
00446 
00447 /* Returns true if the multi-process extensions are in effect.  */
00448 static int
00449 remote_multi_process_p (struct remote_state *rs)
00450 {
00451   return rs->multi_process_aware;
00452 }
00453 
00454 /* This data could be associated with a target, but we do not always
00455    have access to the current target when we need it, so for now it is
00456    static.  This will be fine for as long as only one target is in use
00457    at a time.  */
00458 static struct remote_state *remote_state;
00459 
00460 static struct remote_state *
00461 get_remote_state_raw (void)
00462 {
00463   return remote_state;
00464 }
00465 
00466 /* Allocate a new struct remote_state with xmalloc, initialize it, and
00467    return it.  */
00468 
00469 static struct remote_state *
00470 new_remote_state (void)
00471 {
00472   struct remote_state *result = XCNEW (struct remote_state);
00473 
00474   /* The default buffer size is unimportant; it will be expanded
00475      whenever a larger buffer is needed. */
00476   result->buf_size = 400;
00477   result->buf = xmalloc (result->buf_size);
00478   result->remote_traceframe_number = -1;
00479   result->last_sent_signal = GDB_SIGNAL_0;
00480 
00481   return result;
00482 }
00483 
00484 /* Description of the remote protocol for a given architecture.  */
00485 
00486 struct packet_reg
00487 {
00488   long offset; /* Offset into G packet.  */
00489   long regnum; /* GDB's internal register number.  */
00490   LONGEST pnum; /* Remote protocol register number.  */
00491   int in_g_packet; /* Always part of G packet.  */
00492   /* long size in bytes;  == register_size (target_gdbarch (), regnum);
00493      at present.  */
00494   /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
00495      at present.  */
00496 };
00497 
00498 struct remote_arch_state
00499 {
00500   /* Description of the remote protocol registers.  */
00501   long sizeof_g_packet;
00502 
00503   /* Description of the remote protocol registers indexed by REGNUM
00504      (making an array gdbarch_num_regs in size).  */
00505   struct packet_reg *regs;
00506 
00507   /* This is the size (in chars) of the first response to the ``g''
00508      packet.  It is used as a heuristic when determining the maximum
00509      size of memory-read and memory-write packets.  A target will
00510      typically only reserve a buffer large enough to hold the ``g''
00511      packet.  The size does not include packet overhead (headers and
00512      trailers).  */
00513   long actual_register_packet_size;
00514 
00515   /* This is the maximum size (in chars) of a non read/write packet.
00516      It is also used as a cap on the size of read/write packets.  */
00517   long remote_packet_size;
00518 };
00519 
00520 /* Utility: generate error from an incoming stub packet.  */
00521 static void
00522 trace_error (char *buf)
00523 {
00524   if (*buf++ != 'E')
00525     return;                     /* not an error msg */
00526   switch (*buf)
00527     {
00528     case '1':                   /* malformed packet error */
00529       if (*++buf == '0')        /*   general case: */
00530         error (_("remote.c: error in outgoing packet."));
00531       else
00532         error (_("remote.c: error in outgoing packet at field #%ld."),
00533                strtol (buf, NULL, 16));
00534     default:
00535       error (_("Target returns error code '%s'."), buf);
00536     }
00537 }
00538 
00539 /* Utility: wait for reply from stub, while accepting "O" packets.  */
00540 static char *
00541 remote_get_noisy_reply (char **buf_p,
00542                         long *sizeof_buf)
00543 {
00544   do                            /* Loop on reply from remote stub.  */
00545     {
00546       char *buf;
00547 
00548       QUIT;                     /* Allow user to bail out with ^C.  */
00549       getpkt (buf_p, sizeof_buf, 0);
00550       buf = *buf_p;
00551       if (buf[0] == 'E')
00552         trace_error (buf);
00553       else if (strncmp (buf, "qRelocInsn:", strlen ("qRelocInsn:")) == 0)
00554         {
00555           ULONGEST ul;
00556           CORE_ADDR from, to, org_to;
00557           char *p, *pp;
00558           int adjusted_size = 0;
00559           volatile struct gdb_exception ex;
00560 
00561           p = buf + strlen ("qRelocInsn:");
00562           pp = unpack_varlen_hex (p, &ul);
00563           if (*pp != ';')
00564             error (_("invalid qRelocInsn packet: %s"), buf);
00565           from = ul;
00566 
00567           p = pp + 1;
00568           unpack_varlen_hex (p, &ul);
00569           to = ul;
00570 
00571           org_to = to;
00572 
00573           TRY_CATCH (ex, RETURN_MASK_ALL)
00574             {
00575               gdbarch_relocate_instruction (target_gdbarch (), &to, from);
00576             }
00577           if (ex.reason >= 0)
00578             {
00579               adjusted_size = to - org_to;
00580 
00581               xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
00582               putpkt (buf);
00583             }
00584           else if (ex.reason < 0 && ex.error == MEMORY_ERROR)
00585             {
00586               /* Propagate memory errors silently back to the target.
00587                  The stub may have limited the range of addresses we
00588                  can write to, for example.  */
00589               putpkt ("E01");
00590             }
00591           else
00592             {
00593               /* Something unexpectedly bad happened.  Be verbose so
00594                  we can tell what, and propagate the error back to the
00595                  stub, so it doesn't get stuck waiting for a
00596                  response.  */
00597               exception_fprintf (gdb_stderr, ex,
00598                                  _("warning: relocating instruction: "));
00599               putpkt ("E01");
00600             }
00601         }
00602       else if (buf[0] == 'O' && buf[1] != 'K')
00603         remote_console_output (buf + 1);        /* 'O' message from stub */
00604       else
00605         return buf;             /* Here's the actual reply.  */
00606     }
00607   while (1);
00608 }
00609 
00610 /* Handle for retreving the remote protocol data from gdbarch.  */
00611 static struct gdbarch_data *remote_gdbarch_data_handle;
00612 
00613 static struct remote_arch_state *
00614 get_remote_arch_state (void)
00615 {
00616   return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
00617 }
00618 
00619 /* Fetch the global remote target state.  */
00620 
00621 static struct remote_state *
00622 get_remote_state (void)
00623 {
00624   /* Make sure that the remote architecture state has been
00625      initialized, because doing so might reallocate rs->buf.  Any
00626      function which calls getpkt also needs to be mindful of changes
00627      to rs->buf, but this call limits the number of places which run
00628      into trouble.  */
00629   get_remote_arch_state ();
00630 
00631   return get_remote_state_raw ();
00632 }
00633 
00634 static int
00635 compare_pnums (const void *lhs_, const void *rhs_)
00636 {
00637   const struct packet_reg * const *lhs = lhs_;
00638   const struct packet_reg * const *rhs = rhs_;
00639 
00640   if ((*lhs)->pnum < (*rhs)->pnum)
00641     return -1;
00642   else if ((*lhs)->pnum == (*rhs)->pnum)
00643     return 0;
00644   else
00645     return 1;
00646 }
00647 
00648 static int
00649 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
00650 {
00651   int regnum, num_remote_regs, offset;
00652   struct packet_reg **remote_regs;
00653 
00654   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
00655     {
00656       struct packet_reg *r = &regs[regnum];
00657 
00658       if (register_size (gdbarch, regnum) == 0)
00659         /* Do not try to fetch zero-sized (placeholder) registers.  */
00660         r->pnum = -1;
00661       else
00662         r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
00663 
00664       r->regnum = regnum;
00665     }
00666 
00667   /* Define the g/G packet format as the contents of each register
00668      with a remote protocol number, in order of ascending protocol
00669      number.  */
00670 
00671   remote_regs = alloca (gdbarch_num_regs (gdbarch)
00672                         * sizeof (struct packet_reg *));
00673   for (num_remote_regs = 0, regnum = 0;
00674        regnum < gdbarch_num_regs (gdbarch);
00675        regnum++)
00676     if (regs[regnum].pnum != -1)
00677       remote_regs[num_remote_regs++] = &regs[regnum];
00678 
00679   qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
00680          compare_pnums);
00681 
00682   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
00683     {
00684       remote_regs[regnum]->in_g_packet = 1;
00685       remote_regs[regnum]->offset = offset;
00686       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
00687     }
00688 
00689   return offset;
00690 }
00691 
00692 /* Given the architecture described by GDBARCH, return the remote
00693    protocol register's number and the register's offset in the g/G
00694    packets of GDB register REGNUM, in PNUM and POFFSET respectively.
00695    If the target does not have a mapping for REGNUM, return false,
00696    otherwise, return true.  */
00697 
00698 int
00699 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
00700                                    int *pnum, int *poffset)
00701 {
00702   int sizeof_g_packet;
00703   struct packet_reg *regs;
00704   struct cleanup *old_chain;
00705 
00706   gdb_assert (regnum < gdbarch_num_regs (gdbarch));
00707 
00708   regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
00709   old_chain = make_cleanup (xfree, regs);
00710 
00711   sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
00712 
00713   *pnum = regs[regnum].pnum;
00714   *poffset = regs[regnum].offset;
00715 
00716   do_cleanups (old_chain);
00717 
00718   return *pnum != -1;
00719 }
00720 
00721 static void *
00722 init_remote_state (struct gdbarch *gdbarch)
00723 {
00724   struct remote_state *rs = get_remote_state_raw ();
00725   struct remote_arch_state *rsa;
00726 
00727   rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
00728 
00729   /* Use the architecture to build a regnum<->pnum table, which will be
00730      1:1 unless a feature set specifies otherwise.  */
00731   rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
00732                                       gdbarch_num_regs (gdbarch),
00733                                       struct packet_reg);
00734 
00735   /* Record the maximum possible size of the g packet - it may turn out
00736      to be smaller.  */
00737   rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
00738 
00739   /* Default maximum number of characters in a packet body.  Many
00740      remote stubs have a hardwired buffer size of 400 bytes
00741      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
00742      as the maximum packet-size to ensure that the packet and an extra
00743      NUL character can always fit in the buffer.  This stops GDB
00744      trashing stubs that try to squeeze an extra NUL into what is
00745      already a full buffer (As of 1999-12-04 that was most stubs).  */
00746   rsa->remote_packet_size = 400 - 1;
00747 
00748   /* This one is filled in when a ``g'' packet is received.  */
00749   rsa->actual_register_packet_size = 0;
00750 
00751   /* Should rsa->sizeof_g_packet needs more space than the
00752      default, adjust the size accordingly.  Remember that each byte is
00753      encoded as two characters.  32 is the overhead for the packet
00754      header / footer.  NOTE: cagney/1999-10-26: I suspect that 8
00755      (``$NN:G...#NN'') is a better guess, the below has been padded a
00756      little.  */
00757   if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
00758     rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
00759 
00760   /* Make sure that the packet buffer is plenty big enough for
00761      this architecture.  */
00762   if (rs->buf_size < rsa->remote_packet_size)
00763     {
00764       rs->buf_size = 2 * rsa->remote_packet_size;
00765       rs->buf = xrealloc (rs->buf, rs->buf_size);
00766     }
00767 
00768   return rsa;
00769 }
00770 
00771 /* Return the current allowed size of a remote packet.  This is
00772    inferred from the current architecture, and should be used to
00773    limit the length of outgoing packets.  */
00774 static long
00775 get_remote_packet_size (void)
00776 {
00777   struct remote_state *rs = get_remote_state ();
00778   struct remote_arch_state *rsa = get_remote_arch_state ();
00779 
00780   if (rs->explicit_packet_size)
00781     return rs->explicit_packet_size;
00782 
00783   return rsa->remote_packet_size;
00784 }
00785 
00786 static struct packet_reg *
00787 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
00788 {
00789   if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
00790     return NULL;
00791   else
00792     {
00793       struct packet_reg *r = &rsa->regs[regnum];
00794 
00795       gdb_assert (r->regnum == regnum);
00796       return r;
00797     }
00798 }
00799 
00800 static struct packet_reg *
00801 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
00802 {
00803   int i;
00804 
00805   for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
00806     {
00807       struct packet_reg *r = &rsa->regs[i];
00808 
00809       if (r->pnum == pnum)
00810         return r;
00811     }
00812   return NULL;
00813 }
00814 
00815 static struct target_ops remote_ops;
00816 
00817 static struct target_ops extended_remote_ops;
00818 
00819 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
00820    ``forever'' still use the normal timeout mechanism.  This is
00821    currently used by the ASYNC code to guarentee that target reads
00822    during the initial connect always time-out.  Once getpkt has been
00823    modified to return a timeout indication and, in turn
00824    remote_wait()/wait_for_inferior() have gained a timeout parameter
00825    this can go away.  */
00826 static int wait_forever_enabled_p = 1;
00827 
00828 /* Allow the user to specify what sequence to send to the remote
00829    when he requests a program interruption: Although ^C is usually
00830    what remote systems expect (this is the default, here), it is
00831    sometimes preferable to send a break.  On other systems such
00832    as the Linux kernel, a break followed by g, which is Magic SysRq g
00833    is required in order to interrupt the execution.  */
00834 const char interrupt_sequence_control_c[] = "Ctrl-C";
00835 const char interrupt_sequence_break[] = "BREAK";
00836 const char interrupt_sequence_break_g[] = "BREAK-g";
00837 static const char *const interrupt_sequence_modes[] =
00838   {
00839     interrupt_sequence_control_c,
00840     interrupt_sequence_break,
00841     interrupt_sequence_break_g,
00842     NULL
00843   };
00844 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
00845 
00846 static void
00847 show_interrupt_sequence (struct ui_file *file, int from_tty,
00848                          struct cmd_list_element *c,
00849                          const char *value)
00850 {
00851   if (interrupt_sequence_mode == interrupt_sequence_control_c)
00852     fprintf_filtered (file,
00853                       _("Send the ASCII ETX character (Ctrl-c) "
00854                         "to the remote target to interrupt the "
00855                         "execution of the program.\n"));
00856   else if (interrupt_sequence_mode == interrupt_sequence_break)
00857     fprintf_filtered (file,
00858                       _("send a break signal to the remote target "
00859                         "to interrupt the execution of the program.\n"));
00860   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
00861     fprintf_filtered (file,
00862                       _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
00863                         "the remote target to interrupt the execution "
00864                         "of Linux kernel.\n"));
00865   else
00866     internal_error (__FILE__, __LINE__,
00867                     _("Invalid value for interrupt_sequence_mode: %s."),
00868                     interrupt_sequence_mode);
00869 }
00870 
00871 /* This boolean variable specifies whether interrupt_sequence is sent
00872    to the remote target when gdb connects to it.
00873    This is mostly needed when you debug the Linux kernel: The Linux kernel
00874    expects BREAK g which is Magic SysRq g for connecting gdb.  */
00875 static int interrupt_on_connect = 0;
00876 
00877 /* This variable is used to implement the "set/show remotebreak" commands.
00878    Since these commands are now deprecated in favor of "set/show remote
00879    interrupt-sequence", it no longer has any effect on the code.  */
00880 static int remote_break;
00881 
00882 static void
00883 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
00884 {
00885   if (remote_break)
00886     interrupt_sequence_mode = interrupt_sequence_break;
00887   else
00888     interrupt_sequence_mode = interrupt_sequence_control_c;
00889 }
00890 
00891 static void
00892 show_remotebreak (struct ui_file *file, int from_tty,
00893                   struct cmd_list_element *c,
00894                   const char *value)
00895 {
00896 }
00897 
00898 /* This variable sets the number of bits in an address that are to be
00899    sent in a memory ("M" or "m") packet.  Normally, after stripping
00900    leading zeros, the entire address would be sent.  This variable
00901    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
00902    initial implementation of remote.c restricted the address sent in
00903    memory packets to ``host::sizeof long'' bytes - (typically 32
00904    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
00905    address was never sent.  Since fixing this bug may cause a break in
00906    some remote targets this variable is principly provided to
00907    facilitate backward compatibility.  */
00908 
00909 static unsigned int remote_address_size;
00910 
00911 /* Temporary to track who currently owns the terminal.  See
00912    remote_terminal_* for more details.  */
00913 
00914 static int remote_async_terminal_ours_p;
00915 
00916 /* The executable file to use for "run" on the remote side.  */
00917 
00918 static char *remote_exec_file = "";
00919 
00920 
00921 /* User configurable variables for the number of characters in a
00922    memory read/write packet.  MIN (rsa->remote_packet_size,
00923    rsa->sizeof_g_packet) is the default.  Some targets need smaller
00924    values (fifo overruns, et.al.) and some users need larger values
00925    (speed up transfers).  The variables ``preferred_*'' (the user
00926    request), ``current_*'' (what was actually set) and ``forced_*''
00927    (Positive - a soft limit, negative - a hard limit).  */
00928 
00929 struct memory_packet_config
00930 {
00931   char *name;
00932   long size;
00933   int fixed_p;
00934 };
00935 
00936 /* Compute the current size of a read/write packet.  Since this makes
00937    use of ``actual_register_packet_size'' the computation is dynamic.  */
00938 
00939 static long
00940 get_memory_packet_size (struct memory_packet_config *config)
00941 {
00942   struct remote_state *rs = get_remote_state ();
00943   struct remote_arch_state *rsa = get_remote_arch_state ();
00944 
00945   /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
00946      law?) that some hosts don't cope very well with large alloca()
00947      calls.  Eventually the alloca() code will be replaced by calls to
00948      xmalloc() and make_cleanups() allowing this restriction to either
00949      be lifted or removed.  */
00950 #ifndef MAX_REMOTE_PACKET_SIZE
00951 #define MAX_REMOTE_PACKET_SIZE 16384
00952 #endif
00953   /* NOTE: 20 ensures we can write at least one byte.  */
00954 #ifndef MIN_REMOTE_PACKET_SIZE
00955 #define MIN_REMOTE_PACKET_SIZE 20
00956 #endif
00957   long what_they_get;
00958   if (config->fixed_p)
00959     {
00960       if (config->size <= 0)
00961         what_they_get = MAX_REMOTE_PACKET_SIZE;
00962       else
00963         what_they_get = config->size;
00964     }
00965   else
00966     {
00967       what_they_get = get_remote_packet_size ();
00968       /* Limit the packet to the size specified by the user.  */
00969       if (config->size > 0
00970           && what_they_get > config->size)
00971         what_they_get = config->size;
00972 
00973       /* Limit it to the size of the targets ``g'' response unless we have
00974          permission from the stub to use a larger packet size.  */
00975       if (rs->explicit_packet_size == 0
00976           && rsa->actual_register_packet_size > 0
00977           && what_they_get > rsa->actual_register_packet_size)
00978         what_they_get = rsa->actual_register_packet_size;
00979     }
00980   if (what_they_get > MAX_REMOTE_PACKET_SIZE)
00981     what_they_get = MAX_REMOTE_PACKET_SIZE;
00982   if (what_they_get < MIN_REMOTE_PACKET_SIZE)
00983     what_they_get = MIN_REMOTE_PACKET_SIZE;
00984 
00985   /* Make sure there is room in the global buffer for this packet
00986      (including its trailing NUL byte).  */
00987   if (rs->buf_size < what_they_get + 1)
00988     {
00989       rs->buf_size = 2 * what_they_get;
00990       rs->buf = xrealloc (rs->buf, 2 * what_they_get);
00991     }
00992 
00993   return what_they_get;
00994 }
00995 
00996 /* Update the size of a read/write packet.  If they user wants
00997    something really big then do a sanity check.  */
00998 
00999 static void
01000 set_memory_packet_size (char *args, struct memory_packet_config *config)
01001 {
01002   int fixed_p = config->fixed_p;
01003   long size = config->size;
01004 
01005   if (args == NULL)
01006     error (_("Argument required (integer, `fixed' or `limited')."));
01007   else if (strcmp (args, "hard") == 0
01008       || strcmp (args, "fixed") == 0)
01009     fixed_p = 1;
01010   else if (strcmp (args, "soft") == 0
01011            || strcmp (args, "limit") == 0)
01012     fixed_p = 0;
01013   else
01014     {
01015       char *end;
01016 
01017       size = strtoul (args, &end, 0);
01018       if (args == end)
01019         error (_("Invalid %s (bad syntax)."), config->name);
01020 #if 0
01021       /* Instead of explicitly capping the size of a packet to
01022          MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
01023          instead allowed to set the size to something arbitrarily
01024          large.  */
01025       if (size > MAX_REMOTE_PACKET_SIZE)
01026         error (_("Invalid %s (too large)."), config->name);
01027 #endif
01028     }
01029   /* Extra checks?  */
01030   if (fixed_p && !config->fixed_p)
01031     {
01032       if (! query (_("The target may not be able to correctly handle a %s\n"
01033                    "of %ld bytes. Change the packet size? "),
01034                    config->name, size))
01035         error (_("Packet size not changed."));
01036     }
01037   /* Update the config.  */
01038   config->fixed_p = fixed_p;
01039   config->size = size;
01040 }
01041 
01042 static void
01043 show_memory_packet_size (struct memory_packet_config *config)
01044 {
01045   printf_filtered (_("The %s is %ld. "), config->name, config->size);
01046   if (config->fixed_p)
01047     printf_filtered (_("Packets are fixed at %ld bytes.\n"),
01048                      get_memory_packet_size (config));
01049   else
01050     printf_filtered (_("Packets are limited to %ld bytes.\n"),
01051                      get_memory_packet_size (config));
01052 }
01053 
01054 static struct memory_packet_config memory_write_packet_config =
01055 {
01056   "memory-write-packet-size",
01057 };
01058 
01059 static void
01060 set_memory_write_packet_size (char *args, int from_tty)
01061 {
01062   set_memory_packet_size (args, &memory_write_packet_config);
01063 }
01064 
01065 static void
01066 show_memory_write_packet_size (char *args, int from_tty)
01067 {
01068   show_memory_packet_size (&memory_write_packet_config);
01069 }
01070 
01071 static long
01072 get_memory_write_packet_size (void)
01073 {
01074   return get_memory_packet_size (&memory_write_packet_config);
01075 }
01076 
01077 static struct memory_packet_config memory_read_packet_config =
01078 {
01079   "memory-read-packet-size",
01080 };
01081 
01082 static void
01083 set_memory_read_packet_size (char *args, int from_tty)
01084 {
01085   set_memory_packet_size (args, &memory_read_packet_config);
01086 }
01087 
01088 static void
01089 show_memory_read_packet_size (char *args, int from_tty)
01090 {
01091   show_memory_packet_size (&memory_read_packet_config);
01092 }
01093 
01094 static long
01095 get_memory_read_packet_size (void)
01096 {
01097   long size = get_memory_packet_size (&memory_read_packet_config);
01098 
01099   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
01100      extra buffer size argument before the memory read size can be
01101      increased beyond this.  */
01102   if (size > get_remote_packet_size ())
01103     size = get_remote_packet_size ();
01104   return size;
01105 }
01106 
01107 
01108 /* Generic configuration support for packets the stub optionally
01109    supports.  Allows the user to specify the use of the packet as well
01110    as allowing GDB to auto-detect support in the remote stub.  */
01111 
01112 enum packet_support
01113   {
01114     PACKET_SUPPORT_UNKNOWN = 0,
01115     PACKET_ENABLE,
01116     PACKET_DISABLE
01117   };
01118 
01119 struct packet_config
01120   {
01121     const char *name;
01122     const char *title;
01123     enum auto_boolean detect;
01124     enum packet_support support;
01125   };
01126 
01127 /* Analyze a packet's return value and update the packet config
01128    accordingly.  */
01129 
01130 enum packet_result
01131 {
01132   PACKET_ERROR,
01133   PACKET_OK,
01134   PACKET_UNKNOWN
01135 };
01136 
01137 static void
01138 update_packet_config (struct packet_config *config)
01139 {
01140   switch (config->detect)
01141     {
01142     case AUTO_BOOLEAN_TRUE:
01143       config->support = PACKET_ENABLE;
01144       break;
01145     case AUTO_BOOLEAN_FALSE:
01146       config->support = PACKET_DISABLE;
01147       break;
01148     case AUTO_BOOLEAN_AUTO:
01149       config->support = PACKET_SUPPORT_UNKNOWN;
01150       break;
01151     }
01152 }
01153 
01154 static void
01155 show_packet_config_cmd (struct packet_config *config)
01156 {
01157   char *support = "internal-error";
01158 
01159   switch (config->support)
01160     {
01161     case PACKET_ENABLE:
01162       support = "enabled";
01163       break;
01164     case PACKET_DISABLE:
01165       support = "disabled";
01166       break;
01167     case PACKET_SUPPORT_UNKNOWN:
01168       support = "unknown";
01169       break;
01170     }
01171   switch (config->detect)
01172     {
01173     case AUTO_BOOLEAN_AUTO:
01174       printf_filtered (_("Support for the `%s' packet "
01175                          "is auto-detected, currently %s.\n"),
01176                        config->name, support);
01177       break;
01178     case AUTO_BOOLEAN_TRUE:
01179     case AUTO_BOOLEAN_FALSE:
01180       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
01181                        config->name, support);
01182       break;
01183     }
01184 }
01185 
01186 static void
01187 add_packet_config_cmd (struct packet_config *config, const char *name,
01188                        const char *title, int legacy)
01189 {
01190   char *set_doc;
01191   char *show_doc;
01192   char *cmd_name;
01193 
01194   config->name = name;
01195   config->title = title;
01196   config->detect = AUTO_BOOLEAN_AUTO;
01197   config->support = PACKET_SUPPORT_UNKNOWN;
01198   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
01199                         name, title);
01200   show_doc = xstrprintf ("Show current use of remote "
01201                          "protocol `%s' (%s) packet",
01202                          name, title);
01203   /* set/show TITLE-packet {auto,on,off} */
01204   cmd_name = xstrprintf ("%s-packet", title);
01205   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
01206                                 &config->detect, set_doc,
01207                                 show_doc, NULL, /* help_doc */
01208                                 set_remote_protocol_packet_cmd,
01209                                 show_remote_protocol_packet_cmd,
01210                                 &remote_set_cmdlist, &remote_show_cmdlist);
01211   /* The command code copies the documentation strings.  */
01212   xfree (set_doc);
01213   xfree (show_doc);
01214   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
01215   if (legacy)
01216     {
01217       char *legacy_name;
01218 
01219       legacy_name = xstrprintf ("%s-packet", name);
01220       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
01221                      &remote_set_cmdlist);
01222       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
01223                      &remote_show_cmdlist);
01224     }
01225 }
01226 
01227 static enum packet_result
01228 packet_check_result (const char *buf)
01229 {
01230   if (buf[0] != '\0')
01231     {
01232       /* The stub recognized the packet request.  Check that the
01233          operation succeeded.  */
01234       if (buf[0] == 'E'
01235           && isxdigit (buf[1]) && isxdigit (buf[2])
01236           && buf[3] == '\0')
01237         /* "Enn"  - definitly an error.  */
01238         return PACKET_ERROR;
01239 
01240       /* Always treat "E." as an error.  This will be used for
01241          more verbose error messages, such as E.memtypes.  */
01242       if (buf[0] == 'E' && buf[1] == '.')
01243         return PACKET_ERROR;
01244 
01245       /* The packet may or may not be OK.  Just assume it is.  */
01246       return PACKET_OK;
01247     }
01248   else
01249     /* The stub does not support the packet.  */
01250     return PACKET_UNKNOWN;
01251 }
01252 
01253 static enum packet_result
01254 packet_ok (const char *buf, struct packet_config *config)
01255 {
01256   enum packet_result result;
01257 
01258   result = packet_check_result (buf);
01259   switch (result)
01260     {
01261     case PACKET_OK:
01262     case PACKET_ERROR:
01263       /* The stub recognized the packet request.  */
01264       switch (config->support)
01265         {
01266         case PACKET_SUPPORT_UNKNOWN:
01267           if (remote_debug)
01268             fprintf_unfiltered (gdb_stdlog,
01269                                     "Packet %s (%s) is supported\n",
01270                                     config->name, config->title);
01271           config->support = PACKET_ENABLE;
01272           break;
01273         case PACKET_DISABLE:
01274           internal_error (__FILE__, __LINE__,
01275                           _("packet_ok: attempt to use a disabled packet"));
01276           break;
01277         case PACKET_ENABLE:
01278           break;
01279         }
01280       break;
01281     case PACKET_UNKNOWN:
01282       /* The stub does not support the packet.  */
01283       switch (config->support)
01284         {
01285         case PACKET_ENABLE:
01286           if (config->detect == AUTO_BOOLEAN_AUTO)
01287             /* If the stub previously indicated that the packet was
01288                supported then there is a protocol error..  */
01289             error (_("Protocol error: %s (%s) conflicting enabled responses."),
01290                    config->name, config->title);
01291           else
01292             /* The user set it wrong.  */
01293             error (_("Enabled packet %s (%s) not recognized by stub"),
01294                    config->name, config->title);
01295           break;
01296         case PACKET_SUPPORT_UNKNOWN:
01297           if (remote_debug)
01298             fprintf_unfiltered (gdb_stdlog,
01299                                 "Packet %s (%s) is NOT supported\n",
01300                                 config->name, config->title);
01301           config->support = PACKET_DISABLE;
01302           break;
01303         case PACKET_DISABLE:
01304           break;
01305         }
01306       break;
01307     }
01308 
01309   return result;
01310 }
01311 
01312 enum {
01313   PACKET_vCont = 0,
01314   PACKET_X,
01315   PACKET_qSymbol,
01316   PACKET_P,
01317   PACKET_p,
01318   PACKET_Z0,
01319   PACKET_Z1,
01320   PACKET_Z2,
01321   PACKET_Z3,
01322   PACKET_Z4,
01323   PACKET_vFile_open,
01324   PACKET_vFile_pread,
01325   PACKET_vFile_pwrite,
01326   PACKET_vFile_close,
01327   PACKET_vFile_unlink,
01328   PACKET_vFile_readlink,
01329   PACKET_qXfer_auxv,
01330   PACKET_qXfer_features,
01331   PACKET_qXfer_libraries,
01332   PACKET_qXfer_libraries_svr4,
01333   PACKET_qXfer_memory_map,
01334   PACKET_qXfer_spu_read,
01335   PACKET_qXfer_spu_write,
01336   PACKET_qXfer_osdata,
01337   PACKET_qXfer_threads,
01338   PACKET_qXfer_statictrace_read,
01339   PACKET_qXfer_traceframe_info,
01340   PACKET_qXfer_uib,
01341   PACKET_qGetTIBAddr,
01342   PACKET_qGetTLSAddr,
01343   PACKET_qSupported,
01344   PACKET_qTStatus,
01345   PACKET_QPassSignals,
01346   PACKET_QProgramSignals,
01347   PACKET_qSearch_memory,
01348   PACKET_vAttach,
01349   PACKET_vRun,
01350   PACKET_QStartNoAckMode,
01351   PACKET_vKill,
01352   PACKET_qXfer_siginfo_read,
01353   PACKET_qXfer_siginfo_write,
01354   PACKET_qAttached,
01355   PACKET_ConditionalTracepoints,
01356   PACKET_ConditionalBreakpoints,
01357   PACKET_BreakpointCommands,
01358   PACKET_FastTracepoints,
01359   PACKET_StaticTracepoints,
01360   PACKET_InstallInTrace,
01361   PACKET_bc,
01362   PACKET_bs,
01363   PACKET_TracepointSource,
01364   PACKET_QAllow,
01365   PACKET_qXfer_fdpic,
01366   PACKET_QDisableRandomization,
01367   PACKET_QAgent,
01368   PACKET_QTBuffer_size,
01369   PACKET_Qbtrace_off,
01370   PACKET_Qbtrace_bts,
01371   PACKET_qXfer_btrace,
01372   PACKET_MAX
01373 };
01374 
01375 static struct packet_config remote_protocol_packets[PACKET_MAX];
01376 
01377 static void
01378 set_remote_protocol_packet_cmd (char *args, int from_tty,
01379                                 struct cmd_list_element *c)
01380 {
01381   struct packet_config *packet;
01382 
01383   for (packet = remote_protocol_packets;
01384        packet < &remote_protocol_packets[PACKET_MAX];
01385        packet++)
01386     {
01387       if (&packet->detect == c->var)
01388         {
01389           update_packet_config (packet);
01390           return;
01391         }
01392     }
01393   internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
01394                   c->name);
01395 }
01396 
01397 static void
01398 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
01399                                  struct cmd_list_element *c,
01400                                  const char *value)
01401 {
01402   struct packet_config *packet;
01403 
01404   for (packet = remote_protocol_packets;
01405        packet < &remote_protocol_packets[PACKET_MAX];
01406        packet++)
01407     {
01408       if (&packet->detect == c->var)
01409         {
01410           show_packet_config_cmd (packet);
01411           return;
01412         }
01413     }
01414   internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
01415                   c->name);
01416 }
01417 
01418 /* Should we try one of the 'Z' requests?  */
01419 
01420 enum Z_packet_type
01421 {
01422   Z_PACKET_SOFTWARE_BP,
01423   Z_PACKET_HARDWARE_BP,
01424   Z_PACKET_WRITE_WP,
01425   Z_PACKET_READ_WP,
01426   Z_PACKET_ACCESS_WP,
01427   NR_Z_PACKET_TYPES
01428 };
01429 
01430 /* For compatibility with older distributions.  Provide a ``set remote
01431    Z-packet ...'' command that updates all the Z packet types.  */
01432 
01433 static enum auto_boolean remote_Z_packet_detect;
01434 
01435 static void
01436 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
01437                                   struct cmd_list_element *c)
01438 {
01439   int i;
01440 
01441   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
01442     {
01443       remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
01444       update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
01445     }
01446 }
01447 
01448 static void
01449 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
01450                                    struct cmd_list_element *c,
01451                                    const char *value)
01452 {
01453   int i;
01454 
01455   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
01456     {
01457       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
01458     }
01459 }
01460 
01461 /* Tokens for use by the asynchronous signal handlers for SIGINT.  */
01462 static struct async_signal_handler *async_sigint_remote_twice_token;
01463 static struct async_signal_handler *async_sigint_remote_token;
01464 
01465 
01466 /* Asynchronous signal handle registered as event loop source for
01467    when we have pending events ready to be passed to the core.  */
01468 
01469 static struct async_event_handler *remote_async_inferior_event_token;
01470 
01471 
01472 
01473 static ptid_t magic_null_ptid;
01474 static ptid_t not_sent_ptid;
01475 static ptid_t any_thread_ptid;
01476 
01477 /* Find out if the stub attached to PID (and hence GDB should offer to
01478    detach instead of killing it when bailing out).  */
01479 
01480 static int
01481 remote_query_attached (int pid)
01482 {
01483   struct remote_state *rs = get_remote_state ();
01484   size_t size = get_remote_packet_size ();
01485 
01486   if (remote_protocol_packets[PACKET_qAttached].support == PACKET_DISABLE)
01487     return 0;
01488 
01489   if (remote_multi_process_p (rs))
01490     xsnprintf (rs->buf, size, "qAttached:%x", pid);
01491   else
01492     xsnprintf (rs->buf, size, "qAttached");
01493 
01494   putpkt (rs->buf);
01495   getpkt (&rs->buf, &rs->buf_size, 0);
01496 
01497   switch (packet_ok (rs->buf,
01498                      &remote_protocol_packets[PACKET_qAttached]))
01499     {
01500     case PACKET_OK:
01501       if (strcmp (rs->buf, "1") == 0)
01502         return 1;
01503       break;
01504     case PACKET_ERROR:
01505       warning (_("Remote failure reply: %s"), rs->buf);
01506       break;
01507     case PACKET_UNKNOWN:
01508       break;
01509     }
01510 
01511   return 0;
01512 }
01513 
01514 /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
01515    has been invented by GDB, instead of reported by the target.  Since
01516    we can be connected to a remote system before before knowing about
01517    any inferior, mark the target with execution when we find the first
01518    inferior.  If ATTACHED is 1, then we had just attached to this
01519    inferior.  If it is 0, then we just created this inferior.  If it
01520    is -1, then try querying the remote stub to find out if it had
01521    attached to the inferior or not.  */
01522 
01523 static struct inferior *
01524 remote_add_inferior (int fake_pid_p, int pid, int attached)
01525 {
01526   struct inferior *inf;
01527 
01528   /* Check whether this process we're learning about is to be
01529      considered attached, or if is to be considered to have been
01530      spawned by the stub.  */
01531   if (attached == -1)
01532     attached = remote_query_attached (pid);
01533 
01534   if (gdbarch_has_global_solist (target_gdbarch ()))
01535     {
01536       /* If the target shares code across all inferiors, then every
01537          attach adds a new inferior.  */
01538       inf = add_inferior (pid);
01539 
01540       /* ... and every inferior is bound to the same program space.
01541          However, each inferior may still have its own address
01542          space.  */
01543       inf->aspace = maybe_new_address_space ();
01544       inf->pspace = current_program_space;
01545     }
01546   else
01547     {
01548       /* In the traditional debugging scenario, there's a 1-1 match
01549          between program/address spaces.  We simply bind the inferior
01550          to the program space's address space.  */
01551       inf = current_inferior ();
01552       inferior_appeared (inf, pid);
01553     }
01554 
01555   inf->attach_flag = attached;
01556   inf->fake_pid_p = fake_pid_p;
01557 
01558   return inf;
01559 }
01560 
01561 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
01562    according to RUNNING.  */
01563 
01564 static void
01565 remote_add_thread (ptid_t ptid, int running)
01566 {
01567   add_thread (ptid);
01568 
01569   set_executing (ptid, running);
01570   set_running (ptid, running);
01571 }
01572 
01573 /* Come here when we learn about a thread id from the remote target.
01574    It may be the first time we hear about such thread, so take the
01575    opportunity to add it to GDB's thread list.  In case this is the
01576    first time we're noticing its corresponding inferior, add it to
01577    GDB's inferior list as well.  */
01578 
01579 static void
01580 remote_notice_new_inferior (ptid_t currthread, int running)
01581 {
01582   /* If this is a new thread, add it to GDB's thread list.
01583      If we leave it up to WFI to do this, bad things will happen.  */
01584 
01585   if (in_thread_list (currthread) && is_exited (currthread))
01586     {
01587       /* We're seeing an event on a thread id we knew had exited.
01588          This has to be a new thread reusing the old id.  Add it.  */
01589       remote_add_thread (currthread, running);
01590       return;
01591     }
01592 
01593   if (!in_thread_list (currthread))
01594     {
01595       struct inferior *inf = NULL;
01596       int pid = ptid_get_pid (currthread);
01597 
01598       if (ptid_is_pid (inferior_ptid)
01599           && pid == ptid_get_pid (inferior_ptid))
01600         {
01601           /* inferior_ptid has no thread member yet.  This can happen
01602              with the vAttach -> remote_wait,"TAAthread:" path if the
01603              stub doesn't support qC.  This is the first stop reported
01604              after an attach, so this is the main thread.  Update the
01605              ptid in the thread list.  */
01606           if (in_thread_list (pid_to_ptid (pid)))
01607             thread_change_ptid (inferior_ptid, currthread);
01608           else
01609             {
01610               remote_add_thread (currthread, running);
01611               inferior_ptid = currthread;
01612             }
01613           return;
01614         }
01615 
01616       if (ptid_equal (magic_null_ptid, inferior_ptid))
01617         {
01618           /* inferior_ptid is not set yet.  This can happen with the
01619              vRun -> remote_wait,"TAAthread:" path if the stub
01620              doesn't support qC.  This is the first stop reported
01621              after an attach, so this is the main thread.  Update the
01622              ptid in the thread list.  */
01623           thread_change_ptid (inferior_ptid, currthread);
01624           return;
01625         }
01626 
01627       /* When connecting to a target remote, or to a target
01628          extended-remote which already was debugging an inferior, we
01629          may not know about it yet.  Add it before adding its child
01630          thread, so notifications are emitted in a sensible order.  */
01631       if (!in_inferior_list (ptid_get_pid (currthread)))
01632         {
01633           struct remote_state *rs = get_remote_state ();
01634           int fake_pid_p = !remote_multi_process_p (rs);
01635 
01636           inf = remote_add_inferior (fake_pid_p,
01637                                      ptid_get_pid (currthread), -1);
01638         }
01639 
01640       /* This is really a new thread.  Add it.  */
01641       remote_add_thread (currthread, running);
01642 
01643       /* If we found a new inferior, let the common code do whatever
01644          it needs to with it (e.g., read shared libraries, insert
01645          breakpoints).  */
01646       if (inf != NULL)
01647         notice_new_inferior (currthread, running, 0);
01648     }
01649 }
01650 
01651 /* Return the private thread data, creating it if necessary.  */
01652 
01653 static struct private_thread_info *
01654 demand_private_info (ptid_t ptid)
01655 {
01656   struct thread_info *info = find_thread_ptid (ptid);
01657 
01658   gdb_assert (info);
01659 
01660   if (!info->private)
01661     {
01662       info->private = xmalloc (sizeof (*(info->private)));
01663       info->private_dtor = free_private_thread_info;
01664       info->private->core = -1;
01665       info->private->extra = 0;
01666     }
01667 
01668   return info->private;
01669 }
01670 
01671 /* Call this function as a result of
01672    1) A halt indication (T packet) containing a thread id
01673    2) A direct query of currthread
01674    3) Successful execution of set thread */
01675 
01676 static void
01677 record_currthread (struct remote_state *rs, ptid_t currthread)
01678 {
01679   rs->general_thread = currthread;
01680 }
01681 
01682 /* If 'QPassSignals' is supported, tell the remote stub what signals
01683    it can simply pass through to the inferior without reporting.  */
01684 
01685 static void
01686 remote_pass_signals (int numsigs, unsigned char *pass_signals)
01687 {
01688   if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
01689     {
01690       char *pass_packet, *p;
01691       int count = 0, i;
01692       struct remote_state *rs = get_remote_state ();
01693 
01694       gdb_assert (numsigs < 256);
01695       for (i = 0; i < numsigs; i++)
01696         {
01697           if (pass_signals[i])
01698             count++;
01699         }
01700       pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
01701       strcpy (pass_packet, "QPassSignals:");
01702       p = pass_packet + strlen (pass_packet);
01703       for (i = 0; i < numsigs; i++)
01704         {
01705           if (pass_signals[i])
01706             {
01707               if (i >= 16)
01708                 *p++ = tohex (i >> 4);
01709               *p++ = tohex (i & 15);
01710               if (count)
01711                 *p++ = ';';
01712               else
01713                 break;
01714               count--;
01715             }
01716         }
01717       *p = 0;
01718       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
01719         {
01720           char *buf = rs->buf;
01721 
01722           putpkt (pass_packet);
01723           getpkt (&rs->buf, &rs->buf_size, 0);
01724           packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
01725           if (rs->last_pass_packet)
01726             xfree (rs->last_pass_packet);
01727           rs->last_pass_packet = pass_packet;
01728         }
01729       else
01730         xfree (pass_packet);
01731     }
01732 }
01733 
01734 /* If 'QProgramSignals' is supported, tell the remote stub what
01735    signals it should pass through to the inferior when detaching.  */
01736 
01737 static void
01738 remote_program_signals (int numsigs, unsigned char *signals)
01739 {
01740   if (remote_protocol_packets[PACKET_QProgramSignals].support != PACKET_DISABLE)
01741     {
01742       char *packet, *p;
01743       int count = 0, i;
01744       struct remote_state *rs = get_remote_state ();
01745 
01746       gdb_assert (numsigs < 256);
01747       for (i = 0; i < numsigs; i++)
01748         {
01749           if (signals[i])
01750             count++;
01751         }
01752       packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
01753       strcpy (packet, "QProgramSignals:");
01754       p = packet + strlen (packet);
01755       for (i = 0; i < numsigs; i++)
01756         {
01757           if (signal_pass_state (i))
01758             {
01759               if (i >= 16)
01760                 *p++ = tohex (i >> 4);
01761               *p++ = tohex (i & 15);
01762               if (count)
01763                 *p++ = ';';
01764               else
01765                 break;
01766               count--;
01767             }
01768         }
01769       *p = 0;
01770       if (!rs->last_program_signals_packet
01771           || strcmp (rs->last_program_signals_packet, packet) != 0)
01772         {
01773           char *buf = rs->buf;
01774 
01775           putpkt (packet);
01776           getpkt (&rs->buf, &rs->buf_size, 0);
01777           packet_ok (buf, &remote_protocol_packets[PACKET_QProgramSignals]);
01778           xfree (rs->last_program_signals_packet);
01779           rs->last_program_signals_packet = packet;
01780         }
01781       else
01782         xfree (packet);
01783     }
01784 }
01785 
01786 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
01787    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
01788    thread.  If GEN is set, set the general thread, if not, then set
01789    the step/continue thread.  */
01790 static void
01791 set_thread (struct ptid ptid, int gen)
01792 {
01793   struct remote_state *rs = get_remote_state ();
01794   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
01795   char *buf = rs->buf;
01796   char *endbuf = rs->buf + get_remote_packet_size ();
01797 
01798   if (ptid_equal (state, ptid))
01799     return;
01800 
01801   *buf++ = 'H';
01802   *buf++ = gen ? 'g' : 'c';
01803   if (ptid_equal (ptid, magic_null_ptid))
01804     xsnprintf (buf, endbuf - buf, "0");
01805   else if (ptid_equal (ptid, any_thread_ptid))
01806     xsnprintf (buf, endbuf - buf, "0");
01807   else if (ptid_equal (ptid, minus_one_ptid))
01808     xsnprintf (buf, endbuf - buf, "-1");
01809   else
01810     write_ptid (buf, endbuf, ptid);
01811   putpkt (rs->buf);
01812   getpkt (&rs->buf, &rs->buf_size, 0);
01813   if (gen)
01814     rs->general_thread = ptid;
01815   else
01816     rs->continue_thread = ptid;
01817 }
01818 
01819 static void
01820 set_general_thread (struct ptid ptid)
01821 {
01822   set_thread (ptid, 1);
01823 }
01824 
01825 static void
01826 set_continue_thread (struct ptid ptid)
01827 {
01828   set_thread (ptid, 0);
01829 }
01830 
01831 /* Change the remote current process.  Which thread within the process
01832    ends up selected isn't important, as long as it is the same process
01833    as what INFERIOR_PTID points to.
01834 
01835    This comes from that fact that there is no explicit notion of
01836    "selected process" in the protocol.  The selected process for
01837    general operations is the process the selected general thread
01838    belongs to.  */
01839 
01840 static void
01841 set_general_process (void)
01842 {
01843   struct remote_state *rs = get_remote_state ();
01844 
01845   /* If the remote can't handle multiple processes, don't bother.  */
01846   if (!rs->extended || !remote_multi_process_p (rs))
01847     return;
01848 
01849   /* We only need to change the remote current thread if it's pointing
01850      at some other process.  */
01851   if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
01852     set_general_thread (inferior_ptid);
01853 }
01854 
01855 
01856 /*  Return nonzero if the thread PTID is still alive on the remote
01857     system.  */
01858 
01859 static int
01860 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
01861 {
01862   struct remote_state *rs = get_remote_state ();
01863   char *p, *endp;
01864 
01865   if (ptid_equal (ptid, magic_null_ptid))
01866     /* The main thread is always alive.  */
01867     return 1;
01868 
01869   if (ptid_get_pid (ptid) != 0 && ptid_get_tid (ptid) == 0)
01870     /* The main thread is always alive.  This can happen after a
01871        vAttach, if the remote side doesn't support
01872        multi-threading.  */
01873     return 1;
01874 
01875   p = rs->buf;
01876   endp = rs->buf + get_remote_packet_size ();
01877 
01878   *p++ = 'T';
01879   write_ptid (p, endp, ptid);
01880 
01881   putpkt (rs->buf);
01882   getpkt (&rs->buf, &rs->buf_size, 0);
01883   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
01884 }
01885 
01886 /* About these extended threadlist and threadinfo packets.  They are
01887    variable length packets but, the fields within them are often fixed
01888    length.  They are redundent enough to send over UDP as is the
01889    remote protocol in general.  There is a matching unit test module
01890    in libstub.  */
01891 
01892 /* WARNING: This threadref data structure comes from the remote O.S.,
01893    libstub protocol encoding, and remote.c.  It is not particularly
01894    changable.  */
01895 
01896 /* Right now, the internal structure is int. We want it to be bigger.
01897    Plan to fix this.  */
01898 
01899 typedef int gdb_threadref;      /* Internal GDB thread reference.  */
01900 
01901 /* gdb_ext_thread_info is an internal GDB data structure which is
01902    equivalent to the reply of the remote threadinfo packet.  */
01903 
01904 struct gdb_ext_thread_info
01905   {
01906     threadref threadid;         /* External form of thread reference.  */
01907     int active;                 /* Has state interesting to GDB?
01908                                    regs, stack.  */
01909     char display[256];          /* Brief state display, name,
01910                                    blocked/suspended.  */
01911     char shortname[32];         /* To be used to name threads.  */
01912     char more_display[256];     /* Long info, statistics, queue depth,
01913                                    whatever.  */
01914   };
01915 
01916 /* The volume of remote transfers can be limited by submitting
01917    a mask containing bits specifying the desired information.
01918    Use a union of these values as the 'selection' parameter to
01919    get_thread_info.  FIXME: Make these TAG names more thread specific.  */
01920 
01921 #define TAG_THREADID 1
01922 #define TAG_EXISTS 2
01923 #define TAG_DISPLAY 4
01924 #define TAG_THREADNAME 8
01925 #define TAG_MOREDISPLAY 16
01926 
01927 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
01928 
01929 char *unpack_varlen_hex (char *buff, ULONGEST *result);
01930 
01931 static char *unpack_nibble (char *buf, int *val);
01932 
01933 static char *pack_nibble (char *buf, int nibble);
01934 
01935 static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
01936 
01937 static char *unpack_byte (char *buf, int *value);
01938 
01939 static char *pack_int (char *buf, int value);
01940 
01941 static char *unpack_int (char *buf, int *value);
01942 
01943 static char *unpack_string (char *src, char *dest, int length);
01944 
01945 static char *pack_threadid (char *pkt, threadref *id);
01946 
01947 static char *unpack_threadid (char *inbuf, threadref *id);
01948 
01949 void int_to_threadref (threadref *id, int value);
01950 
01951 static int threadref_to_int (threadref *ref);
01952 
01953 static void copy_threadref (threadref *dest, threadref *src);
01954 
01955 static int threadmatch (threadref *dest, threadref *src);
01956 
01957 static char *pack_threadinfo_request (char *pkt, int mode,
01958                                       threadref *id);
01959 
01960 static int remote_unpack_thread_info_response (char *pkt,
01961                                                threadref *expectedref,
01962                                                struct gdb_ext_thread_info
01963                                                *info);
01964 
01965 
01966 static int remote_get_threadinfo (threadref *threadid,
01967                                   int fieldset, /*TAG mask */
01968                                   struct gdb_ext_thread_info *info);
01969 
01970 static char *pack_threadlist_request (char *pkt, int startflag,
01971                                       int threadcount,
01972                                       threadref *nextthread);
01973 
01974 static int parse_threadlist_response (char *pkt,
01975                                       int result_limit,
01976                                       threadref *original_echo,
01977                                       threadref *resultlist,
01978                                       int *doneflag);
01979 
01980 static int remote_get_threadlist (int startflag,
01981                                   threadref *nextthread,
01982                                   int result_limit,
01983                                   int *done,
01984                                   int *result_count,
01985                                   threadref *threadlist);
01986 
01987 typedef int (*rmt_thread_action) (threadref *ref, void *context);
01988 
01989 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
01990                                        void *context, int looplimit);
01991 
01992 static int remote_newthread_step (threadref *ref, void *context);
01993 
01994 
01995 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
01996    buffer we're allowed to write to.  Returns
01997    BUF+CHARACTERS_WRITTEN.  */
01998 
01999 static char *
02000 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
02001 {
02002   int pid, tid;
02003   struct remote_state *rs = get_remote_state ();
02004 
02005   if (remote_multi_process_p (rs))
02006     {
02007       pid = ptid_get_pid (ptid);
02008       if (pid < 0)
02009         buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
02010       else
02011         buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
02012     }
02013   tid = ptid_get_tid (ptid);
02014   if (tid < 0)
02015     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
02016   else
02017     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
02018 
02019   return buf;
02020 }
02021 
02022 /* Extract a PTID from BUF.  If non-null, OBUF is set to the to one
02023    passed the last parsed char.  Returns null_ptid on error.  */
02024 
02025 static ptid_t
02026 read_ptid (char *buf, char **obuf)
02027 {
02028   char *p = buf;
02029   char *pp;
02030   ULONGEST pid = 0, tid = 0;
02031 
02032   if (*p == 'p')
02033     {
02034       /* Multi-process ptid.  */
02035       pp = unpack_varlen_hex (p + 1, &pid);
02036       if (*pp != '.')
02037         error (_("invalid remote ptid: %s"), p);
02038 
02039       p = pp;
02040       pp = unpack_varlen_hex (p + 1, &tid);
02041       if (obuf)
02042         *obuf = pp;
02043       return ptid_build (pid, 0, tid);
02044     }
02045 
02046   /* No multi-process.  Just a tid.  */
02047   pp = unpack_varlen_hex (p, &tid);
02048 
02049   /* Since the stub is not sending a process id, then default to
02050      what's in inferior_ptid, unless it's null at this point.  If so,
02051      then since there's no way to know the pid of the reported
02052      threads, use the magic number.  */
02053   if (ptid_equal (inferior_ptid, null_ptid))
02054     pid = ptid_get_pid (magic_null_ptid);
02055   else
02056     pid = ptid_get_pid (inferior_ptid);
02057 
02058   if (obuf)
02059     *obuf = pp;
02060   return ptid_build (pid, 0, tid);
02061 }
02062 
02063 /* Encode 64 bits in 16 chars of hex.  */
02064 
02065 static const char hexchars[] = "0123456789abcdef";
02066 
02067 static int
02068 ishex (int ch, int *val)
02069 {
02070   if ((ch >= 'a') && (ch <= 'f'))
02071     {
02072       *val = ch - 'a' + 10;
02073       return 1;
02074     }
02075   if ((ch >= 'A') && (ch <= 'F'))
02076     {
02077       *val = ch - 'A' + 10;
02078       return 1;
02079     }
02080   if ((ch >= '0') && (ch <= '9'))
02081     {
02082       *val = ch - '0';
02083       return 1;
02084     }
02085   return 0;
02086 }
02087 
02088 static int
02089 stubhex (int ch)
02090 {
02091   if (ch >= 'a' && ch <= 'f')
02092     return ch - 'a' + 10;
02093   if (ch >= '0' && ch <= '9')
02094     return ch - '0';
02095   if (ch >= 'A' && ch <= 'F')
02096     return ch - 'A' + 10;
02097   return -1;
02098 }
02099 
02100 static int
02101 stub_unpack_int (char *buff, int fieldlength)
02102 {
02103   int nibble;
02104   int retval = 0;
02105 
02106   while (fieldlength)
02107     {
02108       nibble = stubhex (*buff++);
02109       retval |= nibble;
02110       fieldlength--;
02111       if (fieldlength)
02112         retval = retval << 4;
02113     }
02114   return retval;
02115 }
02116 
02117 char *
02118 unpack_varlen_hex (char *buff,  /* packet to parse */
02119                    ULONGEST *result)
02120 {
02121   int nibble;
02122   ULONGEST retval = 0;
02123 
02124   while (ishex (*buff, &nibble))
02125     {
02126       buff++;
02127       retval = retval << 4;
02128       retval |= nibble & 0x0f;
02129     }
02130   *result = retval;
02131   return buff;
02132 }
02133 
02134 static char *
02135 unpack_nibble (char *buf, int *val)
02136 {
02137   *val = fromhex (*buf++);
02138   return buf;
02139 }
02140 
02141 static char *
02142 pack_nibble (char *buf, int nibble)
02143 {
02144   *buf++ = hexchars[(nibble & 0x0f)];
02145   return buf;
02146 }
02147 
02148 static char *
02149 pack_hex_byte (char *pkt, int byte)
02150 {
02151   *pkt++ = hexchars[(byte >> 4) & 0xf];
02152   *pkt++ = hexchars[(byte & 0xf)];
02153   return pkt;
02154 }
02155 
02156 static char *
02157 unpack_byte (char *buf, int *value)
02158 {
02159   *value = stub_unpack_int (buf, 2);
02160   return buf + 2;
02161 }
02162 
02163 static char *
02164 pack_int (char *buf, int value)
02165 {
02166   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
02167   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
02168   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
02169   buf = pack_hex_byte (buf, (value & 0xff));
02170   return buf;
02171 }
02172 
02173 static char *
02174 unpack_int (char *buf, int *value)
02175 {
02176   *value = stub_unpack_int (buf, 8);
02177   return buf + 8;
02178 }
02179 
02180 #if 0                   /* Currently unused, uncomment when needed.  */
02181 static char *pack_string (char *pkt, char *string);
02182 
02183 static char *
02184 pack_string (char *pkt, char *string)
02185 {
02186   char ch;
02187   int len;
02188 
02189   len = strlen (string);
02190   if (len > 200)
02191     len = 200;          /* Bigger than most GDB packets, junk???  */
02192   pkt = pack_hex_byte (pkt, len);
02193   while (len-- > 0)
02194     {
02195       ch = *string++;
02196       if ((ch == '\0') || (ch == '#'))
02197         ch = '*';               /* Protect encapsulation.  */
02198       *pkt++ = ch;
02199     }
02200   return pkt;
02201 }
02202 #endif /* 0 (unused) */
02203 
02204 static char *
02205 unpack_string (char *src, char *dest, int length)
02206 {
02207   while (length--)
02208     *dest++ = *src++;
02209   *dest = '\0';
02210   return src;
02211 }
02212 
02213 static char *
02214 pack_threadid (char *pkt, threadref *id)
02215 {
02216   char *limit;
02217   unsigned char *altid;
02218 
02219   altid = (unsigned char *) id;
02220   limit = pkt + BUF_THREAD_ID_SIZE;
02221   while (pkt < limit)
02222     pkt = pack_hex_byte (pkt, *altid++);
02223   return pkt;
02224 }
02225 
02226 
02227 static char *
02228 unpack_threadid (char *inbuf, threadref *id)
02229 {
02230   char *altref;
02231   char *limit = inbuf + BUF_THREAD_ID_SIZE;
02232   int x, y;
02233 
02234   altref = (char *) id;
02235 
02236   while (inbuf < limit)
02237     {
02238       x = stubhex (*inbuf++);
02239       y = stubhex (*inbuf++);
02240       *altref++ = (x << 4) | y;
02241     }
02242   return inbuf;
02243 }
02244 
02245 /* Externally, threadrefs are 64 bits but internally, they are still
02246    ints.  This is due to a mismatch of specifications.  We would like
02247    to use 64bit thread references internally.  This is an adapter
02248    function.  */
02249 
02250 void
02251 int_to_threadref (threadref *id, int value)
02252 {
02253   unsigned char *scan;
02254 
02255   scan = (unsigned char *) id;
02256   {
02257     int i = 4;
02258     while (i--)
02259       *scan++ = 0;
02260   }
02261   *scan++ = (value >> 24) & 0xff;
02262   *scan++ = (value >> 16) & 0xff;
02263   *scan++ = (value >> 8) & 0xff;
02264   *scan++ = (value & 0xff);
02265 }
02266 
02267 static int
02268 threadref_to_int (threadref *ref)
02269 {
02270   int i, value = 0;
02271   unsigned char *scan;
02272 
02273   scan = *ref;
02274   scan += 4;
02275   i = 4;
02276   while (i-- > 0)
02277     value = (value << 8) | ((*scan++) & 0xff);
02278   return value;
02279 }
02280 
02281 static void
02282 copy_threadref (threadref *dest, threadref *src)
02283 {
02284   int i;
02285   unsigned char *csrc, *cdest;
02286 
02287   csrc = (unsigned char *) src;
02288   cdest = (unsigned char *) dest;
02289   i = 8;
02290   while (i--)
02291     *cdest++ = *csrc++;
02292 }
02293 
02294 static int
02295 threadmatch (threadref *dest, threadref *src)
02296 {
02297   /* Things are broken right now, so just assume we got a match.  */
02298 #if 0
02299   unsigned char *srcp, *destp;
02300   int i, result;
02301   srcp = (char *) src;
02302   destp = (char *) dest;
02303 
02304   result = 1;
02305   while (i-- > 0)
02306     result &= (*srcp++ == *destp++) ? 1 : 0;
02307   return result;
02308 #endif
02309   return 1;
02310 }
02311 
02312 /*
02313    threadid:1,        # always request threadid
02314    context_exists:2,
02315    display:4,
02316    unique_name:8,
02317    more_display:16
02318  */
02319 
02320 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
02321 
02322 static char *
02323 pack_threadinfo_request (char *pkt, int mode, threadref *id)
02324 {
02325   *pkt++ = 'q';                         /* Info Query */
02326   *pkt++ = 'P';                         /* process or thread info */
02327   pkt = pack_int (pkt, mode);           /* mode */
02328   pkt = pack_threadid (pkt, id);        /* threadid */
02329   *pkt = '\0';                          /* terminate */
02330   return pkt;
02331 }
02332 
02333 /* These values tag the fields in a thread info response packet.  */
02334 /* Tagging the fields allows us to request specific fields and to
02335    add more fields as time goes by.  */
02336 
02337 #define TAG_THREADID 1          /* Echo the thread identifier.  */
02338 #define TAG_EXISTS 2            /* Is this process defined enough to
02339                                    fetch registers and its stack?  */
02340 #define TAG_DISPLAY 4           /* A short thing maybe to put on a window */
02341 #define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is.  */
02342 #define TAG_MOREDISPLAY 16      /* Whatever the kernel wants to say about
02343                                    the process.  */
02344 
02345 static int
02346 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
02347                                     struct gdb_ext_thread_info *info)
02348 {
02349   struct remote_state *rs = get_remote_state ();
02350   int mask, length;
02351   int tag;
02352   threadref ref;
02353   char *limit = pkt + rs->buf_size; /* Plausible parsing limit.  */
02354   int retval = 1;
02355 
02356   /* info->threadid = 0; FIXME: implement zero_threadref.  */
02357   info->active = 0;
02358   info->display[0] = '\0';
02359   info->shortname[0] = '\0';
02360   info->more_display[0] = '\0';
02361 
02362   /* Assume the characters indicating the packet type have been
02363      stripped.  */
02364   pkt = unpack_int (pkt, &mask);        /* arg mask */
02365   pkt = unpack_threadid (pkt, &ref);
02366 
02367   if (mask == 0)
02368     warning (_("Incomplete response to threadinfo request."));
02369   if (!threadmatch (&ref, expectedref))
02370     {                   /* This is an answer to a different request.  */
02371       warning (_("ERROR RMT Thread info mismatch."));
02372       return 0;
02373     }
02374   copy_threadref (&info->threadid, &ref);
02375 
02376   /* Loop on tagged fields , try to bail if somthing goes wrong.  */
02377 
02378   /* Packets are terminated with nulls.  */
02379   while ((pkt < limit) && mask && *pkt)
02380     {
02381       pkt = unpack_int (pkt, &tag);     /* tag */
02382       pkt = unpack_byte (pkt, &length); /* length */
02383       if (!(tag & mask))                /* Tags out of synch with mask.  */
02384         {
02385           warning (_("ERROR RMT: threadinfo tag mismatch."));
02386           retval = 0;
02387           break;
02388         }
02389       if (tag == TAG_THREADID)
02390         {
02391           if (length != 16)
02392             {
02393               warning (_("ERROR RMT: length of threadid is not 16."));
02394               retval = 0;
02395               break;
02396             }
02397           pkt = unpack_threadid (pkt, &ref);
02398           mask = mask & ~TAG_THREADID;
02399           continue;
02400         }
02401       if (tag == TAG_EXISTS)
02402         {
02403           info->active = stub_unpack_int (pkt, length);
02404           pkt += length;
02405           mask = mask & ~(TAG_EXISTS);
02406           if (length > 8)
02407             {
02408               warning (_("ERROR RMT: 'exists' length too long."));
02409               retval = 0;
02410               break;
02411             }
02412           continue;
02413         }
02414       if (tag == TAG_THREADNAME)
02415         {
02416           pkt = unpack_string (pkt, &info->shortname[0], length);
02417           mask = mask & ~TAG_THREADNAME;
02418           continue;
02419         }
02420       if (tag == TAG_DISPLAY)
02421         {
02422           pkt = unpack_string (pkt, &info->display[0], length);
02423           mask = mask & ~TAG_DISPLAY;
02424           continue;
02425         }
02426       if (tag == TAG_MOREDISPLAY)
02427         {
02428           pkt = unpack_string (pkt, &info->more_display[0], length);
02429           mask = mask & ~TAG_MOREDISPLAY;
02430           continue;
02431         }
02432       warning (_("ERROR RMT: unknown thread info tag."));
02433       break;                    /* Not a tag we know about.  */
02434     }
02435   return retval;
02436 }
02437 
02438 static int
02439 remote_get_threadinfo (threadref *threadid, int fieldset,       /* TAG mask */
02440                        struct gdb_ext_thread_info *info)
02441 {
02442   struct remote_state *rs = get_remote_state ();
02443   int result;
02444 
02445   pack_threadinfo_request (rs->buf, fieldset, threadid);
02446   putpkt (rs->buf);
02447   getpkt (&rs->buf, &rs->buf_size, 0);
02448 
02449   if (rs->buf[0] == '\0')
02450     return 0;
02451 
02452   result = remote_unpack_thread_info_response (rs->buf + 2,
02453                                                threadid, info);
02454   return result;
02455 }
02456 
02457 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
02458 
02459 static char *
02460 pack_threadlist_request (char *pkt, int startflag, int threadcount,
02461                          threadref *nextthread)
02462 {
02463   *pkt++ = 'q';                 /* info query packet */
02464   *pkt++ = 'L';                 /* Process LIST or threadLIST request */
02465   pkt = pack_nibble (pkt, startflag);           /* initflag 1 bytes */
02466   pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
02467   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
02468   *pkt = '\0';
02469   return pkt;
02470 }
02471 
02472 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
02473 
02474 static int
02475 parse_threadlist_response (char *pkt, int result_limit,
02476                            threadref *original_echo, threadref *resultlist,
02477                            int *doneflag)
02478 {
02479   struct remote_state *rs = get_remote_state ();
02480   char *limit;
02481   int count, resultcount, done;
02482 
02483   resultcount = 0;
02484   /* Assume the 'q' and 'M chars have been stripped.  */
02485   limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
02486   /* done parse past here */
02487   pkt = unpack_byte (pkt, &count);      /* count field */
02488   pkt = unpack_nibble (pkt, &done);
02489   /* The first threadid is the argument threadid.  */
02490   pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
02491   while ((count-- > 0) && (pkt < limit))
02492     {
02493       pkt = unpack_threadid (pkt, resultlist++);
02494       if (resultcount++ >= result_limit)
02495         break;
02496     }
02497   if (doneflag)
02498     *doneflag = done;
02499   return resultcount;
02500 }
02501 
02502 static int
02503 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
02504                        int *done, int *result_count, threadref *threadlist)
02505 {
02506   struct remote_state *rs = get_remote_state ();
02507   int result = 1;
02508 
02509   /* Trancate result limit to be smaller than the packet size.  */
02510   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
02511       >= get_remote_packet_size ())
02512     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
02513 
02514   pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
02515   putpkt (rs->buf);
02516   getpkt (&rs->buf, &rs->buf_size, 0);
02517 
02518   if (*rs->buf == '\0')
02519     return 0;
02520   else
02521     *result_count =
02522       parse_threadlist_response (rs->buf + 2, result_limit,
02523                                  &rs->echo_nextthread, threadlist, done);
02524 
02525   if (!threadmatch (&rs->echo_nextthread, nextthread))
02526     {
02527       /* FIXME: This is a good reason to drop the packet.  */
02528       /* Possably, there is a duplicate response.  */
02529       /* Possabilities :
02530          retransmit immediatly - race conditions
02531          retransmit after timeout - yes
02532          exit
02533          wait for packet, then exit
02534        */
02535       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
02536       return 0;                 /* I choose simply exiting.  */
02537     }
02538   if (*result_count <= 0)
02539     {
02540       if (*done != 1)
02541         {
02542           warning (_("RMT ERROR : failed to get remote thread list."));
02543           result = 0;
02544         }
02545       return result;            /* break; */
02546     }
02547   if (*result_count > result_limit)
02548     {
02549       *result_count = 0;
02550       warning (_("RMT ERROR: threadlist response longer than requested."));
02551       return 0;
02552     }
02553   return result;
02554 }
02555 
02556 /* This is the interface between remote and threads, remotes upper
02557    interface.  */
02558 
02559 /* remote_find_new_threads retrieves the thread list and for each
02560    thread in the list, looks up the thread in GDB's internal list,
02561    adding the thread if it does not already exist.  This involves
02562    getting partial thread lists from the remote target so, polling the
02563    quit_flag is required.  */
02564 
02565 
02566 static int
02567 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
02568                             int looplimit)
02569 {
02570   struct remote_state *rs = get_remote_state ();
02571   int done, i, result_count;
02572   int startflag = 1;
02573   int result = 1;
02574   int loopcount = 0;
02575 
02576   done = 0;
02577   while (!done)
02578     {
02579       if (loopcount++ > looplimit)
02580         {
02581           result = 0;
02582           warning (_("Remote fetch threadlist -infinite loop-."));
02583           break;
02584         }
02585       if (!remote_get_threadlist (startflag, &rs->nextthread,
02586                                   MAXTHREADLISTRESULTS,
02587                                   &done, &result_count, rs->resultthreadlist))
02588         {
02589           result = 0;
02590           break;
02591         }
02592       /* Clear for later iterations.  */
02593       startflag = 0;
02594       /* Setup to resume next batch of thread references, set nextthread.  */
02595       if (result_count >= 1)
02596         copy_threadref (&rs->nextthread,
02597                         &rs->resultthreadlist[result_count - 1]);
02598       i = 0;
02599       while (result_count--)
02600         if (!(result = (*stepfunction) (&rs->resultthreadlist[i++], context)))
02601           break;
02602     }
02603   return result;
02604 }
02605 
02606 static int
02607 remote_newthread_step (threadref *ref, void *context)
02608 {
02609   int pid = ptid_get_pid (inferior_ptid);
02610   ptid_t ptid = ptid_build (pid, 0, threadref_to_int (ref));
02611 
02612   if (!in_thread_list (ptid))
02613     add_thread (ptid);
02614   return 1;                     /* continue iterator */
02615 }
02616 
02617 #define CRAZY_MAX_THREADS 1000
02618 
02619 static ptid_t
02620 remote_current_thread (ptid_t oldpid)
02621 {
02622   struct remote_state *rs = get_remote_state ();
02623 
02624   putpkt ("qC");
02625   getpkt (&rs->buf, &rs->buf_size, 0);
02626   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
02627     return read_ptid (&rs->buf[2], NULL);
02628   else
02629     return oldpid;
02630 }
02631 
02632 /* Find new threads for info threads command.
02633  * Original version, using John Metzler's thread protocol.
02634  */
02635 
02636 static void
02637 remote_find_new_threads (void)
02638 {
02639   remote_threadlist_iterator (remote_newthread_step, 0,
02640                               CRAZY_MAX_THREADS);
02641 }
02642 
02643 #if defined(HAVE_LIBEXPAT)
02644 
02645 typedef struct thread_item
02646 {
02647   ptid_t ptid;
02648   char *extra;
02649   int core;
02650 } thread_item_t;
02651 DEF_VEC_O(thread_item_t);
02652 
02653 struct threads_parsing_context
02654 {
02655   VEC (thread_item_t) *items;
02656 };
02657 
02658 static void
02659 start_thread (struct gdb_xml_parser *parser,
02660               const struct gdb_xml_element *element,
02661               void *user_data, VEC(gdb_xml_value_s) *attributes)
02662 {
02663   struct threads_parsing_context *data = user_data;
02664 
02665   struct thread_item item;
02666   char *id;
02667   struct gdb_xml_value *attr;
02668 
02669   id = xml_find_attribute (attributes, "id")->value;
02670   item.ptid = read_ptid (id, NULL);
02671 
02672   attr = xml_find_attribute (attributes, "core");
02673   if (attr != NULL)
02674     item.core = *(ULONGEST *) attr->value;
02675   else
02676     item.core = -1;
02677 
02678   item.extra = 0;
02679 
02680   VEC_safe_push (thread_item_t, data->items, &item);
02681 }
02682 
02683 static void
02684 end_thread (struct gdb_xml_parser *parser,
02685             const struct gdb_xml_element *element,
02686             void *user_data, const char *body_text)
02687 {
02688   struct threads_parsing_context *data = user_data;
02689 
02690   if (body_text && *body_text)
02691     VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
02692 }
02693 
02694 const struct gdb_xml_attribute thread_attributes[] = {
02695   { "id", GDB_XML_AF_NONE, NULL, NULL },
02696   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
02697   { NULL, GDB_XML_AF_NONE, NULL, NULL }
02698 };
02699 
02700 const struct gdb_xml_element thread_children[] = {
02701   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
02702 };
02703 
02704 const struct gdb_xml_element threads_children[] = {
02705   { "thread", thread_attributes, thread_children,
02706     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
02707     start_thread, end_thread },
02708   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
02709 };
02710 
02711 const struct gdb_xml_element threads_elements[] = {
02712   { "threads", NULL, threads_children,
02713     GDB_XML_EF_NONE, NULL, NULL },
02714   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
02715 };
02716 
02717 /* Discard the contents of the constructed thread info context.  */
02718 
02719 static void
02720 clear_threads_parsing_context (void *p)
02721 {
02722   struct threads_parsing_context *context = p;
02723   int i;
02724   struct thread_item *item;
02725 
02726   for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
02727     xfree (item->extra);
02728 
02729   VEC_free (thread_item_t, context->items);
02730 }
02731 
02732 #endif
02733 
02734 /*
02735  * Find all threads for info threads command.
02736  * Uses new thread protocol contributed by Cisco.
02737  * Falls back and attempts to use the older method (above)
02738  * if the target doesn't respond to the new method.
02739  */
02740 
02741 static void
02742 remote_threads_info (struct target_ops *ops)
02743 {
02744   struct remote_state *rs = get_remote_state ();
02745   char *bufp;
02746   ptid_t new_thread;
02747 
02748   if (rs->remote_desc == 0)             /* paranoia */
02749     error (_("Command can only be used when connected to the remote target."));
02750 
02751 #if defined(HAVE_LIBEXPAT)
02752   if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
02753     {
02754       char *xml = target_read_stralloc (&current_target,
02755                                          TARGET_OBJECT_THREADS, NULL);
02756 
02757       struct cleanup *back_to = make_cleanup (xfree, xml);
02758 
02759       if (xml && *xml)
02760         {
02761           struct threads_parsing_context context;
02762 
02763           context.items = NULL;
02764           make_cleanup (clear_threads_parsing_context, &context);
02765 
02766           if (gdb_xml_parse_quick (_("threads"), "threads.dtd",
02767                                    threads_elements, xml, &context) == 0)
02768             {
02769               int i;
02770               struct thread_item *item;
02771 
02772               for (i = 0;
02773                    VEC_iterate (thread_item_t, context.items, i, item);
02774                    ++i)
02775                 {
02776                   if (!ptid_equal (item->ptid, null_ptid))
02777                     {
02778                       struct private_thread_info *info;
02779                       /* In non-stop mode, we assume new found threads
02780                          are running until proven otherwise with a
02781                          stop reply.  In all-stop, we can only get
02782                          here if all threads are stopped.  */
02783                       int running = non_stop ? 1 : 0;
02784 
02785                       remote_notice_new_inferior (item->ptid, running);
02786 
02787                       info = demand_private_info (item->ptid);
02788                       info->core = item->core;
02789                       info->extra = item->extra;
02790                       item->extra = NULL;
02791                     }
02792                 }
02793             }
02794         }
02795 
02796       do_cleanups (back_to);
02797       return;
02798     }
02799 #endif
02800 
02801   if (rs->use_threadinfo_query)
02802     {
02803       putpkt ("qfThreadInfo");
02804       getpkt (&rs->buf, &rs->buf_size, 0);
02805       bufp = rs->buf;
02806       if (bufp[0] != '\0')              /* q packet recognized */
02807         {
02808           struct cleanup *old_chain;
02809           char *saved_reply;
02810 
02811           /* remote_notice_new_inferior (in the loop below) may make
02812              new RSP calls, which clobber rs->buf.  Work with a
02813              copy.  */
02814           bufp = saved_reply = xstrdup (rs->buf);
02815           old_chain = make_cleanup (free_current_contents, &saved_reply);
02816 
02817           while (*bufp++ == 'm')        /* reply contains one or more TID */
02818             {
02819               do
02820                 {
02821                   new_thread = read_ptid (bufp, &bufp);
02822                   if (!ptid_equal (new_thread, null_ptid))
02823                     {
02824                       /* In non-stop mode, we assume new found threads
02825                          are running until proven otherwise with a
02826                          stop reply.  In all-stop, we can only get
02827                          here if all threads are stopped.  */
02828                       int running = non_stop ? 1 : 0;
02829 
02830                       remote_notice_new_inferior (new_thread, running);
02831                     }
02832                 }
02833               while (*bufp++ == ',');   /* comma-separated list */
02834               free_current_contents (&saved_reply);
02835               putpkt ("qsThreadInfo");
02836               getpkt (&rs->buf, &rs->buf_size, 0);
02837               bufp = saved_reply = xstrdup (rs->buf);
02838             }
02839           do_cleanups (old_chain);
02840           return;       /* done */
02841         }
02842     }
02843 
02844   /* Only qfThreadInfo is supported in non-stop mode.  */
02845   if (non_stop)
02846     return;
02847 
02848   /* Else fall back to old method based on jmetzler protocol.  */
02849   rs->use_threadinfo_query = 0;
02850   remote_find_new_threads ();
02851   return;
02852 }
02853 
02854 /*
02855  * Collect a descriptive string about the given thread.
02856  * The target may say anything it wants to about the thread
02857  * (typically info about its blocked / runnable state, name, etc.).
02858  * This string will appear in the info threads display.
02859  *
02860  * Optional: targets are not required to implement this function.
02861  */
02862 
02863 static char *
02864 remote_threads_extra_info (struct thread_info *tp)
02865 {
02866   struct remote_state *rs = get_remote_state ();
02867   int result;
02868   int set;
02869   threadref id;
02870   struct gdb_ext_thread_info threadinfo;
02871   static char display_buf[100]; /* arbitrary...  */
02872   int n = 0;                    /* position in display_buf */
02873 
02874   if (rs->remote_desc == 0)             /* paranoia */
02875     internal_error (__FILE__, __LINE__,
02876                     _("remote_threads_extra_info"));
02877 
02878   if (ptid_equal (tp->ptid, magic_null_ptid)
02879       || (ptid_get_pid (tp->ptid) != 0 && ptid_get_tid (tp->ptid) == 0))
02880     /* This is the main thread which was added by GDB.  The remote
02881        server doesn't know about it.  */
02882     return NULL;
02883 
02884   if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
02885     {
02886       struct thread_info *info = find_thread_ptid (tp->ptid);
02887 
02888       if (info && info->private)
02889         return info->private->extra;
02890       else
02891         return NULL;
02892     }
02893 
02894   if (rs->use_threadextra_query)
02895     {
02896       char *b = rs->buf;
02897       char *endb = rs->buf + get_remote_packet_size ();
02898 
02899       xsnprintf (b, endb - b, "qThreadExtraInfo,");
02900       b += strlen (b);
02901       write_ptid (b, endb, tp->ptid);
02902 
02903       putpkt (rs->buf);
02904       getpkt (&rs->buf, &rs->buf_size, 0);
02905       if (rs->buf[0] != 0)
02906         {
02907           n = min (strlen (rs->buf) / 2, sizeof (display_buf));
02908           result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
02909           display_buf [result] = '\0';
02910           return display_buf;
02911         }
02912     }
02913 
02914   /* If the above query fails, fall back to the old method.  */
02915   rs->use_threadextra_query = 0;
02916   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
02917     | TAG_MOREDISPLAY | TAG_DISPLAY;
02918   int_to_threadref (&id, ptid_get_tid (tp->ptid));
02919   if (remote_get_threadinfo (&id, set, &threadinfo))
02920     if (threadinfo.active)
02921       {
02922         if (*threadinfo.shortname)
02923           n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
02924                           " Name: %s,", threadinfo.shortname);
02925         if (*threadinfo.display)
02926           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
02927                           " State: %s,", threadinfo.display);
02928         if (*threadinfo.more_display)
02929           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
02930                           " Priority: %s", threadinfo.more_display);
02931 
02932         if (n > 0)
02933           {
02934             /* For purely cosmetic reasons, clear up trailing commas.  */
02935             if (',' == display_buf[n-1])
02936               display_buf[n-1] = ' ';
02937             return display_buf;
02938           }
02939       }
02940   return NULL;
02941 }
02942 
02943 
02944 static int
02945 remote_static_tracepoint_marker_at (CORE_ADDR addr,
02946                                     struct static_tracepoint_marker *marker)
02947 {
02948   struct remote_state *rs = get_remote_state ();
02949   char *p = rs->buf;
02950 
02951   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
02952   p += strlen (p);
02953   p += hexnumstr (p, addr);
02954   putpkt (rs->buf);
02955   getpkt (&rs->buf, &rs->buf_size, 0);
02956   p = rs->buf;
02957 
02958   if (*p == 'E')
02959     error (_("Remote failure reply: %s"), p);
02960 
02961   if (*p++ == 'm')
02962     {
02963       parse_static_tracepoint_marker_definition (p, &p, marker);
02964       return 1;
02965     }
02966 
02967   return 0;
02968 }
02969 
02970 static VEC(static_tracepoint_marker_p) *
02971 remote_static_tracepoint_markers_by_strid (const char *strid)
02972 {
02973   struct remote_state *rs = get_remote_state ();
02974   VEC(static_tracepoint_marker_p) *markers = NULL;
02975   struct static_tracepoint_marker *marker = NULL;
02976   struct cleanup *old_chain;
02977   char *p;
02978 
02979   /* Ask for a first packet of static tracepoint marker
02980      definition.  */
02981   putpkt ("qTfSTM");
02982   getpkt (&rs->buf, &rs->buf_size, 0);
02983   p = rs->buf;
02984   if (*p == 'E')
02985     error (_("Remote failure reply: %s"), p);
02986 
02987   old_chain = make_cleanup (free_current_marker, &marker);
02988 
02989   while (*p++ == 'm')
02990     {
02991       if (marker == NULL)
02992         marker = XCNEW (struct static_tracepoint_marker);
02993 
02994       do
02995         {
02996           parse_static_tracepoint_marker_definition (p, &p, marker);
02997 
02998           if (strid == NULL || strcmp (strid, marker->str_id) == 0)
02999             {
03000               VEC_safe_push (static_tracepoint_marker_p,
03001                              markers, marker);
03002               marker = NULL;
03003             }
03004           else
03005             {
03006               release_static_tracepoint_marker (marker);
03007               memset (marker, 0, sizeof (*marker));
03008             }
03009         }
03010       while (*p++ == ',');      /* comma-separated list */
03011       /* Ask for another packet of static tracepoint definition.  */
03012       putpkt ("qTsSTM");
03013       getpkt (&rs->buf, &rs->buf_size, 0);
03014       p = rs->buf;
03015     }
03016 
03017   do_cleanups (old_chain);
03018   return markers;
03019 }
03020 
03021 
03022 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
03023 
03024 static ptid_t
03025 remote_get_ada_task_ptid (long lwp, long thread)
03026 {
03027   return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp);
03028 }
03029 
03030 
03031 /* Restart the remote side; this is an extended protocol operation.  */
03032 
03033 static void
03034 extended_remote_restart (void)
03035 {
03036   struct remote_state *rs = get_remote_state ();
03037 
03038   /* Send the restart command; for reasons I don't understand the
03039      remote side really expects a number after the "R".  */
03040   xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
03041   putpkt (rs->buf);
03042 
03043   remote_fileio_reset ();
03044 }
03045 
03046 /* Clean up connection to a remote debugger.  */
03047 
03048 static void
03049 remote_close (void)
03050 {
03051   struct remote_state *rs = get_remote_state ();
03052 
03053   if (rs->remote_desc == NULL)
03054     return; /* already closed */
03055 
03056   /* Make sure we leave stdin registered in the event loop, and we
03057      don't leave the async SIGINT signal handler installed.  */
03058   remote_terminal_ours ();
03059 
03060   serial_close (rs->remote_desc);
03061   rs->remote_desc = NULL;
03062 
03063   /* We don't have a connection to the remote stub anymore.  Get rid
03064      of all the inferiors and their threads we were controlling.
03065      Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
03066      will be unable to find the thread corresponding to (pid, 0, 0).  */
03067   inferior_ptid = null_ptid;
03068   discard_all_inferiors ();
03069 
03070   /* We are closing the remote target, so we should discard
03071      everything of this target.  */
03072   discard_pending_stop_replies_in_queue (rs);
03073 
03074   if (remote_async_inferior_event_token)
03075     delete_async_event_handler (&remote_async_inferior_event_token);
03076 
03077   remote_notif_state_xfree (rs->notif_state);
03078 
03079   trace_reset_local_state ();
03080 }
03081 
03082 /* Query the remote side for the text, data and bss offsets.  */
03083 
03084 static void
03085 get_offsets (void)
03086 {
03087   struct remote_state *rs = get_remote_state ();
03088   char *buf;
03089   char *ptr;
03090   int lose, num_segments = 0, do_sections, do_segments;
03091   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
03092   struct section_offsets *offs;
03093   struct symfile_segment_data *data;
03094 
03095   if (symfile_objfile == NULL)
03096     return;
03097 
03098   putpkt ("qOffsets");
03099   getpkt (&rs->buf, &rs->buf_size, 0);
03100   buf = rs->buf;
03101 
03102   if (buf[0] == '\000')
03103     return;                     /* Return silently.  Stub doesn't support
03104                                    this command.  */
03105   if (buf[0] == 'E')
03106     {
03107       warning (_("Remote failure reply: %s"), buf);
03108       return;
03109     }
03110 
03111   /* Pick up each field in turn.  This used to be done with scanf, but
03112      scanf will make trouble if CORE_ADDR size doesn't match
03113      conversion directives correctly.  The following code will work
03114      with any size of CORE_ADDR.  */
03115   text_addr = data_addr = bss_addr = 0;
03116   ptr = buf;
03117   lose = 0;
03118 
03119   if (strncmp (ptr, "Text=", 5) == 0)
03120     {
03121       ptr += 5;
03122       /* Don't use strtol, could lose on big values.  */
03123       while (*ptr && *ptr != ';')
03124         text_addr = (text_addr << 4) + fromhex (*ptr++);
03125 
03126       if (strncmp (ptr, ";Data=", 6) == 0)
03127         {
03128           ptr += 6;
03129           while (*ptr && *ptr != ';')
03130             data_addr = (data_addr << 4) + fromhex (*ptr++);
03131         }
03132       else
03133         lose = 1;
03134 
03135       if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
03136         {
03137           ptr += 5;
03138           while (*ptr && *ptr != ';')
03139             bss_addr = (bss_addr << 4) + fromhex (*ptr++);
03140 
03141           if (bss_addr != data_addr)
03142             warning (_("Target reported unsupported offsets: %s"), buf);
03143         }
03144       else
03145         lose = 1;
03146     }
03147   else if (strncmp (ptr, "TextSeg=", 8) == 0)
03148     {
03149       ptr += 8;
03150       /* Don't use strtol, could lose on big values.  */
03151       while (*ptr && *ptr != ';')
03152         text_addr = (text_addr << 4) + fromhex (*ptr++);
03153       num_segments = 1;
03154 
03155       if (strncmp (ptr, ";DataSeg=", 9) == 0)
03156         {
03157           ptr += 9;
03158           while (*ptr && *ptr != ';')
03159             data_addr = (data_addr << 4) + fromhex (*ptr++);
03160           num_segments++;
03161         }
03162     }
03163   else
03164     lose = 1;
03165 
03166   if (lose)
03167     error (_("Malformed response to offset query, %s"), buf);
03168   else if (*ptr != '\0')
03169     warning (_("Target reported unsupported offsets: %s"), buf);
03170 
03171   offs = ((struct section_offsets *)
03172           alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
03173   memcpy (offs, symfile_objfile->section_offsets,
03174           SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
03175 
03176   data = get_symfile_segment_data (symfile_objfile->obfd);
03177   do_segments = (data != NULL);
03178   do_sections = num_segments == 0;
03179 
03180   if (num_segments > 0)
03181     {
03182       segments[0] = text_addr;
03183       segments[1] = data_addr;
03184     }
03185   /* If we have two segments, we can still try to relocate everything
03186      by assuming that the .text and .data offsets apply to the whole
03187      text and data segments.  Convert the offsets given in the packet
03188      to base addresses for symfile_map_offsets_to_segments.  */
03189   else if (data && data->num_segments == 2)
03190     {
03191       segments[0] = data->segment_bases[0] + text_addr;
03192       segments[1] = data->segment_bases[1] + data_addr;
03193       num_segments = 2;
03194     }
03195   /* If the object file has only one segment, assume that it is text
03196      rather than data; main programs with no writable data are rare,
03197      but programs with no code are useless.  Of course the code might
03198      have ended up in the data segment... to detect that we would need
03199      the permissions here.  */
03200   else if (data && data->num_segments == 1)
03201     {
03202       segments[0] = data->segment_bases[0] + text_addr;
03203       num_segments = 1;
03204     }
03205   /* There's no way to relocate by segment.  */
03206   else
03207     do_segments = 0;
03208 
03209   if (do_segments)
03210     {
03211       int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
03212                                                  offs, num_segments, segments);
03213 
03214       if (ret == 0 && !do_sections)
03215         error (_("Can not handle qOffsets TextSeg "
03216                  "response with this symbol file"));
03217 
03218       if (ret > 0)
03219         do_sections = 0;
03220     }
03221 
03222   if (data)
03223     free_symfile_segment_data (data);
03224 
03225   if (do_sections)
03226     {
03227       offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
03228 
03229       /* This is a temporary kludge to force data and bss to use the
03230          same offsets because that's what nlmconv does now.  The real
03231          solution requires changes to the stub and remote.c that I
03232          don't have time to do right now.  */
03233 
03234       offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
03235       offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
03236     }
03237 
03238   objfile_relocate (symfile_objfile, offs);
03239 }
03240 
03241 /* Callback for iterate_over_threads.  Set the STOP_REQUESTED flags in
03242    threads we know are stopped already.  This is used during the
03243    initial remote connection in non-stop mode --- threads that are
03244    reported as already being stopped are left stopped.  */
03245 
03246 static int
03247 set_stop_requested_callback (struct thread_info *thread, void *data)
03248 {
03249   /* If we have a stop reply for this thread, it must be stopped.  */
03250   if (peek_stop_reply (thread->ptid))
03251     set_stop_requested (thread->ptid, 1);
03252 
03253   return 0;
03254 }
03255 
03256 /* Send interrupt_sequence to remote target.  */
03257 static void
03258 send_interrupt_sequence (void)
03259 {
03260   struct remote_state *rs = get_remote_state ();
03261 
03262   if (interrupt_sequence_mode == interrupt_sequence_control_c)
03263     remote_serial_write ("\x03", 1);
03264   else if (interrupt_sequence_mode == interrupt_sequence_break)
03265     serial_send_break (rs->remote_desc);
03266   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
03267     {
03268       serial_send_break (rs->remote_desc);
03269       remote_serial_write ("g", 1);
03270     }
03271   else
03272     internal_error (__FILE__, __LINE__,
03273                     _("Invalid value for interrupt_sequence_mode: %s."),
03274                     interrupt_sequence_mode);
03275 }
03276 
03277 
03278 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
03279    and extract the PTID.  Returns NULL_PTID if not found.  */
03280 
03281 static ptid_t
03282 stop_reply_extract_thread (char *stop_reply)
03283 {
03284   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
03285     {
03286       char *p;
03287 
03288       /* Txx r:val ; r:val (...)  */
03289       p = &stop_reply[3];
03290 
03291       /* Look for "register" named "thread".  */
03292       while (*p != '\0')
03293         {
03294           char *p1;
03295 
03296           p1 = strchr (p, ':');
03297           if (p1 == NULL)
03298             return null_ptid;
03299 
03300           if (strncmp (p, "thread", p1 - p) == 0)
03301             return read_ptid (++p1, &p);
03302 
03303           p1 = strchr (p, ';');
03304           if (p1 == NULL)
03305             return null_ptid;
03306           p1++;
03307 
03308           p = p1;
03309         }
03310     }
03311 
03312   return null_ptid;
03313 }
03314 
03315 /* Query the remote target for which is the current thread/process,
03316    add it to our tables, and update INFERIOR_PTID.  The caller is
03317    responsible for setting the state such that the remote end is ready
03318    to return the current thread.
03319 
03320    This function is called after handling the '?' or 'vRun' packets,
03321    whose response is a stop reply from which we can also try
03322    extracting the thread.  If the target doesn't support the explicit
03323    qC query, we infer the current thread from that stop reply, passed
03324    in in WAIT_STATUS, which may be NULL.  */
03325 
03326 static void
03327 add_current_inferior_and_thread (char *wait_status)
03328 {
03329   struct remote_state *rs = get_remote_state ();
03330   int fake_pid_p = 0;
03331   ptid_t ptid = null_ptid;
03332 
03333   inferior_ptid = null_ptid;
03334 
03335   /* Now, if we have thread information, update inferior_ptid.  First
03336      if we have a stop reply handy, maybe it's a T stop reply with a
03337      "thread" register we can extract the current thread from.  If
03338      not, ask the remote which is the current thread, with qC.  The
03339      former method avoids a roundtrip.  Note we don't use
03340      remote_parse_stop_reply as that makes use of the target
03341      architecture, which we haven't yet fully determined at this
03342      point.  */
03343   if (wait_status != NULL)
03344     ptid = stop_reply_extract_thread (wait_status);
03345   if (ptid_equal (ptid, null_ptid))
03346     ptid = remote_current_thread (inferior_ptid);
03347 
03348   if (!ptid_equal (ptid, null_ptid))
03349     {
03350       if (!remote_multi_process_p (rs))
03351         fake_pid_p = 1;
03352 
03353       inferior_ptid = ptid;
03354     }
03355   else
03356     {
03357       /* Without this, some commands which require an active target
03358          (such as kill) won't work.  This variable serves (at least)
03359          double duty as both the pid of the target process (if it has
03360          such), and as a flag indicating that a target is active.  */
03361       inferior_ptid = magic_null_ptid;
03362       fake_pid_p = 1;
03363     }
03364 
03365   remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1);
03366 
03367   /* Add the main thread.  */
03368   add_thread_silent (inferior_ptid);
03369 }
03370 
03371 static void
03372 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
03373 {
03374   struct remote_state *rs = get_remote_state ();
03375   struct packet_config *noack_config;
03376   char *wait_status = NULL;
03377 
03378   immediate_quit++;             /* Allow user to interrupt it.  */
03379   QUIT;
03380 
03381   if (interrupt_on_connect)
03382     send_interrupt_sequence ();
03383 
03384   /* Ack any packet which the remote side has already sent.  */
03385   serial_write (rs->remote_desc, "+", 1);
03386 
03387   /* Signal other parts that we're going through the initial setup,
03388      and so things may not be stable yet.  */
03389   rs->starting_up = 1;
03390 
03391   /* The first packet we send to the target is the optional "supported
03392      packets" request.  If the target can answer this, it will tell us
03393      which later probes to skip.  */
03394   remote_query_supported ();
03395 
03396   /* If the stub wants to get a QAllow, compose one and send it.  */
03397   if (remote_protocol_packets[PACKET_QAllow].support != PACKET_DISABLE)
03398     remote_set_permissions ();
03399 
03400   /* Next, we possibly activate noack mode.
03401 
03402      If the QStartNoAckMode packet configuration is set to AUTO,
03403      enable noack mode if the stub reported a wish for it with
03404      qSupported.
03405 
03406      If set to TRUE, then enable noack mode even if the stub didn't
03407      report it in qSupported.  If the stub doesn't reply OK, the
03408      session ends with an error.
03409 
03410      If FALSE, then don't activate noack mode, regardless of what the
03411      stub claimed should be the default with qSupported.  */
03412 
03413   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
03414 
03415   if (noack_config->detect == AUTO_BOOLEAN_TRUE
03416       || (noack_config->detect == AUTO_BOOLEAN_AUTO
03417           && noack_config->support == PACKET_ENABLE))
03418     {
03419       putpkt ("QStartNoAckMode");
03420       getpkt (&rs->buf, &rs->buf_size, 0);
03421       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
03422         rs->noack_mode = 1;
03423     }
03424 
03425   if (extended_p)
03426     {
03427       /* Tell the remote that we are using the extended protocol.  */
03428       putpkt ("!");
03429       getpkt (&rs->buf, &rs->buf_size, 0);
03430     }
03431 
03432   /* Let the target know which signals it is allowed to pass down to
03433      the program.  */
03434   update_signals_program_target ();
03435 
03436   /* Next, if the target can specify a description, read it.  We do
03437      this before anything involving memory or registers.  */
03438   target_find_description ();
03439 
03440   /* Next, now that we know something about the target, update the
03441      address spaces in the program spaces.  */
03442   update_address_spaces ();
03443 
03444   /* On OSs where the list of libraries is global to all
03445      processes, we fetch them early.  */
03446   if (gdbarch_has_global_solist (target_gdbarch ()))
03447     solib_add (NULL, from_tty, target, auto_solib_add);
03448 
03449   if (non_stop)
03450     {
03451       if (!rs->non_stop_aware)
03452         error (_("Non-stop mode requested, but remote "
03453                  "does not support non-stop"));
03454 
03455       putpkt ("QNonStop:1");
03456       getpkt (&rs->buf, &rs->buf_size, 0);
03457 
03458       if (strcmp (rs->buf, "OK") != 0)
03459         error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
03460 
03461       /* Find about threads and processes the stub is already
03462          controlling.  We default to adding them in the running state.
03463          The '?' query below will then tell us about which threads are
03464          stopped.  */
03465       remote_threads_info (target);
03466     }
03467   else if (rs->non_stop_aware)
03468     {
03469       /* Don't assume that the stub can operate in all-stop mode.
03470          Request it explicitly.  */
03471       putpkt ("QNonStop:0");
03472       getpkt (&rs->buf, &rs->buf_size, 0);
03473 
03474       if (strcmp (rs->buf, "OK") != 0)
03475         error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
03476     }
03477 
03478   /* Upload TSVs regardless of whether the target is running or not.  The
03479      remote stub, such as GDBserver, may have some predefined or builtin
03480      TSVs, even if the target is not running.  */
03481   if (remote_get_trace_status (current_trace_status ()) != -1)
03482     {
03483       struct uploaded_tsv *uploaded_tsvs = NULL;
03484 
03485       remote_upload_trace_state_variables (&uploaded_tsvs);
03486       merge_uploaded_trace_state_variables (&uploaded_tsvs);
03487     }
03488 
03489   /* Check whether the target is running now.  */
03490   putpkt ("?");
03491   getpkt (&rs->buf, &rs->buf_size, 0);
03492 
03493   if (!non_stop)
03494     {
03495       ptid_t ptid;
03496       int fake_pid_p = 0;
03497       struct inferior *inf;
03498 
03499       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
03500         {
03501           if (!extended_p)
03502             error (_("The target is not running (try extended-remote?)"));
03503 
03504           /* We're connected, but not running.  Drop out before we
03505              call start_remote.  */
03506           rs->starting_up = 0;
03507           return;
03508         }
03509       else
03510         {
03511           /* Save the reply for later.  */
03512           wait_status = alloca (strlen (rs->buf) + 1);
03513           strcpy (wait_status, rs->buf);
03514         }
03515 
03516       /* Let the stub know that we want it to return the thread.  */
03517       set_continue_thread (minus_one_ptid);
03518 
03519       add_current_inferior_and_thread (wait_status);
03520 
03521       /* init_wait_for_inferior should be called before get_offsets in order
03522          to manage `inserted' flag in bp loc in a correct state.
03523          breakpoint_init_inferior, called from init_wait_for_inferior, set
03524          `inserted' flag to 0, while before breakpoint_re_set, called from
03525          start_remote, set `inserted' flag to 1.  In the initialization of
03526          inferior, breakpoint_init_inferior should be called first, and then
03527          breakpoint_re_set can be called.  If this order is broken, state of
03528          `inserted' flag is wrong, and cause some problems on breakpoint
03529          manipulation.  */
03530       init_wait_for_inferior ();
03531 
03532       get_offsets ();           /* Get text, data & bss offsets.  */
03533 
03534       /* If we could not find a description using qXfer, and we know
03535          how to do it some other way, try again.  This is not
03536          supported for non-stop; it could be, but it is tricky if
03537          there are no stopped threads when we connect.  */
03538       if (remote_read_description_p (target)
03539           && gdbarch_target_desc (target_gdbarch ()) == NULL)
03540         {
03541           target_clear_description ();
03542           target_find_description ();
03543         }
03544 
03545       /* Use the previously fetched status.  */
03546       gdb_assert (wait_status != NULL);
03547       strcpy (rs->buf, wait_status);
03548       rs->cached_wait_status = 1;
03549 
03550       immediate_quit--;
03551       start_remote (from_tty); /* Initialize gdb process mechanisms.  */
03552     }
03553   else
03554     {
03555       /* Clear WFI global state.  Do this before finding about new
03556          threads and inferiors, and setting the current inferior.
03557          Otherwise we would clear the proceed status of the current
03558          inferior when we want its stop_soon state to be preserved
03559          (see notice_new_inferior).  */
03560       init_wait_for_inferior ();
03561 
03562       /* In non-stop, we will either get an "OK", meaning that there
03563          are no stopped threads at this time; or, a regular stop
03564          reply.  In the latter case, there may be more than one thread
03565          stopped --- we pull them all out using the vStopped
03566          mechanism.  */
03567       if (strcmp (rs->buf, "OK") != 0)
03568         {
03569           struct notif_client *notif = &notif_client_stop;
03570 
03571           /* remote_notif_get_pending_replies acks this one, and gets
03572              the rest out.  */
03573           rs->notif_state->pending_event[notif_client_stop.id]
03574             = remote_notif_parse (notif, rs->buf);
03575           remote_notif_get_pending_events (notif);
03576 
03577           /* Make sure that threads that were stopped remain
03578              stopped.  */
03579           iterate_over_threads (set_stop_requested_callback, NULL);
03580         }
03581 
03582       if (target_can_async_p ())
03583         target_async (inferior_event_handler, 0);
03584 
03585       if (thread_count () == 0)
03586         {
03587           if (!extended_p)
03588             error (_("The target is not running (try extended-remote?)"));
03589 
03590           /* We're connected, but not running.  Drop out before we
03591              call start_remote.  */
03592           rs->starting_up = 0;
03593           return;
03594         }
03595 
03596       /* Let the stub know that we want it to return the thread.  */
03597 
03598       /* Force the stub to choose a thread.  */
03599       set_general_thread (null_ptid);
03600 
03601       /* Query it.  */
03602       inferior_ptid = remote_current_thread (minus_one_ptid);
03603       if (ptid_equal (inferior_ptid, minus_one_ptid))
03604         error (_("remote didn't report the current thread in non-stop mode"));
03605 
03606       get_offsets ();           /* Get text, data & bss offsets.  */
03607 
03608       /* In non-stop mode, any cached wait status will be stored in
03609          the stop reply queue.  */
03610       gdb_assert (wait_status == NULL);
03611 
03612       /* Report all signals during attach/startup.  */
03613       remote_pass_signals (0, NULL);
03614     }
03615 
03616   /* If we connected to a live target, do some additional setup.  */
03617   if (target_has_execution)
03618     {
03619       if (exec_bfd)     /* No use without an exec file.  */
03620         remote_check_symbols ();
03621     }
03622 
03623   /* Possibly the target has been engaged in a trace run started
03624      previously; find out where things are at.  */
03625   if (remote_get_trace_status (current_trace_status ()) != -1)
03626     {
03627       struct uploaded_tp *uploaded_tps = NULL;
03628 
03629       if (current_trace_status ()->running)
03630         printf_filtered (_("Trace is already running on the target.\n"));
03631 
03632       remote_upload_tracepoints (&uploaded_tps);
03633 
03634       merge_uploaded_tracepoints (&uploaded_tps);
03635     }
03636 
03637   /* The thread and inferior lists are now synchronized with the
03638      target, our symbols have been relocated, and we're merged the
03639      target's tracepoints with ours.  We're done with basic start
03640      up.  */
03641   rs->starting_up = 0;
03642 
03643   /* If breakpoints are global, insert them now.  */
03644   if (gdbarch_has_global_breakpoints (target_gdbarch ())
03645       && breakpoints_always_inserted_mode ())
03646     insert_breakpoints ();
03647 }
03648 
03649 /* Open a connection to a remote debugger.
03650    NAME is the filename used for communication.  */
03651 
03652 static void
03653 remote_open (char *name, int from_tty)
03654 {
03655   remote_open_1 (name, from_tty, &remote_ops, 0);
03656 }
03657 
03658 /* Open a connection to a remote debugger using the extended
03659    remote gdb protocol.  NAME is the filename used for communication.  */
03660 
03661 static void
03662 extended_remote_open (char *name, int from_tty)
03663 {
03664   remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
03665 }
03666 
03667 /* Generic code for opening a connection to a remote target.  */
03668 
03669 static void
03670 init_all_packet_configs (void)
03671 {
03672   int i;
03673 
03674   for (i = 0; i < PACKET_MAX; i++)
03675     update_packet_config (&remote_protocol_packets[i]);
03676 }
03677 
03678 /* Symbol look-up.  */
03679 
03680 static void
03681 remote_check_symbols (void)
03682 {
03683   struct remote_state *rs = get_remote_state ();
03684   char *msg, *reply, *tmp;
03685   struct minimal_symbol *sym;
03686   int end;
03687 
03688   /* The remote side has no concept of inferiors that aren't running
03689      yet, it only knows about running processes.  If we're connected
03690      but our current inferior is not running, we should not invite the
03691      remote target to request symbol lookups related to its
03692      (unrelated) current process.  */
03693   if (!target_has_execution)
03694     return;
03695 
03696   if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
03697     return;
03698 
03699   /* Make sure the remote is pointing at the right process.  Note
03700      there's no way to select "no process".  */
03701   set_general_process ();
03702 
03703   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
03704      because we need both at the same time.  */
03705   msg = alloca (get_remote_packet_size ());
03706 
03707   /* Invite target to request symbol lookups.  */
03708 
03709   putpkt ("qSymbol::");
03710   getpkt (&rs->buf, &rs->buf_size, 0);
03711   packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
03712   reply = rs->buf;
03713 
03714   while (strncmp (reply, "qSymbol:", 8) == 0)
03715     {
03716       tmp = &reply[8];
03717       end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
03718       msg[end] = '\0';
03719       sym = lookup_minimal_symbol (msg, NULL, NULL);
03720       if (sym == NULL)
03721         xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
03722       else
03723         {
03724           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
03725           CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
03726 
03727           /* If this is a function address, return the start of code
03728              instead of any data function descriptor.  */
03729           sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
03730                                                          sym_addr,
03731                                                          &current_target);
03732 
03733           xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
03734                      phex_nz (sym_addr, addr_size), &reply[8]);
03735         }
03736   
03737       putpkt (msg);
03738       getpkt (&rs->buf, &rs->buf_size, 0);
03739       reply = rs->buf;
03740     }
03741 }
03742 
03743 static struct serial *
03744 remote_serial_open (char *name)
03745 {
03746   static int udp_warning = 0;
03747 
03748   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
03749      of in ser-tcp.c, because it is the remote protocol assuming that the
03750      serial connection is reliable and not the serial connection promising
03751      to be.  */
03752   if (!udp_warning && strncmp (name, "udp:", 4) == 0)
03753     {
03754       warning (_("The remote protocol may be unreliable over UDP.\n"
03755                  "Some events may be lost, rendering further debugging "
03756                  "impossible."));
03757       udp_warning = 1;
03758     }
03759 
03760   return serial_open (name);
03761 }
03762 
03763 /* Inform the target of our permission settings.  The permission flags
03764    work without this, but if the target knows the settings, it can do
03765    a couple things.  First, it can add its own check, to catch cases
03766    that somehow manage to get by the permissions checks in target
03767    methods.  Second, if the target is wired to disallow particular
03768    settings (for instance, a system in the field that is not set up to
03769    be able to stop at a breakpoint), it can object to any unavailable
03770    permissions.  */
03771 
03772 void
03773 remote_set_permissions (void)
03774 {
03775   struct remote_state *rs = get_remote_state ();
03776 
03777   xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
03778              "WriteReg:%x;WriteMem:%x;"
03779              "InsertBreak:%x;InsertTrace:%x;"
03780              "InsertFastTrace:%x;Stop:%x",
03781              may_write_registers, may_write_memory,
03782              may_insert_breakpoints, may_insert_tracepoints,
03783              may_insert_fast_tracepoints, may_stop);
03784   putpkt (rs->buf);
03785   getpkt (&rs->buf, &rs->buf_size, 0);
03786 
03787   /* If the target didn't like the packet, warn the user.  Do not try
03788      to undo the user's settings, that would just be maddening.  */
03789   if (strcmp (rs->buf, "OK") != 0)
03790     warning (_("Remote refused setting permissions with: %s"), rs->buf);
03791 }
03792 
03793 /* This type describes each known response to the qSupported
03794    packet.  */
03795 struct protocol_feature
03796 {
03797   /* The name of this protocol feature.  */
03798   const char *name;
03799 
03800   /* The default for this protocol feature.  */
03801   enum packet_support default_support;
03802 
03803   /* The function to call when this feature is reported, or after
03804      qSupported processing if the feature is not supported.
03805      The first argument points to this structure.  The second
03806      argument indicates whether the packet requested support be
03807      enabled, disabled, or probed (or the default, if this function
03808      is being called at the end of processing and this feature was
03809      not reported).  The third argument may be NULL; if not NULL, it
03810      is a NUL-terminated string taken from the packet following
03811      this feature's name and an equals sign.  */
03812   void (*func) (const struct protocol_feature *, enum packet_support,
03813                 const char *);
03814 
03815   /* The corresponding packet for this feature.  Only used if
03816      FUNC is remote_supported_packet.  */
03817   int packet;
03818 };
03819 
03820 static void
03821 remote_supported_packet (const struct protocol_feature *feature,
03822                          enum packet_support support,
03823                          const char *argument)
03824 {
03825   if (argument)
03826     {
03827       warning (_("Remote qSupported response supplied an unexpected value for"
03828                  " \"%s\"."), feature->name);
03829       return;
03830     }
03831 
03832   if (remote_protocol_packets[feature->packet].support
03833       == PACKET_SUPPORT_UNKNOWN)
03834     remote_protocol_packets[feature->packet].support = support;
03835 }
03836 
03837 static void
03838 remote_packet_size (const struct protocol_feature *feature,
03839                     enum packet_support support, const char *value)
03840 {
03841   struct remote_state *rs = get_remote_state ();
03842 
03843   int packet_size;
03844   char *value_end;
03845 
03846   if (support != PACKET_ENABLE)
03847     return;
03848 
03849   if (value == NULL || *value == '\0')
03850     {
03851       warning (_("Remote target reported \"%s\" without a size."),
03852                feature->name);
03853       return;
03854     }
03855 
03856   errno = 0;
03857   packet_size = strtol (value, &value_end, 16);
03858   if (errno != 0 || *value_end != '\0' || packet_size < 0)
03859     {
03860       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
03861                feature->name, value);
03862       return;
03863     }
03864 
03865   if (packet_size > MAX_REMOTE_PACKET_SIZE)
03866     {
03867       warning (_("limiting remote suggested packet size (%d bytes) to %d"),
03868                packet_size, MAX_REMOTE_PACKET_SIZE);
03869       packet_size = MAX_REMOTE_PACKET_SIZE;
03870     }
03871 
03872   /* Record the new maximum packet size.  */
03873   rs->explicit_packet_size = packet_size;
03874 }
03875 
03876 static void
03877 remote_multi_process_feature (const struct protocol_feature *feature,
03878                               enum packet_support support, const char *value)
03879 {
03880   struct remote_state *rs = get_remote_state ();
03881 
03882   rs->multi_process_aware = (support == PACKET_ENABLE);
03883 }
03884 
03885 static void
03886 remote_non_stop_feature (const struct protocol_feature *feature,
03887                               enum packet_support support, const char *value)
03888 {
03889   struct remote_state *rs = get_remote_state ();
03890 
03891   rs->non_stop_aware = (support == PACKET_ENABLE);
03892 }
03893 
03894 static void
03895 remote_cond_tracepoint_feature (const struct protocol_feature *feature,
03896                                        enum packet_support support,
03897                                        const char *value)
03898 {
03899   struct remote_state *rs = get_remote_state ();
03900 
03901   rs->cond_tracepoints = (support == PACKET_ENABLE);
03902 }
03903 
03904 static void
03905 remote_cond_breakpoint_feature (const struct protocol_feature *feature,
03906                                 enum packet_support support,
03907                                 const char *value)
03908 {
03909   struct remote_state *rs = get_remote_state ();
03910 
03911   rs->cond_breakpoints = (support == PACKET_ENABLE);
03912 }
03913 
03914 static void
03915 remote_breakpoint_commands_feature (const struct protocol_feature *feature,
03916                                     enum packet_support support,
03917                                     const char *value)
03918 {
03919   struct remote_state *rs = get_remote_state ();
03920 
03921   rs->breakpoint_commands = (support == PACKET_ENABLE);
03922 }
03923 
03924 static void
03925 remote_fast_tracepoint_feature (const struct protocol_feature *feature,
03926                                 enum packet_support support,
03927                                 const char *value)
03928 {
03929   struct remote_state *rs = get_remote_state ();
03930 
03931   rs->fast_tracepoints = (support == PACKET_ENABLE);
03932 }
03933 
03934 static void
03935 remote_static_tracepoint_feature (const struct protocol_feature *feature,
03936                                   enum packet_support support,
03937                                   const char *value)
03938 {
03939   struct remote_state *rs = get_remote_state ();
03940 
03941   rs->static_tracepoints = (support == PACKET_ENABLE);
03942 }
03943 
03944 static void
03945 remote_install_in_trace_feature (const struct protocol_feature *feature,
03946                                  enum packet_support support,
03947                                  const char *value)
03948 {
03949   struct remote_state *rs = get_remote_state ();
03950 
03951   rs->install_in_trace = (support == PACKET_ENABLE);
03952 }
03953 
03954 static void
03955 remote_disconnected_tracing_feature (const struct protocol_feature *feature,
03956                                      enum packet_support support,
03957                                      const char *value)
03958 {
03959   struct remote_state *rs = get_remote_state ();
03960 
03961   rs->disconnected_tracing = (support == PACKET_ENABLE);
03962 }
03963 
03964 static void
03965 remote_enable_disable_tracepoint_feature (const struct protocol_feature *feature,
03966                                           enum packet_support support,
03967                                           const char *value)
03968 {
03969   struct remote_state *rs = get_remote_state ();
03970 
03971   rs->enable_disable_tracepoints = (support == PACKET_ENABLE);
03972 }
03973 
03974 static void
03975 remote_string_tracing_feature (const struct protocol_feature *feature,
03976                                enum packet_support support,
03977                                const char *value)
03978 {
03979   struct remote_state *rs = get_remote_state ();
03980 
03981   rs->string_tracing = (support == PACKET_ENABLE);
03982 }
03983 
03984 static void
03985 remote_augmented_libraries_svr4_read_feature
03986   (const struct protocol_feature *feature,
03987    enum packet_support support, const char *value)
03988 {
03989   struct remote_state *rs = get_remote_state ();
03990 
03991   rs->augmented_libraries_svr4_read = (support == PACKET_ENABLE);
03992 }
03993 
03994 static const struct protocol_feature remote_protocol_features[] = {
03995   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
03996   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
03997     PACKET_qXfer_auxv },
03998   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
03999     PACKET_qXfer_features },
04000   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
04001     PACKET_qXfer_libraries },
04002   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
04003     PACKET_qXfer_libraries_svr4 },
04004   { "augmented-libraries-svr4-read", PACKET_DISABLE,
04005     remote_augmented_libraries_svr4_read_feature, -1 },
04006   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
04007     PACKET_qXfer_memory_map },
04008   { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
04009     PACKET_qXfer_spu_read },
04010   { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
04011     PACKET_qXfer_spu_write },
04012   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
04013     PACKET_qXfer_osdata },
04014   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
04015     PACKET_qXfer_threads },
04016   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
04017     PACKET_qXfer_traceframe_info },
04018   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
04019     PACKET_QPassSignals },
04020   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
04021     PACKET_QProgramSignals },
04022   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
04023     PACKET_QStartNoAckMode },
04024   { "multiprocess", PACKET_DISABLE, remote_multi_process_feature, -1 },
04025   { "QNonStop", PACKET_DISABLE, remote_non_stop_feature, -1 },
04026   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
04027     PACKET_qXfer_siginfo_read },
04028   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
04029     PACKET_qXfer_siginfo_write },
04030   { "ConditionalTracepoints", PACKET_DISABLE, remote_cond_tracepoint_feature,
04031     PACKET_ConditionalTracepoints },
04032   { "ConditionalBreakpoints", PACKET_DISABLE, remote_cond_breakpoint_feature,
04033     PACKET_ConditionalBreakpoints },
04034   { "BreakpointCommands", PACKET_DISABLE, remote_breakpoint_commands_feature,
04035     PACKET_BreakpointCommands },
04036   { "FastTracepoints", PACKET_DISABLE, remote_fast_tracepoint_feature,
04037     PACKET_FastTracepoints },
04038   { "StaticTracepoints", PACKET_DISABLE, remote_static_tracepoint_feature,
04039     PACKET_StaticTracepoints },
04040   {"InstallInTrace", PACKET_DISABLE, remote_install_in_trace_feature,
04041    PACKET_InstallInTrace},
04042   { "DisconnectedTracing", PACKET_DISABLE, remote_disconnected_tracing_feature,
04043     -1 },
04044   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
04045     PACKET_bc },
04046   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
04047     PACKET_bs },
04048   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
04049     PACKET_TracepointSource },
04050   { "QAllow", PACKET_DISABLE, remote_supported_packet,
04051     PACKET_QAllow },
04052   { "EnableDisableTracepoints", PACKET_DISABLE,
04053     remote_enable_disable_tracepoint_feature, -1 },
04054   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
04055     PACKET_qXfer_fdpic },
04056   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
04057     PACKET_qXfer_uib },
04058   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
04059     PACKET_QDisableRandomization },
04060   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
04061   { "QTBuffer:size", PACKET_DISABLE,
04062     remote_supported_packet, PACKET_QTBuffer_size},
04063   { "tracenz", PACKET_DISABLE,
04064     remote_string_tracing_feature, -1 },
04065   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
04066   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
04067   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
04068     PACKET_qXfer_btrace }
04069 };
04070 
04071 static char *remote_support_xml;
04072 
04073 /* Register string appended to "xmlRegisters=" in qSupported query.  */
04074 
04075 void
04076 register_remote_support_xml (const char *xml)
04077 {
04078 #if defined(HAVE_LIBEXPAT)
04079   if (remote_support_xml == NULL)
04080     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
04081   else
04082     {
04083       char *copy = xstrdup (remote_support_xml + 13);
04084       char *p = strtok (copy, ",");
04085 
04086       do
04087         {
04088           if (strcmp (p, xml) == 0)
04089             {
04090               /* already there */
04091               xfree (copy);
04092               return;
04093             }
04094         }
04095       while ((p = strtok (NULL, ",")) != NULL);
04096       xfree (copy);
04097 
04098       remote_support_xml = reconcat (remote_support_xml,
04099                                      remote_support_xml, ",", xml,
04100                                      (char *) NULL);
04101     }
04102 #endif
04103 }
04104 
04105 static char *
04106 remote_query_supported_append (char *msg, const char *append)
04107 {
04108   if (msg)
04109     return reconcat (msg, msg, ";", append, (char *) NULL);
04110   else
04111     return xstrdup (append);
04112 }
04113 
04114 static void
04115 remote_query_supported (void)
04116 {
04117   struct remote_state *rs = get_remote_state ();
04118   char *next;
04119   int i;
04120   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
04121 
04122   /* The packet support flags are handled differently for this packet
04123      than for most others.  We treat an error, a disabled packet, and
04124      an empty response identically: any features which must be reported
04125      to be used will be automatically disabled.  An empty buffer
04126      accomplishes this, since that is also the representation for a list
04127      containing no features.  */
04128 
04129   rs->buf[0] = 0;
04130   if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
04131     {
04132       char *q = NULL;
04133       struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
04134 
04135       q = remote_query_supported_append (q, "multiprocess+");
04136 
04137       if (remote_support_xml)
04138         q = remote_query_supported_append (q, remote_support_xml);
04139 
04140       q = remote_query_supported_append (q, "qRelocInsn+");
04141 
04142       q = reconcat (q, "qSupported:", q, (char *) NULL);
04143       putpkt (q);
04144 
04145       do_cleanups (old_chain);
04146 
04147       getpkt (&rs->buf, &rs->buf_size, 0);
04148 
04149       /* If an error occured, warn, but do not return - just reset the
04150          buffer to empty and go on to disable features.  */
04151       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
04152           == PACKET_ERROR)
04153         {
04154           warning (_("Remote failure reply: %s"), rs->buf);
04155           rs->buf[0] = 0;
04156         }
04157     }
04158 
04159   memset (seen, 0, sizeof (seen));
04160 
04161   next = rs->buf;
04162   while (*next)
04163     {
04164       enum packet_support is_supported;
04165       char *p, *end, *name_end, *value;
04166 
04167       /* First separate out this item from the rest of the packet.  If
04168          there's another item after this, we overwrite the separator
04169          (terminated strings are much easier to work with).  */
04170       p = next;
04171       end = strchr (p, ';');
04172       if (end == NULL)
04173         {
04174           end = p + strlen (p);
04175           next = end;
04176         }
04177       else
04178         {
04179           *end = '\0';
04180           next = end + 1;
04181 
04182           if (end == p)
04183             {
04184               warning (_("empty item in \"qSupported\" response"));
04185               continue;
04186             }
04187         }
04188 
04189       name_end = strchr (p, '=');
04190       if (name_end)
04191         {
04192           /* This is a name=value entry.  */
04193           is_supported = PACKET_ENABLE;
04194           value = name_end + 1;
04195           *name_end = '\0';
04196         }
04197       else
04198         {
04199           value = NULL;
04200           switch (end[-1])
04201             {
04202             case '+':
04203               is_supported = PACKET_ENABLE;
04204               break;
04205 
04206             case '-':
04207               is_supported = PACKET_DISABLE;
04208               break;
04209 
04210             case '?':
04211               is_supported = PACKET_SUPPORT_UNKNOWN;
04212               break;
04213 
04214             default:
04215               warning (_("unrecognized item \"%s\" "
04216                          "in \"qSupported\" response"), p);
04217               continue;
04218             }
04219           end[-1] = '\0';
04220         }
04221 
04222       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
04223         if (strcmp (remote_protocol_features[i].name, p) == 0)
04224           {
04225             const struct protocol_feature *feature;
04226 
04227             seen[i] = 1;
04228             feature = &remote_protocol_features[i];
04229             feature->func (feature, is_supported, value);
04230             break;
04231           }
04232     }
04233 
04234   /* If we increased the packet size, make sure to increase the global
04235      buffer size also.  We delay this until after parsing the entire
04236      qSupported packet, because this is the same buffer we were
04237      parsing.  */
04238   if (rs->buf_size < rs->explicit_packet_size)
04239     {
04240       rs->buf_size = rs->explicit_packet_size;
04241       rs->buf = xrealloc (rs->buf, rs->buf_size);
04242     }
04243 
04244   /* Handle the defaults for unmentioned features.  */
04245   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
04246     if (!seen[i])
04247       {
04248         const struct protocol_feature *feature;
04249 
04250         feature = &remote_protocol_features[i];
04251         feature->func (feature, feature->default_support, NULL);
04252       }
04253 }
04254 
04255 /* Remove any of the remote.c targets from target stack.  Upper targets depend
04256    on it so remove them first.  */
04257 
04258 static void
04259 remote_unpush_target (void)
04260 {
04261   pop_all_targets_above (process_stratum - 1);
04262 }
04263 
04264 static void
04265 remote_open_1 (char *name, int from_tty,
04266                struct target_ops *target, int extended_p)
04267 {
04268   struct remote_state *rs = get_remote_state ();
04269 
04270   if (name == 0)
04271     error (_("To open a remote debug connection, you need to specify what\n"
04272            "serial device is attached to the remote system\n"
04273            "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
04274 
04275   /* See FIXME above.  */
04276   if (!target_async_permitted)
04277     wait_forever_enabled_p = 1;
04278 
04279   /* If we're connected to a running target, target_preopen will kill it.
04280      Ask this question first, before target_preopen has a chance to kill
04281      anything.  */
04282   if (rs->remote_desc != NULL && !have_inferiors ())
04283     {
04284       if (from_tty
04285           && !query (_("Already connected to a remote target.  Disconnect? ")))
04286         error (_("Still connected."));
04287     }
04288 
04289   /* Here the possibly existing remote target gets unpushed.  */
04290   target_preopen (from_tty);
04291 
04292   /* Make sure we send the passed signals list the next time we resume.  */
04293   xfree (rs->last_pass_packet);
04294   rs->last_pass_packet = NULL;
04295 
04296   /* Make sure we send the program signals list the next time we
04297      resume.  */
04298   xfree (rs->last_program_signals_packet);
04299   rs->last_program_signals_packet = NULL;
04300 
04301   remote_fileio_reset ();
04302   reopen_exec_file ();
04303   reread_symbols ();
04304 
04305   rs->remote_desc = remote_serial_open (name);
04306   if (!rs->remote_desc)
04307     perror_with_name (name);
04308 
04309   if (baud_rate != -1)
04310     {
04311       if (serial_setbaudrate (rs->remote_desc, baud_rate))
04312         {
04313           /* The requested speed could not be set.  Error out to
04314              top level after closing remote_desc.  Take care to
04315              set remote_desc to NULL to avoid closing remote_desc
04316              more than once.  */
04317           serial_close (rs->remote_desc);
04318           rs->remote_desc = NULL;
04319           perror_with_name (name);
04320         }
04321     }
04322 
04323   serial_raw (rs->remote_desc);
04324 
04325   /* If there is something sitting in the buffer we might take it as a
04326      response to a command, which would be bad.  */
04327   serial_flush_input (rs->remote_desc);
04328 
04329   if (from_tty)
04330     {
04331       puts_filtered ("Remote debugging using ");
04332       puts_filtered (name);
04333       puts_filtered ("\n");
04334     }
04335   push_target (target);         /* Switch to using remote target now.  */
04336 
04337   /* Register extra event sources in the event loop.  */
04338   remote_async_inferior_event_token
04339     = create_async_event_handler (remote_async_inferior_event_handler,
04340                                   NULL);
04341   rs->notif_state = remote_notif_state_allocate ();
04342 
04343   /* Reset the target state; these things will be queried either by
04344      remote_query_supported or as they are needed.  */
04345   init_all_packet_configs ();
04346   rs->cached_wait_status = 0;
04347   rs->explicit_packet_size = 0;
04348   rs->noack_mode = 0;
04349   rs->multi_process_aware = 0;
04350   rs->extended = extended_p;
04351   rs->non_stop_aware = 0;
04352   rs->waiting_for_stop_reply = 0;
04353   rs->ctrlc_pending_p = 0;
04354 
04355   rs->general_thread = not_sent_ptid;
04356   rs->continue_thread = not_sent_ptid;
04357   rs->remote_traceframe_number = -1;
04358 
04359   /* Probe for ability to use "ThreadInfo" query, as required.  */
04360   rs->use_threadinfo_query = 1;
04361   rs->use_threadextra_query = 1;
04362 
04363   if (target_async_permitted)
04364     {
04365       /* With this target we start out by owning the terminal.  */
04366       remote_async_terminal_ours_p = 1;
04367 
04368       /* FIXME: cagney/1999-09-23: During the initial connection it is
04369          assumed that the target is already ready and able to respond to
04370          requests.  Unfortunately remote_start_remote() eventually calls
04371          wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
04372          around this.  Eventually a mechanism that allows
04373          wait_for_inferior() to expect/get timeouts will be
04374          implemented.  */
04375       wait_forever_enabled_p = 0;
04376     }
04377 
04378   /* First delete any symbols previously loaded from shared libraries.  */
04379   no_shared_libraries (NULL, 0);
04380 
04381   /* Start afresh.  */
04382   init_thread_list ();
04383 
04384   /* Start the remote connection.  If error() or QUIT, discard this
04385      target (we'd otherwise be in an inconsistent state) and then
04386      propogate the error on up the exception chain.  This ensures that
04387      the caller doesn't stumble along blindly assuming that the
04388      function succeeded.  The CLI doesn't have this problem but other
04389      UI's, such as MI do.
04390 
04391      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
04392      this function should return an error indication letting the
04393      caller restore the previous state.  Unfortunately the command
04394      ``target remote'' is directly wired to this function making that
04395      impossible.  On a positive note, the CLI side of this problem has
04396      been fixed - the function set_cmd_context() makes it possible for
04397      all the ``target ....'' commands to share a common callback
04398      function.  See cli-dump.c.  */
04399   {
04400     volatile struct gdb_exception ex;
04401 
04402     TRY_CATCH (ex, RETURN_MASK_ALL)
04403       {
04404         remote_start_remote (from_tty, target, extended_p);
04405       }
04406     if (ex.reason < 0)
04407       {
04408         /* Pop the partially set up target - unless something else did
04409            already before throwing the exception.  */
04410         if (rs->remote_desc != NULL)
04411           remote_unpush_target ();
04412         if (target_async_permitted)
04413           wait_forever_enabled_p = 1;
04414         throw_exception (ex);
04415       }
04416   }
04417 
04418   if (target_async_permitted)
04419     wait_forever_enabled_p = 1;
04420 }
04421 
04422 /* This takes a program previously attached to and detaches it.  After
04423    this is done, GDB can be used to debug some other program.  We
04424    better not have left any breakpoints in the target program or it'll
04425    die when it hits one.  */
04426 
04427 static void
04428 remote_detach_1 (char *args, int from_tty, int extended)
04429 {
04430   int pid = ptid_get_pid (inferior_ptid);
04431   struct remote_state *rs = get_remote_state ();
04432 
04433   if (args)
04434     error (_("Argument given to \"detach\" when remotely debugging."));
04435 
04436   if (!target_has_execution)
04437     error (_("No process to detach from."));
04438 
04439   if (from_tty)
04440     {
04441       char *exec_file = get_exec_file (0);
04442       if (exec_file == NULL)
04443         exec_file = "";
04444       printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
04445                          target_pid_to_str (pid_to_ptid (pid)));
04446       gdb_flush (gdb_stdout);
04447     }
04448 
04449   /* Tell the remote target to detach.  */
04450   if (remote_multi_process_p (rs))
04451     xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
04452   else
04453     strcpy (rs->buf, "D");
04454 
04455   putpkt (rs->buf);
04456   getpkt (&rs->buf, &rs->buf_size, 0);
04457 
04458   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
04459     ;
04460   else if (rs->buf[0] == '\0')
04461     error (_("Remote doesn't know how to detach"));
04462   else
04463     error (_("Can't detach process."));
04464 
04465   if (from_tty && !extended)
04466     puts_filtered (_("Ending remote debugging.\n"));
04467 
04468   target_mourn_inferior ();
04469 }
04470 
04471 static void
04472 remote_detach (struct target_ops *ops, char *args, int from_tty)
04473 {
04474   remote_detach_1 (args, from_tty, 0);
04475 }
04476 
04477 static void
04478 extended_remote_detach (struct target_ops *ops, char *args, int from_tty)
04479 {
04480   remote_detach_1 (args, from_tty, 1);
04481 }
04482 
04483 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
04484 
04485 static void
04486 remote_disconnect (struct target_ops *target, char *args, int from_tty)
04487 {
04488   if (args)
04489     error (_("Argument given to \"disconnect\" when remotely debugging."));
04490 
04491   /* Make sure we unpush even the extended remote targets; mourn
04492      won't do it.  So call remote_mourn_1 directly instead of
04493      target_mourn_inferior.  */
04494   remote_mourn_1 (target);
04495 
04496   if (from_tty)
04497     puts_filtered ("Ending remote debugging.\n");
04498 }
04499 
04500 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
04501    be chatty about it.  */
04502 
04503 static void
04504 extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
04505 {
04506   struct remote_state *rs = get_remote_state ();
04507   int pid;
04508   char *wait_status = NULL;
04509 
04510   pid = parse_pid_to_attach (args);
04511 
04512   /* Remote PID can be freely equal to getpid, do not check it here the same
04513      way as in other targets.  */
04514 
04515   if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
04516     error (_("This target does not support attaching to a process"));
04517 
04518   if (from_tty)
04519     {
04520       char *exec_file = get_exec_file (0);
04521 
04522       if (exec_file)
04523         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
04524                            target_pid_to_str (pid_to_ptid (pid)));
04525       else
04526         printf_unfiltered (_("Attaching to %s\n"),
04527                            target_pid_to_str (pid_to_ptid (pid)));
04528 
04529       gdb_flush (gdb_stdout);
04530     }
04531 
04532   xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
04533   putpkt (rs->buf);
04534   getpkt (&rs->buf, &rs->buf_size, 0);
04535 
04536   if (packet_ok (rs->buf,
04537                  &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
04538     {
04539       if (!non_stop)
04540         {
04541           /* Save the reply for later.  */
04542           wait_status = alloca (strlen (rs->buf) + 1);
04543           strcpy (wait_status, rs->buf);
04544         }
04545       else if (strcmp (rs->buf, "OK") != 0)
04546         error (_("Attaching to %s failed with: %s"),
04547                target_pid_to_str (pid_to_ptid (pid)),
04548                rs->buf);
04549     }
04550   else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
04551     error (_("This target does not support attaching to a process"));
04552   else
04553     error (_("Attaching to %s failed"),
04554            target_pid_to_str (pid_to_ptid (pid)));
04555 
04556   set_current_inferior (remote_add_inferior (0, pid, 1));
04557 
04558   inferior_ptid = pid_to_ptid (pid);
04559 
04560   if (non_stop)
04561     {
04562       struct thread_info *thread;
04563 
04564       /* Get list of threads.  */
04565       remote_threads_info (target);
04566 
04567       thread = first_thread_of_process (pid);
04568       if (thread)
04569         inferior_ptid = thread->ptid;
04570       else
04571         inferior_ptid = pid_to_ptid (pid);
04572 
04573       /* Invalidate our notion of the remote current thread.  */
04574       record_currthread (rs, minus_one_ptid);
04575     }
04576   else
04577     {
04578       /* Now, if we have thread information, update inferior_ptid.  */
04579       inferior_ptid = remote_current_thread (inferior_ptid);
04580 
04581       /* Add the main thread to the thread list.  */
04582       add_thread_silent (inferior_ptid);
04583     }
04584 
04585   /* Next, if the target can specify a description, read it.  We do
04586      this before anything involving memory or registers.  */
04587   target_find_description ();
04588 
04589   if (!non_stop)
04590     {
04591       /* Use the previously fetched status.  */
04592       gdb_assert (wait_status != NULL);
04593 
04594       if (target_can_async_p ())
04595         {
04596           struct notif_event *reply
04597             =  remote_notif_parse (&notif_client_stop, wait_status);
04598 
04599           push_stop_reply ((struct stop_reply *) reply);
04600 
04601           target_async (inferior_event_handler, 0);
04602         }
04603       else
04604         {
04605           gdb_assert (wait_status != NULL);
04606           strcpy (rs->buf, wait_status);
04607           rs->cached_wait_status = 1;
04608         }
04609     }
04610   else
04611     gdb_assert (wait_status == NULL);
04612 }
04613 
04614 static void
04615 extended_remote_attach (struct target_ops *ops, char *args, int from_tty)
04616 {
04617   extended_remote_attach_1 (ops, args, from_tty);
04618 }
04619 
04620 /* Convert hex digit A to a number.  */
04621 
04622 static int
04623 fromhex (int a)
04624 {
04625   if (a >= '0' && a <= '9')
04626     return a - '0';
04627   else if (a >= 'a' && a <= 'f')
04628     return a - 'a' + 10;
04629   else if (a >= 'A' && a <= 'F')
04630     return a - 'A' + 10;
04631   else
04632     error (_("Reply contains invalid hex digit %d"), a);
04633 }
04634 
04635 int
04636 hex2bin (const char *hex, gdb_byte *bin, int count)
04637 {
04638   int i;
04639 
04640   for (i = 0; i < count; i++)
04641     {
04642       if (hex[0] == 0 || hex[1] == 0)
04643         {
04644           /* Hex string is short, or of uneven length.
04645              Return the count that has been converted so far.  */
04646           return i;
04647         }
04648       *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
04649       hex += 2;
04650     }
04651   return i;
04652 }
04653 
04654 /* Convert number NIB to a hex digit.  */
04655 
04656 static int
04657 tohex (int nib)
04658 {
04659   if (nib < 10)
04660     return '0' + nib;
04661   else
04662     return 'a' + nib - 10;
04663 }
04664 
04665 int
04666 bin2hex (const gdb_byte *bin, char *hex, int count)
04667 {
04668   int i;
04669 
04670   /* May use a length, or a nul-terminated string as input.  */
04671   if (count == 0)
04672     count = strlen ((char *) bin);
04673 
04674   for (i = 0; i < count; i++)
04675     {
04676       *hex++ = tohex ((*bin >> 4) & 0xf);
04677       *hex++ = tohex (*bin++ & 0xf);
04678     }
04679   *hex = 0;
04680   return i;
04681 }
04682 
04683 /* Check for the availability of vCont.  This function should also check
04684    the response.  */
04685 
04686 static void
04687 remote_vcont_probe (struct remote_state *rs)
04688 {
04689   char *buf;
04690 
04691   strcpy (rs->buf, "vCont?");
04692   putpkt (rs->buf);
04693   getpkt (&rs->buf, &rs->buf_size, 0);
04694   buf = rs->buf;
04695 
04696   /* Make sure that the features we assume are supported.  */
04697   if (strncmp (buf, "vCont", 5) == 0)
04698     {
04699       char *p = &buf[5];
04700       int support_s, support_S, support_c, support_C;
04701 
04702       support_s = 0;
04703       support_S = 0;
04704       support_c = 0;
04705       support_C = 0;
04706       rs->supports_vCont.t = 0;
04707       rs->supports_vCont.r = 0;
04708       while (p && *p == ';')
04709         {
04710           p++;
04711           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
04712             support_s = 1;
04713           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
04714             support_S = 1;
04715           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
04716             support_c = 1;
04717           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
04718             support_C = 1;
04719           else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
04720             rs->supports_vCont.t = 1;
04721           else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
04722             rs->supports_vCont.r = 1;
04723 
04724           p = strchr (p, ';');
04725         }
04726 
04727       /* If s, S, c, and C are not all supported, we can't use vCont.  Clearing
04728          BUF will make packet_ok disable the packet.  */
04729       if (!support_s || !support_S || !support_c || !support_C)
04730         buf[0] = 0;
04731     }
04732 
04733   packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
04734 }
04735 
04736 /* Helper function for building "vCont" resumptions.  Write a
04737    resumption to P.  ENDP points to one-passed-the-end of the buffer
04738    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
04739    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
04740    resumed thread should be single-stepped and/or signalled.  If PTID
04741    equals minus_one_ptid, then all threads are resumed; if PTID
04742    represents a process, then all threads of the process are resumed;
04743    the thread to be stepped and/or signalled is given in the global
04744    INFERIOR_PTID.  */
04745 
04746 static char *
04747 append_resumption (char *p, char *endp,
04748                    ptid_t ptid, int step, enum gdb_signal siggnal)
04749 {
04750   struct remote_state *rs = get_remote_state ();
04751 
04752   if (step && siggnal != GDB_SIGNAL_0)
04753     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
04754   else if (step
04755            /* GDB is willing to range step.  */
04756            && use_range_stepping
04757            /* Target supports range stepping.  */
04758            && rs->supports_vCont.r
04759            /* We don't currently support range stepping multiple
04760               threads with a wildcard (though the protocol allows it,
04761               so stubs shouldn't make an active effort to forbid
04762               it).  */
04763            && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
04764     {
04765       struct thread_info *tp;
04766 
04767       if (ptid_equal (ptid, minus_one_ptid))
04768         {
04769           /* If we don't know about the target thread's tid, then
04770              we're resuming magic_null_ptid (see caller).  */
04771           tp = find_thread_ptid (magic_null_ptid);
04772         }
04773       else
04774         tp = find_thread_ptid (ptid);
04775       gdb_assert (tp != NULL);
04776 
04777       if (tp->control.may_range_step)
04778         {
04779           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
04780 
04781           p += xsnprintf (p, endp - p, ";r%s,%s",
04782                           phex_nz (tp->control.step_range_start,
04783                                    addr_size),
04784                           phex_nz (tp->control.step_range_end,
04785                                    addr_size));
04786         }
04787       else
04788         p += xsnprintf (p, endp - p, ";s");
04789     }
04790   else if (step)
04791     p += xsnprintf (p, endp - p, ";s");
04792   else if (siggnal != GDB_SIGNAL_0)
04793     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
04794   else
04795     p += xsnprintf (p, endp - p, ";c");
04796 
04797   if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
04798     {
04799       ptid_t nptid;
04800 
04801       /* All (-1) threads of process.  */
04802       nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
04803 
04804       p += xsnprintf (p, endp - p, ":");
04805       p = write_ptid (p, endp, nptid);
04806     }
04807   else if (!ptid_equal (ptid, minus_one_ptid))
04808     {
04809       p += xsnprintf (p, endp - p, ":");
04810       p = write_ptid (p, endp, ptid);
04811     }
04812 
04813   return p;
04814 }
04815 
04816 /* Append a vCont continue-with-signal action for threads that have a
04817    non-zero stop signal.  */
04818 
04819 static char *
04820 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
04821 {
04822   struct thread_info *thread;
04823 
04824   ALL_THREADS (thread)
04825     if (ptid_match (thread->ptid, ptid)
04826         && !ptid_equal (inferior_ptid, thread->ptid)
04827         && thread->suspend.stop_signal != GDB_SIGNAL_0
04828         && signal_pass_state (thread->suspend.stop_signal))
04829       {
04830         p = append_resumption (p, endp, thread->ptid,
04831                                0, thread->suspend.stop_signal);
04832         thread->suspend.stop_signal = GDB_SIGNAL_0;
04833       }
04834 
04835   return p;
04836 }
04837 
04838 /* Resume the remote inferior by using a "vCont" packet.  The thread
04839    to be resumed is PTID; STEP and SIGGNAL indicate whether the
04840    resumed thread should be single-stepped and/or signalled.  If PTID
04841    equals minus_one_ptid, then all threads are resumed; the thread to
04842    be stepped and/or signalled is given in the global INFERIOR_PTID.
04843    This function returns non-zero iff it resumes the inferior.
04844 
04845    This function issues a strict subset of all possible vCont commands at the
04846    moment.  */
04847 
04848 static int
04849 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
04850 {
04851   struct remote_state *rs = get_remote_state ();
04852   char *p;
04853   char *endp;
04854 
04855   if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
04856     remote_vcont_probe (rs);
04857 
04858   if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
04859     return 0;
04860 
04861   p = rs->buf;
04862   endp = rs->buf + get_remote_packet_size ();
04863 
04864   /* If we could generate a wider range of packets, we'd have to worry
04865      about overflowing BUF.  Should there be a generic
04866      "multi-part-packet" packet?  */
04867 
04868   p += xsnprintf (p, endp - p, "vCont");
04869 
04870   if (ptid_equal (ptid, magic_null_ptid))
04871     {
04872       /* MAGIC_NULL_PTID means that we don't have any active threads,
04873          so we don't have any TID numbers the inferior will
04874          understand.  Make sure to only send forms that do not specify
04875          a TID.  */
04876       append_resumption (p, endp, minus_one_ptid, step, siggnal);
04877     }
04878   else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
04879     {
04880       /* Resume all threads (of all processes, or of a single
04881          process), with preference for INFERIOR_PTID.  This assumes
04882          inferior_ptid belongs to the set of all threads we are about
04883          to resume.  */
04884       if (step || siggnal != GDB_SIGNAL_0)
04885         {
04886           /* Step inferior_ptid, with or without signal.  */
04887           p = append_resumption (p, endp, inferior_ptid, step, siggnal);
04888         }
04889 
04890       /* Also pass down any pending signaled resumption for other
04891          threads not the current.  */
04892       p = append_pending_thread_resumptions (p, endp, ptid);
04893 
04894       /* And continue others without a signal.  */
04895       append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
04896     }
04897   else
04898     {
04899       /* Scheduler locking; resume only PTID.  */
04900       append_resumption (p, endp, ptid, step, siggnal);
04901     }
04902 
04903   gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
04904   putpkt (rs->buf);
04905 
04906   if (non_stop)
04907     {
04908       /* In non-stop, the stub replies to vCont with "OK".  The stop
04909          reply will be reported asynchronously by means of a `%Stop'
04910          notification.  */
04911       getpkt (&rs->buf, &rs->buf_size, 0);
04912       if (strcmp (rs->buf, "OK") != 0)
04913         error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
04914     }
04915 
04916   return 1;
04917 }
04918 
04919 /* Tell the remote machine to resume.  */
04920 
04921 static void
04922 remote_resume (struct target_ops *ops,
04923                ptid_t ptid, int step, enum gdb_signal siggnal)
04924 {
04925   struct remote_state *rs = get_remote_state ();
04926   char *buf;
04927 
04928   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
04929      (explained in remote-notif.c:handle_notification) so
04930      remote_notif_process is not called.  We need find a place where
04931      it is safe to start a 'vNotif' sequence.  It is good to do it
04932      before resuming inferior, because inferior was stopped and no RSP
04933      traffic at that moment.  */
04934   if (!non_stop)
04935     remote_notif_process (rs->notif_state, &notif_client_stop);
04936 
04937   rs->last_sent_signal = siggnal;
04938   rs->last_sent_step = step;
04939 
04940   /* The vCont packet doesn't need to specify threads via Hc.  */
04941   /* No reverse support (yet) for vCont.  */
04942   if (execution_direction != EXEC_REVERSE)
04943     if (remote_vcont_resume (ptid, step, siggnal))
04944       goto done;
04945 
04946   /* All other supported resume packets do use Hc, so set the continue
04947      thread.  */
04948   if (ptid_equal (ptid, minus_one_ptid))
04949     set_continue_thread (any_thread_ptid);
04950   else
04951     set_continue_thread (ptid);
04952 
04953   buf = rs->buf;
04954   if (execution_direction == EXEC_REVERSE)
04955     {
04956       /* We don't pass signals to the target in reverse exec mode.  */
04957       if (info_verbose && siggnal != GDB_SIGNAL_0)
04958         warning (_(" - Can't pass signal %d to target in reverse: ignored."),
04959                  siggnal);
04960 
04961       if (step 
04962           && remote_protocol_packets[PACKET_bs].support == PACKET_DISABLE)
04963         error (_("Remote reverse-step not supported."));
04964       if (!step
04965           && remote_protocol_packets[PACKET_bc].support == PACKET_DISABLE)
04966         error (_("Remote reverse-continue not supported."));
04967 
04968       strcpy (buf, step ? "bs" : "bc");
04969     }
04970   else if (siggnal != GDB_SIGNAL_0)
04971     {
04972       buf[0] = step ? 'S' : 'C';
04973       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
04974       buf[2] = tohex (((int) siggnal) & 0xf);
04975       buf[3] = '\0';
04976     }
04977   else
04978     strcpy (buf, step ? "s" : "c");
04979 
04980   putpkt (buf);
04981 
04982  done:
04983   /* We are about to start executing the inferior, let's register it
04984      with the event loop.  NOTE: this is the one place where all the
04985      execution commands end up.  We could alternatively do this in each
04986      of the execution commands in infcmd.c.  */
04987   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
04988      into infcmd.c in order to allow inferior function calls to work
04989      NOT asynchronously.  */
04990   if (target_can_async_p ())
04991     target_async (inferior_event_handler, 0);
04992 
04993   /* We've just told the target to resume.  The remote server will
04994      wait for the inferior to stop, and then send a stop reply.  In
04995      the mean time, we can't start another command/query ourselves
04996      because the stub wouldn't be ready to process it.  This applies
04997      only to the base all-stop protocol, however.  In non-stop (which
04998      only supports vCont), the stub replies with an "OK", and is
04999      immediate able to process further serial input.  */
05000   if (!non_stop)
05001     rs->waiting_for_stop_reply = 1;
05002 }
05003 
05004 
05005 /* Set up the signal handler for SIGINT, while the target is
05006    executing, ovewriting the 'regular' SIGINT signal handler.  */
05007 static void
05008 async_initialize_sigint_signal_handler (void)
05009 {
05010   signal (SIGINT, async_handle_remote_sigint);
05011 }
05012 
05013 /* Signal handler for SIGINT, while the target is executing.  */
05014 static void
05015 async_handle_remote_sigint (int sig)
05016 {
05017   signal (sig, async_handle_remote_sigint_twice);
05018   mark_async_signal_handler (async_sigint_remote_token);
05019 }
05020 
05021 /* Signal handler for SIGINT, installed after SIGINT has already been
05022    sent once.  It will take effect the second time that the user sends
05023    a ^C.  */
05024 static void
05025 async_handle_remote_sigint_twice (int sig)
05026 {
05027   signal (sig, async_handle_remote_sigint);
05028   mark_async_signal_handler (async_sigint_remote_twice_token);
05029 }
05030 
05031 /* Perform the real interruption of the target execution, in response
05032    to a ^C.  */
05033 static void
05034 async_remote_interrupt (gdb_client_data arg)
05035 {
05036   if (remote_debug)
05037     fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
05038 
05039   target_stop (inferior_ptid);
05040 }
05041 
05042 /* Perform interrupt, if the first attempt did not succeed.  Just give
05043    up on the target alltogether.  */
05044 static void
05045 async_remote_interrupt_twice (gdb_client_data arg)
05046 {
05047   if (remote_debug)
05048     fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
05049 
05050   interrupt_query ();
05051 }
05052 
05053 /* Reinstall the usual SIGINT handlers, after the target has
05054    stopped.  */
05055 static void
05056 async_cleanup_sigint_signal_handler (void *dummy)
05057 {
05058   signal (SIGINT, handle_sigint);
05059 }
05060 
05061 /* Send ^C to target to halt it.  Target will respond, and send us a
05062    packet.  */
05063 static void (*ofunc) (int);
05064 
05065 /* The command line interface's stop routine.  This function is installed
05066    as a signal handler for SIGINT.  The first time a user requests a
05067    stop, we call remote_stop to send a break or ^C.  If there is no
05068    response from the target (it didn't stop when the user requested it),
05069    we ask the user if he'd like to detach from the target.  */
05070 static void
05071 sync_remote_interrupt (int signo)
05072 {
05073   /* If this doesn't work, try more severe steps.  */
05074   signal (signo, sync_remote_interrupt_twice);
05075 
05076   gdb_call_async_signal_handler (async_sigint_remote_token, 1);
05077 }
05078 
05079 /* The user typed ^C twice.  */
05080 
05081 static void
05082 sync_remote_interrupt_twice (int signo)
05083 {
05084   signal (signo, ofunc);
05085   gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
05086   signal (signo, sync_remote_interrupt);
05087 }
05088 
05089 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
05090    thread, all threads of a remote process, or all threads of all
05091    processes.  */
05092 
05093 static void
05094 remote_stop_ns (ptid_t ptid)
05095 {
05096   struct remote_state *rs = get_remote_state ();
05097   char *p = rs->buf;
05098   char *endp = rs->buf + get_remote_packet_size ();
05099 
05100   if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
05101     remote_vcont_probe (rs);
05102 
05103   if (!rs->supports_vCont.t)
05104     error (_("Remote server does not support stopping threads"));
05105 
05106   if (ptid_equal (ptid, minus_one_ptid)
05107       || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
05108     p += xsnprintf (p, endp - p, "vCont;t");
05109   else
05110     {
05111       ptid_t nptid;
05112 
05113       p += xsnprintf (p, endp - p, "vCont;t:");
05114 
05115       if (ptid_is_pid (ptid))
05116           /* All (-1) threads of process.  */
05117         nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
05118       else
05119         {
05120           /* Small optimization: if we already have a stop reply for
05121              this thread, no use in telling the stub we want this
05122              stopped.  */
05123           if (peek_stop_reply (ptid))
05124             return;
05125 
05126           nptid = ptid;
05127         }
05128 
05129       write_ptid (p, endp, nptid);
05130     }
05131 
05132   /* In non-stop, we get an immediate OK reply.  The stop reply will
05133      come in asynchronously by notification.  */
05134   putpkt (rs->buf);
05135   getpkt (&rs->buf, &rs->buf_size, 0);
05136   if (strcmp (rs->buf, "OK") != 0)
05137     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
05138 }
05139 
05140 /* All-stop version of target_stop.  Sends a break or a ^C to stop the
05141    remote target.  It is undefined which thread of which process
05142    reports the stop.  */
05143 
05144 static void
05145 remote_stop_as (ptid_t ptid)
05146 {
05147   struct remote_state *rs = get_remote_state ();
05148 
05149   rs->ctrlc_pending_p = 1;
05150 
05151   /* If the inferior is stopped already, but the core didn't know
05152      about it yet, just ignore the request.  The cached wait status
05153      will be collected in remote_wait.  */
05154   if (rs->cached_wait_status)
05155     return;
05156 
05157   /* Send interrupt_sequence to remote target.  */
05158   send_interrupt_sequence ();
05159 }
05160 
05161 /* This is the generic stop called via the target vector.  When a target
05162    interrupt is requested, either by the command line or the GUI, we
05163    will eventually end up here.  */
05164 
05165 static void
05166 remote_stop (ptid_t ptid)
05167 {
05168   if (remote_debug)
05169     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
05170 
05171   if (non_stop)
05172     remote_stop_ns (ptid);
05173   else
05174     remote_stop_as (ptid);
05175 }
05176 
05177 /* Ask the user what to do when an interrupt is received.  */
05178 
05179 static void
05180 interrupt_query (void)
05181 {
05182   target_terminal_ours ();
05183 
05184   if (target_can_async_p ())
05185     {
05186       signal (SIGINT, handle_sigint);
05187       quit ();
05188     }
05189   else
05190     {
05191       if (query (_("Interrupted while waiting for the program.\n\
05192 Give up (and stop debugging it)? ")))
05193         {
05194           remote_unpush_target ();
05195           quit ();
05196         }
05197     }
05198 
05199   target_terminal_inferior ();
05200 }
05201 
05202 /* Enable/disable target terminal ownership.  Most targets can use
05203    terminal groups to control terminal ownership.  Remote targets are
05204    different in that explicit transfer of ownership to/from GDB/target
05205    is required.  */
05206 
05207 static void
05208 remote_terminal_inferior (void)
05209 {
05210   if (!target_async_permitted)
05211     /* Nothing to do.  */
05212     return;
05213 
05214   /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
05215      idempotent.  The event-loop GDB talking to an asynchronous target
05216      with a synchronous command calls this function from both
05217      event-top.c and infrun.c/infcmd.c.  Once GDB stops trying to
05218      transfer the terminal to the target when it shouldn't this guard
05219      can go away.  */
05220   if (!remote_async_terminal_ours_p)
05221     return;
05222   delete_file_handler (input_fd);
05223   remote_async_terminal_ours_p = 0;
05224   async_initialize_sigint_signal_handler ();
05225   /* NOTE: At this point we could also register our selves as the
05226      recipient of all input.  Any characters typed could then be
05227      passed on down to the target.  */
05228 }
05229 
05230 static void
05231 remote_terminal_ours (void)
05232 {
05233   if (!target_async_permitted)
05234     /* Nothing to do.  */
05235     return;
05236 
05237   /* See FIXME in remote_terminal_inferior.  */
05238   if (remote_async_terminal_ours_p)
05239     return;
05240   async_cleanup_sigint_signal_handler (NULL);
05241   add_file_handler (input_fd, stdin_event_handler, 0);
05242   remote_async_terminal_ours_p = 1;
05243 }
05244 
05245 static void
05246 remote_console_output (char *msg)
05247 {
05248   char *p;
05249 
05250   for (p = msg; p[0] && p[1]; p += 2)
05251     {
05252       char tb[2];
05253       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
05254 
05255       tb[0] = c;
05256       tb[1] = 0;
05257       fputs_unfiltered (tb, gdb_stdtarg);
05258     }
05259   gdb_flush (gdb_stdtarg);
05260 }
05261 
05262 typedef struct cached_reg
05263 {
05264   int num;
05265   gdb_byte data[MAX_REGISTER_SIZE];
05266 } cached_reg_t;
05267 
05268 DEF_VEC_O(cached_reg_t);
05269 
05270 typedef struct stop_reply
05271 {
05272   struct notif_event base;
05273 
05274   /* The identifier of the thread about this event  */
05275   ptid_t ptid;
05276 
05277   /* The remote state this event is associated with.  When the remote
05278      connection, represented by a remote_state object, is closed,
05279      all the associated stop_reply events should be released.  */
05280   struct remote_state *rs;
05281 
05282   struct target_waitstatus ws;
05283 
05284   /* Expedited registers.  This makes remote debugging a bit more
05285      efficient for those targets that provide critical registers as
05286      part of their normal status mechanism (as another roundtrip to
05287      fetch them is avoided).  */
05288   VEC(cached_reg_t) *regcache;
05289 
05290   int stopped_by_watchpoint_p;
05291   CORE_ADDR watch_data_address;
05292 
05293   int core;
05294 } *stop_reply_p;
05295 
05296 DECLARE_QUEUE_P (stop_reply_p);
05297 DEFINE_QUEUE_P (stop_reply_p);
05298 /* The list of already fetched and acknowledged stop events.  This
05299    queue is used for notification Stop, and other notifications
05300    don't need queue for their events, because the notification events
05301    of Stop can't be consumed immediately, so that events should be
05302    queued first, and be consumed by remote_wait_{ns,as} one per
05303    time.  Other notifications can consume their events immediately,
05304    so queue is not needed for them.  */
05305 static QUEUE (stop_reply_p) *stop_reply_queue;
05306 
05307 static void
05308 stop_reply_xfree (struct stop_reply *r)
05309 {
05310   notif_event_xfree ((struct notif_event *) r);
05311 }
05312 
05313 static void
05314 remote_notif_stop_parse (struct notif_client *self, char *buf,
05315                          struct notif_event *event)
05316 {
05317   remote_parse_stop_reply (buf, (struct stop_reply *) event);
05318 }
05319 
05320 static void
05321 remote_notif_stop_ack (struct notif_client *self, char *buf,
05322                        struct notif_event *event)
05323 {
05324   struct stop_reply *stop_reply = (struct stop_reply *) event;
05325 
05326   /* acknowledge */
05327   putpkt ((char *) self->ack_command);
05328 
05329   if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
05330       /* We got an unknown stop reply.  */
05331       error (_("Unknown stop reply"));
05332 
05333   push_stop_reply (stop_reply);
05334 }
05335 
05336 static int
05337 remote_notif_stop_can_get_pending_events (struct notif_client *self)
05338 {
05339   /* We can't get pending events in remote_notif_process for
05340      notification stop, and we have to do this in remote_wait_ns
05341      instead.  If we fetch all queued events from stub, remote stub
05342      may exit and we have no chance to process them back in
05343      remote_wait_ns.  */
05344   mark_async_event_handler (remote_async_inferior_event_token);
05345   return 0;
05346 }
05347 
05348 static void
05349 stop_reply_dtr (struct notif_event *event)
05350 {
05351   struct stop_reply *r = (struct stop_reply *) event;
05352 
05353   VEC_free (cached_reg_t, r->regcache);
05354 }
05355 
05356 static struct notif_event *
05357 remote_notif_stop_alloc_reply (void)
05358 {
05359   struct notif_event *r
05360     = (struct notif_event *) XMALLOC (struct stop_reply);
05361 
05362   r->dtr = stop_reply_dtr;
05363 
05364   return r;
05365 }
05366 
05367 /* A client of notification Stop.  */
05368 
05369 struct notif_client notif_client_stop =
05370 {
05371   "Stop",
05372   "vStopped",
05373   remote_notif_stop_parse,
05374   remote_notif_stop_ack,
05375   remote_notif_stop_can_get_pending_events,
05376   remote_notif_stop_alloc_reply,
05377   REMOTE_NOTIF_STOP,
05378 };
05379 
05380 /* A parameter to pass data in and out.  */
05381 
05382 struct queue_iter_param
05383 {
05384   void *input;
05385   struct stop_reply *output;
05386 };
05387 
05388 /* Remove stop replies in the queue if its pid is equal to the given
05389    inferior's pid.  */
05390 
05391 static int
05392 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
05393                                 QUEUE_ITER (stop_reply_p) *iter,
05394                                 stop_reply_p event,
05395                                 void *data)
05396 {
05397   struct queue_iter_param *param = data;
05398   struct inferior *inf = param->input;
05399 
05400   if (ptid_get_pid (event->ptid) == inf->pid)
05401     {
05402       stop_reply_xfree (event);
05403       QUEUE_remove_elem (stop_reply_p, q, iter);
05404     }
05405 
05406   return 1;
05407 }
05408 
05409 /* Discard all pending stop replies of inferior INF.  */
05410 
05411 static void
05412 discard_pending_stop_replies (struct inferior *inf)
05413 {
05414   int i;
05415   struct queue_iter_param param;
05416   struct stop_reply *reply;
05417   struct remote_state *rs = get_remote_state ();
05418   struct remote_notif_state *rns = rs->notif_state;
05419 
05420   /* This function can be notified when an inferior exists.  When the
05421      target is not remote, the notification state is NULL.  */
05422   if (rs->remote_desc == NULL)
05423     return;
05424 
05425   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
05426 
05427   /* Discard the in-flight notification.  */
05428   if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
05429     {
05430       stop_reply_xfree (reply);
05431       rns->pending_event[notif_client_stop.id] = NULL;
05432     }
05433 
05434   param.input = inf;
05435   param.output = NULL;
05436   /* Discard the stop replies we have already pulled with
05437      vStopped.  */
05438   QUEUE_iterate (stop_reply_p, stop_reply_queue,
05439                  remove_stop_reply_for_inferior, &param);
05440 }
05441 
05442 /* If its remote state is equal to the given remote state,
05443    remove EVENT from the stop reply queue.  */
05444 
05445 static int
05446 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
05447                                    QUEUE_ITER (stop_reply_p) *iter,
05448                                    stop_reply_p event,
05449                                    void *data)
05450 {
05451   struct queue_iter_param *param = data;
05452   struct remote_state *rs = param->input;
05453 
05454   if (event->rs == rs)
05455     {
05456       stop_reply_xfree (event);
05457       QUEUE_remove_elem (stop_reply_p, q, iter);
05458     }
05459 
05460   return 1;
05461 }
05462 
05463 /* Discard the stop replies for RS in stop_reply_queue.  */
05464 
05465 static void
05466 discard_pending_stop_replies_in_queue (struct remote_state *rs)
05467 {
05468   struct queue_iter_param param;
05469 
05470   param.input = rs;
05471   param.output = NULL;
05472   /* Discard the stop replies we have already pulled with
05473      vStopped.  */
05474   QUEUE_iterate (stop_reply_p, stop_reply_queue,
05475                  remove_stop_reply_of_remote_state, &param);
05476 }
05477 
05478 /* A parameter to pass data in and out.  */
05479 
05480 static int
05481 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
05482                                    QUEUE_ITER (stop_reply_p) *iter,
05483                                    stop_reply_p event,
05484                                    void *data)
05485 {
05486   struct queue_iter_param *param = data;
05487   ptid_t *ptid = param->input;
05488 
05489   if (ptid_match (event->ptid, *ptid))
05490     {
05491       param->output = event;
05492       QUEUE_remove_elem (stop_reply_p, q, iter);
05493       return 0;
05494     }
05495 
05496   return 1;
05497 }
05498 
05499 /* Remove the first reply in 'stop_reply_queue' which matches
05500    PTID.  */
05501 
05502 static struct stop_reply *
05503 remote_notif_remove_queued_reply (ptid_t ptid)
05504 {
05505   struct queue_iter_param param;
05506 
05507   param.input = &ptid;
05508   param.output = NULL;
05509 
05510   QUEUE_iterate (stop_reply_p, stop_reply_queue,
05511                  remote_notif_remove_once_on_match, &param);
05512   if (notif_debug)
05513     fprintf_unfiltered (gdb_stdlog,
05514                         "notif: discard queued event: 'Stop' in %s\n",
05515                         target_pid_to_str (ptid));
05516 
05517   return param.output;
05518 }
05519 
05520 /* Look for a queued stop reply belonging to PTID.  If one is found,
05521    remove it from the queue, and return it.  Returns NULL if none is
05522    found.  If there are still queued events left to process, tell the
05523    event loop to get back to target_wait soon.  */
05524 
05525 static struct stop_reply *
05526 queued_stop_reply (ptid_t ptid)
05527 {
05528   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
05529 
05530   if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
05531     /* There's still at least an event left.  */
05532     mark_async_event_handler (remote_async_inferior_event_token);
05533 
05534   return r;
05535 }
05536 
05537 /* Push a fully parsed stop reply in the stop reply queue.  Since we
05538    know that we now have at least one queued event left to pass to the
05539    core side, tell the event loop to get back to target_wait soon.  */
05540 
05541 static void
05542 push_stop_reply (struct stop_reply *new_event)
05543 {
05544   QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
05545 
05546   if (notif_debug)
05547     fprintf_unfiltered (gdb_stdlog,
05548                         "notif: push 'Stop' %s to queue %d\n",
05549                         target_pid_to_str (new_event->ptid),
05550                         QUEUE_length (stop_reply_p,
05551                                       stop_reply_queue));
05552 
05553   mark_async_event_handler (remote_async_inferior_event_token);
05554 }
05555 
05556 static int
05557 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
05558                               QUEUE_ITER (stop_reply_p) *iter,
05559                               struct stop_reply *event,
05560                               void *data)
05561 {
05562   ptid_t *ptid = data;
05563 
05564   return !(ptid_equal (*ptid, event->ptid)
05565            && event->ws.kind == TARGET_WAITKIND_STOPPED);
05566 }
05567 
05568 /* Returns true if we have a stop reply for PTID.  */
05569 
05570 static int
05571 peek_stop_reply (ptid_t ptid)
05572 {
05573   return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
05574                          stop_reply_match_ptid_and_ws, &ptid);
05575 }
05576 
05577 /* Parse the stop reply in BUF.  Either the function succeeds, and the
05578    result is stored in EVENT, or throws an error.  */
05579 
05580 static void
05581 remote_parse_stop_reply (char *buf, struct stop_reply *event)
05582 {
05583   struct remote_arch_state *rsa = get_remote_arch_state ();
05584   ULONGEST addr;
05585   char *p;
05586 
05587   event->ptid = null_ptid;
05588   event->rs = get_remote_state ();
05589   event->ws.kind = TARGET_WAITKIND_IGNORE;
05590   event->ws.value.integer = 0;
05591   event->stopped_by_watchpoint_p = 0;
05592   event->regcache = NULL;
05593   event->core = -1;
05594 
05595   switch (buf[0])
05596     {
05597     case 'T':           /* Status with PC, SP, FP, ...  */
05598       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
05599       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
05600             ss = signal number
05601             n... = register number
05602             r... = register contents
05603       */
05604 
05605       p = &buf[3];      /* after Txx */
05606       while (*p)
05607         {
05608           char *p1;
05609           char *p_temp;
05610           int fieldsize;
05611           LONGEST pnum = 0;
05612 
05613           /* If the packet contains a register number, save it in
05614              pnum and set p1 to point to the character following it.
05615              Otherwise p1 points to p.  */
05616 
05617           /* If this packet is an awatch packet, don't parse the 'a'
05618              as a register number.  */
05619 
05620           if (strncmp (p, "awatch", strlen("awatch")) != 0
05621               && strncmp (p, "core", strlen ("core") != 0))
05622             {
05623               /* Read the ``P'' register number.  */
05624               pnum = strtol (p, &p_temp, 16);
05625               p1 = p_temp;
05626             }
05627           else
05628             p1 = p;
05629 
05630           if (p1 == p)  /* No register number present here.  */
05631             {
05632               p1 = strchr (p, ':');
05633               if (p1 == NULL)
05634                 error (_("Malformed packet(a) (missing colon): %s\n\
05635 Packet: '%s'\n"),
05636                        p, buf);
05637               if (strncmp (p, "thread", p1 - p) == 0)
05638                 event->ptid = read_ptid (++p1, &p);
05639               else if ((strncmp (p, "watch", p1 - p) == 0)
05640                        || (strncmp (p, "rwatch", p1 - p) == 0)
05641                        || (strncmp (p, "awatch", p1 - p) == 0))
05642                 {
05643                   event->stopped_by_watchpoint_p = 1;
05644                   p = unpack_varlen_hex (++p1, &addr);
05645                   event->watch_data_address = (CORE_ADDR) addr;
05646                 }
05647               else if (strncmp (p, "library", p1 - p) == 0)
05648                 {
05649                   p1++;
05650                   p_temp = p1;
05651                   while (*p_temp && *p_temp != ';')
05652                     p_temp++;
05653 
05654                   event->ws.kind = TARGET_WAITKIND_LOADED;
05655                   p = p_temp;
05656                 }
05657               else if (strncmp (p, "replaylog", p1 - p) == 0)
05658                 {
05659                   event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
05660                   /* p1 will indicate "begin" or "end", but it makes
05661                      no difference for now, so ignore it.  */
05662                   p_temp = strchr (p1 + 1, ';');
05663                   if (p_temp)
05664                     p = p_temp;
05665                 }
05666               else if (strncmp (p, "core", p1 - p) == 0)
05667                 {
05668                   ULONGEST c;
05669 
05670                   p = unpack_varlen_hex (++p1, &c);
05671                   event->core = c;
05672                 }
05673               else
05674                 {
05675                   /* Silently skip unknown optional info.  */
05676                   p_temp = strchr (p1 + 1, ';');
05677                   if (p_temp)
05678                     p = p_temp;
05679                 }
05680             }
05681           else
05682             {
05683               struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
05684               cached_reg_t cached_reg;
05685 
05686               p = p1;
05687 
05688               if (*p != ':')
05689                 error (_("Malformed packet(b) (missing colon): %s\n\
05690 Packet: '%s'\n"),
05691                        p, buf);
05692               ++p;
05693 
05694               if (reg == NULL)
05695                 error (_("Remote sent bad register number %s: %s\n\
05696 Packet: '%s'\n"),
05697                        hex_string (pnum), p, buf);
05698 
05699               cached_reg.num = reg->regnum;
05700 
05701               fieldsize = hex2bin (p, cached_reg.data,
05702                                    register_size (target_gdbarch (),
05703                                                   reg->regnum));
05704               p += 2 * fieldsize;
05705               if (fieldsize < register_size (target_gdbarch (),
05706                                              reg->regnum))
05707                 warning (_("Remote reply is too short: %s"), buf);
05708 
05709               VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
05710             }
05711 
05712           if (*p != ';')
05713             error (_("Remote register badly formatted: %s\nhere: %s"),
05714                    buf, p);
05715           ++p;
05716         }
05717 
05718       if (event->ws.kind != TARGET_WAITKIND_IGNORE)
05719         break;
05720 
05721       /* fall through */
05722     case 'S':           /* Old style status, just signal only.  */
05723       event->ws.kind = TARGET_WAITKIND_STOPPED;
05724       event->ws.value.sig = (enum gdb_signal)
05725         (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
05726       break;
05727     case 'W':           /* Target exited.  */
05728     case 'X':
05729       {
05730         char *p;
05731         int pid;
05732         ULONGEST value;
05733 
05734         /* GDB used to accept only 2 hex chars here.  Stubs should
05735            only send more if they detect GDB supports multi-process
05736            support.  */
05737         p = unpack_varlen_hex (&buf[1], &value);
05738 
05739         if (buf[0] == 'W')
05740           {
05741             /* The remote process exited.  */
05742             event->ws.kind = TARGET_WAITKIND_EXITED;
05743             event->ws.value.integer = value;
05744           }
05745         else
05746           {
05747             /* The remote process exited with a signal.  */
05748             event->ws.kind = TARGET_WAITKIND_SIGNALLED;
05749             event->ws.value.sig = (enum gdb_signal) value;
05750           }
05751 
05752         /* If no process is specified, assume inferior_ptid.  */
05753         pid = ptid_get_pid (inferior_ptid);
05754         if (*p == '\0')
05755           ;
05756         else if (*p == ';')
05757           {
05758             p++;
05759 
05760             if (p == '\0')
05761               ;
05762             else if (strncmp (p,
05763                               "process:", sizeof ("process:") - 1) == 0)
05764               {
05765                 ULONGEST upid;
05766 
05767                 p += sizeof ("process:") - 1;
05768                 unpack_varlen_hex (p, &upid);
05769                 pid = upid;
05770               }
05771             else
05772               error (_("unknown stop reply packet: %s"), buf);
05773           }
05774         else
05775           error (_("unknown stop reply packet: %s"), buf);
05776         event->ptid = pid_to_ptid (pid);
05777       }
05778       break;
05779     }
05780 
05781   if (non_stop && ptid_equal (event->ptid, null_ptid))
05782     error (_("No process or thread specified in stop reply: %s"), buf);
05783 }
05784 
05785 /* When the stub wants to tell GDB about a new notification reply, it
05786    sends a notification (%Stop, for example).  Those can come it at
05787    any time, hence, we have to make sure that any pending
05788    putpkt/getpkt sequence we're making is finished, before querying
05789    the stub for more events with the corresponding ack command
05790    (vStopped, for example).  E.g., if we started a vStopped sequence
05791    immediately upon receiving the notification, something like this
05792    could happen:
05793 
05794     1.1) --> Hg 1
05795     1.2) <-- OK
05796     1.3) --> g
05797     1.4) <-- %Stop
05798     1.5) --> vStopped
05799     1.6) <-- (registers reply to step #1.3)
05800 
05801    Obviously, the reply in step #1.6 would be unexpected to a vStopped
05802    query.
05803 
05804    To solve this, whenever we parse a %Stop notification successfully,
05805    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
05806    doing whatever we were doing:
05807 
05808     2.1) --> Hg 1
05809     2.2) <-- OK
05810     2.3) --> g
05811     2.4) <-- %Stop
05812       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
05813     2.5) <-- (registers reply to step #2.3)
05814 
05815    Eventualy after step #2.5, we return to the event loop, which
05816    notices there's an event on the
05817    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
05818    associated callback --- the function below.  At this point, we're
05819    always safe to start a vStopped sequence. :
05820 
05821     2.6) --> vStopped
05822     2.7) <-- T05 thread:2
05823     2.8) --> vStopped
05824     2.9) --> OK
05825 */
05826 
05827 void
05828 remote_notif_get_pending_events (struct notif_client *nc)
05829 {
05830   struct remote_state *rs = get_remote_state ();
05831 
05832   if (rs->notif_state->pending_event[nc->id] != NULL)
05833     {
05834       if (notif_debug)
05835         fprintf_unfiltered (gdb_stdlog,
05836                             "notif: process: '%s' ack pending event\n",
05837                             nc->name);
05838 
05839       /* acknowledge */
05840       nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
05841       rs->notif_state->pending_event[nc->id] = NULL;
05842 
05843       while (1)
05844         {
05845           getpkt (&rs->buf, &rs->buf_size, 0);
05846           if (strcmp (rs->buf, "OK") == 0)
05847             break;
05848           else
05849             remote_notif_ack (nc, rs->buf);
05850         }
05851     }
05852   else
05853     {
05854       if (notif_debug)
05855         fprintf_unfiltered (gdb_stdlog,
05856                             "notif: process: '%s' no pending reply\n",
05857                             nc->name);
05858     }
05859 }
05860 
05861 /* Called when it is decided that STOP_REPLY holds the info of the
05862    event that is to be returned to the core.  This function always
05863    destroys STOP_REPLY.  */
05864 
05865 static ptid_t
05866 process_stop_reply (struct stop_reply *stop_reply,
05867                     struct target_waitstatus *status)
05868 {
05869   ptid_t ptid;
05870 
05871   *status = stop_reply->ws;
05872   ptid = stop_reply->ptid;
05873 
05874   /* If no thread/process was reported by the stub, assume the current
05875      inferior.  */
05876   if (ptid_equal (ptid, null_ptid))
05877     ptid = inferior_ptid;
05878 
05879   if (status->kind != TARGET_WAITKIND_EXITED
05880       && status->kind != TARGET_WAITKIND_SIGNALLED)
05881     {
05882       struct remote_state *rs = get_remote_state ();
05883 
05884       /* Expedited registers.  */
05885       if (stop_reply->regcache)
05886         {
05887           struct regcache *regcache
05888             = get_thread_arch_regcache (ptid, target_gdbarch ());
05889           cached_reg_t *reg;
05890           int ix;
05891 
05892           for (ix = 0;
05893                VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
05894                ix++)
05895             regcache_raw_supply (regcache, reg->num, reg->data);
05896           VEC_free (cached_reg_t, stop_reply->regcache);
05897         }
05898 
05899       rs->remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
05900       rs->remote_watch_data_address = stop_reply->watch_data_address;
05901 
05902       remote_notice_new_inferior (ptid, 0);
05903       demand_private_info (ptid)->core = stop_reply->core;
05904     }
05905 
05906   stop_reply_xfree (stop_reply);
05907   return ptid;
05908 }
05909 
05910 /* The non-stop mode version of target_wait.  */
05911 
05912 static ptid_t
05913 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
05914 {
05915   struct remote_state *rs = get_remote_state ();
05916   struct stop_reply *stop_reply;
05917   int ret;
05918   int is_notif = 0;
05919 
05920   /* If in non-stop mode, get out of getpkt even if a
05921      notification is received.  */
05922 
05923   ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
05924                               0 /* forever */, &is_notif);
05925   while (1)
05926     {
05927       if (ret != -1 && !is_notif)
05928         switch (rs->buf[0])
05929           {
05930           case 'E':             /* Error of some sort.  */
05931             /* We're out of sync with the target now.  Did it continue
05932                or not?  We can't tell which thread it was in non-stop,
05933                so just ignore this.  */
05934             warning (_("Remote failure reply: %s"), rs->buf);
05935             break;
05936           case 'O':             /* Console output.  */
05937             remote_console_output (rs->buf + 1);
05938             break;
05939           default:
05940             warning (_("Invalid remote reply: %s"), rs->buf);
05941             break;
05942           }
05943 
05944       /* Acknowledge a pending stop reply that may have arrived in the
05945          mean time.  */
05946       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
05947         remote_notif_get_pending_events (&notif_client_stop);
05948 
05949       /* If indeed we noticed a stop reply, we're done.  */
05950       stop_reply = queued_stop_reply (ptid);
05951       if (stop_reply != NULL)
05952         return process_stop_reply (stop_reply, status);
05953 
05954       /* Still no event.  If we're just polling for an event, then
05955          return to the event loop.  */
05956       if (options & TARGET_WNOHANG)
05957         {
05958           status->kind = TARGET_WAITKIND_IGNORE;
05959           return minus_one_ptid;
05960         }
05961 
05962       /* Otherwise do a blocking wait.  */
05963       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
05964                                   1 /* forever */, &is_notif);
05965     }
05966 }
05967 
05968 /* Wait until the remote machine stops, then return, storing status in
05969    STATUS just as `wait' would.  */
05970 
05971 static ptid_t
05972 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
05973 {
05974   struct remote_state *rs = get_remote_state ();
05975   ptid_t event_ptid = null_ptid;
05976   char *buf;
05977   struct stop_reply *stop_reply;
05978 
05979  again:
05980 
05981   status->kind = TARGET_WAITKIND_IGNORE;
05982   status->value.integer = 0;
05983 
05984   stop_reply = queued_stop_reply (ptid);
05985   if (stop_reply != NULL)
05986     return process_stop_reply (stop_reply, status);
05987 
05988   if (rs->cached_wait_status)
05989     /* Use the cached wait status, but only once.  */
05990     rs->cached_wait_status = 0;
05991   else
05992     {
05993       int ret;
05994       int is_notif;
05995 
05996       if (!target_is_async_p ())
05997         {
05998           ofunc = signal (SIGINT, sync_remote_interrupt);
05999           /* If the user hit C-c before this packet, or between packets,
06000              pretend that it was hit right here.  */
06001           if (check_quit_flag ())
06002             {
06003               clear_quit_flag ();
06004               sync_remote_interrupt (SIGINT);
06005             }
06006         }
06007 
06008       /* FIXME: cagney/1999-09-27: If we're in async mode we should
06009          _never_ wait for ever -> test on target_is_async_p().
06010          However, before we do that we need to ensure that the caller
06011          knows how to take the target into/out of async mode.  */
06012       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
06013                                   wait_forever_enabled_p, &is_notif);
06014 
06015       if (!target_is_async_p ())
06016         signal (SIGINT, ofunc);
06017 
06018       /* GDB gets a notification.  Return to core as this event is
06019          not interesting.  */
06020       if (ret != -1 && is_notif)
06021         return minus_one_ptid;
06022     }
06023 
06024   buf = rs->buf;
06025 
06026   rs->remote_stopped_by_watchpoint_p = 0;
06027 
06028   /* We got something.  */
06029   rs->waiting_for_stop_reply = 0;
06030 
06031   /* Assume that the target has acknowledged Ctrl-C unless we receive
06032      an 'F' or 'O' packet.  */
06033   if (buf[0] != 'F' && buf[0] != 'O')
06034     rs->ctrlc_pending_p = 0;
06035 
06036   switch (buf[0])
06037     {
06038     case 'E':           /* Error of some sort.  */
06039       /* We're out of sync with the target now.  Did it continue or
06040          not?  Not is more likely, so report a stop.  */
06041       warning (_("Remote failure reply: %s"), buf);
06042       status->kind = TARGET_WAITKIND_STOPPED;
06043       status->value.sig = GDB_SIGNAL_0;
06044       break;
06045     case 'F':           /* File-I/O request.  */
06046       remote_fileio_request (buf, rs->ctrlc_pending_p);
06047       rs->ctrlc_pending_p = 0;
06048       break;
06049     case 'T': case 'S': case 'X': case 'W':
06050       {
06051         struct stop_reply *stop_reply
06052           = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
06053                                                       rs->buf);
06054 
06055         event_ptid = process_stop_reply (stop_reply, status);
06056         break;
06057       }
06058     case 'O':           /* Console output.  */
06059       remote_console_output (buf + 1);
06060 
06061       /* The target didn't really stop; keep waiting.  */
06062       rs->waiting_for_stop_reply = 1;
06063 
06064       break;
06065     case '\0':
06066       if (rs->last_sent_signal != GDB_SIGNAL_0)
06067         {
06068           /* Zero length reply means that we tried 'S' or 'C' and the
06069              remote system doesn't support it.  */
06070           target_terminal_ours_for_output ();
06071           printf_filtered
06072             ("Can't send signals to this remote system.  %s not sent.\n",
06073              gdb_signal_to_name (rs->last_sent_signal));
06074           rs->last_sent_signal = GDB_SIGNAL_0;
06075           target_terminal_inferior ();
06076 
06077           strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
06078           putpkt ((char *) buf);
06079 
06080           /* We just told the target to resume, so a stop reply is in
06081              order.  */
06082           rs->waiting_for_stop_reply = 1;
06083           break;
06084         }
06085       /* else fallthrough */
06086     default:
06087       warning (_("Invalid remote reply: %s"), buf);
06088       /* Keep waiting.  */
06089       rs->waiting_for_stop_reply = 1;
06090       break;
06091     }
06092 
06093   if (status->kind == TARGET_WAITKIND_IGNORE)
06094     {
06095       /* Nothing interesting happened.  If we're doing a non-blocking
06096          poll, we're done.  Otherwise, go back to waiting.  */
06097       if (options & TARGET_WNOHANG)
06098         return minus_one_ptid;
06099       else
06100         goto again;
06101     }
06102   else if (status->kind != TARGET_WAITKIND_EXITED
06103            && status->kind != TARGET_WAITKIND_SIGNALLED)
06104     {
06105       if (!ptid_equal (event_ptid, null_ptid))
06106         record_currthread (rs, event_ptid);
06107       else
06108         event_ptid = inferior_ptid;
06109     }
06110   else
06111     /* A process exit.  Invalidate our notion of current thread.  */
06112     record_currthread (rs, minus_one_ptid);
06113 
06114   return event_ptid;
06115 }
06116 
06117 /* Wait until the remote machine stops, then return, storing status in
06118    STATUS just as `wait' would.  */
06119 
06120 static ptid_t
06121 remote_wait (struct target_ops *ops,
06122              ptid_t ptid, struct target_waitstatus *status, int options)
06123 {
06124   ptid_t event_ptid;
06125 
06126   if (non_stop)
06127     event_ptid = remote_wait_ns (ptid, status, options);
06128   else
06129     event_ptid = remote_wait_as (ptid, status, options);
06130 
06131   if (target_can_async_p ())
06132     {
06133       /* If there are are events left in the queue tell the event loop
06134          to return here.  */
06135       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
06136         mark_async_event_handler (remote_async_inferior_event_token);
06137     }
06138 
06139   return event_ptid;
06140 }
06141 
06142 /* Fetch a single register using a 'p' packet.  */
06143 
06144 static int
06145 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
06146 {
06147   struct remote_state *rs = get_remote_state ();
06148   char *buf, *p;
06149   char regp[MAX_REGISTER_SIZE];
06150   int i;
06151 
06152   if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
06153     return 0;
06154 
06155   if (reg->pnum == -1)
06156     return 0;
06157 
06158   p = rs->buf;
06159   *p++ = 'p';
06160   p += hexnumstr (p, reg->pnum);
06161   *p++ = '\0';
06162   putpkt (rs->buf);
06163   getpkt (&rs->buf, &rs->buf_size, 0);
06164 
06165   buf = rs->buf;
06166 
06167   switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
06168     {
06169     case PACKET_OK:
06170       break;
06171     case PACKET_UNKNOWN:
06172       return 0;
06173     case PACKET_ERROR:
06174       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
06175              gdbarch_register_name (get_regcache_arch (regcache), 
06176                                     reg->regnum), 
06177              buf);
06178     }
06179 
06180   /* If this register is unfetchable, tell the regcache.  */
06181   if (buf[0] == 'x')
06182     {
06183       regcache_raw_supply (regcache, reg->regnum, NULL);
06184       return 1;
06185     }
06186 
06187   /* Otherwise, parse and supply the value.  */
06188   p = buf;
06189   i = 0;
06190   while (p[0] != 0)
06191     {
06192       if (p[1] == 0)
06193         error (_("fetch_register_using_p: early buf termination"));
06194 
06195       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
06196       p += 2;
06197     }
06198   regcache_raw_supply (regcache, reg->regnum, regp);
06199   return 1;
06200 }
06201 
06202 /* Fetch the registers included in the target's 'g' packet.  */
06203 
06204 static int
06205 send_g_packet (void)
06206 {
06207   struct remote_state *rs = get_remote_state ();
06208   int buf_len;
06209 
06210   xsnprintf (rs->buf, get_remote_packet_size (), "g");
06211   remote_send (&rs->buf, &rs->buf_size);
06212 
06213   /* We can get out of synch in various cases.  If the first character
06214      in the buffer is not a hex character, assume that has happened
06215      and try to fetch another packet to read.  */
06216   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
06217          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
06218          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
06219          && rs->buf[0] != 'x')  /* New: unavailable register value.  */
06220     {
06221       if (remote_debug)
06222         fprintf_unfiltered (gdb_stdlog,
06223                             "Bad register packet; fetching a new packet\n");
06224       getpkt (&rs->buf, &rs->buf_size, 0);
06225     }
06226 
06227   buf_len = strlen (rs->buf);
06228 
06229   /* Sanity check the received packet.  */
06230   if (buf_len % 2 != 0)
06231     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
06232 
06233   return buf_len / 2;
06234 }
06235 
06236 static void
06237 process_g_packet (struct regcache *regcache)
06238 {
06239   struct gdbarch *gdbarch = get_regcache_arch (regcache);
06240   struct remote_state *rs = get_remote_state ();
06241   struct remote_arch_state *rsa = get_remote_arch_state ();
06242   int i, buf_len;
06243   char *p;
06244   char *regs;
06245 
06246   buf_len = strlen (rs->buf);
06247 
06248   /* Further sanity checks, with knowledge of the architecture.  */
06249   if (buf_len > 2 * rsa->sizeof_g_packet)
06250     error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
06251 
06252   /* Save the size of the packet sent to us by the target.  It is used
06253      as a heuristic when determining the max size of packets that the
06254      target can safely receive.  */
06255   if (rsa->actual_register_packet_size == 0)
06256     rsa->actual_register_packet_size = buf_len;
06257 
06258   /* If this is smaller than we guessed the 'g' packet would be,
06259      update our records.  A 'g' reply that doesn't include a register's
06260      value implies either that the register is not available, or that
06261      the 'p' packet must be used.  */
06262   if (buf_len < 2 * rsa->sizeof_g_packet)
06263     {
06264       rsa->sizeof_g_packet = buf_len / 2;
06265 
06266       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
06267         {
06268           if (rsa->regs[i].pnum == -1)
06269             continue;
06270 
06271           if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
06272             rsa->regs[i].in_g_packet = 0;
06273           else
06274             rsa->regs[i].in_g_packet = 1;
06275         }
06276     }
06277 
06278   regs = alloca (rsa->sizeof_g_packet);
06279 
06280   /* Unimplemented registers read as all bits zero.  */
06281   memset (regs, 0, rsa->sizeof_g_packet);
06282 
06283   /* Reply describes registers byte by byte, each byte encoded as two
06284      hex characters.  Suck them all up, then supply them to the
06285      register cacheing/storage mechanism.  */
06286 
06287   p = rs->buf;
06288   for (i = 0; i < rsa->sizeof_g_packet; i++)
06289     {
06290       if (p[0] == 0 || p[1] == 0)
06291         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
06292         internal_error (__FILE__, __LINE__,
06293                         _("unexpected end of 'g' packet reply"));
06294 
06295       if (p[0] == 'x' && p[1] == 'x')
06296         regs[i] = 0;            /* 'x' */
06297       else
06298         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
06299       p += 2;
06300     }
06301 
06302   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
06303     {
06304       struct packet_reg *r = &rsa->regs[i];
06305 
06306       if (r->in_g_packet)
06307         {
06308           if (r->offset * 2 >= strlen (rs->buf))
06309             /* This shouldn't happen - we adjusted in_g_packet above.  */
06310             internal_error (__FILE__, __LINE__,
06311                             _("unexpected end of 'g' packet reply"));
06312           else if (rs->buf[r->offset * 2] == 'x')
06313             {
06314               gdb_assert (r->offset * 2 < strlen (rs->buf));
06315               /* The register isn't available, mark it as such (at
06316                  the same time setting the value to zero).  */
06317               regcache_raw_supply (regcache, r->regnum, NULL);
06318             }
06319           else
06320             regcache_raw_supply (regcache, r->regnum,
06321                                  regs + r->offset);
06322         }
06323     }
06324 }
06325 
06326 static void
06327 fetch_registers_using_g (struct regcache *regcache)
06328 {
06329   send_g_packet ();
06330   process_g_packet (regcache);
06331 }
06332 
06333 /* Make the remote selected traceframe match GDB's selected
06334    traceframe.  */
06335 
06336 static void
06337 set_remote_traceframe (void)
06338 {
06339   int newnum;
06340   struct remote_state *rs = get_remote_state ();
06341 
06342   if (rs->remote_traceframe_number == get_traceframe_number ())
06343     return;
06344 
06345   /* Avoid recursion, remote_trace_find calls us again.  */
06346   rs->remote_traceframe_number = get_traceframe_number ();
06347 
06348   newnum = target_trace_find (tfind_number,
06349                               get_traceframe_number (), 0, 0, NULL);
06350 
06351   /* Should not happen.  If it does, all bets are off.  */
06352   if (newnum != get_traceframe_number ())
06353     warning (_("could not set remote traceframe"));
06354 }
06355 
06356 static void
06357 remote_fetch_registers (struct target_ops *ops,
06358                         struct regcache *regcache, int regnum)
06359 {
06360   struct remote_arch_state *rsa = get_remote_arch_state ();
06361   int i;
06362 
06363   set_remote_traceframe ();
06364   set_general_thread (inferior_ptid);
06365 
06366   if (regnum >= 0)
06367     {
06368       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
06369 
06370       gdb_assert (reg != NULL);
06371 
06372       /* If this register might be in the 'g' packet, try that first -
06373          we are likely to read more than one register.  If this is the
06374          first 'g' packet, we might be overly optimistic about its
06375          contents, so fall back to 'p'.  */
06376       if (reg->in_g_packet)
06377         {
06378           fetch_registers_using_g (regcache);
06379           if (reg->in_g_packet)
06380             return;
06381         }
06382 
06383       if (fetch_register_using_p (regcache, reg))
06384         return;
06385 
06386       /* This register is not available.  */
06387       regcache_raw_supply (regcache, reg->regnum, NULL);
06388 
06389       return;
06390     }
06391 
06392   fetch_registers_using_g (regcache);
06393 
06394   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
06395     if (!rsa->regs[i].in_g_packet)
06396       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
06397         {
06398           /* This register is not available.  */
06399           regcache_raw_supply (regcache, i, NULL);
06400         }
06401 }
06402 
06403 /* Prepare to store registers.  Since we may send them all (using a
06404    'G' request), we have to read out the ones we don't want to change
06405    first.  */
06406 
06407 static void
06408 remote_prepare_to_store (struct regcache *regcache)
06409 {
06410   struct remote_arch_state *rsa = get_remote_arch_state ();
06411   int i;
06412   gdb_byte buf[MAX_REGISTER_SIZE];
06413 
06414   /* Make sure the entire registers array is valid.  */
06415   switch (remote_protocol_packets[PACKET_P].support)
06416     {
06417     case PACKET_DISABLE:
06418     case PACKET_SUPPORT_UNKNOWN:
06419       /* Make sure all the necessary registers are cached.  */
06420       for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
06421         if (rsa->regs[i].in_g_packet)
06422           regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
06423       break;
06424     case PACKET_ENABLE:
06425       break;
06426     }
06427 }
06428 
06429 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
06430    packet was not recognized.  */
06431 
06432 static int
06433 store_register_using_P (const struct regcache *regcache, 
06434                         struct packet_reg *reg)
06435 {
06436   struct gdbarch *gdbarch = get_regcache_arch (regcache);
06437   struct remote_state *rs = get_remote_state ();
06438   /* Try storing a single register.  */
06439   char *buf = rs->buf;
06440   gdb_byte regp[MAX_REGISTER_SIZE];
06441   char *p;
06442 
06443   if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
06444     return 0;
06445 
06446   if (reg->pnum == -1)
06447     return 0;
06448 
06449   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
06450   p = buf + strlen (buf);
06451   regcache_raw_collect (regcache, reg->regnum, regp);
06452   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
06453   putpkt (rs->buf);
06454   getpkt (&rs->buf, &rs->buf_size, 0);
06455 
06456   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
06457     {
06458     case PACKET_OK:
06459       return 1;
06460     case PACKET_ERROR:
06461       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
06462              gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
06463     case PACKET_UNKNOWN:
06464       return 0;
06465     default:
06466       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
06467     }
06468 }
06469 
06470 /* Store register REGNUM, or all registers if REGNUM == -1, from the
06471    contents of the register cache buffer.  FIXME: ignores errors.  */
06472 
06473 static void
06474 store_registers_using_G (const struct regcache *regcache)
06475 {
06476   struct remote_state *rs = get_remote_state ();
06477   struct remote_arch_state *rsa = get_remote_arch_state ();
06478   gdb_byte *regs;
06479   char *p;
06480 
06481   /* Extract all the registers in the regcache copying them into a
06482      local buffer.  */
06483   {
06484     int i;
06485 
06486     regs = alloca (rsa->sizeof_g_packet);
06487     memset (regs, 0, rsa->sizeof_g_packet);
06488     for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
06489       {
06490         struct packet_reg *r = &rsa->regs[i];
06491 
06492         if (r->in_g_packet)
06493           regcache_raw_collect (regcache, r->regnum, regs + r->offset);
06494       }
06495   }
06496 
06497   /* Command describes registers byte by byte,
06498      each byte encoded as two hex characters.  */
06499   p = rs->buf;
06500   *p++ = 'G';
06501   /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
06502      updated.  */
06503   bin2hex (regs, p, rsa->sizeof_g_packet);
06504   putpkt (rs->buf);
06505   getpkt (&rs->buf, &rs->buf_size, 0);
06506   if (packet_check_result (rs->buf) == PACKET_ERROR)
06507     error (_("Could not write registers; remote failure reply '%s'"), 
06508            rs->buf);
06509 }
06510 
06511 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
06512    of the register cache buffer.  FIXME: ignores errors.  */
06513 
06514 static void
06515 remote_store_registers (struct target_ops *ops,
06516                         struct regcache *regcache, int regnum)
06517 {
06518   struct remote_arch_state *rsa = get_remote_arch_state ();
06519   int i;
06520 
06521   set_remote_traceframe ();
06522   set_general_thread (inferior_ptid);
06523 
06524   if (regnum >= 0)
06525     {
06526       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
06527 
06528       gdb_assert (reg != NULL);
06529 
06530       /* Always prefer to store registers using the 'P' packet if
06531          possible; we often change only a small number of registers.
06532          Sometimes we change a larger number; we'd need help from a
06533          higher layer to know to use 'G'.  */
06534       if (store_register_using_P (regcache, reg))
06535         return;
06536 
06537       /* For now, don't complain if we have no way to write the
06538          register.  GDB loses track of unavailable registers too
06539          easily.  Some day, this may be an error.  We don't have
06540          any way to read the register, either...  */
06541       if (!reg->in_g_packet)
06542         return;
06543 
06544       store_registers_using_G (regcache);
06545       return;
06546     }
06547 
06548   store_registers_using_G (regcache);
06549 
06550   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
06551     if (!rsa->regs[i].in_g_packet)
06552       if (!store_register_using_P (regcache, &rsa->regs[i]))
06553         /* See above for why we do not issue an error here.  */
06554         continue;
06555 }
06556 
06557 
06558 /* Return the number of hex digits in num.  */
06559 
06560 static int
06561 hexnumlen (ULONGEST num)
06562 {
06563   int i;
06564 
06565   for (i = 0; num != 0; i++)
06566     num >>= 4;
06567 
06568   return max (i, 1);
06569 }
06570 
06571 /* Set BUF to the minimum number of hex digits representing NUM.  */
06572 
06573 static int
06574 hexnumstr (char *buf, ULONGEST num)
06575 {
06576   int len = hexnumlen (num);
06577 
06578   return hexnumnstr (buf, num, len);
06579 }
06580 
06581 
06582 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
06583 
06584 static int
06585 hexnumnstr (char *buf, ULONGEST num, int width)
06586 {
06587   int i;
06588 
06589   buf[width] = '\0';
06590 
06591   for (i = width - 1; i >= 0; i--)
06592     {
06593       buf[i] = "0123456789abcdef"[(num & 0xf)];
06594       num >>= 4;
06595     }
06596 
06597   return width;
06598 }
06599 
06600 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
06601 
06602 static CORE_ADDR
06603 remote_address_masked (CORE_ADDR addr)
06604 {
06605   unsigned int address_size = remote_address_size;
06606 
06607   /* If "remoteaddresssize" was not set, default to target address size.  */
06608   if (!address_size)
06609     address_size = gdbarch_addr_bit (target_gdbarch ());
06610 
06611   if (address_size > 0
06612       && address_size < (sizeof (ULONGEST) * 8))
06613     {
06614       /* Only create a mask when that mask can safely be constructed
06615          in a ULONGEST variable.  */
06616       ULONGEST mask = 1;
06617 
06618       mask = (mask << address_size) - 1;
06619       addr &= mask;
06620     }
06621   return addr;
06622 }
06623 
06624 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
06625    binary data in OUT_BUF.  Set *OUT_LEN to the length of the data
06626    encoded in OUT_BUF, and return the number of bytes in OUT_BUF
06627    (which may be more than *OUT_LEN due to escape characters).  The
06628    total number of bytes in the output buffer will be at most
06629    OUT_MAXLEN.  */
06630 
06631 static int
06632 remote_escape_output (const gdb_byte *buffer, int len,
06633                       gdb_byte *out_buf, int *out_len,
06634                       int out_maxlen)
06635 {
06636   int input_index, output_index;
06637 
06638   output_index = 0;
06639   for (input_index = 0; input_index < len; input_index++)
06640     {
06641       gdb_byte b = buffer[input_index];
06642 
06643       if (b == '$' || b == '#' || b == '}')
06644         {
06645           /* These must be escaped.  */
06646           if (output_index + 2 > out_maxlen)
06647             break;
06648           out_buf[output_index++] = '}';
06649           out_buf[output_index++] = b ^ 0x20;
06650         }
06651       else
06652         {
06653           if (output_index + 1 > out_maxlen)
06654             break;
06655           out_buf[output_index++] = b;
06656         }
06657     }
06658 
06659   *out_len = input_index;
06660   return output_index;
06661 }
06662 
06663 /* Convert BUFFER, escaped data LEN bytes long, into binary data
06664    in OUT_BUF.  Return the number of bytes written to OUT_BUF.
06665    Raise an error if the total number of bytes exceeds OUT_MAXLEN.
06666 
06667    This function reverses remote_escape_output.  It allows more
06668    escaped characters than that function does, in particular because
06669    '*' must be escaped to avoid the run-length encoding processing
06670    in reading packets.  */
06671 
06672 static int
06673 remote_unescape_input (const gdb_byte *buffer, int len,
06674                        gdb_byte *out_buf, int out_maxlen)
06675 {
06676   int input_index, output_index;
06677   int escaped;
06678 
06679   output_index = 0;
06680   escaped = 0;
06681   for (input_index = 0; input_index < len; input_index++)
06682     {
06683       gdb_byte b = buffer[input_index];
06684 
06685       if (output_index + 1 > out_maxlen)
06686         {
06687           warning (_("Received too much data from remote target;"
06688                      " ignoring overflow."));
06689           return output_index;
06690         }
06691 
06692       if (escaped)
06693         {
06694           out_buf[output_index++] = b ^ 0x20;
06695           escaped = 0;
06696         }
06697       else if (b == '}')
06698         escaped = 1;
06699       else
06700         out_buf[output_index++] = b;
06701     }
06702 
06703   if (escaped)
06704     error (_("Unmatched escape character in target response."));
06705 
06706   return output_index;
06707 }
06708 
06709 /* Determine whether the remote target supports binary downloading.
06710    This is accomplished by sending a no-op memory write of zero length
06711    to the target at the specified address. It does not suffice to send
06712    the whole packet, since many stubs strip the eighth bit and
06713    subsequently compute a wrong checksum, which causes real havoc with
06714    remote_write_bytes.
06715 
06716    NOTE: This can still lose if the serial line is not eight-bit
06717    clean.  In cases like this, the user should clear "remote
06718    X-packet".  */
06719 
06720 static void
06721 check_binary_download (CORE_ADDR addr)
06722 {
06723   struct remote_state *rs = get_remote_state ();
06724 
06725   switch (remote_protocol_packets[PACKET_X].support)
06726     {
06727     case PACKET_DISABLE:
06728       break;
06729     case PACKET_ENABLE:
06730       break;
06731     case PACKET_SUPPORT_UNKNOWN:
06732       {
06733         char *p;
06734 
06735         p = rs->buf;
06736         *p++ = 'X';
06737         p += hexnumstr (p, (ULONGEST) addr);
06738         *p++ = ',';
06739         p += hexnumstr (p, (ULONGEST) 0);
06740         *p++ = ':';
06741         *p = '\0';
06742 
06743         putpkt_binary (rs->buf, (int) (p - rs->buf));
06744         getpkt (&rs->buf, &rs->buf_size, 0);
06745 
06746         if (rs->buf[0] == '\0')
06747           {
06748             if (remote_debug)
06749               fprintf_unfiltered (gdb_stdlog,
06750                                   "binary downloading NOT "
06751                                   "supported by target\n");
06752             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
06753           }
06754         else
06755           {
06756             if (remote_debug)
06757               fprintf_unfiltered (gdb_stdlog,
06758                                   "binary downloading supported by target\n");
06759             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
06760           }
06761         break;
06762       }
06763     }
06764 }
06765 
06766 /* Write memory data directly to the remote machine.
06767    This does not inform the data cache; the data cache uses this.
06768    HEADER is the starting part of the packet.
06769    MEMADDR is the address in the remote memory space.
06770    MYADDR is the address of the buffer in our space.
06771    LEN is the number of bytes.
06772    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
06773    should send data as binary ('X'), or hex-encoded ('M').
06774 
06775    The function creates packet of the form
06776        <HEADER><ADDRESS>,<LENGTH>:<DATA>
06777 
06778    where encoding of <DATA> is termined by PACKET_FORMAT.
06779 
06780    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
06781    are omitted.
06782 
06783    Returns the number of bytes transferred, or a negative value (an
06784    'enum target_xfer_error' value) for error.  Only transfer a single
06785    packet.  */
06786 
06787 static LONGEST
06788 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
06789                         const gdb_byte *myaddr, ssize_t len,
06790                         char packet_format, int use_length)
06791 {
06792   struct remote_state *rs = get_remote_state ();
06793   char *p;
06794   char *plen = NULL;
06795   int plenlen = 0;
06796   int todo;
06797   int nr_bytes;
06798   int payload_size;
06799   int payload_length;
06800   int header_length;
06801 
06802   if (packet_format != 'X' && packet_format != 'M')
06803     internal_error (__FILE__, __LINE__,
06804                     _("remote_write_bytes_aux: bad packet format"));
06805 
06806   if (len <= 0)
06807     return 0;
06808 
06809   payload_size = get_memory_write_packet_size ();
06810 
06811   /* The packet buffer will be large enough for the payload;
06812      get_memory_packet_size ensures this.  */
06813   rs->buf[0] = '\0';
06814 
06815   /* Compute the size of the actual payload by subtracting out the
06816      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
06817 
06818   payload_size -= strlen ("$,:#NN");
06819   if (!use_length)
06820     /* The comma won't be used.  */
06821     payload_size += 1;
06822   header_length = strlen (header);
06823   payload_size -= header_length;
06824   payload_size -= hexnumlen (memaddr);
06825 
06826   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
06827 
06828   strcat (rs->buf, header);
06829   p = rs->buf + strlen (header);
06830 
06831   /* Compute a best guess of the number of bytes actually transfered.  */
06832   if (packet_format == 'X')
06833     {
06834       /* Best guess at number of bytes that will fit.  */
06835       todo = min (len, payload_size);
06836       if (use_length)
06837         payload_size -= hexnumlen (todo);
06838       todo = min (todo, payload_size);
06839     }
06840   else
06841     {
06842       /* Num bytes that will fit.  */
06843       todo = min (len, payload_size / 2);
06844       if (use_length)
06845         payload_size -= hexnumlen (todo);
06846       todo = min (todo, payload_size / 2);
06847     }
06848 
06849   if (todo <= 0)
06850     internal_error (__FILE__, __LINE__,
06851                     _("minimum packet size too small to write data"));
06852 
06853   /* If we already need another packet, then try to align the end
06854      of this packet to a useful boundary.  */
06855   if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
06856     todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
06857 
06858   /* Append "<memaddr>".  */
06859   memaddr = remote_address_masked (memaddr);
06860   p += hexnumstr (p, (ULONGEST) memaddr);
06861 
06862   if (use_length)
06863     {
06864       /* Append ",".  */
06865       *p++ = ',';
06866 
06867       /* Append <len>.  Retain the location/size of <len>.  It may need to
06868          be adjusted once the packet body has been created.  */
06869       plen = p;
06870       plenlen = hexnumstr (p, (ULONGEST) todo);
06871       p += plenlen;
06872     }
06873 
06874   /* Append ":".  */
06875   *p++ = ':';
06876   *p = '\0';
06877 
06878   /* Append the packet body.  */
06879   if (packet_format == 'X')
06880     {
06881       /* Binary mode.  Send target system values byte by byte, in
06882          increasing byte addresses.  Only escape certain critical
06883          characters.  */
06884       payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
06885                                              &nr_bytes, payload_size);
06886 
06887       /* If not all TODO bytes fit, then we'll need another packet.  Make
06888          a second try to keep the end of the packet aligned.  Don't do
06889          this if the packet is tiny.  */
06890       if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
06891         {
06892           int new_nr_bytes;
06893 
06894           new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
06895                           - memaddr);
06896           if (new_nr_bytes != nr_bytes)
06897             payload_length = remote_escape_output (myaddr, new_nr_bytes,
06898                                                    (gdb_byte *) p, &nr_bytes,
06899                                                    payload_size);
06900         }
06901 
06902       p += payload_length;
06903       if (use_length && nr_bytes < todo)
06904         {
06905           /* Escape chars have filled up the buffer prematurely,
06906              and we have actually sent fewer bytes than planned.
06907              Fix-up the length field of the packet.  Use the same
06908              number of characters as before.  */
06909           plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
06910           *plen = ':';  /* overwrite \0 from hexnumnstr() */
06911         }
06912     }
06913   else
06914     {
06915       /* Normal mode: Send target system values byte by byte, in
06916          increasing byte addresses.  Each byte is encoded as a two hex
06917          value.  */
06918       nr_bytes = bin2hex (myaddr, p, todo);
06919       p += 2 * nr_bytes;
06920     }
06921 
06922   putpkt_binary (rs->buf, (int) (p - rs->buf));
06923   getpkt (&rs->buf, &rs->buf_size, 0);
06924 
06925   if (rs->buf[0] == 'E')
06926     return TARGET_XFER_E_IO;
06927 
06928   /* Return NR_BYTES, not TODO, in case escape chars caused us to send
06929      fewer bytes than we'd planned.  */
06930   return nr_bytes;
06931 }
06932 
06933 /* Write memory data directly to the remote machine.
06934    This does not inform the data cache; the data cache uses this.
06935    MEMADDR is the address in the remote memory space.
06936    MYADDR is the address of the buffer in our space.
06937    LEN is the number of bytes.
06938 
06939    Returns number of bytes transferred, or a negative value (an 'enum
06940    target_xfer_error' value) for error.  Only transfer a single
06941    packet.  */
06942 
06943 static LONGEST
06944 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ssize_t len)
06945 {
06946   char *packet_format = 0;
06947 
06948   /* Check whether the target supports binary download.  */
06949   check_binary_download (memaddr);
06950 
06951   switch (remote_protocol_packets[PACKET_X].support)
06952     {
06953     case PACKET_ENABLE:
06954       packet_format = "X";
06955       break;
06956     case PACKET_DISABLE:
06957       packet_format = "M";
06958       break;
06959     case PACKET_SUPPORT_UNKNOWN:
06960       internal_error (__FILE__, __LINE__,
06961                       _("remote_write_bytes: bad internal state"));
06962     default:
06963       internal_error (__FILE__, __LINE__, _("bad switch"));
06964     }
06965 
06966   return remote_write_bytes_aux (packet_format,
06967                                  memaddr, myaddr, len, packet_format[0], 1);
06968 }
06969 
06970 /* Read memory data directly from the remote machine.
06971    This does not use the data cache; the data cache uses this.
06972    MEMADDR is the address in the remote memory space.
06973    MYADDR is the address of the buffer in our space.
06974    LEN is the number of bytes.
06975 
06976    Returns number of bytes transferred, or a negative value (an 'enum
06977    target_xfer_error' value) for error.  */
06978 
06979 static LONGEST
06980 remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
06981 {
06982   struct remote_state *rs = get_remote_state ();
06983   int max_buf_size;             /* Max size of packet output buffer.  */
06984   char *p;
06985   int todo;
06986   int i;
06987 
06988   if (len <= 0)
06989     return 0;
06990 
06991   max_buf_size = get_memory_read_packet_size ();
06992   /* The packet buffer will be large enough for the payload;
06993      get_memory_packet_size ensures this.  */
06994 
06995   /* Number if bytes that will fit.  */
06996   todo = min (len, max_buf_size / 2);
06997 
06998   /* Construct "m"<memaddr>","<len>".  */
06999   memaddr = remote_address_masked (memaddr);
07000   p = rs->buf;
07001   *p++ = 'm';
07002   p += hexnumstr (p, (ULONGEST) memaddr);
07003   *p++ = ',';
07004   p += hexnumstr (p, (ULONGEST) todo);
07005   *p = '\0';
07006   putpkt (rs->buf);
07007   getpkt (&rs->buf, &rs->buf_size, 0);
07008   if (rs->buf[0] == 'E'
07009       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
07010       && rs->buf[3] == '\0')
07011     return TARGET_XFER_E_IO;
07012   /* Reply describes memory byte by byte, each byte encoded as two hex
07013      characters.  */
07014   p = rs->buf;
07015   i = hex2bin (p, myaddr, todo);
07016   /* Return what we have.  Let higher layers handle partial reads.  */
07017   return i;
07018 }
07019 
07020 
07021 
07022 /* Sends a packet with content determined by the printf format string
07023    FORMAT and the remaining arguments, then gets the reply.  Returns
07024    whether the packet was a success, a failure, or unknown.  */
07025 
07026 static enum packet_result
07027 remote_send_printf (const char *format, ...)
07028 {
07029   struct remote_state *rs = get_remote_state ();
07030   int max_size = get_remote_packet_size ();
07031   va_list ap;
07032 
07033   va_start (ap, format);
07034 
07035   rs->buf[0] = '\0';
07036   if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
07037     internal_error (__FILE__, __LINE__, _("Too long remote packet."));
07038 
07039   if (putpkt (rs->buf) < 0)
07040     error (_("Communication problem with target."));
07041 
07042   rs->buf[0] = '\0';
07043   getpkt (&rs->buf, &rs->buf_size, 0);
07044 
07045   return packet_check_result (rs->buf);
07046 }
07047 
07048 static void
07049 restore_remote_timeout (void *p)
07050 {
07051   int value = *(int *)p;
07052 
07053   remote_timeout = value;
07054 }
07055 
07056 /* Flash writing can take quite some time.  We'll set
07057    effectively infinite timeout for flash operations.
07058    In future, we'll need to decide on a better approach.  */
07059 static const int remote_flash_timeout = 1000;
07060 
07061 static void
07062 remote_flash_erase (struct target_ops *ops,
07063                     ULONGEST address, LONGEST length)
07064 {
07065   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
07066   int saved_remote_timeout = remote_timeout;
07067   enum packet_result ret;
07068   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
07069                                           &saved_remote_timeout);
07070 
07071   remote_timeout = remote_flash_timeout;
07072 
07073   ret = remote_send_printf ("vFlashErase:%s,%s",
07074                             phex (address, addr_size),
07075                             phex (length, 4));
07076   switch (ret)
07077     {
07078     case PACKET_UNKNOWN:
07079       error (_("Remote target does not support flash erase"));
07080     case PACKET_ERROR:
07081       error (_("Error erasing flash with vFlashErase packet"));
07082     default:
07083       break;
07084     }
07085 
07086   do_cleanups (back_to);
07087 }
07088 
07089 static LONGEST
07090 remote_flash_write (struct target_ops *ops,
07091                     ULONGEST address, LONGEST length,
07092                     const gdb_byte *data)
07093 {
07094   int saved_remote_timeout = remote_timeout;
07095   LONGEST ret;
07096   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
07097                                           &saved_remote_timeout);
07098 
07099   remote_timeout = remote_flash_timeout;
07100   ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
07101   do_cleanups (back_to);
07102 
07103   return ret;
07104 }
07105 
07106 static void
07107 remote_flash_done (struct target_ops *ops)
07108 {
07109   int saved_remote_timeout = remote_timeout;
07110   int ret;
07111   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
07112                                           &saved_remote_timeout);
07113 
07114   remote_timeout = remote_flash_timeout;
07115   ret = remote_send_printf ("vFlashDone");
07116   do_cleanups (back_to);
07117 
07118   switch (ret)
07119     {
07120     case PACKET_UNKNOWN:
07121       error (_("Remote target does not support vFlashDone"));
07122     case PACKET_ERROR:
07123       error (_("Error finishing flash operation"));
07124     default:
07125       break;
07126     }
07127 }
07128 
07129 static void
07130 remote_files_info (struct target_ops *ignore)
07131 {
07132   puts_filtered ("Debugging a target over a serial line.\n");
07133 }
07134 
07135 /* Stuff for dealing with the packets which are part of this protocol.
07136    See comment at top of file for details.  */
07137 
07138 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
07139    error to higher layers.  Called when a serial error is detected.
07140    The exception message is STRING, followed by a colon and a blank,
07141    the system error message for errno at function entry and final dot
07142    for output compatibility with throw_perror_with_name.  */
07143 
07144 static void
07145 unpush_and_perror (const char *string)
07146 {
07147   int saved_errno = errno;
07148 
07149   remote_unpush_target ();
07150   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
07151                safe_strerror (saved_errno));
07152 }
07153 
07154 /* Read a single character from the remote end.  */
07155 
07156 static int
07157 readchar (int timeout)
07158 {
07159   int ch;
07160   struct remote_state *rs = get_remote_state ();
07161 
07162   ch = serial_readchar (rs->remote_desc, timeout);
07163 
07164   if (ch >= 0)
07165     return ch;
07166 
07167   switch ((enum serial_rc) ch)
07168     {
07169     case SERIAL_EOF:
07170       remote_unpush_target ();
07171       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
07172       /* no return */
07173     case SERIAL_ERROR:
07174       unpush_and_perror (_("Remote communication error.  "
07175                            "Target disconnected."));
07176       /* no return */
07177     case SERIAL_TIMEOUT:
07178       break;
07179     }
07180   return ch;
07181 }
07182 
07183 /* Wrapper for serial_write that closes the target and throws if
07184    writing fails.  */
07185 
07186 static void
07187 remote_serial_write (const char *str, int len)
07188 {
07189   struct remote_state *rs = get_remote_state ();
07190 
07191   if (serial_write (rs->remote_desc, str, len))
07192     {
07193       unpush_and_perror (_("Remote communication error.  "
07194                            "Target disconnected."));
07195     }
07196 }
07197 
07198 /* Send the command in *BUF to the remote machine, and read the reply
07199    into *BUF.  Report an error if we get an error reply.  Resize
07200    *BUF using xrealloc if necessary to hold the result, and update
07201    *SIZEOF_BUF.  */
07202 
07203 static void
07204 remote_send (char **buf,
07205              long *sizeof_buf)
07206 {
07207   putpkt (*buf);
07208   getpkt (buf, sizeof_buf, 0);
07209 
07210   if ((*buf)[0] == 'E')
07211     error (_("Remote failure reply: %s"), *buf);
07212 }
07213 
07214 /* Return a pointer to an xmalloc'ed string representing an escaped
07215    version of BUF, of len N.  E.g. \n is converted to \\n, \t to \\t,
07216    etc.  The caller is responsible for releasing the returned
07217    memory.  */
07218 
07219 static char *
07220 escape_buffer (const char *buf, int n)
07221 {
07222   struct cleanup *old_chain;
07223   struct ui_file *stb;
07224   char *str;
07225 
07226   stb = mem_fileopen ();
07227   old_chain = make_cleanup_ui_file_delete (stb);
07228 
07229   fputstrn_unfiltered (buf, n, 0, stb);
07230   str = ui_file_xstrdup (stb, NULL);
07231   do_cleanups (old_chain);
07232   return str;
07233 }
07234 
07235 /* Display a null-terminated packet on stdout, for debugging, using C
07236    string notation.  */
07237 
07238 static void
07239 print_packet (char *buf)
07240 {
07241   puts_filtered ("\"");
07242   fputstr_filtered (buf, '"', gdb_stdout);
07243   puts_filtered ("\"");
07244 }
07245 
07246 int
07247 putpkt (char *buf)
07248 {
07249   return putpkt_binary (buf, strlen (buf));
07250 }
07251 
07252 /* Send a packet to the remote machine, with error checking.  The data
07253    of the packet is in BUF.  The string in BUF can be at most
07254    get_remote_packet_size () - 5 to account for the $, # and checksum,
07255    and for a possible /0 if we are debugging (remote_debug) and want
07256    to print the sent packet as a string.  */
07257 
07258 static int
07259 putpkt_binary (char *buf, int cnt)
07260 {
07261   struct remote_state *rs = get_remote_state ();
07262   int i;
07263   unsigned char csum = 0;
07264   char *buf2 = alloca (cnt + 6);
07265 
07266   int ch;
07267   int tcount = 0;
07268   char *p;
07269   char *message;
07270 
07271   /* Catch cases like trying to read memory or listing threads while
07272      we're waiting for a stop reply.  The remote server wouldn't be
07273      ready to handle this request, so we'd hang and timeout.  We don't
07274      have to worry about this in synchronous mode, because in that
07275      case it's not possible to issue a command while the target is
07276      running.  This is not a problem in non-stop mode, because in that
07277      case, the stub is always ready to process serial input.  */
07278   if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
07279     error (_("Cannot execute this command while the target is running."));
07280 
07281   /* We're sending out a new packet.  Make sure we don't look at a
07282      stale cached response.  */
07283   rs->cached_wait_status = 0;
07284 
07285   /* Copy the packet into buffer BUF2, encapsulating it
07286      and giving it a checksum.  */
07287 
07288   p = buf2;
07289   *p++ = '$';
07290 
07291   for (i = 0; i < cnt; i++)
07292     {
07293       csum += buf[i];
07294       *p++ = buf[i];
07295     }
07296   *p++ = '#';
07297   *p++ = tohex ((csum >> 4) & 0xf);
07298   *p++ = tohex (csum & 0xf);
07299 
07300   /* Send it over and over until we get a positive ack.  */
07301 
07302   while (1)
07303     {
07304       int started_error_output = 0;
07305 
07306       if (remote_debug)
07307         {
07308           struct cleanup *old_chain;
07309           char *str;
07310 
07311           *p = '\0';
07312           str = escape_buffer (buf2, p - buf2);
07313           old_chain = make_cleanup (xfree, str);
07314           fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
07315           gdb_flush (gdb_stdlog);
07316           do_cleanups (old_chain);
07317         }
07318       remote_serial_write (buf2, p - buf2);
07319 
07320       /* If this is a no acks version of the remote protocol, send the
07321          packet and move on.  */
07322       if (rs->noack_mode)
07323         break;
07324 
07325       /* Read until either a timeout occurs (-2) or '+' is read.
07326          Handle any notification that arrives in the mean time.  */
07327       while (1)
07328         {
07329           ch = readchar (remote_timeout);
07330 
07331           if (remote_debug)
07332             {
07333               switch (ch)
07334                 {
07335                 case '+':
07336                 case '-':
07337                 case SERIAL_TIMEOUT:
07338                 case '$':
07339                 case '%':
07340                   if (started_error_output)
07341                     {
07342                       putchar_unfiltered ('\n');
07343                       started_error_output = 0;
07344                     }
07345                 }
07346             }
07347 
07348           switch (ch)
07349             {
07350             case '+':
07351               if (remote_debug)
07352                 fprintf_unfiltered (gdb_stdlog, "Ack\n");
07353               return 1;
07354             case '-':
07355               if (remote_debug)
07356                 fprintf_unfiltered (gdb_stdlog, "Nak\n");
07357               /* FALLTHROUGH */
07358             case SERIAL_TIMEOUT:
07359               tcount++;
07360               if (tcount > 3)
07361                 return 0;
07362               break;            /* Retransmit buffer.  */
07363             case '$':
07364               {
07365                 if (remote_debug)
07366                   fprintf_unfiltered (gdb_stdlog,
07367                                       "Packet instead of Ack, ignoring it\n");
07368                 /* It's probably an old response sent because an ACK
07369                    was lost.  Gobble up the packet and ack it so it
07370                    doesn't get retransmitted when we resend this
07371                    packet.  */
07372                 skip_frame ();
07373                 remote_serial_write ("+", 1);
07374                 continue;       /* Now, go look for +.  */
07375               }
07376 
07377             case '%':
07378               {
07379                 int val;
07380 
07381                 /* If we got a notification, handle it, and go back to looking
07382                    for an ack.  */
07383                 /* We've found the start of a notification.  Now
07384                    collect the data.  */
07385                 val = read_frame (&rs->buf, &rs->buf_size);
07386                 if (val >= 0)
07387                   {
07388                     if (remote_debug)
07389                       {
07390                         struct cleanup *old_chain;
07391                         char *str;
07392 
07393                         str = escape_buffer (rs->buf, val);
07394                         old_chain = make_cleanup (xfree, str);
07395                         fprintf_unfiltered (gdb_stdlog,
07396                                             "  Notification received: %s\n",
07397                                             str);
07398                         do_cleanups (old_chain);
07399                       }
07400                     handle_notification (rs->notif_state, rs->buf);
07401                     /* We're in sync now, rewait for the ack.  */
07402                     tcount = 0;
07403                   }
07404                 else
07405                   {
07406                     if (remote_debug)
07407                       {
07408                         if (!started_error_output)
07409                           {
07410                             started_error_output = 1;
07411                             fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
07412                           }
07413                         fputc_unfiltered (ch & 0177, gdb_stdlog);
07414                         fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
07415                       }
07416                   }
07417                 continue;
07418               }
07419               /* fall-through */
07420             default:
07421               if (remote_debug)
07422                 {
07423                   if (!started_error_output)
07424                     {
07425                       started_error_output = 1;
07426                       fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
07427                     }
07428                   fputc_unfiltered (ch & 0177, gdb_stdlog);
07429                 }
07430               continue;
07431             }
07432           break;                /* Here to retransmit.  */
07433         }
07434 
07435 #if 0
07436       /* This is wrong.  If doing a long backtrace, the user should be
07437          able to get out next time we call QUIT, without anything as
07438          violent as interrupt_query.  If we want to provide a way out of
07439          here without getting to the next QUIT, it should be based on
07440          hitting ^C twice as in remote_wait.  */
07441       if (quit_flag)
07442         {
07443           quit_flag = 0;
07444           interrupt_query ();
07445         }
07446 #endif
07447     }
07448   return 0;
07449 }
07450 
07451 /* Come here after finding the start of a frame when we expected an
07452    ack.  Do our best to discard the rest of this packet.  */
07453 
07454 static void
07455 skip_frame (void)
07456 {
07457   int c;
07458 
07459   while (1)
07460     {
07461       c = readchar (remote_timeout);
07462       switch (c)
07463         {
07464         case SERIAL_TIMEOUT:
07465           /* Nothing we can do.  */
07466           return;
07467         case '#':
07468           /* Discard the two bytes of checksum and stop.  */
07469           c = readchar (remote_timeout);
07470           if (c >= 0)
07471             c = readchar (remote_timeout);
07472 
07473           return;
07474         case '*':               /* Run length encoding.  */
07475           /* Discard the repeat count.  */
07476           c = readchar (remote_timeout);
07477           if (c < 0)
07478             return;
07479           break;
07480         default:
07481           /* A regular character.  */
07482           break;
07483         }
07484     }
07485 }
07486 
07487 /* Come here after finding the start of the frame.  Collect the rest
07488    into *BUF, verifying the checksum, length, and handling run-length
07489    compression.  NUL terminate the buffer.  If there is not enough room,
07490    expand *BUF using xrealloc.
07491 
07492    Returns -1 on error, number of characters in buffer (ignoring the
07493    trailing NULL) on success. (could be extended to return one of the
07494    SERIAL status indications).  */
07495 
07496 static long
07497 read_frame (char **buf_p,
07498             long *sizeof_buf)
07499 {
07500   unsigned char csum;
07501   long bc;
07502   int c;
07503   char *buf = *buf_p;
07504   struct remote_state *rs = get_remote_state ();
07505 
07506   csum = 0;
07507   bc = 0;
07508 
07509   while (1)
07510     {
07511       c = readchar (remote_timeout);
07512       switch (c)
07513         {
07514         case SERIAL_TIMEOUT:
07515           if (remote_debug)
07516             fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
07517           return -1;
07518         case '$':
07519           if (remote_debug)
07520             fputs_filtered ("Saw new packet start in middle of old one\n",
07521                             gdb_stdlog);
07522           return -1;            /* Start a new packet, count retries.  */
07523         case '#':
07524           {
07525             unsigned char pktcsum;
07526             int check_0 = 0;
07527             int check_1 = 0;
07528 
07529             buf[bc] = '\0';
07530 
07531             check_0 = readchar (remote_timeout);
07532             if (check_0 >= 0)
07533               check_1 = readchar (remote_timeout);
07534 
07535             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
07536               {
07537                 if (remote_debug)
07538                   fputs_filtered ("Timeout in checksum, retrying\n",
07539                                   gdb_stdlog);
07540                 return -1;
07541               }
07542             else if (check_0 < 0 || check_1 < 0)
07543               {
07544                 if (remote_debug)
07545                   fputs_filtered ("Communication error in checksum\n",
07546                                   gdb_stdlog);
07547                 return -1;
07548               }
07549 
07550             /* Don't recompute the checksum; with no ack packets we
07551                don't have any way to indicate a packet retransmission
07552                is necessary.  */
07553             if (rs->noack_mode)
07554               return bc;
07555 
07556             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
07557             if (csum == pktcsum)
07558               return bc;
07559 
07560             if (remote_debug)
07561               {
07562                 struct cleanup *old_chain;
07563                 char *str;
07564 
07565                 str = escape_buffer (buf, bc);
07566                 old_chain = make_cleanup (xfree, str);
07567                 fprintf_unfiltered (gdb_stdlog,
07568                                     "Bad checksum, sentsum=0x%x, "
07569                                     "csum=0x%x, buf=%s\n",
07570                                     pktcsum, csum, str);
07571                 do_cleanups (old_chain);
07572               }
07573             /* Number of characters in buffer ignoring trailing
07574                NULL.  */
07575             return -1;
07576           }
07577         case '*':               /* Run length encoding.  */
07578           {
07579             int repeat;
07580 
07581             csum += c;
07582             c = readchar (remote_timeout);
07583             csum += c;
07584             repeat = c - ' ' + 3;       /* Compute repeat count.  */
07585 
07586             /* The character before ``*'' is repeated.  */
07587 
07588             if (repeat > 0 && repeat <= 255 && bc > 0)
07589               {
07590                 if (bc + repeat - 1 >= *sizeof_buf - 1)
07591                   {
07592                     /* Make some more room in the buffer.  */
07593                     *sizeof_buf += repeat;
07594                     *buf_p = xrealloc (*buf_p, *sizeof_buf);
07595                     buf = *buf_p;
07596                   }
07597 
07598                 memset (&buf[bc], buf[bc - 1], repeat);
07599                 bc += repeat;
07600                 continue;
07601               }
07602 
07603             buf[bc] = '\0';
07604             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
07605             return -1;
07606           }
07607         default:
07608           if (bc >= *sizeof_buf - 1)
07609             {
07610               /* Make some more room in the buffer.  */
07611               *sizeof_buf *= 2;
07612               *buf_p = xrealloc (*buf_p, *sizeof_buf);
07613               buf = *buf_p;
07614             }
07615 
07616           buf[bc++] = c;
07617           csum += c;
07618           continue;
07619         }
07620     }
07621 }
07622 
07623 /* Read a packet from the remote machine, with error checking, and
07624    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
07625    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
07626    rather than timing out; this is used (in synchronous mode) to wait
07627    for a target that is is executing user code to stop.  */
07628 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
07629    don't have to change all the calls to getpkt to deal with the
07630    return value, because at the moment I don't know what the right
07631    thing to do it for those.  */
07632 void
07633 getpkt (char **buf,
07634         long *sizeof_buf,
07635         int forever)
07636 {
07637   int timed_out;
07638 
07639   timed_out = getpkt_sane (buf, sizeof_buf, forever);
07640 }
07641 
07642 
07643 /* Read a packet from the remote machine, with error checking, and
07644    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
07645    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
07646    rather than timing out; this is used (in synchronous mode) to wait
07647    for a target that is is executing user code to stop.  If FOREVER ==
07648    0, this function is allowed to time out gracefully and return an
07649    indication of this to the caller.  Otherwise return the number of
07650    bytes read.  If EXPECTING_NOTIF, consider receiving a notification
07651    enough reason to return to the caller.  *IS_NOTIF is an output
07652    boolean that indicates whether *BUF holds a notification or not
07653    (a regular packet).  */
07654 
07655 static int
07656 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
07657                         int expecting_notif, int *is_notif)
07658 {
07659   struct remote_state *rs = get_remote_state ();
07660   int c;
07661   int tries;
07662   int timeout;
07663   int val = -1;
07664 
07665   /* We're reading a new response.  Make sure we don't look at a
07666      previously cached response.  */
07667   rs->cached_wait_status = 0;
07668 
07669   strcpy (*buf, "timeout");
07670 
07671   if (forever)
07672     timeout = watchdog > 0 ? watchdog : -1;
07673   else if (expecting_notif)
07674     timeout = 0; /* There should already be a char in the buffer.  If
07675                     not, bail out.  */
07676   else
07677     timeout = remote_timeout;
07678 
07679 #define MAX_TRIES 3
07680 
07681   /* Process any number of notifications, and then return when
07682      we get a packet.  */
07683   for (;;)
07684     {
07685       /* If we get a timeout or bad checksm, retry up to MAX_TRIES
07686          times.  */
07687       for (tries = 1; tries <= MAX_TRIES; tries++)
07688         {
07689           /* This can loop forever if the remote side sends us
07690              characters continuously, but if it pauses, we'll get
07691              SERIAL_TIMEOUT from readchar because of timeout.  Then
07692              we'll count that as a retry.
07693 
07694              Note that even when forever is set, we will only wait
07695              forever prior to the start of a packet.  After that, we
07696              expect characters to arrive at a brisk pace.  They should
07697              show up within remote_timeout intervals.  */
07698           do
07699             c = readchar (timeout);
07700           while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
07701 
07702           if (c == SERIAL_TIMEOUT)
07703             {
07704               if (expecting_notif)
07705                 return -1; /* Don't complain, it's normal to not get
07706                               anything in this case.  */
07707 
07708               if (forever)      /* Watchdog went off?  Kill the target.  */
07709                 {
07710                   QUIT;
07711                   remote_unpush_target ();
07712                   throw_error (TARGET_CLOSE_ERROR,
07713                                _("Watchdog timeout has expired.  "
07714                                  "Target detached."));
07715                 }
07716               if (remote_debug)
07717                 fputs_filtered ("Timed out.\n", gdb_stdlog);
07718             }
07719           else
07720             {
07721               /* We've found the start of a packet or notification.
07722                  Now collect the data.  */
07723               val = read_frame (buf, sizeof_buf);
07724               if (val >= 0)
07725                 break;
07726             }
07727 
07728           remote_serial_write ("-", 1);
07729         }
07730 
07731       if (tries > MAX_TRIES)
07732         {
07733           /* We have tried hard enough, and just can't receive the
07734              packet/notification.  Give up.  */
07735           printf_unfiltered (_("Ignoring packet error, continuing...\n"));
07736 
07737           /* Skip the ack char if we're in no-ack mode.  */
07738           if (!rs->noack_mode)
07739             remote_serial_write ("+", 1);
07740           return -1;
07741         }
07742 
07743       /* If we got an ordinary packet, return that to our caller.  */
07744       if (c == '$')
07745         {
07746           if (remote_debug)
07747             {
07748              struct cleanup *old_chain;
07749              char *str;
07750 
07751              str = escape_buffer (*buf, val);
07752              old_chain = make_cleanup (xfree, str);
07753              fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
07754              do_cleanups (old_chain);
07755             }
07756 
07757           /* Skip the ack char if we're in no-ack mode.  */
07758           if (!rs->noack_mode)
07759             remote_serial_write ("+", 1);
07760           if (is_notif != NULL)
07761             *is_notif = 0;
07762           return val;
07763         }
07764 
07765        /* If we got a notification, handle it, and go back to looking
07766          for a packet.  */
07767       else
07768         {
07769           gdb_assert (c == '%');
07770 
07771           if (remote_debug)
07772             {
07773               struct cleanup *old_chain;
07774               char *str;
07775 
07776               str = escape_buffer (*buf, val);
07777               old_chain = make_cleanup (xfree, str);
07778               fprintf_unfiltered (gdb_stdlog,
07779                                   "  Notification received: %s\n",
07780                                   str);
07781               do_cleanups (old_chain);
07782             }
07783           if (is_notif != NULL)
07784             *is_notif = 1;
07785 
07786           handle_notification (rs->notif_state, *buf);
07787 
07788           /* Notifications require no acknowledgement.  */
07789 
07790           if (expecting_notif)
07791             return val;
07792         }
07793     }
07794 }
07795 
07796 static int
07797 getpkt_sane (char **buf, long *sizeof_buf, int forever)
07798 {
07799   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
07800 }
07801 
07802 static int
07803 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
07804                       int *is_notif)
07805 {
07806   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
07807                                  is_notif);
07808 }
07809 
07810 
07811 /* A helper function that just calls putpkt; for type correctness.  */
07812 
07813 static int
07814 putpkt_for_catch_errors (void *arg)
07815 {
07816   return putpkt (arg);
07817 }
07818 
07819 static void
07820 remote_kill (struct target_ops *ops)
07821 {
07822   /* Use catch_errors so the user can quit from gdb even when we
07823      aren't on speaking terms with the remote system.  */
07824   catch_errors (putpkt_for_catch_errors, "k", "", RETURN_MASK_ERROR);
07825 
07826   /* Don't wait for it to die.  I'm not really sure it matters whether
07827      we do or not.  For the existing stubs, kill is a noop.  */
07828   target_mourn_inferior ();
07829 }
07830 
07831 static int
07832 remote_vkill (int pid, struct remote_state *rs)
07833 {
07834   if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
07835     return -1;
07836 
07837   /* Tell the remote target to detach.  */
07838   xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
07839   putpkt (rs->buf);
07840   getpkt (&rs->buf, &rs->buf_size, 0);
07841 
07842   if (packet_ok (rs->buf,
07843                  &remote_protocol_packets[PACKET_vKill]) == PACKET_OK)
07844     return 0;
07845   else if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
07846     return -1;
07847   else
07848     return 1;
07849 }
07850 
07851 static void
07852 extended_remote_kill (struct target_ops *ops)
07853 {
07854   int res;
07855   int pid = ptid_get_pid (inferior_ptid);
07856   struct remote_state *rs = get_remote_state ();
07857 
07858   res = remote_vkill (pid, rs);
07859   if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
07860     {
07861       /* Don't try 'k' on a multi-process aware stub -- it has no way
07862          to specify the pid.  */
07863 
07864       putpkt ("k");
07865 #if 0
07866       getpkt (&rs->buf, &rs->buf_size, 0);
07867       if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
07868         res = 1;
07869 #else
07870       /* Don't wait for it to die.  I'm not really sure it matters whether
07871          we do or not.  For the existing stubs, kill is a noop.  */
07872       res = 0;
07873 #endif
07874     }
07875 
07876   if (res != 0)
07877     error (_("Can't kill process"));
07878 
07879   target_mourn_inferior ();
07880 }
07881 
07882 static void
07883 remote_mourn (struct target_ops *ops)
07884 {
07885   remote_mourn_1 (ops);
07886 }
07887 
07888 /* Worker function for remote_mourn.  */
07889 static void
07890 remote_mourn_1 (struct target_ops *target)
07891 {
07892   unpush_target (target);
07893 
07894   /* remote_close takes care of doing most of the clean up.  */
07895   generic_mourn_inferior ();
07896 }
07897 
07898 static void
07899 extended_remote_mourn_1 (struct target_ops *target)
07900 {
07901   struct remote_state *rs = get_remote_state ();
07902 
07903   /* In case we got here due to an error, but we're going to stay
07904      connected.  */
07905   rs->waiting_for_stop_reply = 0;
07906 
07907   /* If the current general thread belonged to the process we just
07908      detached from or has exited, the remote side current general
07909      thread becomes undefined.  Considering a case like this:
07910 
07911      - We just got here due to a detach.
07912      - The process that we're detaching from happens to immediately
07913        report a global breakpoint being hit in non-stop mode, in the
07914        same thread we had selected before.
07915      - GDB attaches to this process again.
07916      - This event happens to be the next event we handle.
07917 
07918      GDB would consider that the current general thread didn't need to
07919      be set on the stub side (with Hg), since for all it knew,
07920      GENERAL_THREAD hadn't changed.
07921 
07922      Notice that although in all-stop mode, the remote server always
07923      sets the current thread to the thread reporting the stop event,
07924      that doesn't happen in non-stop mode; in non-stop, the stub *must
07925      not* change the current thread when reporting a breakpoint hit,
07926      due to the decoupling of event reporting and event handling.
07927 
07928      To keep things simple, we always invalidate our notion of the
07929      current thread.  */
07930   record_currthread (rs, minus_one_ptid);
07931 
07932   /* Unlike "target remote", we do not want to unpush the target; then
07933      the next time the user says "run", we won't be connected.  */
07934 
07935   /* Call common code to mark the inferior as not running.      */
07936   generic_mourn_inferior ();
07937 
07938   if (!have_inferiors ())
07939     {
07940       if (!remote_multi_process_p (rs))
07941         {
07942           /* Check whether the target is running now - some remote stubs
07943              automatically restart after kill.  */
07944           putpkt ("?");
07945           getpkt (&rs->buf, &rs->buf_size, 0);
07946 
07947           if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
07948             {
07949               /* Assume that the target has been restarted.  Set
07950                  inferior_ptid so that bits of core GDB realizes
07951                  there's something here, e.g., so that the user can
07952                  say "kill" again.  */
07953               inferior_ptid = magic_null_ptid;
07954             }
07955         }
07956     }
07957 }
07958 
07959 static void
07960 extended_remote_mourn (struct target_ops *ops)
07961 {
07962   extended_remote_mourn_1 (ops);
07963 }
07964 
07965 static int
07966 extended_remote_supports_disable_randomization (void)
07967 {
07968   return (remote_protocol_packets[PACKET_QDisableRandomization].support
07969           == PACKET_ENABLE);
07970 }
07971 
07972 static void
07973 extended_remote_disable_randomization (int val)
07974 {
07975   struct remote_state *rs = get_remote_state ();
07976   char *reply;
07977 
07978   xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
07979              val);
07980   putpkt (rs->buf);
07981   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
07982   if (*reply == '\0')
07983     error (_("Target does not support QDisableRandomization."));
07984   if (strcmp (reply, "OK") != 0)
07985     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
07986 }
07987 
07988 static int
07989 extended_remote_run (char *args)
07990 {
07991   struct remote_state *rs = get_remote_state ();
07992   int len;
07993 
07994   /* If the user has disabled vRun support, or we have detected that
07995      support is not available, do not try it.  */
07996   if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
07997     return -1;
07998 
07999   strcpy (rs->buf, "vRun;");
08000   len = strlen (rs->buf);
08001 
08002   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
08003     error (_("Remote file name too long for run packet"));
08004   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
08005 
08006   gdb_assert (args != NULL);
08007   if (*args)
08008     {
08009       struct cleanup *back_to;
08010       int i;
08011       char **argv;
08012 
08013       argv = gdb_buildargv (args);
08014       back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
08015       for (i = 0; argv[i] != NULL; i++)
08016         {
08017           if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
08018             error (_("Argument list too long for run packet"));
08019           rs->buf[len++] = ';';
08020           len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
08021         }
08022       do_cleanups (back_to);
08023     }
08024 
08025   rs->buf[len++] = '\0';
08026 
08027   putpkt (rs->buf);
08028   getpkt (&rs->buf, &rs->buf_size, 0);
08029 
08030   if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
08031     {
08032       /* We have a wait response.  All is well.  */
08033       return 0;
08034     }
08035   else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
08036     /* It wasn't disabled before, but it is now.  */
08037     return -1;
08038   else
08039     {
08040       if (remote_exec_file[0] == '\0')
08041         error (_("Running the default executable on the remote target failed; "
08042                  "try \"set remote exec-file\"?"));
08043       else
08044         error (_("Running \"%s\" on the remote target failed"),
08045                remote_exec_file);
08046     }
08047 }
08048 
08049 /* In the extended protocol we want to be able to do things like
08050    "run" and have them basically work as expected.  So we need
08051    a special create_inferior function.  We support changing the
08052    executable file and the command line arguments, but not the
08053    environment.  */
08054 
08055 static void
08056 extended_remote_create_inferior_1 (char *exec_file, char *args,
08057                                    char **env, int from_tty)
08058 {
08059   int run_worked;
08060   char *stop_reply;
08061   struct remote_state *rs = get_remote_state ();
08062 
08063   /* If running asynchronously, register the target file descriptor
08064      with the event loop.  */
08065   if (target_can_async_p ())
08066     target_async (inferior_event_handler, 0);
08067 
08068   /* Disable address space randomization if requested (and supported).  */
08069   if (extended_remote_supports_disable_randomization ())
08070     extended_remote_disable_randomization (disable_randomization);
08071 
08072   /* Now restart the remote server.  */
08073   run_worked = extended_remote_run (args) != -1;
08074   if (!run_worked)
08075     {
08076       /* vRun was not supported.  Fail if we need it to do what the
08077          user requested.  */
08078       if (remote_exec_file[0])
08079         error (_("Remote target does not support \"set remote exec-file\""));
08080       if (args[0])
08081         error (_("Remote target does not support \"set args\" or run <ARGS>"));
08082 
08083       /* Fall back to "R".  */
08084       extended_remote_restart ();
08085     }
08086 
08087   if (!have_inferiors ())
08088     {
08089       /* Clean up from the last time we ran, before we mark the target
08090          running again.  This will mark breakpoints uninserted, and
08091          get_offsets may insert breakpoints.  */
08092       init_thread_list ();
08093       init_wait_for_inferior ();
08094     }
08095 
08096   /* vRun's success return is a stop reply.  */
08097   stop_reply = run_worked ? rs->buf : NULL;
08098   add_current_inferior_and_thread (stop_reply);
08099 
08100   /* Get updated offsets, if the stub uses qOffsets.  */
08101   get_offsets ();
08102 }
08103 
08104 static void
08105 extended_remote_create_inferior (struct target_ops *ops, 
08106                                  char *exec_file, char *args,
08107                                  char **env, int from_tty)
08108 {
08109   extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
08110 }
08111 
08112 
08113 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
08114    the list of conditions (in agent expression bytecode format), if any, the
08115    target needs to evaluate.  The output is placed into the packet buffer
08116    started from BUF and ended at BUF_END.  */
08117 
08118 static int
08119 remote_add_target_side_condition (struct gdbarch *gdbarch,
08120                                   struct bp_target_info *bp_tgt, char *buf,
08121                                   char *buf_end)
08122 {
08123   struct agent_expr *aexpr = NULL;
08124   int i, ix;
08125   char *pkt;
08126   char *buf_start = buf;
08127 
08128   if (VEC_empty (agent_expr_p, bp_tgt->conditions))
08129     return 0;
08130 
08131   buf += strlen (buf);
08132   xsnprintf (buf, buf_end - buf, "%s", ";");
08133   buf++;
08134 
08135   /* Send conditions to the target and free the vector.  */
08136   for (ix = 0;
08137        VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
08138        ix++)
08139     {
08140       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
08141       buf += strlen (buf);
08142       for (i = 0; i < aexpr->len; ++i)
08143         buf = pack_hex_byte (buf, aexpr->buf[i]);
08144       *buf = '\0';
08145     }
08146 
08147   VEC_free (agent_expr_p, bp_tgt->conditions);
08148   return 0;
08149 }
08150 
08151 static void
08152 remote_add_target_side_commands (struct gdbarch *gdbarch,
08153                                  struct bp_target_info *bp_tgt, char *buf)
08154 {
08155   struct agent_expr *aexpr = NULL;
08156   int i, ix;
08157 
08158   if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
08159     return;
08160 
08161   buf += strlen (buf);
08162 
08163   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
08164   buf += strlen (buf);
08165 
08166   /* Concatenate all the agent expressions that are commands into the
08167      cmds parameter.  */
08168   for (ix = 0;
08169        VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
08170        ix++)
08171     {
08172       sprintf (buf, "X%x,", aexpr->len);
08173       buf += strlen (buf);
08174       for (i = 0; i < aexpr->len; ++i)
08175         buf = pack_hex_byte (buf, aexpr->buf[i]);
08176       *buf = '\0';
08177     }
08178 
08179   VEC_free (agent_expr_p, bp_tgt->tcommands);
08180 }
08181 
08182 /* Insert a breakpoint.  On targets that have software breakpoint
08183    support, we ask the remote target to do the work; on targets
08184    which don't, we insert a traditional memory breakpoint.  */
08185 
08186 static int
08187 remote_insert_breakpoint (struct gdbarch *gdbarch,
08188                           struct bp_target_info *bp_tgt)
08189 {
08190   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
08191      If it succeeds, then set the support to PACKET_ENABLE.  If it
08192      fails, and the user has explicitly requested the Z support then
08193      report an error, otherwise, mark it disabled and go on.  */
08194 
08195   if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
08196     {
08197       CORE_ADDR addr = bp_tgt->placed_address;
08198       struct remote_state *rs;
08199       char *p, *endbuf;
08200       int bpsize;
08201       struct condition_list *cond = NULL;
08202 
08203       /* Make sure the remote is pointing at the right process, if
08204          necessary.  */
08205       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
08206         set_general_process ();
08207 
08208       gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
08209 
08210       rs = get_remote_state ();
08211       p = rs->buf;
08212       endbuf = rs->buf + get_remote_packet_size ();
08213 
08214       *(p++) = 'Z';
08215       *(p++) = '0';
08216       *(p++) = ',';
08217       addr = (ULONGEST) remote_address_masked (addr);
08218       p += hexnumstr (p, addr);
08219       xsnprintf (p, endbuf - p, ",%d", bpsize);
08220 
08221       if (remote_supports_cond_breakpoints ())
08222         remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
08223 
08224       if (remote_can_run_breakpoint_commands ())
08225         remote_add_target_side_commands (gdbarch, bp_tgt, p);
08226 
08227       putpkt (rs->buf);
08228       getpkt (&rs->buf, &rs->buf_size, 0);
08229 
08230       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
08231         {
08232         case PACKET_ERROR:
08233           return -1;
08234         case PACKET_OK:
08235           bp_tgt->placed_address = addr;
08236           bp_tgt->placed_size = bpsize;
08237           return 0;
08238         case PACKET_UNKNOWN:
08239           break;
08240         }
08241     }
08242 
08243   return memory_insert_breakpoint (gdbarch, bp_tgt);
08244 }
08245 
08246 static int
08247 remote_remove_breakpoint (struct gdbarch *gdbarch,
08248                           struct bp_target_info *bp_tgt)
08249 {
08250   CORE_ADDR addr = bp_tgt->placed_address;
08251   struct remote_state *rs = get_remote_state ();
08252 
08253   if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
08254     {
08255       char *p = rs->buf;
08256       char *endbuf = rs->buf + get_remote_packet_size ();
08257 
08258       /* Make sure the remote is pointing at the right process, if
08259          necessary.  */
08260       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
08261         set_general_process ();
08262 
08263       *(p++) = 'z';
08264       *(p++) = '0';
08265       *(p++) = ',';
08266 
08267       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
08268       p += hexnumstr (p, addr);
08269       xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
08270 
08271       putpkt (rs->buf);
08272       getpkt (&rs->buf, &rs->buf_size, 0);
08273 
08274       return (rs->buf[0] == 'E');
08275     }
08276 
08277   return memory_remove_breakpoint (gdbarch, bp_tgt);
08278 }
08279 
08280 static int
08281 watchpoint_to_Z_packet (int type)
08282 {
08283   switch (type)
08284     {
08285     case hw_write:
08286       return Z_PACKET_WRITE_WP;
08287       break;
08288     case hw_read:
08289       return Z_PACKET_READ_WP;
08290       break;
08291     case hw_access:
08292       return Z_PACKET_ACCESS_WP;
08293       break;
08294     default:
08295       internal_error (__FILE__, __LINE__,
08296                       _("hw_bp_to_z: bad watchpoint type %d"), type);
08297     }
08298 }
08299 
08300 static int
08301 remote_insert_watchpoint (CORE_ADDR addr, int len, int type,
08302                           struct expression *cond)
08303 {
08304   struct remote_state *rs = get_remote_state ();
08305   char *endbuf = rs->buf + get_remote_packet_size ();
08306   char *p;
08307   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
08308 
08309   if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
08310     return 1;
08311 
08312   /* Make sure the remote is pointing at the right process, if
08313      necessary.  */
08314   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
08315     set_general_process ();
08316 
08317   xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
08318   p = strchr (rs->buf, '\0');
08319   addr = remote_address_masked (addr);
08320   p += hexnumstr (p, (ULONGEST) addr);
08321   xsnprintf (p, endbuf - p, ",%x", len);
08322 
08323   putpkt (rs->buf);
08324   getpkt (&rs->buf, &rs->buf_size, 0);
08325 
08326   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
08327     {
08328     case PACKET_ERROR:
08329       return -1;
08330     case PACKET_UNKNOWN:
08331       return 1;
08332     case PACKET_OK:
08333       return 0;
08334     }
08335   internal_error (__FILE__, __LINE__,
08336                   _("remote_insert_watchpoint: reached end of function"));
08337 }
08338 
08339 static int
08340 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
08341                                      CORE_ADDR start, int length)
08342 {
08343   CORE_ADDR diff = remote_address_masked (addr - start);
08344 
08345   return diff < length;
08346 }
08347 
08348 
08349 static int
08350 remote_remove_watchpoint (CORE_ADDR addr, int len, int type,
08351                           struct expression *cond)
08352 {
08353   struct remote_state *rs = get_remote_state ();
08354   char *endbuf = rs->buf + get_remote_packet_size ();
08355   char *p;
08356   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
08357 
08358   if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
08359     return -1;
08360 
08361   /* Make sure the remote is pointing at the right process, if
08362      necessary.  */
08363   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
08364     set_general_process ();
08365 
08366   xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
08367   p = strchr (rs->buf, '\0');
08368   addr = remote_address_masked (addr);
08369   p += hexnumstr (p, (ULONGEST) addr);
08370   xsnprintf (p, endbuf - p, ",%x", len);
08371   putpkt (rs->buf);
08372   getpkt (&rs->buf, &rs->buf_size, 0);
08373 
08374   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
08375     {
08376     case PACKET_ERROR:
08377     case PACKET_UNKNOWN:
08378       return -1;
08379     case PACKET_OK:
08380       return 0;
08381     }
08382   internal_error (__FILE__, __LINE__,
08383                   _("remote_remove_watchpoint: reached end of function"));
08384 }
08385 
08386 
08387 int remote_hw_watchpoint_limit = -1;
08388 int remote_hw_watchpoint_length_limit = -1;
08389 int remote_hw_breakpoint_limit = -1;
08390 
08391 static int
08392 remote_region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
08393 {
08394   if (remote_hw_watchpoint_length_limit == 0)
08395     return 0;
08396   else if (remote_hw_watchpoint_length_limit < 0)
08397     return 1;
08398   else if (len <= remote_hw_watchpoint_length_limit)
08399     return 1;
08400   else
08401     return 0;
08402 }
08403 
08404 static int
08405 remote_check_watch_resources (int type, int cnt, int ot)
08406 {
08407   if (type == bp_hardware_breakpoint)
08408     {
08409       if (remote_hw_breakpoint_limit == 0)
08410         return 0;
08411       else if (remote_hw_breakpoint_limit < 0)
08412         return 1;
08413       else if (cnt <= remote_hw_breakpoint_limit)
08414         return 1;
08415     }
08416   else
08417     {
08418       if (remote_hw_watchpoint_limit == 0)
08419         return 0;
08420       else if (remote_hw_watchpoint_limit < 0)
08421         return 1;
08422       else if (ot)
08423         return -1;
08424       else if (cnt <= remote_hw_watchpoint_limit)
08425         return 1;
08426     }
08427   return -1;
08428 }
08429 
08430 static int
08431 remote_stopped_by_watchpoint (void)
08432 {
08433   struct remote_state *rs = get_remote_state ();
08434 
08435   return rs->remote_stopped_by_watchpoint_p;
08436 }
08437 
08438 static int
08439 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
08440 {
08441   struct remote_state *rs = get_remote_state ();
08442   int rc = 0;
08443 
08444   if (remote_stopped_by_watchpoint ())
08445     {
08446       *addr_p = rs->remote_watch_data_address;
08447       rc = 1;
08448     }
08449 
08450   return rc;
08451 }
08452 
08453 
08454 static int
08455 remote_insert_hw_breakpoint (struct gdbarch *gdbarch,
08456                              struct bp_target_info *bp_tgt)
08457 {
08458   CORE_ADDR addr;
08459   struct remote_state *rs;
08460   char *p, *endbuf;
08461   char *message;
08462 
08463   /* The length field should be set to the size of a breakpoint
08464      instruction, even though we aren't inserting one ourselves.  */
08465 
08466   gdbarch_remote_breakpoint_from_pc
08467     (gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
08468 
08469   if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
08470     return -1;
08471 
08472   /* Make sure the remote is pointing at the right process, if
08473      necessary.  */
08474   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
08475     set_general_process ();
08476 
08477   rs = get_remote_state ();
08478   p = rs->buf;
08479   endbuf = rs->buf + get_remote_packet_size ();
08480 
08481   *(p++) = 'Z';
08482   *(p++) = '1';
08483   *(p++) = ',';
08484 
08485   addr = remote_address_masked (bp_tgt->placed_address);
08486   p += hexnumstr (p, (ULONGEST) addr);
08487   xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
08488 
08489   if (remote_supports_cond_breakpoints ())
08490     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
08491 
08492   if (remote_can_run_breakpoint_commands ())
08493     remote_add_target_side_commands (gdbarch, bp_tgt, p);
08494 
08495   putpkt (rs->buf);
08496   getpkt (&rs->buf, &rs->buf_size, 0);
08497 
08498   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
08499     {
08500     case PACKET_ERROR:
08501       if (rs->buf[1] == '.')
08502         {
08503           message = strchr (rs->buf + 2, '.');
08504           if (message)
08505             error (_("Remote failure reply: %s"), message + 1);
08506         }
08507       return -1;
08508     case PACKET_UNKNOWN:
08509       return -1;
08510     case PACKET_OK:
08511       return 0;
08512     }
08513   internal_error (__FILE__, __LINE__,
08514                   _("remote_insert_hw_breakpoint: reached end of function"));
08515 }
08516 
08517 
08518 static int
08519 remote_remove_hw_breakpoint (struct gdbarch *gdbarch,
08520                              struct bp_target_info *bp_tgt)
08521 {
08522   CORE_ADDR addr;
08523   struct remote_state *rs = get_remote_state ();
08524   char *p = rs->buf;
08525   char *endbuf = rs->buf + get_remote_packet_size ();
08526 
08527   if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
08528     return -1;
08529 
08530   /* Make sure the remote is pointing at the right process, if
08531      necessary.  */
08532   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
08533     set_general_process ();
08534 
08535   *(p++) = 'z';
08536   *(p++) = '1';
08537   *(p++) = ',';
08538 
08539   addr = remote_address_masked (bp_tgt->placed_address);
08540   p += hexnumstr (p, (ULONGEST) addr);
08541   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->placed_size);
08542 
08543   putpkt (rs->buf);
08544   getpkt (&rs->buf, &rs->buf_size, 0);
08545 
08546   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
08547     {
08548     case PACKET_ERROR:
08549     case PACKET_UNKNOWN:
08550       return -1;
08551     case PACKET_OK:
08552       return 0;
08553     }
08554   internal_error (__FILE__, __LINE__,
08555                   _("remote_remove_hw_breakpoint: reached end of function"));
08556 }
08557 
08558 /* Verify memory using the "qCRC:" request.  */
08559 
08560 static int
08561 remote_verify_memory (struct target_ops *ops,
08562                       const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
08563 {
08564   struct remote_state *rs = get_remote_state ();
08565   unsigned long host_crc, target_crc;
08566   char *tmp;
08567 
08568   /* Make sure the remote is pointing at the right process.  */
08569   set_general_process ();
08570 
08571   /* FIXME: assumes lma can fit into long.  */
08572   xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
08573              (long) lma, (long) size);
08574   putpkt (rs->buf);
08575 
08576   /* Be clever; compute the host_crc before waiting for target
08577      reply.  */
08578   host_crc = xcrc32 (data, size, 0xffffffff);
08579 
08580   getpkt (&rs->buf, &rs->buf_size, 0);
08581   if (rs->buf[0] == 'E')
08582     return -1;
08583 
08584   if (rs->buf[0] != 'C')
08585     error (_("remote target does not support this operation"));
08586 
08587   for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
08588     target_crc = target_crc * 16 + fromhex (*tmp);
08589 
08590   return (host_crc == target_crc);
08591 }
08592 
08593 /* compare-sections command
08594 
08595    With no arguments, compares each loadable section in the exec bfd
08596    with the same memory range on the target, and reports mismatches.
08597    Useful for verifying the image on the target against the exec file.  */
08598 
08599 static void
08600 compare_sections_command (char *args, int from_tty)
08601 {
08602   asection *s;
08603   struct cleanup *old_chain;
08604   gdb_byte *sectdata;
08605   const char *sectname;
08606   bfd_size_type size;
08607   bfd_vma lma;
08608   int matched = 0;
08609   int mismatched = 0;
08610   int res;
08611 
08612   if (!exec_bfd)
08613     error (_("command cannot be used without an exec file"));
08614 
08615   /* Make sure the remote is pointing at the right process.  */
08616   set_general_process ();
08617 
08618   for (s = exec_bfd->sections; s; s = s->next)
08619     {
08620       if (!(s->flags & SEC_LOAD))
08621         continue;               /* Skip non-loadable section.  */
08622 
08623       size = bfd_get_section_size (s);
08624       if (size == 0)
08625         continue;               /* Skip zero-length section.  */
08626 
08627       sectname = bfd_get_section_name (exec_bfd, s);
08628       if (args && strcmp (args, sectname) != 0)
08629         continue;               /* Not the section selected by user.  */
08630 
08631       matched = 1;              /* Do this section.  */
08632       lma = s->lma;
08633 
08634       sectdata = xmalloc (size);
08635       old_chain = make_cleanup (xfree, sectdata);
08636       bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
08637 
08638       res = target_verify_memory (sectdata, lma, size);
08639 
08640       if (res == -1)
08641         error (_("target memory fault, section %s, range %s -- %s"), sectname,
08642                paddress (target_gdbarch (), lma),
08643                paddress (target_gdbarch (), lma + size));
08644 
08645       printf_filtered ("Section %s, range %s -- %s: ", sectname,
08646                        paddress (target_gdbarch (), lma),
08647                        paddress (target_gdbarch (), lma + size));
08648       if (res)
08649         printf_filtered ("matched.\n");
08650       else
08651         {
08652           printf_filtered ("MIS-MATCHED!\n");
08653           mismatched++;
08654         }
08655 
08656       do_cleanups (old_chain);
08657     }
08658   if (mismatched > 0)
08659     warning (_("One or more sections of the remote executable does not match\n\
08660 the loaded file\n"));
08661   if (args && !matched)
08662     printf_filtered (_("No loaded section named '%s'.\n"), args);
08663 }
08664 
08665 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
08666    into remote target.  The number of bytes written to the remote
08667    target is returned, or -1 for error.  */
08668 
08669 static LONGEST
08670 remote_write_qxfer (struct target_ops *ops, const char *object_name,
08671                     const char *annex, const gdb_byte *writebuf, 
08672                     ULONGEST offset, LONGEST len, 
08673                     struct packet_config *packet)
08674 {
08675   int i, buf_len;
08676   ULONGEST n;
08677   struct remote_state *rs = get_remote_state ();
08678   int max_size = get_memory_write_packet_size (); 
08679 
08680   if (packet->support == PACKET_DISABLE)
08681     return -1;
08682 
08683   /* Insert header.  */
08684   i = snprintf (rs->buf, max_size, 
08685                 "qXfer:%s:write:%s:%s:",
08686                 object_name, annex ? annex : "",
08687                 phex_nz (offset, sizeof offset));
08688   max_size -= (i + 1);
08689 
08690   /* Escape as much data as fits into rs->buf.  */
08691   buf_len = remote_escape_output 
08692     (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
08693 
08694   if (putpkt_binary (rs->buf, i + buf_len) < 0
08695       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
08696       || packet_ok (rs->buf, packet) != PACKET_OK)
08697     return -1;
08698 
08699   unpack_varlen_hex (rs->buf, &n);
08700   return n;
08701 }
08702 
08703 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
08704    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
08705    number of bytes read is returned, or 0 for EOF, or -1 for error.
08706    The number of bytes read may be less than LEN without indicating an
08707    EOF.  PACKET is checked and updated to indicate whether the remote
08708    target supports this object.  */
08709 
08710 static LONGEST
08711 remote_read_qxfer (struct target_ops *ops, const char *object_name,
08712                    const char *annex,
08713                    gdb_byte *readbuf, ULONGEST offset, LONGEST len,
08714                    struct packet_config *packet)
08715 {
08716   struct remote_state *rs = get_remote_state ();
08717   LONGEST i, n, packet_len;
08718 
08719   if (packet->support == PACKET_DISABLE)
08720     return -1;
08721 
08722   /* Check whether we've cached an end-of-object packet that matches
08723      this request.  */
08724   if (rs->finished_object)
08725     {
08726       if (strcmp (object_name, rs->finished_object) == 0
08727           && strcmp (annex ? annex : "", rs->finished_annex) == 0
08728           && offset == rs->finished_offset)
08729         return 0;
08730 
08731       /* Otherwise, we're now reading something different.  Discard
08732          the cache.  */
08733       xfree (rs->finished_object);
08734       xfree (rs->finished_annex);
08735       rs->finished_object = NULL;
08736       rs->finished_annex = NULL;
08737     }
08738 
08739   /* Request only enough to fit in a single packet.  The actual data
08740      may not, since we don't know how much of it will need to be escaped;
08741      the target is free to respond with slightly less data.  We subtract
08742      five to account for the response type and the protocol frame.  */
08743   n = min (get_remote_packet_size () - 5, len);
08744   snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
08745             object_name, annex ? annex : "",
08746             phex_nz (offset, sizeof offset),
08747             phex_nz (n, sizeof n));
08748   i = putpkt (rs->buf);
08749   if (i < 0)
08750     return -1;
08751 
08752   rs->buf[0] = '\0';
08753   packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
08754   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
08755     return -1;
08756 
08757   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
08758     error (_("Unknown remote qXfer reply: %s"), rs->buf);
08759 
08760   /* 'm' means there is (or at least might be) more data after this
08761      batch.  That does not make sense unless there's at least one byte
08762      of data in this reply.  */
08763   if (rs->buf[0] == 'm' && packet_len == 1)
08764     error (_("Remote qXfer reply contained no data."));
08765 
08766   /* Got some data.  */
08767   i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
08768                              packet_len - 1, readbuf, n);
08769 
08770   /* 'l' is an EOF marker, possibly including a final block of data,
08771      or possibly empty.  If we have the final block of a non-empty
08772      object, record this fact to bypass a subsequent partial read.  */
08773   if (rs->buf[0] == 'l' && offset + i > 0)
08774     {
08775       rs->finished_object = xstrdup (object_name);
08776       rs->finished_annex = xstrdup (annex ? annex : "");
08777       rs->finished_offset = offset + i;
08778     }
08779 
08780   return i;
08781 }
08782 
08783 static LONGEST
08784 remote_xfer_partial (struct target_ops *ops, enum target_object object,
08785                      const char *annex, gdb_byte *readbuf,
08786                      const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
08787 {
08788   struct remote_state *rs;
08789   int i;
08790   char *p2;
08791   char query_type;
08792 
08793   set_remote_traceframe ();
08794   set_general_thread (inferior_ptid);
08795 
08796   rs = get_remote_state ();
08797 
08798   /* Handle memory using the standard memory routines.  */
08799   if (object == TARGET_OBJECT_MEMORY)
08800     {
08801       LONGEST xfered;
08802 
08803       /* If the remote target is connected but not running, we should
08804          pass this request down to a lower stratum (e.g. the executable
08805          file).  */
08806       if (!target_has_execution)
08807         return 0;
08808 
08809       if (writebuf != NULL)
08810         xfered = remote_write_bytes (offset, writebuf, len);
08811       else
08812         xfered = remote_read_bytes (offset, readbuf, len);
08813 
08814       return xfered;
08815     }
08816 
08817   /* Handle SPU memory using qxfer packets.  */
08818   if (object == TARGET_OBJECT_SPU)
08819     {
08820       if (readbuf)
08821         return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
08822                                   &remote_protocol_packets
08823                                     [PACKET_qXfer_spu_read]);
08824       else
08825         return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
08826                                    &remote_protocol_packets
08827                                      [PACKET_qXfer_spu_write]);
08828     }
08829 
08830   /* Handle extra signal info using qxfer packets.  */
08831   if (object == TARGET_OBJECT_SIGNAL_INFO)
08832     {
08833       if (readbuf)
08834         return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
08835                                   &remote_protocol_packets
08836                                   [PACKET_qXfer_siginfo_read]);
08837       else
08838         return remote_write_qxfer (ops, "siginfo", annex,
08839                                    writebuf, offset, len,
08840                                    &remote_protocol_packets
08841                                    [PACKET_qXfer_siginfo_write]);
08842     }
08843 
08844   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
08845     {
08846       if (readbuf)
08847         return remote_read_qxfer (ops, "statictrace", annex,
08848                                   readbuf, offset, len,
08849                                   &remote_protocol_packets
08850                                   [PACKET_qXfer_statictrace_read]);
08851       else
08852         return -1;
08853     }
08854 
08855   /* Only handle flash writes.  */
08856   if (writebuf != NULL)
08857     {
08858       LONGEST xfered;
08859 
08860       switch (object)
08861         {
08862         case TARGET_OBJECT_FLASH:
08863           return remote_flash_write (ops, offset, len, writebuf);
08864 
08865         default:
08866           return -1;
08867         }
08868     }
08869 
08870   /* Map pre-existing objects onto letters.  DO NOT do this for new
08871      objects!!!  Instead specify new query packets.  */
08872   switch (object)
08873     {
08874     case TARGET_OBJECT_AVR:
08875       query_type = 'R';
08876       break;
08877 
08878     case TARGET_OBJECT_AUXV:
08879       gdb_assert (annex == NULL);
08880       return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
08881                                 &remote_protocol_packets[PACKET_qXfer_auxv]);
08882 
08883     case TARGET_OBJECT_AVAILABLE_FEATURES:
08884       return remote_read_qxfer
08885         (ops, "features", annex, readbuf, offset, len,
08886          &remote_protocol_packets[PACKET_qXfer_features]);
08887 
08888     case TARGET_OBJECT_LIBRARIES:
08889       return remote_read_qxfer
08890         (ops, "libraries", annex, readbuf, offset, len,
08891          &remote_protocol_packets[PACKET_qXfer_libraries]);
08892 
08893     case TARGET_OBJECT_LIBRARIES_SVR4:
08894       return remote_read_qxfer
08895         (ops, "libraries-svr4", annex, readbuf, offset, len,
08896          &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
08897 
08898     case TARGET_OBJECT_MEMORY_MAP:
08899       gdb_assert (annex == NULL);
08900       return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
08901                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);
08902 
08903     case TARGET_OBJECT_OSDATA:
08904       /* Should only get here if we're connected.  */
08905       gdb_assert (rs->remote_desc);
08906       return remote_read_qxfer
08907        (ops, "osdata", annex, readbuf, offset, len,
08908         &remote_protocol_packets[PACKET_qXfer_osdata]);
08909 
08910     case TARGET_OBJECT_THREADS:
08911       gdb_assert (annex == NULL);
08912       return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
08913                                 &remote_protocol_packets[PACKET_qXfer_threads]);
08914 
08915     case TARGET_OBJECT_TRACEFRAME_INFO:
08916       gdb_assert (annex == NULL);
08917       return remote_read_qxfer
08918         (ops, "traceframe-info", annex, readbuf, offset, len,
08919          &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
08920 
08921     case TARGET_OBJECT_FDPIC:
08922       return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
08923                                 &remote_protocol_packets[PACKET_qXfer_fdpic]);
08924 
08925     case TARGET_OBJECT_OPENVMS_UIB:
08926       return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
08927                                 &remote_protocol_packets[PACKET_qXfer_uib]);
08928 
08929     case TARGET_OBJECT_BTRACE:
08930       return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
08931         &remote_protocol_packets[PACKET_qXfer_btrace]);
08932 
08933     default:
08934       return -1;
08935     }
08936 
08937   /* Note: a zero OFFSET and LEN can be used to query the minimum
08938      buffer size.  */
08939   if (offset == 0 && len == 0)
08940     return (get_remote_packet_size ());
08941   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
08942      large enough let the caller deal with it.  */
08943   if (len < get_remote_packet_size ())
08944     return -1;
08945   len = get_remote_packet_size ();
08946 
08947   /* Except for querying the minimum buffer size, target must be open.  */
08948   if (!rs->remote_desc)
08949     error (_("remote query is only available after target open"));
08950 
08951   gdb_assert (annex != NULL);
08952   gdb_assert (readbuf != NULL);
08953 
08954   p2 = rs->buf;
08955   *p2++ = 'q';
08956   *p2++ = query_type;
08957 
08958   /* We used one buffer char for the remote protocol q command and
08959      another for the query type.  As the remote protocol encapsulation
08960      uses 4 chars plus one extra in case we are debugging
08961      (remote_debug), we have PBUFZIZ - 7 left to pack the query
08962      string.  */
08963   i = 0;
08964   while (annex[i] && (i < (get_remote_packet_size () - 8)))
08965     {
08966       /* Bad caller may have sent forbidden characters.  */
08967       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
08968       *p2++ = annex[i];
08969       i++;
08970     }
08971   *p2 = '\0';
08972   gdb_assert (annex[i] == '\0');
08973 
08974   i = putpkt (rs->buf);
08975   if (i < 0)
08976     return i;
08977 
08978   getpkt (&rs->buf, &rs->buf_size, 0);
08979   strcpy ((char *) readbuf, rs->buf);
08980 
08981   return strlen ((char *) readbuf);
08982 }
08983 
08984 static int
08985 remote_search_memory (struct target_ops* ops,
08986                       CORE_ADDR start_addr, ULONGEST search_space_len,
08987                       const gdb_byte *pattern, ULONGEST pattern_len,
08988                       CORE_ADDR *found_addrp)
08989 {
08990   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08991   struct remote_state *rs = get_remote_state ();
08992   int max_size = get_memory_write_packet_size ();
08993   struct packet_config *packet =
08994     &remote_protocol_packets[PACKET_qSearch_memory];
08995   /* Number of packet bytes used to encode the pattern;
08996      this could be more than PATTERN_LEN due to escape characters.  */
08997   int escaped_pattern_len;
08998   /* Amount of pattern that was encodable in the packet.  */
08999   int used_pattern_len;
09000   int i;
09001   int found;
09002   ULONGEST found_addr;
09003 
09004   /* Don't go to the target if we don't have to.
09005      This is done before checking packet->support to avoid the possibility that
09006      a success for this edge case means the facility works in general.  */
09007   if (pattern_len > search_space_len)
09008     return 0;
09009   if (pattern_len == 0)
09010     {
09011       *found_addrp = start_addr;
09012       return 1;
09013     }
09014 
09015   /* If we already know the packet isn't supported, fall back to the simple
09016      way of searching memory.  */
09017 
09018   if (packet->support == PACKET_DISABLE)
09019     {
09020       /* Target doesn't provided special support, fall back and use the
09021          standard support (copy memory and do the search here).  */
09022       return simple_search_memory (ops, start_addr, search_space_len,
09023                                    pattern, pattern_len, found_addrp);
09024     }
09025 
09026   /* Make sure the remote is pointing at the right process.  */
09027   set_general_process ();
09028 
09029   /* Insert header.  */
09030   i = snprintf (rs->buf, max_size, 
09031                 "qSearch:memory:%s;%s;",
09032                 phex_nz (start_addr, addr_size),
09033                 phex_nz (search_space_len, sizeof (search_space_len)));
09034   max_size -= (i + 1);
09035 
09036   /* Escape as much data as fits into rs->buf.  */
09037   escaped_pattern_len =
09038     remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
09039                           &used_pattern_len, max_size);
09040 
09041   /* Bail if the pattern is too large.  */
09042   if (used_pattern_len != pattern_len)
09043     error (_("Pattern is too large to transmit to remote target."));
09044 
09045   if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
09046       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
09047       || packet_ok (rs->buf, packet) != PACKET_OK)
09048     {
09049       /* The request may not have worked because the command is not
09050          supported.  If so, fall back to the simple way.  */
09051       if (packet->support == PACKET_DISABLE)
09052         {
09053           return simple_search_memory (ops, start_addr, search_space_len,
09054                                        pattern, pattern_len, found_addrp);
09055         }
09056       return -1;
09057     }
09058 
09059   if (rs->buf[0] == '0')
09060     found = 0;
09061   else if (rs->buf[0] == '1')
09062     {
09063       found = 1;
09064       if (rs->buf[1] != ',')
09065         error (_("Unknown qSearch:memory reply: %s"), rs->buf);
09066       unpack_varlen_hex (rs->buf + 2, &found_addr);
09067       *found_addrp = found_addr;
09068     }
09069   else
09070     error (_("Unknown qSearch:memory reply: %s"), rs->buf);
09071 
09072   return found;
09073 }
09074 
09075 static void
09076 remote_rcmd (char *command,
09077              struct ui_file *outbuf)
09078 {
09079   struct remote_state *rs = get_remote_state ();
09080   char *p = rs->buf;
09081 
09082   if (!rs->remote_desc)
09083     error (_("remote rcmd is only available after target open"));
09084 
09085   /* Send a NULL command across as an empty command.  */
09086   if (command == NULL)
09087     command = "";
09088 
09089   /* The query prefix.  */
09090   strcpy (rs->buf, "qRcmd,");
09091   p = strchr (rs->buf, '\0');
09092 
09093   if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
09094       > get_remote_packet_size ())
09095     error (_("\"monitor\" command ``%s'' is too long."), command);
09096 
09097   /* Encode the actual command.  */
09098   bin2hex ((gdb_byte *) command, p, 0);
09099 
09100   if (putpkt (rs->buf) < 0)
09101     error (_("Communication problem with target."));
09102 
09103   /* get/display the response */
09104   while (1)
09105     {
09106       char *buf;
09107 
09108       /* XXX - see also remote_get_noisy_reply().  */
09109       QUIT;                     /* Allow user to bail out with ^C.  */
09110       rs->buf[0] = '\0';
09111       if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
09112         { 
09113           /* Timeout.  Continue to (try to) read responses.
09114              This is better than stopping with an error, assuming the stub
09115              is still executing the (long) monitor command.
09116              If needed, the user can interrupt gdb using C-c, obtaining
09117              an effect similar to stop on timeout.  */
09118           continue;
09119         }
09120       buf = rs->buf;
09121       if (buf[0] == '\0')
09122         error (_("Target does not support this command."));
09123       if (buf[0] == 'O' && buf[1] != 'K')
09124         {
09125           remote_console_output (buf + 1); /* 'O' message from stub.  */
09126           continue;
09127         }
09128       if (strcmp (buf, "OK") == 0)
09129         break;
09130       if (strlen (buf) == 3 && buf[0] == 'E'
09131           && isdigit (buf[1]) && isdigit (buf[2]))
09132         {
09133           error (_("Protocol error with Rcmd"));
09134         }
09135       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
09136         {
09137           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
09138 
09139           fputc_unfiltered (c, outbuf);
09140         }
09141       break;
09142     }
09143 }
09144 
09145 static VEC(mem_region_s) *
09146 remote_memory_map (struct target_ops *ops)
09147 {
09148   VEC(mem_region_s) *result = NULL;
09149   char *text = target_read_stralloc (&current_target,
09150                                      TARGET_OBJECT_MEMORY_MAP, NULL);
09151 
09152   if (text)
09153     {
09154       struct cleanup *back_to = make_cleanup (xfree, text);
09155 
09156       result = parse_memory_map (text);
09157       do_cleanups (back_to);
09158     }
09159 
09160   return result;
09161 }
09162 
09163 static void
09164 packet_command (char *args, int from_tty)
09165 {
09166   struct remote_state *rs = get_remote_state ();
09167 
09168   if (!rs->remote_desc)
09169     error (_("command can only be used with remote target"));
09170 
09171   if (!args)
09172     error (_("remote-packet command requires packet text as argument"));
09173 
09174   puts_filtered ("sending: ");
09175   print_packet (args);
09176   puts_filtered ("\n");
09177   putpkt (args);
09178 
09179   getpkt (&rs->buf, &rs->buf_size, 0);
09180   puts_filtered ("received: ");
09181   print_packet (rs->buf);
09182   puts_filtered ("\n");
09183 }
09184 
09185 #if 0
09186 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
09187 
09188 static void display_thread_info (struct gdb_ext_thread_info *info);
09189 
09190 static void threadset_test_cmd (char *cmd, int tty);
09191 
09192 static void threadalive_test (char *cmd, int tty);
09193 
09194 static void threadlist_test_cmd (char *cmd, int tty);
09195 
09196 int get_and_display_threadinfo (threadref *ref);
09197 
09198 static void threadinfo_test_cmd (char *cmd, int tty);
09199 
09200 static int thread_display_step (threadref *ref, void *context);
09201 
09202 static void threadlist_update_test_cmd (char *cmd, int tty);
09203 
09204 static void init_remote_threadtests (void);
09205 
09206 #define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid.  */
09207 
09208 static void
09209 threadset_test_cmd (char *cmd, int tty)
09210 {
09211   int sample_thread = SAMPLE_THREAD;
09212 
09213   printf_filtered (_("Remote threadset test\n"));
09214   set_general_thread (sample_thread);
09215 }
09216 
09217 
09218 static void
09219 threadalive_test (char *cmd, int tty)
09220 {
09221   int sample_thread = SAMPLE_THREAD;
09222   int pid = ptid_get_pid (inferior_ptid);
09223   ptid_t ptid = ptid_build (pid, 0, sample_thread);
09224 
09225   if (remote_thread_alive (ptid))
09226     printf_filtered ("PASS: Thread alive test\n");
09227   else
09228     printf_filtered ("FAIL: Thread alive test\n");
09229 }
09230 
09231 void output_threadid (char *title, threadref *ref);
09232 
09233 void
09234 output_threadid (char *title, threadref *ref)
09235 {
09236   char hexid[20];
09237 
09238   pack_threadid (&hexid[0], ref);       /* Convert threead id into hex.  */
09239   hexid[16] = 0;
09240   printf_filtered ("%s  %s\n", title, (&hexid[0]));
09241 }
09242 
09243 static void
09244 threadlist_test_cmd (char *cmd, int tty)
09245 {
09246   int startflag = 1;
09247   threadref nextthread;
09248   int done, result_count;
09249   threadref threadlist[3];
09250 
09251   printf_filtered ("Remote Threadlist test\n");
09252   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
09253                               &result_count, &threadlist[0]))
09254     printf_filtered ("FAIL: threadlist test\n");
09255   else
09256     {
09257       threadref *scan = threadlist;
09258       threadref *limit = scan + result_count;
09259 
09260       while (scan < limit)
09261         output_threadid (" thread ", scan++);
09262     }
09263 }
09264 
09265 void
09266 display_thread_info (struct gdb_ext_thread_info *info)
09267 {
09268   output_threadid ("Threadid: ", &info->threadid);
09269   printf_filtered ("Name: %s\n ", info->shortname);
09270   printf_filtered ("State: %s\n", info->display);
09271   printf_filtered ("other: %s\n\n", info->more_display);
09272 }
09273 
09274 int
09275 get_and_display_threadinfo (threadref *ref)
09276 {
09277   int result;
09278   int set;
09279   struct gdb_ext_thread_info threadinfo;
09280 
09281   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
09282     | TAG_MOREDISPLAY | TAG_DISPLAY;
09283   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
09284     display_thread_info (&threadinfo);
09285   return result;
09286 }
09287 
09288 static void
09289 threadinfo_test_cmd (char *cmd, int tty)
09290 {
09291   int athread = SAMPLE_THREAD;
09292   threadref thread;
09293   int set;
09294 
09295   int_to_threadref (&thread, athread);
09296   printf_filtered ("Remote Threadinfo test\n");
09297   if (!get_and_display_threadinfo (&thread))
09298     printf_filtered ("FAIL cannot get thread info\n");
09299 }
09300 
09301 static int
09302 thread_display_step (threadref *ref, void *context)
09303 {
09304   /* output_threadid(" threadstep ",ref); *//* simple test */
09305   return get_and_display_threadinfo (ref);
09306 }
09307 
09308 static void
09309 threadlist_update_test_cmd (char *cmd, int tty)
09310 {
09311   printf_filtered ("Remote Threadlist update test\n");
09312   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
09313 }
09314 
09315 static void
09316 init_remote_threadtests (void)
09317 {
09318   add_com ("tlist", class_obscure, threadlist_test_cmd,
09319            _("Fetch and print the remote list of "
09320              "thread identifiers, one pkt only"));
09321   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
09322            _("Fetch and display info about one thread"));
09323   add_com ("tset", class_obscure, threadset_test_cmd,
09324            _("Test setting to a different thread"));
09325   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
09326            _("Iterate through updating all remote thread info"));
09327   add_com ("talive", class_obscure, threadalive_test,
09328            _(" Remote thread alive test "));
09329 }
09330 
09331 #endif /* 0 */
09332 
09333 /* Convert a thread ID to a string.  Returns the string in a static
09334    buffer.  */
09335 
09336 static char *
09337 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
09338 {
09339   static char buf[64];
09340   struct remote_state *rs = get_remote_state ();
09341 
09342   if (ptid_equal (ptid, null_ptid))
09343     return normal_pid_to_str (ptid);
09344   else if (ptid_is_pid (ptid))
09345     {
09346       /* Printing an inferior target id.  */
09347 
09348       /* When multi-process extensions are off, there's no way in the
09349          remote protocol to know the remote process id, if there's any
09350          at all.  There's one exception --- when we're connected with
09351          target extended-remote, and we manually attached to a process
09352          with "attach PID".  We don't record anywhere a flag that
09353          allows us to distinguish that case from the case of
09354          connecting with extended-remote and the stub already being
09355          attached to a process, and reporting yes to qAttached, hence
09356          no smart special casing here.  */
09357       if (!remote_multi_process_p (rs))
09358         {
09359           xsnprintf (buf, sizeof buf, "Remote target");
09360           return buf;
09361         }
09362 
09363       return normal_pid_to_str (ptid);
09364     }
09365   else
09366     {
09367       if (ptid_equal (magic_null_ptid, ptid))
09368         xsnprintf (buf, sizeof buf, "Thread <main>");
09369       else if (rs->extended && remote_multi_process_p (rs))
09370         xsnprintf (buf, sizeof buf, "Thread %d.%ld",
09371                    ptid_get_pid (ptid), ptid_get_tid (ptid));
09372       else
09373         xsnprintf (buf, sizeof buf, "Thread %ld",
09374                    ptid_get_tid (ptid));
09375       return buf;
09376     }
09377 }
09378 
09379 /* Get the address of the thread local variable in OBJFILE which is
09380    stored at OFFSET within the thread local storage for thread PTID.  */
09381 
09382 static CORE_ADDR
09383 remote_get_thread_local_address (struct target_ops *ops,
09384                                  ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
09385 {
09386   if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
09387     {
09388       struct remote_state *rs = get_remote_state ();
09389       char *p = rs->buf;
09390       char *endp = rs->buf + get_remote_packet_size ();
09391       enum packet_result result;
09392 
09393       strcpy (p, "qGetTLSAddr:");
09394       p += strlen (p);
09395       p = write_ptid (p, endp, ptid);
09396       *p++ = ',';
09397       p += hexnumstr (p, offset);
09398       *p++ = ',';
09399       p += hexnumstr (p, lm);
09400       *p++ = '\0';
09401 
09402       putpkt (rs->buf);
09403       getpkt (&rs->buf, &rs->buf_size, 0);
09404       result = packet_ok (rs->buf,
09405                           &remote_protocol_packets[PACKET_qGetTLSAddr]);
09406       if (result == PACKET_OK)
09407         {
09408           ULONGEST result;
09409 
09410           unpack_varlen_hex (rs->buf, &result);
09411           return result;
09412         }
09413       else if (result == PACKET_UNKNOWN)
09414         throw_error (TLS_GENERIC_ERROR,
09415                      _("Remote target doesn't support qGetTLSAddr packet"));
09416       else
09417         throw_error (TLS_GENERIC_ERROR,
09418                      _("Remote target failed to process qGetTLSAddr request"));
09419     }
09420   else
09421     throw_error (TLS_GENERIC_ERROR,
09422                  _("TLS not supported or disabled on this target"));
09423   /* Not reached.  */
09424   return 0;
09425 }
09426 
09427 /* Provide thread local base, i.e. Thread Information Block address.
09428    Returns 1 if ptid is found and thread_local_base is non zero.  */
09429 
09430 static int
09431 remote_get_tib_address (ptid_t ptid, CORE_ADDR *addr)
09432 {
09433   if (remote_protocol_packets[PACKET_qGetTIBAddr].support != PACKET_DISABLE)
09434     {
09435       struct remote_state *rs = get_remote_state ();
09436       char *p = rs->buf;
09437       char *endp = rs->buf + get_remote_packet_size ();
09438       enum packet_result result;
09439 
09440       strcpy (p, "qGetTIBAddr:");
09441       p += strlen (p);
09442       p = write_ptid (p, endp, ptid);
09443       *p++ = '\0';
09444 
09445       putpkt (rs->buf);
09446       getpkt (&rs->buf, &rs->buf_size, 0);
09447       result = packet_ok (rs->buf,
09448                           &remote_protocol_packets[PACKET_qGetTIBAddr]);
09449       if (result == PACKET_OK)
09450         {
09451           ULONGEST result;
09452 
09453           unpack_varlen_hex (rs->buf, &result);
09454           if (addr)
09455             *addr = (CORE_ADDR) result;
09456           return 1;
09457         }
09458       else if (result == PACKET_UNKNOWN)
09459         error (_("Remote target doesn't support qGetTIBAddr packet"));
09460       else
09461         error (_("Remote target failed to process qGetTIBAddr request"));
09462     }
09463   else
09464     error (_("qGetTIBAddr not supported or disabled on this target"));
09465   /* Not reached.  */
09466   return 0;
09467 }
09468 
09469 /* Support for inferring a target description based on the current
09470    architecture and the size of a 'g' packet.  While the 'g' packet
09471    can have any size (since optional registers can be left off the
09472    end), some sizes are easily recognizable given knowledge of the
09473    approximate architecture.  */
09474 
09475 struct remote_g_packet_guess
09476 {
09477   int bytes;
09478   const struct target_desc *tdesc;
09479 };
09480 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
09481 DEF_VEC_O(remote_g_packet_guess_s);
09482 
09483 struct remote_g_packet_data
09484 {
09485   VEC(remote_g_packet_guess_s) *guesses;
09486 };
09487 
09488 static struct gdbarch_data *remote_g_packet_data_handle;
09489 
09490 static void *
09491 remote_g_packet_data_init (struct obstack *obstack)
09492 {
09493   return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
09494 }
09495 
09496 void
09497 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
09498                                 const struct target_desc *tdesc)
09499 {
09500   struct remote_g_packet_data *data
09501     = gdbarch_data (gdbarch, remote_g_packet_data_handle);
09502   struct remote_g_packet_guess new_guess, *guess;
09503   int ix;
09504 
09505   gdb_assert (tdesc != NULL);
09506 
09507   for (ix = 0;
09508        VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
09509        ix++)
09510     if (guess->bytes == bytes)
09511       internal_error (__FILE__, __LINE__,
09512                       _("Duplicate g packet description added for size %d"),
09513                       bytes);
09514 
09515   new_guess.bytes = bytes;
09516   new_guess.tdesc = tdesc;
09517   VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
09518 }
09519 
09520 /* Return 1 if remote_read_description would do anything on this target
09521    and architecture, 0 otherwise.  */
09522 
09523 static int
09524 remote_read_description_p (struct target_ops *target)
09525 {
09526   struct remote_g_packet_data *data
09527     = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
09528 
09529   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
09530     return 1;
09531 
09532   return 0;
09533 }
09534 
09535 static const struct target_desc *
09536 remote_read_description (struct target_ops *target)
09537 {
09538   struct remote_g_packet_data *data
09539     = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
09540 
09541   /* Do not try this during initial connection, when we do not know
09542      whether there is a running but stopped thread.  */
09543   if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
09544     return NULL;
09545 
09546   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
09547     {
09548       struct remote_g_packet_guess *guess;
09549       int ix;
09550       int bytes = send_g_packet ();
09551 
09552       for (ix = 0;
09553            VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
09554            ix++)
09555         if (guess->bytes == bytes)
09556           return guess->tdesc;
09557 
09558       /* We discard the g packet.  A minor optimization would be to
09559          hold on to it, and fill the register cache once we have selected
09560          an architecture, but it's too tricky to do safely.  */
09561     }
09562 
09563   return NULL;
09564 }
09565 
09566 /* Remote file transfer support.  This is host-initiated I/O, not
09567    target-initiated; for target-initiated, see remote-fileio.c.  */
09568 
09569 /* If *LEFT is at least the length of STRING, copy STRING to
09570    *BUFFER, update *BUFFER to point to the new end of the buffer, and
09571    decrease *LEFT.  Otherwise raise an error.  */
09572 
09573 static void
09574 remote_buffer_add_string (char **buffer, int *left, char *string)
09575 {
09576   int len = strlen (string);
09577 
09578   if (len > *left)
09579     error (_("Packet too long for target."));
09580 
09581   memcpy (*buffer, string, len);
09582   *buffer += len;
09583   *left -= len;
09584 
09585   /* NUL-terminate the buffer as a convenience, if there is
09586      room.  */
09587   if (*left)
09588     **buffer = '\0';
09589 }
09590 
09591 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
09592    *BUFFER, update *BUFFER to point to the new end of the buffer, and
09593    decrease *LEFT.  Otherwise raise an error.  */
09594 
09595 static void
09596 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
09597                          int len)
09598 {
09599   if (2 * len > *left)
09600     error (_("Packet too long for target."));
09601 
09602   bin2hex (bytes, *buffer, len);
09603   *buffer += 2 * len;
09604   *left -= 2 * len;
09605 
09606   /* NUL-terminate the buffer as a convenience, if there is
09607      room.  */
09608   if (*left)
09609     **buffer = '\0';
09610 }
09611 
09612 /* If *LEFT is large enough, convert VALUE to hex and add it to
09613    *BUFFER, update *BUFFER to point to the new end of the buffer, and
09614    decrease *LEFT.  Otherwise raise an error.  */
09615 
09616 static void
09617 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
09618 {
09619   int len = hexnumlen (value);
09620 
09621   if (len > *left)
09622     error (_("Packet too long for target."));
09623 
09624   hexnumstr (*buffer, value);
09625   *buffer += len;
09626   *left -= len;
09627 
09628   /* NUL-terminate the buffer as a convenience, if there is
09629      room.  */
09630   if (*left)
09631     **buffer = '\0';
09632 }
09633 
09634 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
09635    value, *REMOTE_ERRNO to the remote error number or zero if none
09636    was included, and *ATTACHMENT to point to the start of the annex
09637    if any.  The length of the packet isn't needed here; there may
09638    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
09639 
09640    Return 0 if the packet could be parsed, -1 if it could not.  If
09641    -1 is returned, the other variables may not be initialized.  */
09642 
09643 static int
09644 remote_hostio_parse_result (char *buffer, int *retcode,
09645                             int *remote_errno, char **attachment)
09646 {
09647   char *p, *p2;
09648 
09649   *remote_errno = 0;
09650   *attachment = NULL;
09651 
09652   if (buffer[0] != 'F')
09653     return -1;
09654 
09655   errno = 0;
09656   *retcode = strtol (&buffer[1], &p, 16);
09657   if (errno != 0 || p == &buffer[1])
09658     return -1;
09659 
09660   /* Check for ",errno".  */
09661   if (*p == ',')
09662     {
09663       errno = 0;
09664       *remote_errno = strtol (p + 1, &p2, 16);
09665       if (errno != 0 || p + 1 == p2)
09666         return -1;
09667       p = p2;
09668     }
09669 
09670   /* Check for ";attachment".  If there is no attachment, the
09671      packet should end here.  */
09672   if (*p == ';')
09673     {
09674       *attachment = p + 1;
09675       return 0;
09676     }
09677   else if (*p == '\0')
09678     return 0;
09679   else
09680     return -1;
09681 }
09682 
09683 /* Send a prepared I/O packet to the target and read its response.
09684    The prepared packet is in the global RS->BUF before this function
09685    is called, and the answer is there when we return.
09686 
09687    COMMAND_BYTES is the length of the request to send, which may include
09688    binary data.  WHICH_PACKET is the packet configuration to check
09689    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
09690    is set to the error number and -1 is returned.  Otherwise the value
09691    returned by the function is returned.
09692 
09693    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
09694    attachment is expected; an error will be reported if there's a
09695    mismatch.  If one is found, *ATTACHMENT will be set to point into
09696    the packet buffer and *ATTACHMENT_LEN will be set to the
09697    attachment's length.  */
09698 
09699 static int
09700 remote_hostio_send_command (int command_bytes, int which_packet,
09701                             int *remote_errno, char **attachment,
09702                             int *attachment_len)
09703 {
09704   struct remote_state *rs = get_remote_state ();
09705   int ret, bytes_read;
09706   char *attachment_tmp;
09707 
09708   if (!rs->remote_desc
09709       || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
09710     {
09711       *remote_errno = FILEIO_ENOSYS;
09712       return -1;
09713     }
09714 
09715   putpkt_binary (rs->buf, command_bytes);
09716   bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
09717 
09718   /* If it timed out, something is wrong.  Don't try to parse the
09719      buffer.  */
09720   if (bytes_read < 0)
09721     {
09722       *remote_errno = FILEIO_EINVAL;
09723       return -1;
09724     }
09725 
09726   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
09727     {
09728     case PACKET_ERROR:
09729       *remote_errno = FILEIO_EINVAL;
09730       return -1;
09731     case PACKET_UNKNOWN:
09732       *remote_errno = FILEIO_ENOSYS;
09733       return -1;
09734     case PACKET_OK:
09735       break;
09736     }
09737 
09738   if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
09739                                   &attachment_tmp))
09740     {
09741       *remote_errno = FILEIO_EINVAL;
09742       return -1;
09743     }
09744 
09745   /* Make sure we saw an attachment if and only if we expected one.  */
09746   if ((attachment_tmp == NULL && attachment != NULL)
09747       || (attachment_tmp != NULL && attachment == NULL))
09748     {
09749       *remote_errno = FILEIO_EINVAL;
09750       return -1;
09751     }
09752 
09753   /* If an attachment was found, it must point into the packet buffer;
09754      work out how many bytes there were.  */
09755   if (attachment_tmp != NULL)
09756     {
09757       *attachment = attachment_tmp;
09758       *attachment_len = bytes_read - (*attachment - rs->buf);
09759     }
09760 
09761   return ret;
09762 }
09763 
09764 /* Open FILENAME on the remote target, using FLAGS and MODE.  Return a
09765    remote file descriptor, or -1 if an error occurs (and set
09766    *REMOTE_ERRNO).  */
09767 
09768 static int
09769 remote_hostio_open (const char *filename, int flags, int mode,
09770                     int *remote_errno)
09771 {
09772   struct remote_state *rs = get_remote_state ();
09773   char *p = rs->buf;
09774   int left = get_remote_packet_size () - 1;
09775 
09776   remote_buffer_add_string (&p, &left, "vFile:open:");
09777 
09778   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
09779                            strlen (filename));
09780   remote_buffer_add_string (&p, &left, ",");
09781 
09782   remote_buffer_add_int (&p, &left, flags);
09783   remote_buffer_add_string (&p, &left, ",");
09784 
09785   remote_buffer_add_int (&p, &left, mode);
09786 
09787   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
09788                                      remote_errno, NULL, NULL);
09789 }
09790 
09791 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
09792    Return the number of bytes written, or -1 if an error occurs (and
09793    set *REMOTE_ERRNO).  */
09794 
09795 static int
09796 remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
09797                       ULONGEST offset, int *remote_errno)
09798 {
09799   struct remote_state *rs = get_remote_state ();
09800   char *p = rs->buf;
09801   int left = get_remote_packet_size ();
09802   int out_len;
09803 
09804   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
09805 
09806   remote_buffer_add_int (&p, &left, fd);
09807   remote_buffer_add_string (&p, &left, ",");
09808 
09809   remote_buffer_add_int (&p, &left, offset);
09810   remote_buffer_add_string (&p, &left, ",");
09811 
09812   p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
09813                              get_remote_packet_size () - (p - rs->buf));
09814 
09815   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
09816                                      remote_errno, NULL, NULL);
09817 }
09818 
09819 /* Read up to LEN bytes FD on the remote target into READ_BUF
09820    Return the number of bytes read, or -1 if an error occurs (and
09821    set *REMOTE_ERRNO).  */
09822 
09823 static int
09824 remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
09825                      ULONGEST offset, int *remote_errno)
09826 {
09827   struct remote_state *rs = get_remote_state ();
09828   char *p = rs->buf;
09829   char *attachment;
09830   int left = get_remote_packet_size ();
09831   int ret, attachment_len;
09832   int read_len;
09833 
09834   remote_buffer_add_string (&p, &left, "vFile:pread:");
09835 
09836   remote_buffer_add_int (&p, &left, fd);
09837   remote_buffer_add_string (&p, &left, ",");
09838 
09839   remote_buffer_add_int (&p, &left, len);
09840   remote_buffer_add_string (&p, &left, ",");
09841 
09842   remote_buffer_add_int (&p, &left, offset);
09843 
09844   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
09845                                     remote_errno, &attachment,
09846                                     &attachment_len);
09847 
09848   if (ret < 0)
09849     return ret;
09850 
09851   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
09852                                     read_buf, len);
09853   if (read_len != ret)
09854     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
09855 
09856   return ret;
09857 }
09858 
09859 /* Close FD on the remote target.  Return 0, or -1 if an error occurs
09860    (and set *REMOTE_ERRNO).  */
09861 
09862 static int
09863 remote_hostio_close (int fd, int *remote_errno)
09864 {
09865   struct remote_state *rs = get_remote_state ();
09866   char *p = rs->buf;
09867   int left = get_remote_packet_size () - 1;
09868 
09869   remote_buffer_add_string (&p, &left, "vFile:close:");
09870 
09871   remote_buffer_add_int (&p, &left, fd);
09872 
09873   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
09874                                      remote_errno, NULL, NULL);
09875 }
09876 
09877 /* Unlink FILENAME on the remote target.  Return 0, or -1 if an error
09878    occurs (and set *REMOTE_ERRNO).  */
09879 
09880 static int
09881 remote_hostio_unlink (const char *filename, int *remote_errno)
09882 {
09883   struct remote_state *rs = get_remote_state ();
09884   char *p = rs->buf;
09885   int left = get_remote_packet_size () - 1;
09886 
09887   remote_buffer_add_string (&p, &left, "vFile:unlink:");
09888 
09889   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
09890                            strlen (filename));
09891 
09892   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
09893                                      remote_errno, NULL, NULL);
09894 }
09895 
09896 /* Read value of symbolic link FILENAME on the remote target.  Return
09897    a null-terminated string allocated via xmalloc, or NULL if an error
09898    occurs (and set *REMOTE_ERRNO).  */
09899 
09900 static char *
09901 remote_hostio_readlink (const char *filename, int *remote_errno)
09902 {
09903   struct remote_state *rs = get_remote_state ();
09904   char *p = rs->buf;
09905   char *attachment;
09906   int left = get_remote_packet_size ();
09907   int len, attachment_len;
09908   int read_len;
09909   char *ret;
09910 
09911   remote_buffer_add_string (&p, &left, "vFile:readlink:");
09912 
09913   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
09914                            strlen (filename));
09915 
09916   len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
09917                                     remote_errno, &attachment,
09918                                     &attachment_len);
09919 
09920   if (len < 0)
09921     return NULL;
09922 
09923   ret = xmalloc (len + 1);
09924 
09925   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
09926                                     (gdb_byte *) ret, len);
09927   if (read_len != len)
09928     error (_("Readlink returned %d, but %d bytes."), len, read_len);
09929 
09930   ret[len] = '\0';
09931   return ret;
09932 }
09933 
09934 static int
09935 remote_fileio_errno_to_host (int errnum)
09936 {
09937   switch (errnum)
09938     {
09939       case FILEIO_EPERM:
09940         return EPERM;
09941       case FILEIO_ENOENT:
09942         return ENOENT;
09943       case FILEIO_EINTR:
09944         return EINTR;
09945       case FILEIO_EIO:
09946         return EIO;
09947       case FILEIO_EBADF:
09948         return EBADF;
09949       case FILEIO_EACCES:
09950         return EACCES;
09951       case FILEIO_EFAULT:
09952         return EFAULT;
09953       case FILEIO_EBUSY:
09954         return EBUSY;
09955       case FILEIO_EEXIST:
09956         return EEXIST;
09957       case FILEIO_ENODEV:
09958         return ENODEV;
09959       case FILEIO_ENOTDIR:
09960         return ENOTDIR;
09961       case FILEIO_EISDIR:
09962         return EISDIR;
09963       case FILEIO_EINVAL:
09964         return EINVAL;
09965       case FILEIO_ENFILE:
09966         return ENFILE;
09967       case FILEIO_EMFILE:
09968         return EMFILE;
09969       case FILEIO_EFBIG:
09970         return EFBIG;
09971       case FILEIO_ENOSPC:
09972         return ENOSPC;
09973       case FILEIO_ESPIPE:
09974         return ESPIPE;
09975       case FILEIO_EROFS:
09976         return EROFS;
09977       case FILEIO_ENOSYS:
09978         return ENOSYS;
09979       case FILEIO_ENAMETOOLONG:
09980         return ENAMETOOLONG;
09981     }
09982   return -1;
09983 }
09984 
09985 static char *
09986 remote_hostio_error (int errnum)
09987 {
09988   int host_error = remote_fileio_errno_to_host (errnum);
09989 
09990   if (host_error == -1)
09991     error (_("Unknown remote I/O error %d"), errnum);
09992   else
09993     error (_("Remote I/O error: %s"), safe_strerror (host_error));
09994 }
09995 
09996 static void
09997 remote_hostio_close_cleanup (void *opaque)
09998 {
09999   int fd = *(int *) opaque;
10000   int remote_errno;
10001 
10002   remote_hostio_close (fd, &remote_errno);
10003 }
10004 
10005 
10006 static void *
10007 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
10008 {
10009   const char *filename = bfd_get_filename (abfd);
10010   int fd, remote_errno;
10011   int *stream;
10012 
10013   gdb_assert (remote_filename_p (filename));
10014 
10015   fd = remote_hostio_open (filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
10016   if (fd == -1)
10017     {
10018       errno = remote_fileio_errno_to_host (remote_errno);
10019       bfd_set_error (bfd_error_system_call);
10020       return NULL;
10021     }
10022 
10023   stream = xmalloc (sizeof (int));
10024   *stream = fd;
10025   return stream;
10026 }
10027 
10028 static int
10029 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
10030 {
10031   int fd = *(int *)stream;
10032   int remote_errno;
10033 
10034   xfree (stream);
10035 
10036   /* Ignore errors on close; these may happen if the remote
10037      connection was already torn down.  */
10038   remote_hostio_close (fd, &remote_errno);
10039 
10040   /* Zero means success.  */
10041   return 0;
10042 }
10043 
10044 static file_ptr
10045 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
10046                         file_ptr nbytes, file_ptr offset)
10047 {
10048   int fd = *(int *)stream;
10049   int remote_errno;
10050   file_ptr pos, bytes;
10051 
10052   pos = 0;
10053   while (nbytes > pos)
10054     {
10055       bytes = remote_hostio_pread (fd, (gdb_byte *) buf + pos, nbytes - pos,
10056                                    offset + pos, &remote_errno);
10057       if (bytes == 0)
10058         /* Success, but no bytes, means end-of-file.  */
10059         break;
10060       if (bytes == -1)
10061         {
10062           errno = remote_fileio_errno_to_host (remote_errno);
10063           bfd_set_error (bfd_error_system_call);
10064           return -1;
10065         }
10066 
10067       pos += bytes;
10068     }
10069 
10070   return pos;
10071 }
10072 
10073 static int
10074 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
10075 {
10076   /* FIXME: We should probably implement remote_hostio_stat.  */
10077   sb->st_size = INT_MAX;
10078   return 0;
10079 }
10080 
10081 int
10082 remote_filename_p (const char *filename)
10083 {
10084   return strncmp (filename,
10085                   REMOTE_SYSROOT_PREFIX,
10086                   sizeof (REMOTE_SYSROOT_PREFIX) - 1) == 0;
10087 }
10088 
10089 bfd *
10090 remote_bfd_open (const char *remote_file, const char *target)
10091 {
10092   bfd *abfd = gdb_bfd_openr_iovec (remote_file, target,
10093                                    remote_bfd_iovec_open, NULL,
10094                                    remote_bfd_iovec_pread,
10095                                    remote_bfd_iovec_close,
10096                                    remote_bfd_iovec_stat);
10097 
10098   return abfd;
10099 }
10100 
10101 void
10102 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10103 {
10104   struct cleanup *back_to, *close_cleanup;
10105   int retcode, fd, remote_errno, bytes, io_size;
10106   FILE *file;
10107   gdb_byte *buffer;
10108   int bytes_in_buffer;
10109   int saw_eof;
10110   ULONGEST offset;
10111   struct remote_state *rs = get_remote_state ();
10112 
10113   if (!rs->remote_desc)
10114     error (_("command can only be used with remote target"));
10115 
10116   file = gdb_fopen_cloexec (local_file, "rb");
10117   if (file == NULL)
10118     perror_with_name (local_file);
10119   back_to = make_cleanup_fclose (file);
10120 
10121   fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
10122                                          | FILEIO_O_TRUNC),
10123                            0700, &remote_errno);
10124   if (fd == -1)
10125     remote_hostio_error (remote_errno);
10126 
10127   /* Send up to this many bytes at once.  They won't all fit in the
10128      remote packet limit, so we'll transfer slightly fewer.  */
10129   io_size = get_remote_packet_size ();
10130   buffer = xmalloc (io_size);
10131   make_cleanup (xfree, buffer);
10132 
10133   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10134 
10135   bytes_in_buffer = 0;
10136   saw_eof = 0;
10137   offset = 0;
10138   while (bytes_in_buffer || !saw_eof)
10139     {
10140       if (!saw_eof)
10141         {
10142           bytes = fread (buffer + bytes_in_buffer, 1,
10143                          io_size - bytes_in_buffer,
10144                          file);
10145           if (bytes == 0)
10146             {
10147               if (ferror (file))
10148                 error (_("Error reading %s."), local_file);
10149               else
10150                 {
10151                   /* EOF.  Unless there is something still in the
10152                      buffer from the last iteration, we are done.  */
10153                   saw_eof = 1;
10154                   if (bytes_in_buffer == 0)
10155                     break;
10156                 }
10157             }
10158         }
10159       else
10160         bytes = 0;
10161 
10162       bytes += bytes_in_buffer;
10163       bytes_in_buffer = 0;
10164 
10165       retcode = remote_hostio_pwrite (fd, buffer, bytes,
10166                                       offset, &remote_errno);
10167 
10168       if (retcode < 0)
10169         remote_hostio_error (remote_errno);
10170       else if (retcode == 0)
10171         error (_("Remote write of %d bytes returned 0!"), bytes);
10172       else if (retcode < bytes)
10173         {
10174           /* Short write.  Save the rest of the read data for the next
10175              write.  */
10176           bytes_in_buffer = bytes - retcode;
10177           memmove (buffer, buffer + retcode, bytes_in_buffer);
10178         }
10179 
10180       offset += retcode;
10181     }
10182 
10183   discard_cleanups (close_cleanup);
10184   if (remote_hostio_close (fd, &remote_errno))
10185     remote_hostio_error (remote_errno);
10186 
10187   if (from_tty)
10188     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10189   do_cleanups (back_to);
10190 }
10191 
10192 void
10193 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10194 {
10195   struct cleanup *back_to, *close_cleanup;
10196   int fd, remote_errno, bytes, io_size;
10197   FILE *file;
10198   gdb_byte *buffer;
10199   ULONGEST offset;
10200   struct remote_state *rs = get_remote_state ();
10201 
10202   if (!rs->remote_desc)
10203     error (_("command can only be used with remote target"));
10204 
10205   fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
10206   if (fd == -1)
10207     remote_hostio_error (remote_errno);
10208 
10209   file = gdb_fopen_cloexec (local_file, "wb");
10210   if (file == NULL)
10211     perror_with_name (local_file);
10212   back_to = make_cleanup_fclose (file);
10213 
10214   /* Send up to this many bytes at once.  They won't all fit in the
10215      remote packet limit, so we'll transfer slightly fewer.  */
10216   io_size = get_remote_packet_size ();
10217   buffer = xmalloc (io_size);
10218   make_cleanup (xfree, buffer);
10219 
10220   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10221 
10222   offset = 0;
10223   while (1)
10224     {
10225       bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
10226       if (bytes == 0)
10227         /* Success, but no bytes, means end-of-file.  */
10228         break;
10229       if (bytes == -1)
10230         remote_hostio_error (remote_errno);
10231 
10232       offset += bytes;
10233 
10234       bytes = fwrite (buffer, 1, bytes, file);
10235       if (bytes == 0)
10236         perror_with_name (local_file);
10237     }
10238 
10239   discard_cleanups (close_cleanup);
10240   if (remote_hostio_close (fd, &remote_errno))
10241     remote_hostio_error (remote_errno);
10242 
10243   if (from_tty)
10244     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10245   do_cleanups (back_to);
10246 }
10247 
10248 void
10249 remote_file_delete (const char *remote_file, int from_tty)
10250 {
10251   int retcode, remote_errno;
10252   struct remote_state *rs = get_remote_state ();
10253 
10254   if (!rs->remote_desc)
10255     error (_("command can only be used with remote target"));
10256 
10257   retcode = remote_hostio_unlink (remote_file, &remote_errno);
10258   if (retcode == -1)
10259     remote_hostio_error (remote_errno);
10260 
10261   if (from_tty)
10262     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10263 }
10264 
10265 static void
10266 remote_put_command (char *args, int from_tty)
10267 {
10268   struct cleanup *back_to;
10269   char **argv;
10270 
10271   if (args == NULL)
10272     error_no_arg (_("file to put"));
10273 
10274   argv = gdb_buildargv (args);
10275   back_to = make_cleanup_freeargv (argv);
10276   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10277     error (_("Invalid parameters to remote put"));
10278 
10279   remote_file_put (argv[0], argv[1], from_tty);
10280 
10281   do_cleanups (back_to);
10282 }
10283 
10284 static void
10285 remote_get_command (char *args, int from_tty)
10286 {
10287   struct cleanup *back_to;
10288   char **argv;
10289 
10290   if (args == NULL)
10291     error_no_arg (_("file to get"));
10292 
10293   argv = gdb_buildargv (args);
10294   back_to = make_cleanup_freeargv (argv);
10295   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10296     error (_("Invalid parameters to remote get"));
10297 
10298   remote_file_get (argv[0], argv[1], from_tty);
10299 
10300   do_cleanups (back_to);
10301 }
10302 
10303 static void
10304 remote_delete_command (char *args, int from_tty)
10305 {
10306   struct cleanup *back_to;
10307   char **argv;
10308 
10309   if (args == NULL)
10310     error_no_arg (_("file to delete"));
10311 
10312   argv = gdb_buildargv (args);
10313   back_to = make_cleanup_freeargv (argv);
10314   if (argv[0] == NULL || argv[1] != NULL)
10315     error (_("Invalid parameters to remote delete"));
10316 
10317   remote_file_delete (argv[0], from_tty);
10318 
10319   do_cleanups (back_to);
10320 }
10321 
10322 static void
10323 remote_command (char *args, int from_tty)
10324 {
10325   help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
10326 }
10327 
10328 static int
10329 remote_can_execute_reverse (void)
10330 {
10331   if (remote_protocol_packets[PACKET_bs].support == PACKET_ENABLE
10332       || remote_protocol_packets[PACKET_bc].support == PACKET_ENABLE)
10333     return 1;
10334   else
10335     return 0;
10336 }
10337 
10338 static int
10339 remote_supports_non_stop (void)
10340 {
10341   return 1;
10342 }
10343 
10344 static int
10345 remote_supports_disable_randomization (void)
10346 {
10347   /* Only supported in extended mode.  */
10348   return 0;
10349 }
10350 
10351 static int
10352 remote_supports_multi_process (void)
10353 {
10354   struct remote_state *rs = get_remote_state ();
10355 
10356   /* Only extended-remote handles being attached to multiple
10357      processes, even though plain remote can use the multi-process
10358      thread id extensions, so that GDB knows the target process's
10359      PID.  */
10360   return rs->extended && remote_multi_process_p (rs);
10361 }
10362 
10363 static int
10364 remote_supports_cond_tracepoints (void)
10365 {
10366   struct remote_state *rs = get_remote_state ();
10367 
10368   return rs->cond_tracepoints;
10369 }
10370 
10371 static int
10372 remote_supports_cond_breakpoints (void)
10373 {
10374   struct remote_state *rs = get_remote_state ();
10375 
10376   return rs->cond_breakpoints;
10377 }
10378 
10379 static int
10380 remote_supports_fast_tracepoints (void)
10381 {
10382   struct remote_state *rs = get_remote_state ();
10383 
10384   return rs->fast_tracepoints;
10385 }
10386 
10387 static int
10388 remote_supports_static_tracepoints (void)
10389 {
10390   struct remote_state *rs = get_remote_state ();
10391 
10392   return rs->static_tracepoints;
10393 }
10394 
10395 static int
10396 remote_supports_install_in_trace (void)
10397 {
10398   struct remote_state *rs = get_remote_state ();
10399 
10400   return rs->install_in_trace;
10401 }
10402 
10403 static int
10404 remote_supports_enable_disable_tracepoint (void)
10405 {
10406   struct remote_state *rs = get_remote_state ();
10407 
10408   return rs->enable_disable_tracepoints;
10409 }
10410 
10411 static int
10412 remote_supports_string_tracing (void)
10413 {
10414   struct remote_state *rs = get_remote_state ();
10415 
10416   return rs->string_tracing;
10417 }
10418 
10419 static int
10420 remote_can_run_breakpoint_commands (void)
10421 {
10422   struct remote_state *rs = get_remote_state ();
10423 
10424   return rs->breakpoint_commands;
10425 }
10426 
10427 static void
10428 remote_trace_init (void)
10429 {
10430   putpkt ("QTinit");
10431   remote_get_noisy_reply (&target_buf, &target_buf_size);
10432   if (strcmp (target_buf, "OK") != 0)
10433     error (_("Target does not support this command."));
10434 }
10435 
10436 static void free_actions_list (char **actions_list);
10437 static void free_actions_list_cleanup_wrapper (void *);
10438 static void
10439 free_actions_list_cleanup_wrapper (void *al)
10440 {
10441   free_actions_list (al);
10442 }
10443 
10444 static void
10445 free_actions_list (char **actions_list)
10446 {
10447   int ndx;
10448 
10449   if (actions_list == 0)
10450     return;
10451 
10452   for (ndx = 0; actions_list[ndx]; ndx++)
10453     xfree (actions_list[ndx]);
10454 
10455   xfree (actions_list);
10456 }
10457 
10458 /* Recursive routine to walk through command list including loops, and
10459    download packets for each command.  */
10460 
10461 static void
10462 remote_download_command_source (int num, ULONGEST addr,
10463                                 struct command_line *cmds)
10464 {
10465   struct remote_state *rs = get_remote_state ();
10466   struct command_line *cmd;
10467 
10468   for (cmd = cmds; cmd; cmd = cmd->next)
10469     {
10470       QUIT;     /* Allow user to bail out with ^C.  */
10471       strcpy (rs->buf, "QTDPsrc:");
10472       encode_source_string (num, addr, "cmd", cmd->line,
10473                             rs->buf + strlen (rs->buf),
10474                             rs->buf_size - strlen (rs->buf));
10475       putpkt (rs->buf);
10476       remote_get_noisy_reply (&target_buf, &target_buf_size);
10477       if (strcmp (target_buf, "OK"))
10478         warning (_("Target does not support source download."));
10479 
10480       if (cmd->control_type == while_control
10481           || cmd->control_type == while_stepping_control)
10482         {
10483           remote_download_command_source (num, addr, *cmd->body_list);
10484 
10485           QUIT; /* Allow user to bail out with ^C.  */
10486           strcpy (rs->buf, "QTDPsrc:");
10487           encode_source_string (num, addr, "cmd", "end",
10488                                 rs->buf + strlen (rs->buf),
10489                                 rs->buf_size - strlen (rs->buf));
10490           putpkt (rs->buf);
10491           remote_get_noisy_reply (&target_buf, &target_buf_size);
10492           if (strcmp (target_buf, "OK"))
10493             warning (_("Target does not support source download."));
10494         }
10495     }
10496 }
10497 
10498 static void
10499 remote_download_tracepoint (struct bp_location *loc)
10500 {
10501 #define BUF_SIZE 2048
10502 
10503   CORE_ADDR tpaddr;
10504   char addrbuf[40];
10505   char buf[BUF_SIZE];
10506   char **tdp_actions;
10507   char **stepping_actions;
10508   int ndx;
10509   struct cleanup *old_chain = NULL;
10510   struct agent_expr *aexpr;
10511   struct cleanup *aexpr_chain = NULL;
10512   char *pkt;
10513   struct breakpoint *b = loc->owner;
10514   struct tracepoint *t = (struct tracepoint *) b;
10515 
10516   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
10517   old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10518                             tdp_actions);
10519   (void) make_cleanup (free_actions_list_cleanup_wrapper,
10520                        stepping_actions);
10521 
10522   tpaddr = loc->address;
10523   sprintf_vma (addrbuf, tpaddr);
10524   xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10525              addrbuf, /* address */
10526              (b->enable_state == bp_enabled ? 'E' : 'D'),
10527              t->step_count, t->pass_count);
10528   /* Fast tracepoints are mostly handled by the target, but we can
10529      tell the target how big of an instruction block should be moved
10530      around.  */
10531   if (b->type == bp_fast_tracepoint)
10532     {
10533       /* Only test for support at download time; we may not know
10534          target capabilities at definition time.  */
10535       if (remote_supports_fast_tracepoints ())
10536         {
10537           int isize;
10538 
10539           if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
10540                                                 tpaddr, &isize, NULL))
10541             xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10542                        isize);
10543           else
10544             /* If it passed validation at definition but fails now,
10545                something is very wrong.  */
10546             internal_error (__FILE__, __LINE__,
10547                             _("Fast tracepoint not "
10548                               "valid during download"));
10549         }
10550       else
10551         /* Fast tracepoints are functionally identical to regular
10552            tracepoints, so don't take lack of support as a reason to
10553            give up on the trace run.  */
10554         warning (_("Target does not support fast tracepoints, "
10555                    "downloading %d as regular tracepoint"), b->number);
10556     }
10557   else if (b->type == bp_static_tracepoint)
10558     {
10559       /* Only test for support at download time; we may not know
10560          target capabilities at definition time.  */
10561       if (remote_supports_static_tracepoints ())
10562         {
10563           struct static_tracepoint_marker marker;
10564 
10565           if (target_static_tracepoint_marker_at (tpaddr, &marker))
10566             strcat (buf, ":S");
10567           else
10568             error (_("Static tracepoint not valid during download"));
10569         }
10570       else
10571         /* Fast tracepoints are functionally identical to regular
10572            tracepoints, so don't take lack of support as a reason
10573            to give up on the trace run.  */
10574         error (_("Target does not support static tracepoints"));
10575     }
10576   /* If the tracepoint has a conditional, make it into an agent
10577      expression and append to the definition.  */
10578   if (loc->cond)
10579     {
10580       /* Only test support at download time, we may not know target
10581          capabilities at definition time.  */
10582       if (remote_supports_cond_tracepoints ())
10583         {
10584           aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10585           aexpr_chain = make_cleanup_free_agent_expr (aexpr);
10586           xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10587                      aexpr->len);
10588           pkt = buf + strlen (buf);
10589           for (ndx = 0; ndx < aexpr->len; ++ndx)
10590             pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10591           *pkt = '\0';
10592           do_cleanups (aexpr_chain);
10593         }
10594       else
10595         warning (_("Target does not support conditional tracepoints, "
10596                    "ignoring tp %d cond"), b->number);
10597     }
10598 
10599   if (b->commands || *default_collect)
10600     strcat (buf, "-");
10601   putpkt (buf);
10602   remote_get_noisy_reply (&target_buf, &target_buf_size);
10603   if (strcmp (target_buf, "OK"))
10604     error (_("Target does not support tracepoints."));
10605 
10606   /* do_single_steps (t); */
10607   if (tdp_actions)
10608     {
10609       for (ndx = 0; tdp_actions[ndx]; ndx++)
10610         {
10611           QUIT; /* Allow user to bail out with ^C.  */
10612           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10613                      b->number, addrbuf, /* address */
10614                      tdp_actions[ndx],
10615                      ((tdp_actions[ndx + 1] || stepping_actions)
10616                       ? '-' : 0));
10617           putpkt (buf);
10618           remote_get_noisy_reply (&target_buf,
10619                                   &target_buf_size);
10620           if (strcmp (target_buf, "OK"))
10621             error (_("Error on target while setting tracepoints."));
10622         }
10623     }
10624   if (stepping_actions)
10625     {
10626       for (ndx = 0; stepping_actions[ndx]; ndx++)
10627         {
10628           QUIT; /* Allow user to bail out with ^C.  */
10629           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10630                      b->number, addrbuf, /* address */
10631                      ((ndx == 0) ? "S" : ""),
10632                      stepping_actions[ndx],
10633                      (stepping_actions[ndx + 1] ? "-" : ""));
10634           putpkt (buf);
10635           remote_get_noisy_reply (&target_buf,
10636                                   &target_buf_size);
10637           if (strcmp (target_buf, "OK"))
10638             error (_("Error on target while setting tracepoints."));
10639         }
10640     }
10641 
10642   if (remote_protocol_packets[PACKET_TracepointSource].support
10643       == PACKET_ENABLE)
10644     {
10645       if (b->addr_string)
10646         {
10647           strcpy (buf, "QTDPsrc:");
10648           encode_source_string (b->number, loc->address,
10649                                 "at", b->addr_string, buf + strlen (buf),
10650                                 2048 - strlen (buf));
10651 
10652           putpkt (buf);
10653           remote_get_noisy_reply (&target_buf, &target_buf_size);
10654           if (strcmp (target_buf, "OK"))
10655             warning (_("Target does not support source download."));
10656         }
10657       if (b->cond_string)
10658         {
10659           strcpy (buf, "QTDPsrc:");
10660           encode_source_string (b->number, loc->address,
10661                                 "cond", b->cond_string, buf + strlen (buf),
10662                                 2048 - strlen (buf));
10663           putpkt (buf);
10664           remote_get_noisy_reply (&target_buf, &target_buf_size);
10665           if (strcmp (target_buf, "OK"))
10666             warning (_("Target does not support source download."));
10667         }
10668       remote_download_command_source (b->number, loc->address,
10669                                       breakpoint_commands (b));
10670     }
10671 
10672   do_cleanups (old_chain);
10673 }
10674 
10675 static int
10676 remote_can_download_tracepoint (void)
10677 {
10678   struct remote_state *rs = get_remote_state ();
10679   struct trace_status *ts;
10680   int status;
10681 
10682   /* Don't try to install tracepoints until we've relocated our
10683      symbols, and fetched and merged the target's tracepoint list with
10684      ours.  */
10685   if (rs->starting_up)
10686     return 0;
10687 
10688   ts = current_trace_status ();
10689   status = remote_get_trace_status (ts);
10690 
10691   if (status == -1 || !ts->running_known || !ts->running)
10692     return 0;
10693 
10694   /* If we are in a tracing experiment, but remote stub doesn't support
10695      installing tracepoint in trace, we have to return.  */
10696   if (!remote_supports_install_in_trace ())
10697     return 0;
10698 
10699   return 1;
10700 }
10701 
10702 
10703 static void
10704 remote_download_trace_state_variable (struct trace_state_variable *tsv)
10705 {
10706   struct remote_state *rs = get_remote_state ();
10707   char *p;
10708 
10709   xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10710              tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10711              tsv->builtin);
10712   p = rs->buf + strlen (rs->buf);
10713   if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10714     error (_("Trace state variable name too long for tsv definition packet"));
10715   p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, 0);
10716   *p++ = '\0';
10717   putpkt (rs->buf);
10718   remote_get_noisy_reply (&target_buf, &target_buf_size);
10719   if (*target_buf == '\0')
10720     error (_("Target does not support this command."));
10721   if (strcmp (target_buf, "OK") != 0)
10722     error (_("Error on target while downloading trace state variable."));
10723 }
10724 
10725 static void
10726 remote_enable_tracepoint (struct bp_location *location)
10727 {
10728   struct remote_state *rs = get_remote_state ();
10729   char addr_buf[40];
10730 
10731   sprintf_vma (addr_buf, location->address);
10732   xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
10733              location->owner->number, addr_buf);
10734   putpkt (rs->buf);
10735   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10736   if (*rs->buf == '\0')
10737     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10738   if (strcmp (rs->buf, "OK") != 0)
10739     error (_("Error on target while enabling tracepoint."));
10740 }
10741 
10742 static void
10743 remote_disable_tracepoint (struct bp_location *location)
10744 {
10745   struct remote_state *rs = get_remote_state ();
10746   char addr_buf[40];
10747 
10748   sprintf_vma (addr_buf, location->address);
10749   xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10750              location->owner->number, addr_buf);
10751   putpkt (rs->buf);
10752   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10753   if (*rs->buf == '\0')
10754     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10755   if (strcmp (rs->buf, "OK") != 0)
10756     error (_("Error on target while disabling tracepoint."));
10757 }
10758 
10759 static void
10760 remote_trace_set_readonly_regions (void)
10761 {
10762   asection *s;
10763   bfd *abfd = NULL;
10764   bfd_size_type size;
10765   bfd_vma vma;
10766   int anysecs = 0;
10767   int offset = 0;
10768 
10769   if (!exec_bfd)
10770     return;                     /* No information to give.  */
10771 
10772   strcpy (target_buf, "QTro");
10773   offset = strlen (target_buf);
10774   for (s = exec_bfd->sections; s; s = s->next)
10775     {
10776       char tmp1[40], tmp2[40];
10777       int sec_length;
10778 
10779       if ((s->flags & SEC_LOAD) == 0 ||
10780       /*  (s->flags & SEC_CODE) == 0 || */
10781           (s->flags & SEC_READONLY) == 0)
10782         continue;
10783 
10784       anysecs = 1;
10785       vma = bfd_get_section_vma (abfd, s);
10786       size = bfd_get_section_size (s);
10787       sprintf_vma (tmp1, vma);
10788       sprintf_vma (tmp2, vma + size);
10789       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10790       if (offset + sec_length + 1 > target_buf_size)
10791         {
10792           if (remote_protocol_packets[PACKET_qXfer_traceframe_info].support
10793               != PACKET_ENABLE)
10794             warning (_("\
10795 Too many sections for read-only sections definition packet."));
10796           break;
10797         }
10798       xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
10799                  tmp1, tmp2);
10800       offset += sec_length;
10801     }
10802   if (anysecs)
10803     {
10804       putpkt (target_buf);
10805       getpkt (&target_buf, &target_buf_size, 0);
10806     }
10807 }
10808 
10809 static void
10810 remote_trace_start (void)
10811 {
10812   putpkt ("QTStart");
10813   remote_get_noisy_reply (&target_buf, &target_buf_size);
10814   if (*target_buf == '\0')
10815     error (_("Target does not support this command."));
10816   if (strcmp (target_buf, "OK") != 0)
10817     error (_("Bogus reply from target: %s"), target_buf);
10818 }
10819 
10820 static int
10821 remote_get_trace_status (struct trace_status *ts)
10822 {
10823   /* Initialize it just to avoid a GCC false warning.  */
10824   char *p = NULL;
10825   /* FIXME we need to get register block size some other way.  */
10826   extern int trace_regblock_size;
10827   volatile struct gdb_exception ex;
10828   enum packet_result result;
10829 
10830   if (remote_protocol_packets[PACKET_qTStatus].support == PACKET_DISABLE)
10831     return -1;
10832 
10833   trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10834 
10835   putpkt ("qTStatus");
10836 
10837   TRY_CATCH (ex, RETURN_MASK_ERROR)
10838     {
10839       p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10840     }
10841   if (ex.reason < 0)
10842     {
10843       if (ex.error != TARGET_CLOSE_ERROR)
10844         {
10845           exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10846           return -1;
10847         }
10848       throw_exception (ex);
10849     }
10850 
10851   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
10852 
10853   /* If the remote target doesn't do tracing, flag it.  */
10854   if (result == PACKET_UNKNOWN)
10855     return -1;
10856 
10857   /* We're working with a live target.  */
10858   ts->filename = NULL;
10859 
10860   if (*p++ != 'T')
10861     error (_("Bogus trace status reply from target: %s"), target_buf);
10862 
10863   /* Function 'parse_trace_status' sets default value of each field of
10864      'ts' at first, so we don't have to do it here.  */
10865   parse_trace_status (p, ts);
10866 
10867   return ts->running;
10868 }
10869 
10870 static void
10871 remote_get_tracepoint_status (struct breakpoint *bp,
10872                               struct uploaded_tp *utp)
10873 {
10874   struct remote_state *rs = get_remote_state ();
10875   char *reply;
10876   struct bp_location *loc;
10877   struct tracepoint *tp = (struct tracepoint *) bp;
10878   size_t size = get_remote_packet_size ();
10879 
10880   if (tp)
10881     {
10882       tp->base.hit_count = 0;
10883       tp->traceframe_usage = 0;
10884       for (loc = tp->base.loc; loc; loc = loc->next)
10885         {
10886           /* If the tracepoint was never downloaded, don't go asking for
10887              any status.  */
10888           if (tp->number_on_target == 0)
10889             continue;
10890           xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
10891                      phex_nz (loc->address, 0));
10892           putpkt (rs->buf);
10893           reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10894           if (reply && *reply)
10895             {
10896               if (*reply == 'V')
10897                 parse_tracepoint_status (reply + 1, bp, utp);
10898             }
10899         }
10900     }
10901   else if (utp)
10902     {
10903       utp->hit_count = 0;
10904       utp->traceframe_usage = 0;
10905       xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
10906                  phex_nz (utp->addr, 0));
10907       putpkt (rs->buf);
10908       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10909       if (reply && *reply)
10910         {
10911           if (*reply == 'V')
10912             parse_tracepoint_status (reply + 1, bp, utp);
10913         }
10914     }
10915 }
10916 
10917 static void
10918 remote_trace_stop (void)
10919 {
10920   putpkt ("QTStop");
10921   remote_get_noisy_reply (&target_buf, &target_buf_size);
10922   if (*target_buf == '\0')
10923     error (_("Target does not support this command."));
10924   if (strcmp (target_buf, "OK") != 0)
10925     error (_("Bogus reply from target: %s"), target_buf);
10926 }
10927 
10928 static int
10929 remote_trace_find (enum trace_find_type type, int num,
10930                    CORE_ADDR addr1, CORE_ADDR addr2,
10931                    int *tpp)
10932 {
10933   struct remote_state *rs = get_remote_state ();
10934   char *endbuf = rs->buf + get_remote_packet_size ();
10935   char *p, *reply;
10936   int target_frameno = -1, target_tracept = -1;
10937 
10938   /* Lookups other than by absolute frame number depend on the current
10939      trace selected, so make sure it is correct on the remote end
10940      first.  */
10941   if (type != tfind_number)
10942     set_remote_traceframe ();
10943 
10944   p = rs->buf;
10945   strcpy (p, "QTFrame:");
10946   p = strchr (p, '\0');
10947   switch (type)
10948     {
10949     case tfind_number:
10950       xsnprintf (p, endbuf - p, "%x", num);
10951       break;
10952     case tfind_pc:
10953       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
10954       break;
10955     case tfind_tp:
10956       xsnprintf (p, endbuf - p, "tdp:%x", num);
10957       break;
10958     case tfind_range:
10959       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
10960                  phex_nz (addr2, 0));
10961       break;
10962     case tfind_outside:
10963       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
10964                  phex_nz (addr2, 0));
10965       break;
10966     default:
10967       error (_("Unknown trace find type %d"), type);
10968     }
10969 
10970   putpkt (rs->buf);
10971   reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
10972   if (*reply == '\0')
10973     error (_("Target does not support this command."));
10974 
10975   while (reply && *reply)
10976     switch (*reply)
10977       {
10978       case 'F':
10979         p = ++reply;
10980         target_frameno = (int) strtol (p, &reply, 16);
10981         if (reply == p)
10982           error (_("Unable to parse trace frame number"));
10983         /* Don't update our remote traceframe number cache on failure
10984            to select a remote traceframe.  */
10985         if (target_frameno == -1)
10986           return -1;
10987         break;
10988       case 'T':
10989         p = ++reply;
10990         target_tracept = (int) strtol (p, &reply, 16);
10991         if (reply == p)
10992           error (_("Unable to parse tracepoint number"));
10993         break;
10994       case 'O':         /* "OK"? */
10995         if (reply[1] == 'K' && reply[2] == '\0')
10996           reply += 2;
10997         else
10998           error (_("Bogus reply from target: %s"), reply);
10999         break;
11000       default:
11001         error (_("Bogus reply from target: %s"), reply);
11002       }
11003   if (tpp)
11004     *tpp = target_tracept;
11005 
11006   rs->remote_traceframe_number = target_frameno;
11007   return target_frameno;
11008 }
11009 
11010 static int
11011 remote_get_trace_state_variable_value (int tsvnum, LONGEST *val)
11012 {
11013   struct remote_state *rs = get_remote_state ();
11014   char *reply;
11015   ULONGEST uval;
11016 
11017   set_remote_traceframe ();
11018 
11019   xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
11020   putpkt (rs->buf);
11021   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11022   if (reply && *reply)
11023     {
11024       if (*reply == 'V')
11025         {
11026           unpack_varlen_hex (reply + 1, &uval);
11027           *val = (LONGEST) uval;
11028           return 1;
11029         }
11030     }
11031   return 0;
11032 }
11033 
11034 static int
11035 remote_save_trace_data (const char *filename)
11036 {
11037   struct remote_state *rs = get_remote_state ();
11038   char *p, *reply;
11039 
11040   p = rs->buf;
11041   strcpy (p, "QTSave:");
11042   p += strlen (p);
11043   if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11044     error (_("Remote file name too long for trace save packet"));
11045   p += 2 * bin2hex ((gdb_byte *) filename, p, 0);
11046   *p++ = '\0';
11047   putpkt (rs->buf);
11048   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11049   if (*reply == '\0')
11050     error (_("Target does not support this command."));
11051   if (strcmp (reply, "OK") != 0)
11052     error (_("Bogus reply from target: %s"), reply);
11053   return 0;
11054 }
11055 
11056 /* This is basically a memory transfer, but needs to be its own packet
11057    because we don't know how the target actually organizes its trace
11058    memory, plus we want to be able to ask for as much as possible, but
11059    not be unhappy if we don't get as much as we ask for.  */
11060 
11061 static LONGEST
11062 remote_get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
11063 {
11064   struct remote_state *rs = get_remote_state ();
11065   char *reply;
11066   char *p;
11067   int rslt;
11068 
11069   p = rs->buf;
11070   strcpy (p, "qTBuffer:");
11071   p += strlen (p);
11072   p += hexnumstr (p, offset);
11073   *p++ = ',';
11074   p += hexnumstr (p, len);
11075   *p++ = '\0';
11076 
11077   putpkt (rs->buf);
11078   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11079   if (reply && *reply)
11080     {
11081       /* 'l' by itself means we're at the end of the buffer and
11082          there is nothing more to get.  */
11083       if (*reply == 'l')
11084         return 0;
11085 
11086       /* Convert the reply into binary.  Limit the number of bytes to
11087          convert according to our passed-in buffer size, rather than
11088          what was returned in the packet; if the target is
11089          unexpectedly generous and gives us a bigger reply than we
11090          asked for, we don't want to crash.  */
11091       rslt = hex2bin (target_buf, buf, len);
11092       return rslt;
11093     }
11094 
11095   /* Something went wrong, flag as an error.  */
11096   return -1;
11097 }
11098 
11099 static void
11100 remote_set_disconnected_tracing (int val)
11101 {
11102   struct remote_state *rs = get_remote_state ();
11103 
11104   if (rs->disconnected_tracing)
11105     {
11106       char *reply;
11107 
11108       xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
11109       putpkt (rs->buf);
11110       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11111       if (*reply == '\0')
11112         error (_("Target does not support this command."));
11113       if (strcmp (reply, "OK") != 0)
11114         error (_("Bogus reply from target: %s"), reply);
11115     }
11116   else if (val)
11117     warning (_("Target does not support disconnected tracing."));
11118 }
11119 
11120 static int
11121 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11122 {
11123   struct thread_info *info = find_thread_ptid (ptid);
11124 
11125   if (info && info->private)
11126     return info->private->core;
11127   return -1;
11128 }
11129 
11130 static void
11131 remote_set_circular_trace_buffer (int val)
11132 {
11133   struct remote_state *rs = get_remote_state ();
11134   char *reply;
11135 
11136   xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
11137   putpkt (rs->buf);
11138   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11139   if (*reply == '\0')
11140     error (_("Target does not support this command."));
11141   if (strcmp (reply, "OK") != 0)
11142     error (_("Bogus reply from target: %s"), reply);
11143 }
11144 
11145 static struct traceframe_info *
11146 remote_traceframe_info (void)
11147 {
11148   char *text;
11149 
11150   text = target_read_stralloc (&current_target,
11151                                TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11152   if (text != NULL)
11153     {
11154       struct traceframe_info *info;
11155       struct cleanup *back_to = make_cleanup (xfree, text);
11156 
11157       info = parse_traceframe_info (text);
11158       do_cleanups (back_to);
11159       return info;
11160     }
11161 
11162   return NULL;
11163 }
11164 
11165 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
11166    instruction on which a fast tracepoint may be placed.  Returns -1
11167    if the packet is not supported, and 0 if the minimum instruction
11168    length is unknown.  */
11169 
11170 static int
11171 remote_get_min_fast_tracepoint_insn_len (void)
11172 {
11173   struct remote_state *rs = get_remote_state ();
11174   char *reply;
11175 
11176   /* If we're not debugging a process yet, the IPA can't be
11177      loaded.  */
11178   if (!target_has_execution)
11179     return 0;
11180 
11181   /* Make sure the remote is pointing at the right process.  */
11182   set_general_process ();
11183 
11184   xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
11185   putpkt (rs->buf);
11186   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11187   if (*reply == '\0')
11188     return -1;
11189   else
11190     {
11191       ULONGEST min_insn_len;
11192 
11193       unpack_varlen_hex (reply, &min_insn_len);
11194 
11195       return (int) min_insn_len;
11196     }
11197 }
11198 
11199 static void
11200 remote_set_trace_buffer_size (LONGEST val)
11201 {
11202   if (remote_protocol_packets[PACKET_QTBuffer_size].support
11203       != PACKET_DISABLE)
11204     {
11205       struct remote_state *rs = get_remote_state ();
11206       char *buf = rs->buf;
11207       char *endbuf = rs->buf + get_remote_packet_size ();
11208       enum packet_result result;
11209 
11210       gdb_assert (val >= 0 || val == -1);
11211       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11212       /* Send -1 as literal "-1" to avoid host size dependency.  */
11213       if (val < 0)
11214         {
11215           *buf++ = '-';
11216           buf += hexnumstr (buf, (ULONGEST) -val);
11217         }
11218       else
11219         buf += hexnumstr (buf, (ULONGEST) val);
11220 
11221       putpkt (rs->buf);
11222       remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11223       result = packet_ok (rs->buf,
11224                   &remote_protocol_packets[PACKET_QTBuffer_size]);
11225 
11226       if (result != PACKET_OK)
11227         warning (_("Bogus reply from target: %s"), rs->buf);
11228     }
11229 }
11230 
11231 static int
11232 remote_set_trace_notes (const char *user, const char *notes,
11233                         const char *stop_notes)
11234 {
11235   struct remote_state *rs = get_remote_state ();
11236   char *reply;
11237   char *buf = rs->buf;
11238   char *endbuf = rs->buf + get_remote_packet_size ();
11239   int nbytes;
11240 
11241   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11242   if (user)
11243     {
11244       buf += xsnprintf (buf, endbuf - buf, "user:");
11245       nbytes = bin2hex ((gdb_byte *) user, buf, 0);
11246       buf += 2 * nbytes;
11247       *buf++ = ';';
11248     }
11249   if (notes)
11250     {
11251       buf += xsnprintf (buf, endbuf - buf, "notes:");
11252       nbytes = bin2hex ((gdb_byte *) notes, buf, 0);
11253       buf += 2 * nbytes;
11254       *buf++ = ';';
11255     }
11256   if (stop_notes)
11257     {
11258       buf += xsnprintf (buf, endbuf - buf, "tstop:");
11259       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, 0);
11260       buf += 2 * nbytes;
11261       *buf++ = ';';
11262     }
11263   /* Ensure the buffer is terminated.  */
11264   *buf = '\0';
11265 
11266   putpkt (rs->buf);
11267   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11268   if (*reply == '\0')
11269     return 0;
11270 
11271   if (strcmp (reply, "OK") != 0)
11272     error (_("Bogus reply from target: %s"), reply);
11273 
11274   return 1;
11275 }
11276 
11277 static int
11278 remote_use_agent (int use)
11279 {
11280   if (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE)
11281     {
11282       struct remote_state *rs = get_remote_state ();
11283 
11284       /* If the stub supports QAgent.  */
11285       xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
11286       putpkt (rs->buf);
11287       getpkt (&rs->buf, &rs->buf_size, 0);
11288 
11289       if (strcmp (rs->buf, "OK") == 0)
11290         {
11291           use_agent = use;
11292           return 1;
11293         }
11294     }
11295 
11296   return 0;
11297 }
11298 
11299 static int
11300 remote_can_use_agent (void)
11301 {
11302   return (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE);
11303 }
11304 
11305 struct btrace_target_info
11306 {
11307   /* The ptid of the traced thread.  */
11308   ptid_t ptid;
11309 };
11310 
11311 /* Check whether the target supports branch tracing.  */
11312 
11313 static int
11314 remote_supports_btrace (void)
11315 {
11316   if (remote_protocol_packets[PACKET_Qbtrace_off].support != PACKET_ENABLE)
11317     return 0;
11318   if (remote_protocol_packets[PACKET_Qbtrace_bts].support != PACKET_ENABLE)
11319     return 0;
11320   if (remote_protocol_packets[PACKET_qXfer_btrace].support != PACKET_ENABLE)
11321     return 0;
11322 
11323   return 1;
11324 }
11325 
11326 /* Enable branch tracing.  */
11327 
11328 static struct btrace_target_info *
11329 remote_enable_btrace (ptid_t ptid)
11330 {
11331   struct btrace_target_info *tinfo = NULL;
11332   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11333   struct remote_state *rs = get_remote_state ();
11334   char *buf = rs->buf;
11335   char *endbuf = rs->buf + get_remote_packet_size ();
11336 
11337   if (packet->support != PACKET_ENABLE)
11338     error (_("Target does not support branch tracing."));
11339 
11340   set_general_thread (ptid);
11341 
11342   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11343   putpkt (rs->buf);
11344   getpkt (&rs->buf, &rs->buf_size, 0);
11345 
11346   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11347     {
11348       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11349         error (_("Could not enable branch tracing for %s: %s"),
11350                target_pid_to_str (ptid), rs->buf + 2);
11351       else
11352         error (_("Could not enable branch tracing for %s."),
11353                target_pid_to_str (ptid));
11354     }
11355 
11356   tinfo = xzalloc (sizeof (*tinfo));
11357   tinfo->ptid = ptid;
11358 
11359   return tinfo;
11360 }
11361 
11362 /* Disable branch tracing.  */
11363 
11364 static void
11365 remote_disable_btrace (struct btrace_target_info *tinfo)
11366 {
11367   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
11368   struct remote_state *rs = get_remote_state ();
11369   char *buf = rs->buf;
11370   char *endbuf = rs->buf + get_remote_packet_size ();
11371 
11372   if (packet->support != PACKET_ENABLE)
11373     error (_("Target does not support branch tracing."));
11374 
11375   set_general_thread (tinfo->ptid);
11376 
11377   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11378   putpkt (rs->buf);
11379   getpkt (&rs->buf, &rs->buf_size, 0);
11380 
11381   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11382     {
11383       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11384         error (_("Could not disable branch tracing for %s: %s"),
11385                target_pid_to_str (tinfo->ptid), rs->buf + 2);
11386       else
11387         error (_("Could not disable branch tracing for %s."),
11388                target_pid_to_str (tinfo->ptid));
11389     }
11390 
11391   xfree (tinfo);
11392 }
11393 
11394 /* Teardown branch tracing.  */
11395 
11396 static void
11397 remote_teardown_btrace (struct btrace_target_info *tinfo)
11398 {
11399   /* We must not talk to the target during teardown.  */
11400   xfree (tinfo);
11401 }
11402 
11403 /* Read the branch trace.  */
11404 
11405 static VEC (btrace_block_s) *
11406 remote_read_btrace (struct btrace_target_info *tinfo,
11407                     enum btrace_read_type type)
11408 {
11409   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11410   struct remote_state *rs = get_remote_state ();
11411   VEC (btrace_block_s) *btrace = NULL;
11412   const char *annex;
11413   char *xml;
11414 
11415   if (packet->support != PACKET_ENABLE)
11416     error (_("Target does not support branch tracing."));
11417 
11418 #if !defined(HAVE_LIBEXPAT)
11419   error (_("Cannot process branch tracing result. XML parsing not supported."));
11420 #endif
11421 
11422   switch (type)
11423     {
11424     case btrace_read_all:
11425       annex = "all";
11426       break;
11427     case btrace_read_new:
11428       annex = "new";
11429       break;
11430     default:
11431       internal_error (__FILE__, __LINE__,
11432                       _("Bad branch tracing read type: %u."),
11433                       (unsigned int) type);
11434     }
11435 
11436   xml = target_read_stralloc (&current_target,
11437                               TARGET_OBJECT_BTRACE, annex);
11438   if (xml != NULL)
11439     {
11440       struct cleanup *cleanup = make_cleanup (xfree, xml);
11441 
11442       btrace = parse_xml_btrace (xml);
11443       do_cleanups (cleanup);
11444     }
11445 
11446   return btrace;
11447 }
11448 
11449 static int
11450 remote_augmented_libraries_svr4_read (void)
11451 {
11452   struct remote_state *rs = get_remote_state ();
11453 
11454   return rs->augmented_libraries_svr4_read;
11455 }
11456 
11457 static void
11458 init_remote_ops (void)
11459 {
11460   remote_ops.to_shortname = "remote";
11461   remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
11462   remote_ops.to_doc =
11463     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11464 Specify the serial device it is connected to\n\
11465 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
11466   remote_ops.to_open = remote_open;
11467   remote_ops.to_close = remote_close;
11468   remote_ops.to_detach = remote_detach;
11469   remote_ops.to_disconnect = remote_disconnect;
11470   remote_ops.to_resume = remote_resume;
11471   remote_ops.to_wait = remote_wait;
11472   remote_ops.to_fetch_registers = remote_fetch_registers;
11473   remote_ops.to_store_registers = remote_store_registers;
11474   remote_ops.to_prepare_to_store = remote_prepare_to_store;
11475   remote_ops.to_files_info = remote_files_info;
11476   remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11477   remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
11478   remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11479   remote_ops.to_stopped_data_address = remote_stopped_data_address;
11480   remote_ops.to_watchpoint_addr_within_range =
11481     remote_watchpoint_addr_within_range;
11482   remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11483   remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11484   remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
11485   remote_ops.to_region_ok_for_hw_watchpoint
11486      = remote_region_ok_for_hw_watchpoint;
11487   remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11488   remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
11489   remote_ops.to_kill = remote_kill;
11490   remote_ops.to_load = generic_load;
11491   remote_ops.to_mourn_inferior = remote_mourn;
11492   remote_ops.to_pass_signals = remote_pass_signals;
11493   remote_ops.to_program_signals = remote_program_signals;
11494   remote_ops.to_thread_alive = remote_thread_alive;
11495   remote_ops.to_find_new_threads = remote_threads_info;
11496   remote_ops.to_pid_to_str = remote_pid_to_str;
11497   remote_ops.to_extra_thread_info = remote_threads_extra_info;
11498   remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
11499   remote_ops.to_stop = remote_stop;
11500   remote_ops.to_xfer_partial = remote_xfer_partial;
11501   remote_ops.to_rcmd = remote_rcmd;
11502   remote_ops.to_log_command = serial_log_command;
11503   remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
11504   remote_ops.to_stratum = process_stratum;
11505   remote_ops.to_has_all_memory = default_child_has_all_memory;
11506   remote_ops.to_has_memory = default_child_has_memory;
11507   remote_ops.to_has_stack = default_child_has_stack;
11508   remote_ops.to_has_registers = default_child_has_registers;
11509   remote_ops.to_has_execution = default_child_has_execution;
11510   remote_ops.to_has_thread_control = tc_schedlock;    /* can lock scheduler */
11511   remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
11512   remote_ops.to_magic = OPS_MAGIC;
11513   remote_ops.to_memory_map = remote_memory_map;
11514   remote_ops.to_flash_erase = remote_flash_erase;
11515   remote_ops.to_flash_done = remote_flash_done;
11516   remote_ops.to_read_description = remote_read_description;
11517   remote_ops.to_search_memory = remote_search_memory;
11518   remote_ops.to_can_async_p = remote_can_async_p;
11519   remote_ops.to_is_async_p = remote_is_async_p;
11520   remote_ops.to_async = remote_async;
11521   remote_ops.to_terminal_inferior = remote_terminal_inferior;
11522   remote_ops.to_terminal_ours = remote_terminal_ours;
11523   remote_ops.to_supports_non_stop = remote_supports_non_stop;
11524   remote_ops.to_supports_multi_process = remote_supports_multi_process;
11525   remote_ops.to_supports_disable_randomization
11526     = remote_supports_disable_randomization;
11527   remote_ops.to_fileio_open = remote_hostio_open;
11528   remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11529   remote_ops.to_fileio_pread = remote_hostio_pread;
11530   remote_ops.to_fileio_close = remote_hostio_close;
11531   remote_ops.to_fileio_unlink = remote_hostio_unlink;
11532   remote_ops.to_fileio_readlink = remote_hostio_readlink;
11533   remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
11534   remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
11535   remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
11536   remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
11537   remote_ops.to_trace_init = remote_trace_init;
11538   remote_ops.to_download_tracepoint = remote_download_tracepoint;
11539   remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
11540   remote_ops.to_download_trace_state_variable
11541     = remote_download_trace_state_variable;
11542   remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11543   remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
11544   remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11545   remote_ops.to_trace_start = remote_trace_start;
11546   remote_ops.to_get_trace_status = remote_get_trace_status;
11547   remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
11548   remote_ops.to_trace_stop = remote_trace_stop;
11549   remote_ops.to_trace_find = remote_trace_find;
11550   remote_ops.to_get_trace_state_variable_value
11551     = remote_get_trace_state_variable_value;
11552   remote_ops.to_save_trace_data = remote_save_trace_data;
11553   remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
11554   remote_ops.to_upload_trace_state_variables
11555     = remote_upload_trace_state_variables;
11556   remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
11557   remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
11558   remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
11559   remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
11560   remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
11561   remote_ops.to_set_trace_notes = remote_set_trace_notes;
11562   remote_ops.to_core_of_thread = remote_core_of_thread;
11563   remote_ops.to_verify_memory = remote_verify_memory;
11564   remote_ops.to_get_tib_address = remote_get_tib_address;
11565   remote_ops.to_set_permissions = remote_set_permissions;
11566   remote_ops.to_static_tracepoint_marker_at
11567     = remote_static_tracepoint_marker_at;
11568   remote_ops.to_static_tracepoint_markers_by_strid
11569     = remote_static_tracepoint_markers_by_strid;
11570   remote_ops.to_traceframe_info = remote_traceframe_info;
11571   remote_ops.to_use_agent = remote_use_agent;
11572   remote_ops.to_can_use_agent = remote_can_use_agent;
11573   remote_ops.to_supports_btrace = remote_supports_btrace;
11574   remote_ops.to_enable_btrace = remote_enable_btrace;
11575   remote_ops.to_disable_btrace = remote_disable_btrace;
11576   remote_ops.to_teardown_btrace = remote_teardown_btrace;
11577   remote_ops.to_read_btrace = remote_read_btrace;
11578   remote_ops.to_augmented_libraries_svr4_read =
11579     remote_augmented_libraries_svr4_read;
11580 }
11581 
11582 /* Set up the extended remote vector by making a copy of the standard
11583    remote vector and adding to it.  */
11584 
11585 static void
11586 init_extended_remote_ops (void)
11587 {
11588   extended_remote_ops = remote_ops;
11589 
11590   extended_remote_ops.to_shortname = "extended-remote";
11591   extended_remote_ops.to_longname =
11592     "Extended remote serial target in gdb-specific protocol";
11593   extended_remote_ops.to_doc =
11594     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11595 Specify the serial device it is connected to (e.g. /dev/ttya).";
11596   extended_remote_ops.to_open = extended_remote_open;
11597   extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11598   extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
11599   extended_remote_ops.to_detach = extended_remote_detach;
11600   extended_remote_ops.to_attach = extended_remote_attach;
11601   extended_remote_ops.to_kill = extended_remote_kill;
11602   extended_remote_ops.to_supports_disable_randomization
11603     = extended_remote_supports_disable_randomization;
11604 }
11605 
11606 static int
11607 remote_can_async_p (void)
11608 {
11609   struct remote_state *rs = get_remote_state ();
11610 
11611   if (!target_async_permitted)
11612     /* We only enable async when the user specifically asks for it.  */
11613     return 0;
11614 
11615   /* We're async whenever the serial device is.  */
11616   return serial_can_async_p (rs->remote_desc);
11617 }
11618 
11619 static int
11620 remote_is_async_p (void)
11621 {
11622   struct remote_state *rs = get_remote_state ();
11623 
11624   if (!target_async_permitted)
11625     /* We only enable async when the user specifically asks for it.  */
11626     return 0;
11627 
11628   /* We're async whenever the serial device is.  */
11629   return serial_is_async_p (rs->remote_desc);
11630 }
11631 
11632 /* Pass the SERIAL event on and up to the client.  One day this code
11633    will be able to delay notifying the client of an event until the
11634    point where an entire packet has been received.  */
11635 
11636 static serial_event_ftype remote_async_serial_handler;
11637 
11638 static void
11639 remote_async_serial_handler (struct serial *scb, void *context)
11640 {
11641   struct remote_state *rs = context;
11642 
11643   /* Don't propogate error information up to the client.  Instead let
11644      the client find out about the error by querying the target.  */
11645   rs->async_client_callback (INF_REG_EVENT, rs->async_client_context);
11646 }
11647 
11648 static void
11649 remote_async_inferior_event_handler (gdb_client_data data)
11650 {
11651   inferior_event_handler (INF_REG_EVENT, NULL);
11652 }
11653 
11654 static void
11655 remote_async (void (*callback) (enum inferior_event_type event_type,
11656                                 void *context), void *context)
11657 {
11658   struct remote_state *rs = get_remote_state ();
11659 
11660   if (callback != NULL)
11661     {
11662       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
11663       rs->async_client_callback = callback;
11664       rs->async_client_context = context;
11665     }
11666   else
11667     serial_async (rs->remote_desc, NULL, NULL);
11668 }
11669 
11670 static void
11671 set_remote_cmd (char *args, int from_tty)
11672 {
11673   help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
11674 }
11675 
11676 static void
11677 show_remote_cmd (char *args, int from_tty)
11678 {
11679   /* We can't just use cmd_show_list here, because we want to skip
11680      the redundant "show remote Z-packet" and the legacy aliases.  */
11681   struct cleanup *showlist_chain;
11682   struct cmd_list_element *list = remote_show_cmdlist;
11683   struct ui_out *uiout = current_uiout;
11684 
11685   showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
11686   for (; list != NULL; list = list->next)
11687     if (strcmp (list->name, "Z-packet") == 0)
11688       continue;
11689     else if (list->type == not_set_cmd)
11690       /* Alias commands are exactly like the original, except they
11691          don't have the normal type.  */
11692       continue;
11693     else
11694       {
11695         struct cleanup *option_chain
11696           = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
11697 
11698         ui_out_field_string (uiout, "name", list->name);
11699         ui_out_text (uiout, ":  ");
11700         if (list->type == show_cmd)
11701           do_show_command ((char *) NULL, from_tty, list);
11702         else
11703           cmd_func (list, NULL, from_tty);
11704         /* Close the tuple.  */
11705         do_cleanups (option_chain);
11706       }
11707 
11708   /* Close the tuple.  */
11709   do_cleanups (showlist_chain);
11710 }
11711 
11712 
11713 /* Function to be called whenever a new objfile (shlib) is detected.  */
11714 static void
11715 remote_new_objfile (struct objfile *objfile)
11716 {
11717   struct remote_state *rs = get_remote_state ();
11718 
11719   if (rs->remote_desc != 0)             /* Have a remote connection.  */
11720     remote_check_symbols ();
11721 }
11722 
11723 /* Pull all the tracepoints defined on the target and create local
11724    data structures representing them.  We don't want to create real
11725    tracepoints yet, we don't want to mess up the user's existing
11726    collection.  */
11727   
11728 static int
11729 remote_upload_tracepoints (struct uploaded_tp **utpp)
11730 {
11731   struct remote_state *rs = get_remote_state ();
11732   char *p;
11733 
11734   /* Ask for a first packet of tracepoint definition.  */
11735   putpkt ("qTfP");
11736   getpkt (&rs->buf, &rs->buf_size, 0);
11737   p = rs->buf;
11738   while (*p && *p != 'l')
11739     {
11740       parse_tracepoint_definition (p, utpp);
11741       /* Ask for another packet of tracepoint definition.  */
11742       putpkt ("qTsP");
11743       getpkt (&rs->buf, &rs->buf_size, 0);
11744       p = rs->buf;
11745     }
11746   return 0;
11747 }
11748 
11749 static int
11750 remote_upload_trace_state_variables (struct uploaded_tsv **utsvp)
11751 {
11752   struct remote_state *rs = get_remote_state ();
11753   char *p;
11754 
11755   /* Ask for a first packet of variable definition.  */
11756   putpkt ("qTfV");
11757   getpkt (&rs->buf, &rs->buf_size, 0);
11758   p = rs->buf;
11759   while (*p && *p != 'l')
11760     {
11761       parse_tsv_definition (p, utsvp);
11762       /* Ask for another packet of variable definition.  */
11763       putpkt ("qTsV");
11764       getpkt (&rs->buf, &rs->buf_size, 0);
11765       p = rs->buf;
11766     }
11767   return 0;
11768 }
11769 
11770 /* The "set/show range-stepping" show hook.  */
11771 
11772 static void
11773 show_range_stepping (struct ui_file *file, int from_tty,
11774                      struct cmd_list_element *c,
11775                      const char *value)
11776 {
11777   fprintf_filtered (file,
11778                     _("Debugger's willingness to use range stepping "
11779                       "is %s.\n"), value);
11780 }
11781 
11782 /* The "set/show range-stepping" set hook.  */
11783 
11784 static void
11785 set_range_stepping (char *ignore_args, int from_tty,
11786                     struct cmd_list_element *c)
11787 {
11788   struct remote_state *rs = get_remote_state ();
11789 
11790   /* Whene enabling, check whether range stepping is actually
11791      supported by the target, and warn if not.  */
11792   if (use_range_stepping)
11793     {
11794       if (rs->remote_desc != NULL)
11795         {
11796           if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
11797             remote_vcont_probe (rs);
11798 
11799           if (remote_protocol_packets[PACKET_vCont].support == PACKET_ENABLE
11800               && rs->supports_vCont.r)
11801             return;
11802         }
11803 
11804       warning (_("Range stepping is not supported by the current target"));
11805     }
11806 }
11807 
11808 void
11809 _initialize_remote (void)
11810 {
11811   struct remote_state *rs;
11812   struct cmd_list_element *cmd;
11813   const char *cmd_name;
11814 
11815   /* architecture specific data */
11816   remote_gdbarch_data_handle =
11817     gdbarch_data_register_post_init (init_remote_state);
11818   remote_g_packet_data_handle =
11819     gdbarch_data_register_pre_init (remote_g_packet_data_init);
11820 
11821   /* Initialize the per-target state.  At the moment there is only one
11822      of these, not one per target.  Only one target is active at a
11823      time.  */
11824   remote_state = new_remote_state ();
11825 
11826   init_remote_ops ();
11827   add_target (&remote_ops);
11828 
11829   init_extended_remote_ops ();
11830   add_target (&extended_remote_ops);
11831 
11832   /* Hook into new objfile notification.  */
11833   observer_attach_new_objfile (remote_new_objfile);
11834   /* We're no longer interested in notification events of an inferior
11835      when it exits.  */
11836   observer_attach_inferior_exit (discard_pending_stop_replies);
11837 
11838   /* Set up signal handlers.  */
11839   async_sigint_remote_token =
11840     create_async_signal_handler (async_remote_interrupt, NULL);
11841   async_sigint_remote_twice_token =
11842     create_async_signal_handler (async_remote_interrupt_twice, NULL);
11843 
11844 #if 0
11845   init_remote_threadtests ();
11846 #endif
11847 
11848   stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
11849   /* set/show remote ...  */
11850 
11851   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
11852 Remote protocol specific variables\n\
11853 Configure various remote-protocol specific variables such as\n\
11854 the packets being used"),
11855                   &remote_set_cmdlist, "set remote ",
11856                   0 /* allow-unknown */, &setlist);
11857   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
11858 Remote protocol specific variables\n\
11859 Configure various remote-protocol specific variables such as\n\
11860 the packets being used"),
11861                   &remote_show_cmdlist, "show remote ",
11862                   0 /* allow-unknown */, &showlist);
11863 
11864   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
11865 Compare section data on target to the exec file.\n\
11866 Argument is a single section name (default: all loaded sections)."),
11867            &cmdlist);
11868 
11869   add_cmd ("packet", class_maintenance, packet_command, _("\
11870 Send an arbitrary packet to a remote target.\n\
11871    maintenance packet TEXT\n\
11872 If GDB is talking to an inferior via the GDB serial protocol, then\n\
11873 this command sends the string TEXT to the inferior, and displays the\n\
11874 response packet.  GDB supplies the initial `$' character, and the\n\
11875 terminating `#' character and checksum."),
11876            &maintenancelist);
11877 
11878   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
11879 Set whether to send break if interrupted."), _("\
11880 Show whether to send break if interrupted."), _("\
11881 If set, a break, instead of a cntrl-c, is sent to the remote target."),
11882                            set_remotebreak, show_remotebreak,
11883                            &setlist, &showlist);
11884   cmd_name = "remotebreak";
11885   cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
11886   deprecate_cmd (cmd, "set remote interrupt-sequence");
11887   cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
11888   cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
11889   deprecate_cmd (cmd, "show remote interrupt-sequence");
11890 
11891   add_setshow_enum_cmd ("interrupt-sequence", class_support,
11892                         interrupt_sequence_modes, &interrupt_sequence_mode,
11893                         _("\
11894 Set interrupt sequence to remote target."), _("\
11895 Show interrupt sequence to remote target."), _("\
11896 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
11897                         NULL, show_interrupt_sequence,
11898                         &remote_set_cmdlist,
11899                         &remote_show_cmdlist);
11900 
11901   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
11902                            &interrupt_on_connect, _("\
11903 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("            \
11904 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("           \
11905 If set, interrupt sequence is sent to remote target."),
11906                            NULL, NULL,
11907                            &remote_set_cmdlist, &remote_show_cmdlist);
11908 
11909   /* Install commands for configuring memory read/write packets.  */
11910 
11911   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
11912 Set the maximum number of bytes per memory write packet (deprecated)."),
11913            &setlist);
11914   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
11915 Show the maximum number of bytes per memory write packet (deprecated)."),
11916            &showlist);
11917   add_cmd ("memory-write-packet-size", no_class,
11918            set_memory_write_packet_size, _("\
11919 Set the maximum number of bytes per memory-write packet.\n\
11920 Specify the number of bytes in a packet or 0 (zero) for the\n\
11921 default packet size.  The actual limit is further reduced\n\
11922 dependent on the target.  Specify ``fixed'' to disable the\n\
11923 further restriction and ``limit'' to enable that restriction."),
11924            &remote_set_cmdlist);
11925   add_cmd ("memory-read-packet-size", no_class,
11926            set_memory_read_packet_size, _("\
11927 Set the maximum number of bytes per memory-read packet.\n\
11928 Specify the number of bytes in a packet or 0 (zero) for the\n\
11929 default packet size.  The actual limit is further reduced\n\
11930 dependent on the target.  Specify ``fixed'' to disable the\n\
11931 further restriction and ``limit'' to enable that restriction."),
11932            &remote_set_cmdlist);
11933   add_cmd ("memory-write-packet-size", no_class,
11934            show_memory_write_packet_size,
11935            _("Show the maximum number of bytes per memory-write packet."),
11936            &remote_show_cmdlist);
11937   add_cmd ("memory-read-packet-size", no_class,
11938            show_memory_read_packet_size,
11939            _("Show the maximum number of bytes per memory-read packet."),
11940            &remote_show_cmdlist);
11941 
11942   add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
11943                             &remote_hw_watchpoint_limit, _("\
11944 Set the maximum number of target hardware watchpoints."), _("\
11945 Show the maximum number of target hardware watchpoints."), _("\
11946 Specify a negative limit for unlimited."),
11947                             NULL, NULL, /* FIXME: i18n: The maximum
11948                                            number of target hardware
11949                                            watchpoints is %s.  */
11950                             &remote_set_cmdlist, &remote_show_cmdlist);
11951   add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
11952                             &remote_hw_watchpoint_length_limit, _("\
11953 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
11954 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
11955 Specify a negative limit for unlimited."),
11956                             NULL, NULL, /* FIXME: i18n: The maximum
11957                                            length (in bytes) of a target
11958                                            hardware watchpoint is %s.  */
11959                             &remote_set_cmdlist, &remote_show_cmdlist);
11960   add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
11961                             &remote_hw_breakpoint_limit, _("\
11962 Set the maximum number of target hardware breakpoints."), _("\
11963 Show the maximum number of target hardware breakpoints."), _("\
11964 Specify a negative limit for unlimited."),
11965                             NULL, NULL, /* FIXME: i18n: The maximum
11966                                            number of target hardware
11967                                            breakpoints is %s.  */
11968                             &remote_set_cmdlist, &remote_show_cmdlist);
11969 
11970   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
11971                              &remote_address_size, _("\
11972 Set the maximum size of the address (in bits) in a memory packet."), _("\
11973 Show the maximum size of the address (in bits) in a memory packet."), NULL,
11974                              NULL,
11975                              NULL, /* FIXME: i18n: */
11976                              &setlist, &showlist);
11977 
11978   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
11979                          "X", "binary-download", 1);
11980 
11981   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
11982                          "vCont", "verbose-resume", 0);
11983 
11984   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
11985                          "QPassSignals", "pass-signals", 0);
11986 
11987   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
11988                          "QProgramSignals", "program-signals", 0);
11989 
11990   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
11991                          "qSymbol", "symbol-lookup", 0);
11992 
11993   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
11994                          "P", "set-register", 1);
11995 
11996   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
11997                          "p", "fetch-register", 1);
11998 
11999   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
12000                          "Z0", "software-breakpoint", 0);
12001 
12002   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
12003                          "Z1", "hardware-breakpoint", 0);
12004 
12005   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
12006                          "Z2", "write-watchpoint", 0);
12007 
12008   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
12009                          "Z3", "read-watchpoint", 0);
12010 
12011   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
12012                          "Z4", "access-watchpoint", 0);
12013 
12014   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
12015                          "qXfer:auxv:read", "read-aux-vector", 0);
12016 
12017   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
12018                          "qXfer:features:read", "target-features", 0);
12019 
12020   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
12021                          "qXfer:libraries:read", "library-info", 0);
12022 
12023   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
12024                          "qXfer:libraries-svr4:read", "library-info-svr4", 0);
12025 
12026   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
12027                          "qXfer:memory-map:read", "memory-map", 0);
12028 
12029   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
12030                          "qXfer:spu:read", "read-spu-object", 0);
12031 
12032   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
12033                          "qXfer:spu:write", "write-spu-object", 0);
12034 
12035   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
12036                         "qXfer:osdata:read", "osdata", 0);
12037 
12038   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
12039                          "qXfer:threads:read", "threads", 0);
12040 
12041   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12042                          "qXfer:siginfo:read", "read-siginfo-object", 0);
12043 
12044   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12045                          "qXfer:siginfo:write", "write-siginfo-object", 0);
12046 
12047   add_packet_config_cmd
12048     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
12049      "qXfer:traceframe-info:read", "traceframe-info", 0);
12050 
12051   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12052                          "qXfer:uib:read", "unwind-info-block", 0);
12053 
12054   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
12055                          "qGetTLSAddr", "get-thread-local-storage-address",
12056                          0);
12057 
12058   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12059                          "qGetTIBAddr", "get-thread-information-block-address",
12060                          0);
12061 
12062   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12063                          "bc", "reverse-continue", 0);
12064 
12065   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12066                          "bs", "reverse-step", 0);
12067 
12068   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12069                          "qSupported", "supported-packets", 0);
12070 
12071   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12072                          "qSearch:memory", "search-memory", 0);
12073 
12074   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12075                          "qTStatus", "trace-status", 0);
12076 
12077   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12078                          "vFile:open", "hostio-open", 0);
12079 
12080   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12081                          "vFile:pread", "hostio-pread", 0);
12082 
12083   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12084                          "vFile:pwrite", "hostio-pwrite", 0);
12085 
12086   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12087                          "vFile:close", "hostio-close", 0);
12088 
12089   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12090                          "vFile:unlink", "hostio-unlink", 0);
12091 
12092   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12093                          "vFile:readlink", "hostio-readlink", 0);
12094 
12095   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12096                          "vAttach", "attach", 0);
12097 
12098   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12099                          "vRun", "run", 0);
12100 
12101   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12102                          "QStartNoAckMode", "noack", 0);
12103 
12104   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12105                          "vKill", "kill", 0);
12106 
12107   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12108                          "qAttached", "query-attached", 0);
12109 
12110   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
12111                          "ConditionalTracepoints",
12112                          "conditional-tracepoints", 0);
12113 
12114   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12115                          "ConditionalBreakpoints",
12116                          "conditional-breakpoints", 0);
12117 
12118   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12119                          "BreakpointCommands",
12120                          "breakpoint-commands", 0);
12121 
12122   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12123                          "FastTracepoints", "fast-tracepoints", 0);
12124 
12125   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12126                          "TracepointSource", "TracepointSource", 0);
12127 
12128   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12129                          "QAllow", "allow", 0);
12130 
12131   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12132                          "StaticTracepoints", "static-tracepoints", 0);
12133 
12134   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12135                          "InstallInTrace", "install-in-trace", 0);
12136 
12137   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12138                          "qXfer:statictrace:read", "read-sdata-object", 0);
12139 
12140   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12141                          "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12142 
12143   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12144                          "QDisableRandomization", "disable-randomization", 0);
12145 
12146   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12147                          "QAgent", "agent", 0);
12148 
12149   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12150                          "QTBuffer:size", "trace-buffer-size", 0);
12151 
12152   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12153        "Qbtrace:off", "disable-btrace", 0);
12154 
12155   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12156        "Qbtrace:bts", "enable-btrace", 0);
12157 
12158   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12159        "qXfer:btrace", "read-btrace", 0);
12160 
12161   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
12162      Z sub-packet has its own set and show commands, but users may
12163      have sets to this variable in their .gdbinit files (or in their
12164      documentation).  */
12165   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
12166                                 &remote_Z_packet_detect, _("\
12167 Set use of remote protocol `Z' packets"), _("\
12168 Show use of remote protocol `Z' packets "), _("\
12169 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
12170 packets."),
12171                                 set_remote_protocol_Z_packet_cmd,
12172                                 show_remote_protocol_Z_packet_cmd,
12173                                 /* FIXME: i18n: Use of remote protocol
12174                                    `Z' packets is %s.  */
12175                                 &remote_set_cmdlist, &remote_show_cmdlist);
12176 
12177   add_prefix_cmd ("remote", class_files, remote_command, _("\
12178 Manipulate files on the remote system\n\
12179 Transfer files to and from the remote target system."),
12180                   &remote_cmdlist, "remote ",
12181                   0 /* allow-unknown */, &cmdlist);
12182 
12183   add_cmd ("put", class_files, remote_put_command,
12184            _("Copy a local file to the remote system."),
12185            &remote_cmdlist);
12186 
12187   add_cmd ("get", class_files, remote_get_command,
12188            _("Copy a remote file to the local system."),
12189            &remote_cmdlist);
12190 
12191   add_cmd ("delete", class_files, remote_delete_command,
12192            _("Delete a remote file."),
12193            &remote_cmdlist);
12194 
12195   remote_exec_file = xstrdup ("");
12196   add_setshow_string_noescape_cmd ("exec-file", class_files,
12197                                    &remote_exec_file, _("\
12198 Set the remote pathname for \"run\""), _("\
12199 Show the remote pathname for \"run\""), NULL, NULL, NULL,
12200                                    &remote_set_cmdlist, &remote_show_cmdlist);
12201 
12202   add_setshow_boolean_cmd ("range-stepping", class_run,
12203                            &use_range_stepping, _("\
12204 Enable or disable range stepping."), _("\
12205 Show whether target-assisted range stepping is enabled."), _("\
12206 If on, and the target supports it, when stepping a source line, GDB\n\
12207 tells the target to step the corresponding range of addresses itself instead\n\
12208 of issuing multiple single-steps.  This speeds up source level\n\
12209 stepping.  If off, GDB always issues single-steps, even if range\n\
12210 stepping is supported by the target.  The default is on."),
12211                            set_range_stepping,
12212                            show_range_stepping,
12213                            &setlist,
12214                            &showlist);
12215 
12216   /* Eventually initialize fileio.  See fileio.c */
12217   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
12218 
12219   /* Take advantage of the fact that the LWP field is not used, to tag
12220      special ptids with it set to != 0.  */
12221   magic_null_ptid = ptid_build (42000, 1, -1);
12222   not_sent_ptid = ptid_build (42000, 1, -2);
12223   any_thread_ptid = ptid_build (42000, 1, 0);
12224 
12225   target_buf_size = 2048;
12226   target_buf = xmalloc (target_buf_size);
12227 }
12228 
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Defines