Add target_ops argument to to_fileio_pread
[deliverable/binutils-gdb.git] / gdb / remote.c
index 76c137a2d1db452a897847e2f4caba7c0e958e79..814f945f8c1d54f15b62e5e4c7dd03a77e19f97c 100644 (file)
@@ -1,8 +1,6 @@
 /* Remote target communications for serial-line targets in custom GDB protocol
 
-   Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
-   1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
-   2010, 2011 Free Software Foundation, Inc.
+   Copyright (C) 1988-2014 Free Software Foundation, Inc.
 
    This file is part of GDB.
 
@@ -22,7 +20,7 @@
 /* See the GDB User Guide for details of the GDB remote protocol.  */
 
 #include "defs.h"
-#include "gdb_string.h"
+#include <string.h>
 #include <ctype.h>
 #include <fcntl.h>
 #include "inferior.h"
@@ -36,6 +34,7 @@
 #include "gdb-stabs.h"
 #include "gdbthread.h"
 #include "remote.h"
+#include "remote-notif.h"
 #include "regcache.h"
 #include "value.h"
 #include "gdb_assert.h"
 #include "cli/cli-decode.h"
 #include "cli/cli-setshow.h"
 #include "target-descriptions.h"
+#include "gdb_bfd.h"
+#include "filestuff.h"
+#include "rsp-low.h"
 
-#include <ctype.h>
 #include <sys/time.h>
 
 #include "event-loop.h"
@@ -59,7 +60,7 @@
 
 #include "remote-fileio.h"
 #include "gdb/fileio.h"
-#include "gdb_stat.h"
+#include <sys/stat.h>
 #include "xml-support.h"
 
 #include "memory-map.h"
 #include "tracepoint.h"
 #include "ax.h"
 #include "ax-gdb.h"
+#include "agent.h"
+#include "btrace.h"
 
 /* Temp hacks for tracepoint encoding migration.  */
 static char *target_buf;
 static long target_buf_size;
-/*static*/ void
-encode_actions (struct breakpoint *t, struct bp_location *tloc,
-               char ***tdp_actions, char ***stepping_actions);
 
 /* The size to align memory write packets, when practical.  The protocol
    does not guarantee any alignment, and gdb will generate short
@@ -88,20 +88,18 @@ encode_actions (struct breakpoint *t, struct bp_location *tloc,
 enum { REMOTE_ALIGN_WRITES = 16 };
 
 /* Prototypes for local functions.  */
-static void cleanup_sigint_signal_handler (void *dummy);
-static void initialize_sigint_signal_handler (void);
+static void async_cleanup_sigint_signal_handler (void *dummy);
 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
-                                int forever);
+                                int forever, int *is_notif);
 
-static void handle_remote_sigint (int);
-static void handle_remote_sigint_twice (int);
-static void async_remote_interrupt (gdb_client_data);
-void async_remote_interrupt_twice (gdb_client_data);
+static void async_handle_remote_sigint (int);
+static void async_handle_remote_sigint_twice (int);
 
 static void remote_files_info (struct target_ops *ignore);
 
-static void remote_prepare_to_store (struct regcache *regcache);
+static void remote_prepare_to_store (struct target_ops *self,
+                                    struct regcache *regcache);
 
 static void remote_open (char *name, int from_tty);
 
@@ -109,7 +107,7 @@ static void extended_remote_open (char *name, int from_tty);
 
 static void remote_open_1 (char *, int, struct target_ops *, int extended_p);
 
-static void remote_close (int quitting);
+static void remote_close (struct target_ops *self);
 
 static void remote_mourn (struct target_ops *ops);
 
@@ -123,24 +121,20 @@ static void remote_send (char **buf, long *sizeof_buf_p);
 
 static int readchar (int timeout);
 
-static void remote_kill (struct target_ops *ops);
-
-static int tohex (int nib);
-
-static int remote_can_async_p (void);
+static void remote_serial_write (const char *str, int len);
 
-static int remote_is_async_p (void);
-
-static void remote_async (void (*callback) (enum inferior_event_type event_type,
-                                           void *context), void *context);
+static void remote_kill (struct target_ops *ops);
 
-static int remote_async_mask (int new_mask);
+static int remote_can_async_p (struct target_ops *);
 
-static void remote_detach (struct target_ops *ops, char *args, int from_tty);
+static int remote_is_async_p (struct target_ops *);
 
-static void remote_interrupt (int signo);
+static void remote_async (struct target_ops *ops,
+                         void (*callback) (enum inferior_event_type event_type,
+                                           void *context),
+                         void *context);
 
-static void remote_interrupt_twice (int signo);
+static void sync_remote_interrupt_twice (int signo);
 
 static void interrupt_query (void);
 
@@ -159,9 +153,7 @@ static void init_remote_ops (void);
 
 static void init_extended_remote_ops (void);
 
-static void remote_stop (ptid_t);
-
-static int ishex (int ch, int *val);
+static void remote_stop (struct target_ops *self, ptid_t);
 
 static int stubhex (int ch);
 
@@ -183,14 +175,6 @@ static ptid_t remote_current_thread (ptid_t oldptid);
 
 static void remote_find_new_threads (void);
 
-static void record_currthread (ptid_t currthread);
-
-static int fromhex (int a);
-
-extern int hex2bin (const char *hex, gdb_byte *bin, int count);
-
-extern int bin2hex (const gdb_byte *bin, char *hex, int count);
-
 static int putpkt_binary (char *buf, int cnt);
 
 static void check_binary_download (CORE_ADDR addr);
@@ -223,33 +207,28 @@ static int remote_upload_trace_state_variables (struct uploaded_tsv **utsvp);
   
 static void remote_query_supported (void);
 
-static void remote_check_symbols (struct objfile *objfile);
+static void remote_check_symbols (void);
 
 void _initialize_remote (void);
 
 struct stop_reply;
-static struct stop_reply *stop_reply_xmalloc (void);
 static void stop_reply_xfree (struct stop_reply *);
-static void do_stop_reply_xfree (void *arg);
-static void remote_parse_stop_reply (char *buf, struct stop_reply *);
+static void remote_parse_stop_reply (char *, struct stop_reply *);
 static void push_stop_reply (struct stop_reply *);
-static void remote_get_pending_stop_replies (void);
-static void discard_pending_stop_replies (int pid);
+static void discard_pending_stop_replies_in_queue (struct remote_state *);
 static int peek_stop_reply (ptid_t ptid);
 
 static void remote_async_inferior_event_handler (gdb_client_data);
-static void remote_async_get_pending_events_handler (gdb_client_data);
 
-static void remote_terminal_ours (void);
+static void remote_terminal_ours (struct target_ops *self);
 
 static int remote_read_description_p (struct target_ops *target);
 
 static void remote_console_output (char *msg);
 
-/* The non-stop remote protocol provisions for one pending stop reply.
-   This is where we keep it until it is acknowledged.  */
+static int remote_supports_cond_breakpoints (struct target_ops *self);
 
-static struct stop_reply *pending_stop_reply = NULL;
+static int remote_can_run_breakpoint_commands (struct target_ops *self);
 
 /* For "remote".  */
 
@@ -260,6 +239,33 @@ static struct cmd_list_element *remote_cmdlist;
 static struct cmd_list_element *remote_set_cmdlist;
 static struct cmd_list_element *remote_show_cmdlist;
 
+/* Stub vCont actions support.
+
+   Each field is a boolean flag indicating whether the stub reports
+   support for the corresponding action.  */
+
+struct vCont_action_support
+{
+  /* vCont;t */
+  int t;
+
+  /* vCont;r */
+  int r;
+};
+
+/* Controls whether GDB is willing to use range stepping.  */
+
+static int use_range_stepping = 1;
+
+#define OPAQUETHREADBYTES 8
+
+/* a 64 bit opaque identifier */
+typedef unsigned char threadref[OPAQUETHREADBYTES];
+
+/* About this many threadisds fit in a packet.  */
+
+#define MAXTHREADLISTRESULTS 32
+
 /* Description of the remote protocol state for the currently
    connected target.  This is per-target state, and independent of the
    selected architecture.  */
@@ -275,6 +281,10 @@ struct remote_state
   char *buf;
   long buf_size;
 
+  /* True if we're going through initial connection setup (finding out
+     about the remote side's threads, relocating symbols, etc.).  */
+  int starting_up;
+
   /* If we negotiated packet size explicitly (and thus can bypass
      heuristics for the largest packet size that will not overflow
      a buffer in the stub), this will be set to that packet size.
@@ -313,25 +323,106 @@ struct remote_state
   /* True if the stub reports support for non-stop mode.  */
   int non_stop_aware;
 
-  /* True if the stub reports support for vCont;t.  */
-  int support_vCont_t;
+  /* The status of the stub support for the various vCont actions.  */
+  struct vCont_action_support supports_vCont;
 
   /* True if the stub reports support for conditional tracepoints.  */
   int cond_tracepoints;
 
+  /* True if the stub reports support for target-side breakpoint
+     conditions.  */
+  int cond_breakpoints;
+
+  /* True if the stub reports support for target-side breakpoint
+     commands.  */
+  int breakpoint_commands;
+
   /* True if the stub reports support for fast tracepoints.  */
   int fast_tracepoints;
 
   /* True if the stub reports support for static tracepoints.  */
   int static_tracepoints;
 
+  /* True if the stub reports support for installing tracepoint while
+     tracing.  */
+  int install_in_trace;
+
   /* True if the stub can continue running a trace while GDB is
      disconnected.  */
   int disconnected_tracing;
 
+  /* True if the stub reports support for enabling and disabling
+     tracepoints while a trace experiment is running.  */
+  int enable_disable_tracepoints;
+
+  /* True if the stub can collect strings using tracenz bytecode.  */
+  int string_tracing;
+
+  /* True if the stub supports qXfer:libraries-svr4:read with a
+     non-empty annex.  */
+  int augmented_libraries_svr4_read;
+
   /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
      responded to that.  */
   int ctrlc_pending_p;
+
+  /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
+     remote_open knows that we don't have a file open when the program
+     starts.  */
+  struct serial *remote_desc;
+
+  /* These are the threads which we last sent to the remote system.  The
+     TID member will be -1 for all or -2 for not sent yet.  */
+  ptid_t general_thread;
+  ptid_t continue_thread;
+
+  /* This is the traceframe which we last selected on the remote system.
+     It will be -1 if no traceframe is selected.  */
+  int remote_traceframe_number;
+
+  char *last_pass_packet;
+
+  /* The last QProgramSignals packet sent to the target.  We bypass
+     sending a new program signals list down to the target if the new
+     packet is exactly the same as the last we sent.  IOW, we only let
+     the target know about program signals list changes.  */
+  char *last_program_signals_packet;
+
+  enum gdb_signal last_sent_signal;
+
+  int last_sent_step;
+
+  char *finished_object;
+  char *finished_annex;
+  ULONGEST finished_offset;
+
+  /* Should we try the 'ThreadInfo' query packet?
+
+     This variable (NOT available to the user: auto-detect only!)
+     determines whether GDB will use the new, simpler "ThreadInfo"
+     query or the older, more complex syntax for thread queries.
+     This is an auto-detect variable (set to true at each connect,
+     and set to false when the target fails to recognize it).  */
+  int use_threadinfo_query;
+  int use_threadextra_query;
+
+  void (*async_client_callback) (enum inferior_event_type event_type,
+                                void *context);
+  void *async_client_context;
+
+  /* This is set to the data address of the access causing the target
+     to stop for a watchpoint.  */
+  CORE_ADDR remote_watch_data_address;
+
+  /* This is non-zero if target stopped for a watchpoint.  */
+  int remote_stopped_by_watchpoint_p;
+
+  threadref echo_nextthread;
+  threadref nextthread;
+  threadref resultthreadlist[MAXTHREADLISTRESULTS];
+
+  /* The state of remote notification.  */
+  struct remote_notif_state *notif_state;
 };
 
 /* Private data that we'll store in (struct thread_info)->private.  */
@@ -352,19 +443,37 @@ free_private_thread_info (struct private_thread_info *info)
 static int
 remote_multi_process_p (struct remote_state *rs)
 {
-  return rs->extended && rs->multi_process_aware;
+  return rs->multi_process_aware;
 }
 
 /* This data could be associated with a target, but we do not always
    have access to the current target when we need it, so for now it is
    static.  This will be fine for as long as only one target is in use
    at a time.  */
-static struct remote_state remote_state;
+static struct remote_state *remote_state;
 
 static struct remote_state *
 get_remote_state_raw (void)
 {
-  return &remote_state;
+  return remote_state;
+}
+
+/* Allocate a new struct remote_state with xmalloc, initialize it, and
+   return it.  */
+
+static struct remote_state *
+new_remote_state (void)
+{
+  struct remote_state *result = XCNEW (struct remote_state);
+
+  /* The default buffer size is unimportant; it will be expanded
+     whenever a larger buffer is needed. */
+  result->buf_size = 400;
+  result->buf = xmalloc (result->buf_size);
+  result->remote_traceframe_number = -1;
+  result->last_sent_signal = GDB_SIGNAL_0;
+
+  return result;
 }
 
 /* Description of the remote protocol for a given architecture.  */
@@ -375,9 +484,9 @@ struct packet_reg
   long regnum; /* GDB's internal register number.  */
   LONGEST pnum; /* Remote protocol register number.  */
   int in_g_packet; /* Always part of G packet.  */
-  /* long size in bytes;  == register_size (target_gdbarch, regnum);
+  /* long size in bytes;  == register_size (target_gdbarch (), regnum);
      at present.  */
-  /* char *name; == gdbarch_register_name (target_gdbarch, regnum);
+  /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
      at present.  */
 };
 
@@ -403,8 +512,6 @@ struct remote_arch_state
   long remote_packet_size;
 };
 
-long sizeof_pkt = 2000;
-
 /* Utility: generate error from an incoming stub packet.  */
 static void
 trace_error (char *buf)
@@ -419,8 +526,6 @@ trace_error (char *buf)
       else
        error (_("remote.c: error in outgoing packet at field #%ld."),
               strtol (buf, NULL, 16));
-    case '2':
-      error (_("trace API error 0x%s."), ++buf);
     default:
       error (_("Target returns error code '%s'."), buf);
     }
@@ -462,13 +567,13 @@ remote_get_noisy_reply (char **buf_p,
 
          TRY_CATCH (ex, RETURN_MASK_ALL)
            {
-             gdbarch_relocate_instruction (target_gdbarch, &to, from);
+             gdbarch_relocate_instruction (target_gdbarch (), &to, from);
            }
          if (ex.reason >= 0)
            {
              adjusted_size = to - org_to;
 
-             sprintf (buf, "qRelocInsn:%x", adjusted_size);
+             xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
              putpkt (buf);
            }
          else if (ex.reason < 0 && ex.error == MEMORY_ERROR)
@@ -503,7 +608,7 @@ static struct gdbarch_data *remote_gdbarch_data_handle;
 static struct remote_arch_state *
 get_remote_arch_state (void)
 {
-  return gdbarch_data (target_gdbarch, remote_gdbarch_data_handle);
+  return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
 }
 
 /* Fetch the global remote target state.  */
@@ -676,7 +781,7 @@ get_remote_packet_size (void)
 static struct packet_reg *
 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
 {
-  if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch))
+  if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
     return NULL;
   else
     {
@@ -692,7 +797,7 @@ packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
 {
   int i;
 
-  for (i = 0; i < gdbarch_num_regs (target_gdbarch); i++)
+  for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
     {
       struct packet_reg *r = &rsa->regs[i];
 
@@ -702,23 +807,10 @@ packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
   return NULL;
 }
 
-/* FIXME: graces/2002-08-08: These variables should eventually be
-   bound to an instance of the target object (as in gdbarch-tdep()),
-   when such a thing exists.  */
-
-/* This is set to the data address of the access causing the target
-   to stop for a watchpoint.  */
-static CORE_ADDR remote_watch_data_address;
-
-/* This is non-zero if target stopped for a watchpoint.  */
-static int remote_stopped_by_watchpoint_p;
-
 static struct target_ops remote_ops;
 
 static struct target_ops extended_remote_ops;
 
-static int remote_async_mask_value = 1;
-
 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
    ``forever'' still use the normal timeout mechanism.  This is
    currently used by the ASYNC code to guarentee that target reads
@@ -737,7 +829,7 @@ static int wait_forever_enabled_p = 1;
 const char interrupt_sequence_control_c[] = "Ctrl-C";
 const char interrupt_sequence_break[] = "BREAK";
 const char interrupt_sequence_break_g[] = "BREAK-g";
-static const char *interrupt_sequence_modes[] =
+static const char *const interrupt_sequence_modes[] =
   {
     interrupt_sequence_control_c,
     interrupt_sequence_break,
@@ -798,11 +890,6 @@ show_remotebreak (struct ui_file *file, int from_tty,
 {
 }
 
-/* Descriptor for I/O to remote machine.  Initialize it to NULL so that
-   remote_open knows that we don't have a file open when the program
-   starts.  */
-static struct serial *remote_desc = NULL;
-
 /* This variable sets the number of bits in an address that are to be
    sent in a memory ("M" or "m") packet.  Normally, after stripping
    leading zeros, the entire address would be sent.  This variable
@@ -814,7 +901,7 @@ static struct serial *remote_desc = NULL;
    some remote targets this variable is principly provided to
    facilitate backward compatibility.  */
 
-static int remote_address_size;
+static unsigned int remote_address_size;
 
 /* Temporary to track who currently owns the terminal.  See
    remote_terminal_* for more details.  */
@@ -1233,9 +1320,11 @@ enum {
   PACKET_vFile_pwrite,
   PACKET_vFile_close,
   PACKET_vFile_unlink,
+  PACKET_vFile_readlink,
   PACKET_qXfer_auxv,
   PACKET_qXfer_features,
   PACKET_qXfer_libraries,
+  PACKET_qXfer_libraries_svr4,
   PACKET_qXfer_memory_map,
   PACKET_qXfer_spu_read,
   PACKET_qXfer_spu_write,
@@ -1243,10 +1332,13 @@ enum {
   PACKET_qXfer_threads,
   PACKET_qXfer_statictrace_read,
   PACKET_qXfer_traceframe_info,
+  PACKET_qXfer_uib,
   PACKET_qGetTIBAddr,
   PACKET_qGetTLSAddr,
   PACKET_qSupported,
+  PACKET_qTStatus,
   PACKET_QPassSignals,
+  PACKET_QProgramSignals,
   PACKET_qSearch_memory,
   PACKET_vAttach,
   PACKET_vRun,
@@ -1256,12 +1348,22 @@ enum {
   PACKET_qXfer_siginfo_write,
   PACKET_qAttached,
   PACKET_ConditionalTracepoints,
+  PACKET_ConditionalBreakpoints,
+  PACKET_BreakpointCommands,
   PACKET_FastTracepoints,
   PACKET_StaticTracepoints,
+  PACKET_InstallInTrace,
   PACKET_bc,
   PACKET_bs,
   PACKET_TracepointSource,
   PACKET_QAllow,
+  PACKET_qXfer_fdpic,
+  PACKET_QDisableRandomization,
+  PACKET_QAgent,
+  PACKET_QTBuffer_size,
+  PACKET_Qbtrace_off,
+  PACKET_Qbtrace_bts,
+  PACKET_qXfer_btrace,
   PACKET_MAX
 };
 
@@ -1351,20 +1453,9 @@ show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
     }
 }
 
-/* Should we try the 'ThreadInfo' query packet?
-
-   This variable (NOT available to the user: auto-detect only!)
-   determines whether GDB will use the new, simpler "ThreadInfo"
-   query or the older, more complex syntax for thread queries.
-   This is an auto-detect variable (set to true at each connect,
-   and set to false when the target fails to recognize it).  */
-
-static int use_threadinfo_query;
-static int use_threadextra_query;
-
 /* Tokens for use by the asynchronous signal handlers for SIGINT.  */
-static struct async_signal_handler *sigint_remote_twice_token;
-static struct async_signal_handler *sigint_remote_token;
+static struct async_signal_handler *async_sigint_remote_twice_token;
+static struct async_signal_handler *async_sigint_remote_token;
 
 \f
 /* Asynchronous signal handle registered as event loop source for
@@ -1372,28 +1463,12 @@ static struct async_signal_handler *sigint_remote_token;
 
 static struct async_event_handler *remote_async_inferior_event_token;
 
-/* Asynchronous signal handle registered as event loop source for when
-   the remote sent us a %Stop notification.  The registered callback
-   will do a vStopped sequence to pull the rest of the events out of
-   the remote side into our event queue.  */
-
-static struct async_event_handler *remote_async_get_pending_events_token;
 \f
 
 static ptid_t magic_null_ptid;
 static ptid_t not_sent_ptid;
 static ptid_t any_thread_ptid;
 
-/* These are the threads which we last sent to the remote system.  The
-   TID member will be -1 for all or -2 for not sent yet.  */
-
-static ptid_t general_thread;
-static ptid_t continue_thread;
-
-/* This the traceframe which we last selected on the remote system.
-   It will be -1 if no traceframe is selected.  */
-static int remote_traceframe_number = -1;
-
 /* Find out if the stub attached to PID (and hence GDB should offer to
    detach instead of killing it when bailing out).  */
 
@@ -1401,14 +1476,15 @@ static int
 remote_query_attached (int pid)
 {
   struct remote_state *rs = get_remote_state ();
+  size_t size = get_remote_packet_size ();
 
   if (remote_protocol_packets[PACKET_qAttached].support == PACKET_DISABLE)
     return 0;
 
   if (remote_multi_process_p (rs))
-    sprintf (rs->buf, "qAttached:%x", pid);
+    xsnprintf (rs->buf, size, "qAttached:%x", pid);
   else
-    sprintf (rs->buf, "qAttached");
+    xsnprintf (rs->buf, size, "qAttached");
 
   putpkt (rs->buf);
   getpkt (&rs->buf, &rs->buf_size, 0);
@@ -1430,16 +1506,17 @@ remote_query_attached (int pid)
   return 0;
 }
 
-/* Add PID to GDB's inferior table.  Since we can be connected to a
-   remote system before before knowing about any inferior, mark the
-   target with execution when we find the first inferior.  If ATTACHED
-   is 1, then we had just attached to this inferior.  If it is 0, then
-   we just created this inferior.  If it is -1, then try querying the
-   remote stub to find out if it had attached to the inferior or
-   not.  */
+/* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
+   has been invented by GDB, instead of reported by the target.  Since
+   we can be connected to a remote system before before knowing about
+   any inferior, mark the target with execution when we find the first
+   inferior.  If ATTACHED is 1, then we had just attached to this
+   inferior.  If it is 0, then we just created this inferior.  If it
+   is -1, then try querying the remote stub to find out if it had
+   attached to the inferior or not.  */
 
 static struct inferior *
-remote_add_inferior (int pid, int attached)
+remote_add_inferior (int fake_pid_p, int pid, int attached)
 {
   struct inferior *inf;
 
@@ -1449,7 +1526,7 @@ remote_add_inferior (int pid, int attached)
   if (attached == -1)
     attached = remote_query_attached (pid);
 
-  if (gdbarch_has_global_solist (target_gdbarch))
+  if (gdbarch_has_global_solist (target_gdbarch ()))
     {
       /* If the target shares code across all inferiors, then every
         attach adds a new inferior.  */
@@ -1471,6 +1548,7 @@ remote_add_inferior (int pid, int attached)
     }
 
   inf->attach_flag = attached;
+  inf->fake_pid_p = fake_pid_p;
 
   return inf;
 }
@@ -1481,7 +1559,18 @@ remote_add_inferior (int pid, int attached)
 static void
 remote_add_thread (ptid_t ptid, int running)
 {
-  add_thread (ptid);
+  struct remote_state *rs = get_remote_state ();
+
+  /* GDB historically didn't pull threads in the initial connection
+     setup.  If the remote target doesn't even have a concept of
+     threads (e.g., a bare-metal target), even if internally we
+     consider that a single-threaded target, mentioning a new thread
+     might be confusing to the user.  Be silent then, preserving the
+     age old behavior.  */
+  if (rs->starting_up)
+    add_thread_silent (ptid);
+  else
+    add_thread (ptid);
 
   set_executing (ptid, running);
   set_running (ptid, running);
@@ -1546,22 +1635,34 @@ remote_notice_new_inferior (ptid_t currthread, int running)
         may not know about it yet.  Add it before adding its child
         thread, so notifications are emitted in a sensible order.  */
       if (!in_inferior_list (ptid_get_pid (currthread)))
-       inf = remote_add_inferior (ptid_get_pid (currthread), -1);
+       {
+         struct remote_state *rs = get_remote_state ();
+         int fake_pid_p = !remote_multi_process_p (rs);
+
+         inf = remote_add_inferior (fake_pid_p,
+                                    ptid_get_pid (currthread), -1);
+       }
 
       /* This is really a new thread.  Add it.  */
       remote_add_thread (currthread, running);
 
       /* If we found a new inferior, let the common code do whatever
         it needs to with it (e.g., read shared libraries, insert
-        breakpoints).  */
+        breakpoints), unless we're just setting up an all-stop
+        connection.  */
       if (inf != NULL)
-       notice_new_inferior (currthread, running, 0);
+       {
+         struct remote_state *rs = get_remote_state ();
+
+         if (non_stop || !rs->starting_up)
+           notice_new_inferior (currthread, running, 0);
+       }
     }
 }
 
 /* Return the private thread data, creating it if necessary.  */
 
-struct private_thread_info *
+static struct private_thread_info *
 demand_private_info (ptid_t ptid)
 {
   struct thread_info *info = find_thread_ptid (ptid);
@@ -1585,23 +1686,23 @@ demand_private_info (ptid_t ptid)
    3) Successful execution of set thread */
 
 static void
-record_currthread (ptid_t currthread)
+record_currthread (struct remote_state *rs, ptid_t currthread)
 {
-  general_thread = currthread;
+  rs->general_thread = currthread;
 }
 
-static char *last_pass_packet;
-
 /* If 'QPassSignals' is supported, tell the remote stub what signals
    it can simply pass through to the inferior without reporting.  */
 
 static void
-remote_pass_signals (int numsigs, unsigned char *pass_signals)
+remote_pass_signals (struct target_ops *self,
+                    int numsigs, unsigned char *pass_signals)
 {
   if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
     {
       char *pass_packet, *p;
       int count = 0, i;
+      struct remote_state *rs = get_remote_state ();
 
       gdb_assert (numsigs < 256);
       for (i = 0; i < numsigs; i++)
@@ -1627,23 +1728,71 @@ remote_pass_signals (int numsigs, unsigned char *pass_signals)
            }
        }
       *p = 0;
-      if (!last_pass_packet || strcmp (last_pass_packet, pass_packet))
+      if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
        {
-         struct remote_state *rs = get_remote_state ();
-         char *buf = rs->buf;
-
          putpkt (pass_packet);
          getpkt (&rs->buf, &rs->buf_size, 0);
-         packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
-         if (last_pass_packet)
-           xfree (last_pass_packet);
-         last_pass_packet = pass_packet;
+         packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
+         if (rs->last_pass_packet)
+           xfree (rs->last_pass_packet);
+         rs->last_pass_packet = pass_packet;
        }
       else
        xfree (pass_packet);
     }
 }
 
+/* If 'QProgramSignals' is supported, tell the remote stub what
+   signals it should pass through to the inferior when detaching.  */
+
+static void
+remote_program_signals (struct target_ops *self,
+                       int numsigs, unsigned char *signals)
+{
+  if (remote_protocol_packets[PACKET_QProgramSignals].support != PACKET_DISABLE)
+    {
+      char *packet, *p;
+      int count = 0, i;
+      struct remote_state *rs = get_remote_state ();
+
+      gdb_assert (numsigs < 256);
+      for (i = 0; i < numsigs; i++)
+       {
+         if (signals[i])
+           count++;
+       }
+      packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
+      strcpy (packet, "QProgramSignals:");
+      p = packet + strlen (packet);
+      for (i = 0; i < numsigs; i++)
+       {
+         if (signal_pass_state (i))
+           {
+             if (i >= 16)
+               *p++ = tohex (i >> 4);
+             *p++ = tohex (i & 15);
+             if (count)
+               *p++ = ';';
+             else
+               break;
+             count--;
+           }
+       }
+      *p = 0;
+      if (!rs->last_program_signals_packet
+         || strcmp (rs->last_program_signals_packet, packet) != 0)
+       {
+         putpkt (packet);
+         getpkt (&rs->buf, &rs->buf_size, 0);
+         packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
+         xfree (rs->last_program_signals_packet);
+         rs->last_program_signals_packet = packet;
+       }
+      else
+       xfree (packet);
+    }
+}
+
 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
    thread.  If GEN is set, set the general thread, if not, then set
@@ -1652,7 +1801,7 @@ static void
 set_thread (struct ptid ptid, int gen)
 {
   struct remote_state *rs = get_remote_state ();
-  ptid_t state = gen ? general_thread : continue_thread;
+  ptid_t state = gen ? rs->general_thread : rs->continue_thread;
   char *buf = rs->buf;
   char *endbuf = rs->buf + get_remote_packet_size ();
 
@@ -1672,9 +1821,9 @@ set_thread (struct ptid ptid, int gen)
   putpkt (rs->buf);
   getpkt (&rs->buf, &rs->buf_size, 0);
   if (gen)
-    general_thread = ptid;
+    rs->general_thread = ptid;
   else
-    continue_thread = ptid;
+    rs->continue_thread = ptid;
 }
 
 static void
@@ -1704,12 +1853,12 @@ set_general_process (void)
   struct remote_state *rs = get_remote_state ();
 
   /* If the remote can't handle multiple processes, don't bother.  */
-  if (!remote_multi_process_p (rs))
+  if (!rs->extended || !remote_multi_process_p (rs))
     return;
 
   /* We only need to change the remote current thread if it's pointing
      at some other process.  */
-  if (ptid_get_pid (general_thread) != ptid_get_pid (inferior_ptid))
+  if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
     set_general_thread (inferior_ptid);
 }
 
@@ -1750,11 +1899,6 @@ remote_thread_alive (struct target_ops *ops, ptid_t ptid)
    remote protocol in general.  There is a matching unit test module
    in libstub.  */
 
-#define OPAQUETHREADBYTES 8
-
-/* a 64 bit opaque identifier */
-typedef unsigned char threadref[OPAQUETHREADBYTES];
-
 /* WARNING: This threadref data structure comes from the remote O.S.,
    libstub protocol encoding, and remote.c.  It is not particularly
    changable.  */
@@ -1792,14 +1936,8 @@ struct gdb_ext_thread_info
 
 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
 
-char *unpack_varlen_hex (char *buff, ULONGEST *result);
-
 static char *unpack_nibble (char *buf, int *val);
 
-static char *pack_nibble (char *buf, int nibble);
-
-static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
-
 static char *unpack_byte (char *buf, int *value);
 
 static char *pack_int (char *buf, int value);
@@ -1926,31 +2064,6 @@ read_ptid (char *buf, char **obuf)
   return ptid_build (pid, 0, tid);
 }
 
-/* Encode 64 bits in 16 chars of hex.  */
-
-static const char hexchars[] = "0123456789abcdef";
-
-static int
-ishex (int ch, int *val)
-{
-  if ((ch >= 'a') && (ch <= 'f'))
-    {
-      *val = ch - 'a' + 10;
-      return 1;
-    }
-  if ((ch >= 'A') && (ch <= 'F'))
-    {
-      *val = ch - 'A' + 10;
-      return 1;
-    }
-  if ((ch >= '0') && (ch <= '9'))
-    {
-      *val = ch - '0';
-      return 1;
-    }
-  return 0;
-}
-
 static int
 stubhex (int ch)
 {
@@ -1980,23 +2093,6 @@ stub_unpack_int (char *buff, int fieldlength)
   return retval;
 }
 
-char *
-unpack_varlen_hex (char *buff, /* packet to parse */
-                  ULONGEST *result)
-{
-  int nibble;
-  ULONGEST retval = 0;
-
-  while (ishex (*buff, &nibble))
-    {
-      buff++;
-      retval = retval << 4;
-      retval |= nibble & 0x0f;
-    }
-  *result = retval;
-  return buff;
-}
-
 static char *
 unpack_nibble (char *buf, int *val)
 {
@@ -2004,21 +2100,6 @@ unpack_nibble (char *buf, int *val)
   return buf;
 }
 
-static char *
-pack_nibble (char *buf, int nibble)
-{
-  *buf++ = hexchars[(nibble & 0x0f)];
-  return buf;
-}
-
-static char *
-pack_hex_byte (char *pkt, int byte)
-{
-  *pkt++ = hexchars[(byte >> 4) & 0xf];
-  *pkt++ = hexchars[(byte & 0xf)];
-  return pkt;
-}
-
 static char *
 unpack_byte (char *buf, int *value)
 {
@@ -2370,7 +2451,6 @@ remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
                       int *done, int *result_count, threadref *threadlist)
 {
   struct remote_state *rs = get_remote_state ();
-  static threadref echo_nextthread;
   int result = 1;
 
   /* Trancate result limit to be smaller than the packet size.  */
@@ -2386,10 +2466,10 @@ remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
     return 0;
   else
     *result_count =
-      parse_threadlist_response (rs->buf + 2, result_limit, &echo_nextthread,
-                                 threadlist, done);
+      parse_threadlist_response (rs->buf + 2, result_limit,
+                                &rs->echo_nextthread, threadlist, done);
 
-  if (!threadmatch (&echo_nextthread, nextthread))
+  if (!threadmatch (&rs->echo_nextthread, nextthread))
     {
       /* FIXME: This is a good reason to drop the packet.  */
       /* Possably, there is a duplicate response.  */
@@ -2430,20 +2510,15 @@ remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
    quit_flag is required.  */
 
 
-/* About this many threadisds fit in a packet.  */
-
-#define MAXTHREADLISTRESULTS 32
-
 static int
 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
                            int looplimit)
 {
+  struct remote_state *rs = get_remote_state ();
   int done, i, result_count;
   int startflag = 1;
   int result = 1;
   int loopcount = 0;
-  static threadref nextthread;
-  static threadref resultthreadlist[MAXTHREADLISTRESULTS];
 
   done = 0;
   while (!done)
@@ -2454,8 +2529,9 @@ remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
          warning (_("Remote fetch threadlist -infinite loop-."));
          break;
        }
-      if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
-                                 &done, &result_count, resultthreadlist))
+      if (!remote_get_threadlist (startflag, &rs->nextthread,
+                                 MAXTHREADLISTRESULTS,
+                                 &done, &result_count, rs->resultthreadlist))
        {
          result = 0;
          break;
@@ -2464,10 +2540,11 @@ remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
       startflag = 0;
       /* Setup to resume next batch of thread references, set nextthread.  */
       if (result_count >= 1)
-       copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
+       copy_threadref (&rs->nextthread,
+                       &rs->resultthreadlist[result_count - 1]);
       i = 0;
       while (result_count--)
-       if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
+       if (!(result = (*stepfunction) (&rs->resultthreadlist[i++], context)))
          break;
     }
   return result;
@@ -2615,7 +2692,7 @@ remote_threads_info (struct target_ops *ops)
   char *bufp;
   ptid_t new_thread;
 
-  if (remote_desc == 0)                /* paranoia */
+  if (rs->remote_desc == 0)            /* paranoia */
     error (_("Command can only be used when connected to the remote target."));
 
 #if defined(HAVE_LIBEXPAT)
@@ -2668,13 +2745,22 @@ remote_threads_info (struct target_ops *ops)
     }
 #endif
 
-  if (use_threadinfo_query)
+  if (rs->use_threadinfo_query)
     {
       putpkt ("qfThreadInfo");
       getpkt (&rs->buf, &rs->buf_size, 0);
       bufp = rs->buf;
       if (bufp[0] != '\0')             /* q packet recognized */
        {
+         struct cleanup *old_chain;
+         char *saved_reply;
+
+         /* remote_notice_new_inferior (in the loop below) may make
+            new RSP calls, which clobber rs->buf.  Work with a
+            copy.  */
+         bufp = saved_reply = xstrdup (rs->buf);
+         old_chain = make_cleanup (free_current_contents, &saved_reply);
+
          while (*bufp++ == 'm')        /* reply contains one or more TID */
            {
              do
@@ -2692,10 +2778,12 @@ remote_threads_info (struct target_ops *ops)
                    }
                }
              while (*bufp++ == ',');   /* comma-separated list */
+             free_current_contents (&saved_reply);
              putpkt ("qsThreadInfo");
              getpkt (&rs->buf, &rs->buf_size, 0);
-             bufp = rs->buf;
+             bufp = saved_reply = xstrdup (rs->buf);
            }
+         do_cleanups (old_chain);
          return;       /* done */
        }
     }
@@ -2705,7 +2793,7 @@ remote_threads_info (struct target_ops *ops)
     return;
 
   /* Else fall back to old method based on jmetzler protocol.  */
-  use_threadinfo_query = 0;
+  rs->use_threadinfo_query = 0;
   remote_find_new_threads ();
   return;
 }
@@ -2720,7 +2808,7 @@ remote_threads_info (struct target_ops *ops)
  */
 
 static char *
-remote_threads_extra_info (struct thread_info *tp)
+remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
 {
   struct remote_state *rs = get_remote_state ();
   int result;
@@ -2730,7 +2818,7 @@ remote_threads_extra_info (struct thread_info *tp)
   static char display_buf[100];        /* arbitrary...  */
   int n = 0;                    /* position in display_buf */
 
-  if (remote_desc == 0)                /* paranoia */
+  if (rs->remote_desc == 0)            /* paranoia */
     internal_error (__FILE__, __LINE__,
                    _("remote_threads_extra_info"));
 
@@ -2750,7 +2838,7 @@ remote_threads_extra_info (struct thread_info *tp)
        return NULL;
     }
 
-  if (use_threadextra_query)
+  if (rs->use_threadextra_query)
     {
       char *b = rs->buf;
       char *endb = rs->buf + get_remote_packet_size ();
@@ -2771,7 +2859,7 @@ remote_threads_extra_info (struct thread_info *tp)
     }
 
   /* If the above query fails, fall back to the old method.  */
-  use_threadextra_query = 0;
+  rs->use_threadextra_query = 0;
   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
     | TAG_MOREDISPLAY | TAG_DISPLAY;
   int_to_threadref (&id, ptid_get_tid (tp->ptid));
@@ -2807,7 +2895,7 @@ remote_static_tracepoint_marker_at (CORE_ADDR addr,
   struct remote_state *rs = get_remote_state ();
   char *p = rs->buf;
 
-  sprintf (p, "qTSTMat:");
+  xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
   p += strlen (p);
   p += hexnumstr (p, addr);
   putpkt (rs->buf);
@@ -2826,20 +2914,6 @@ remote_static_tracepoint_marker_at (CORE_ADDR addr,
   return 0;
 }
 
-static void
-free_current_marker (void *arg)
-{
-  struct static_tracepoint_marker **marker_p = arg;
-
-  if (*marker_p != NULL)
-    {
-      release_static_tracepoint_marker (*marker_p);
-      xfree (*marker_p);
-    }
-  else
-    *marker_p = NULL;
-}
-
 static VEC(static_tracepoint_marker_p) *
 remote_static_tracepoint_markers_by_strid (const char *strid)
 {
@@ -2895,7 +2969,7 @@ remote_static_tracepoint_markers_by_strid (const char *strid)
 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
 
 static ptid_t
-remote_get_ada_task_ptid (long lwp, long thread)
+remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
 {
   return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp);
 }
@@ -2919,17 +2993,19 @@ extended_remote_restart (void)
 /* Clean up connection to a remote debugger.  */
 
 static void
-remote_close (int quitting)
+remote_close (struct target_ops *self)
 {
-  if (remote_desc == NULL)
+  struct remote_state *rs = get_remote_state ();
+
+  if (rs->remote_desc == NULL)
     return; /* already closed */
 
   /* Make sure we leave stdin registered in the event loop, and we
      don't leave the async SIGINT signal handler installed.  */
-  remote_terminal_ours ();
+  remote_terminal_ours (self);
 
-  serial_close (remote_desc);
-  remote_desc = NULL;
+  serial_close (rs->remote_desc);
+  rs->remote_desc = NULL;
 
   /* We don't have a connection to the remote stub anymore.  Get rid
      of all the inferiors and their threads we were controlling.
@@ -2938,13 +3014,16 @@ remote_close (int quitting)
   inferior_ptid = null_ptid;
   discard_all_inferiors ();
 
-  /* We're no longer interested in any of these events.  */
-  discard_pending_stop_replies (-1);
+  /* We are closing the remote target, so we should discard
+     everything of this target.  */
+  discard_pending_stop_replies_in_queue (rs);
 
   if (remote_async_inferior_event_token)
     delete_async_event_handler (&remote_async_inferior_event_token);
-  if (remote_async_get_pending_events_token)
-    delete_async_event_handler (&remote_async_get_pending_events_token);
+
+  remote_notif_state_xfree (rs->notif_state);
+
+  trace_reset_local_state ();
 }
 
 /* Query the remote side for the text, data and bss offsets.  */
@@ -3125,14 +3204,16 @@ set_stop_requested_callback (struct thread_info *thread, void *data)
 static void
 send_interrupt_sequence (void)
 {
+  struct remote_state *rs = get_remote_state ();
+
   if (interrupt_sequence_mode == interrupt_sequence_control_c)
-    serial_write (remote_desc, "\x03", 1);
+    remote_serial_write ("\x03", 1);
   else if (interrupt_sequence_mode == interrupt_sequence_break)
-    serial_send_break (remote_desc);
+    serial_send_break (rs->remote_desc);
   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
     {
-      serial_send_break (remote_desc);
-      serial_write (remote_desc, "g", 1);
+      serial_send_break (rs->remote_desc);
+      remote_serial_write ("g", 1);
     }
   else
     internal_error (__FILE__, __LINE__,
@@ -3140,6 +3221,112 @@ send_interrupt_sequence (void)
                    interrupt_sequence_mode);
 }
 
+
+/* If STOP_REPLY is a T stop reply, look for the "thread" register,
+   and extract the PTID.  Returns NULL_PTID if not found.  */
+
+static ptid_t
+stop_reply_extract_thread (char *stop_reply)
+{
+  if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
+    {
+      char *p;
+
+      /* Txx r:val ; r:val (...)  */
+      p = &stop_reply[3];
+
+      /* Look for "register" named "thread".  */
+      while (*p != '\0')
+       {
+         char *p1;
+
+         p1 = strchr (p, ':');
+         if (p1 == NULL)
+           return null_ptid;
+
+         if (strncmp (p, "thread", p1 - p) == 0)
+           return read_ptid (++p1, &p);
+
+         p1 = strchr (p, ';');
+         if (p1 == NULL)
+           return null_ptid;
+         p1++;
+
+         p = p1;
+       }
+    }
+
+  return null_ptid;
+}
+
+/* Determine the remote side's current thread.  If we have a stop
+   reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
+   "thread" register we can extract the current thread from.  If not,
+   ask the remote which is the current thread with qC.  The former
+   method avoids a roundtrip.  */
+
+static ptid_t
+get_current_thread (char *wait_status)
+{
+  ptid_t ptid;
+
+  /* Note we don't use remote_parse_stop_reply as that makes use of
+     the target architecture, which we haven't yet fully determined at
+     this point.  */
+  if (wait_status != NULL)
+    ptid = stop_reply_extract_thread (wait_status);
+  if (ptid_equal (ptid, null_ptid))
+    ptid = remote_current_thread (inferior_ptid);
+
+  return ptid;
+}
+
+/* Query the remote target for which is the current thread/process,
+   add it to our tables, and update INFERIOR_PTID.  The caller is
+   responsible for setting the state such that the remote end is ready
+   to return the current thread.
+
+   This function is called after handling the '?' or 'vRun' packets,
+   whose response is a stop reply from which we can also try
+   extracting the thread.  If the target doesn't support the explicit
+   qC query, we infer the current thread from that stop reply, passed
+   in in WAIT_STATUS, which may be NULL.  */
+
+static void
+add_current_inferior_and_thread (char *wait_status)
+{
+  struct remote_state *rs = get_remote_state ();
+  int fake_pid_p = 0;
+  ptid_t ptid = null_ptid;
+
+  inferior_ptid = null_ptid;
+
+  /* Now, if we have thread information, update inferior_ptid.  */
+  ptid = get_current_thread (wait_status);
+
+  if (!ptid_equal (ptid, null_ptid))
+    {
+      if (!remote_multi_process_p (rs))
+       fake_pid_p = 1;
+
+      inferior_ptid = ptid;
+    }
+  else
+    {
+      /* Without this, some commands which require an active target
+        (such as kill) won't work.  This variable serves (at least)
+        double duty as both the pid of the target process (if it has
+        such), and as a flag indicating that a target is active.  */
+      inferior_ptid = magic_null_ptid;
+      fake_pid_p = 1;
+    }
+
+  remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1);
+
+  /* Add the main thread.  */
+  add_thread_silent (inferior_ptid);
+}
+
 static void
 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
 {
@@ -3148,12 +3335,17 @@ remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
   char *wait_status = NULL;
 
   immediate_quit++;            /* Allow user to interrupt it.  */
+  QUIT;
 
   if (interrupt_on_connect)
     send_interrupt_sequence ();
 
   /* Ack any packet which the remote side has already sent.  */
-  serial_write (remote_desc, "+", 1);
+  serial_write (rs->remote_desc, "+", 1);
+
+  /* Signal other parts that we're going through the initial setup,
+     and so things may not be stable yet.  */
+  rs->starting_up = 1;
 
   /* The first packet we send to the target is the optional "supported
      packets" request.  If the target can answer this, it will tell us
@@ -3196,6 +3388,10 @@ remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
       getpkt (&rs->buf, &rs->buf_size, 0);
     }
 
+  /* Let the target know which signals it is allowed to pass down to
+     the program.  */
+  update_signals_program_target ();
+
   /* Next, if the target can specify a description, read it.  We do
      this before anything involving memory or registers.  */
   target_find_description ();
@@ -3206,7 +3402,7 @@ remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
 
   /* On OSs where the list of libraries is global to all
      processes, we fetch them early.  */
-  if (gdbarch_has_global_solist (target_gdbarch))
+  if (gdbarch_has_global_solist (target_gdbarch ()))
     solib_add (NULL, from_tty, target, auto_solib_add);
 
   if (non_stop)
@@ -3230,7 +3426,7 @@ remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
   else if (rs->non_stop_aware)
     {
       /* Don't assume that the stub can operate in all-stop mode.
-        Request it explicitely.  */
+        Request it explicitly.  */
       putpkt ("QNonStop:0");
       getpkt (&rs->buf, &rs->buf_size, 0);
 
@@ -3238,12 +3434,27 @@ remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
        error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
     }
 
+  /* Upload TSVs regardless of whether the target is running or not.  The
+     remote stub, such as GDBserver, may have some predefined or builtin
+     TSVs, even if the target is not running.  */
+  if (remote_get_trace_status (current_trace_status ()) != -1)
+    {
+      struct uploaded_tsv *uploaded_tsvs = NULL;
+
+      remote_upload_trace_state_variables (&uploaded_tsvs);
+      merge_uploaded_trace_state_variables (&uploaded_tsvs);
+    }
+
   /* Check whether the target is running now.  */
   putpkt ("?");
   getpkt (&rs->buf, &rs->buf_size, 0);
 
   if (!non_stop)
     {
+      ptid_t ptid;
+      int fake_pid_p = 0;
+      struct inferior *inf;
+
       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
        {
          if (!extended_p)
@@ -3251,6 +3462,7 @@ remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
 
          /* We're connected, but not running.  Drop out before we
             call start_remote.  */
+         rs->starting_up = 0;
          return;
        }
       else
@@ -3260,25 +3472,46 @@ remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
          strcpy (wait_status, rs->buf);
        }
 
+      /* Fetch thread list.  */
+      target_find_new_threads ();
+
       /* Let the stub know that we want it to return the thread.  */
       set_continue_thread (minus_one_ptid);
 
-      /* Without this, some commands which require an active target
-        (such as kill) won't work.  This variable serves (at least)
-        double duty as both the pid of the target process (if it has
-        such), and as a flag indicating that a target is active.
-        These functions should be split out into seperate variables,
-        especially since GDB will someday have a notion of debugging
-        several processes.  */
-      inferior_ptid = magic_null_ptid;
-
-      /* Now, if we have thread information, update inferior_ptid.  */
-      inferior_ptid = remote_current_thread (inferior_ptid);
-
-      remote_add_inferior (ptid_get_pid (inferior_ptid), -1);
+      if (thread_count () == 0)
+       {
+         /* Target has no concept of threads at all.  GDB treats
+            non-threaded target as single-threaded; add a main
+            thread.  */
+         add_current_inferior_and_thread (wait_status);
+       }
+      else
+       {
+         /* We have thread information; select the thread the target
+            says should be current.  If we're reconnecting to a
+            multi-threaded program, this will ideally be the thread
+            that last reported an event before GDB disconnected.  */
+         inferior_ptid = get_current_thread (wait_status);
+         if (ptid_equal (inferior_ptid, null_ptid))
+           {
+             /* Odd... The target was able to list threads, but not
+                tell us which thread was current (no "thread"
+                register in T stop reply?).  Just pick the first
+                thread in the thread list then.  */
+             inferior_ptid = thread_list->ptid;
+           }
+       }
 
-      /* Always add the main thread.  */
-      add_thread_silent (inferior_ptid);
+      /* init_wait_for_inferior should be called before get_offsets in order
+        to manage `inserted' flag in bp loc in a correct state.
+        breakpoint_init_inferior, called from init_wait_for_inferior, set
+        `inserted' flag to 0, while before breakpoint_re_set, called from
+        start_remote, set `inserted' flag to 1.  In the initialization of
+        inferior, breakpoint_init_inferior should be called first, and then
+        breakpoint_re_set can be called.  If this order is broken, state of
+        `inserted' flag is wrong, and cause some problems on breakpoint
+        manipulation.  */
+      init_wait_for_inferior ();
 
       get_offsets ();          /* Get text, data & bss offsets.  */
 
@@ -3287,7 +3520,7 @@ remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
         supported for non-stop; it could be, but it is tricky if
         there are no stopped threads when we connect.  */
       if (remote_read_description_p (target)
-         && gdbarch_target_desc (target_gdbarch) == NULL)
+         && gdbarch_target_desc (target_gdbarch ()) == NULL)
        {
          target_clear_description ();
          target_find_description ();
@@ -3317,19 +3550,13 @@ remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
         mechanism.  */
       if (strcmp (rs->buf, "OK") != 0)
        {
-         struct stop_reply *stop_reply;
-         struct cleanup *old_chain;
-
-         stop_reply = stop_reply_xmalloc ();
-         old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
+         struct notif_client *notif = &notif_client_stop;
 
-         remote_parse_stop_reply (rs->buf, stop_reply);
-         discard_cleanups (old_chain);
-
-         /* get_pending_stop_replies acks this one, and gets the rest
-            out.  */
-         pending_stop_reply = stop_reply;
-         remote_get_pending_stop_replies ();
+         /* remote_notif_get_pending_replies acks this one, and gets
+            the rest out.  */
+         rs->notif_state->pending_event[notif_client_stop.id]
+           = remote_notif_parse (notif, rs->buf);
+         remote_notif_get_pending_events (notif);
 
          /* Make sure that threads that were stopped remain
             stopped.  */
@@ -3346,6 +3573,7 @@ remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
 
          /* We're connected, but not running.  Drop out before we
             call start_remote.  */
+         rs->starting_up = 0;
          return;
        }
 
@@ -3366,14 +3594,14 @@ remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
       gdb_assert (wait_status == NULL);
 
       /* Report all signals during attach/startup.  */
-      remote_pass_signals (0, NULL);
+      remote_pass_signals (target, 0, NULL);
     }
 
   /* If we connected to a live target, do some additional setup.  */
   if (target_has_execution)
     {
-      if (exec_bfd)    /* No use without an exec file.  */
-       remote_check_symbols (symfile_objfile);
+      if (symfile_objfile)     /* No use without a symbol-file.  */
+       remote_check_symbols ();
     }
 
   /* Possibly the target has been engaged in a trace run started
@@ -3381,25 +3609,23 @@ remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
   if (remote_get_trace_status (current_trace_status ()) != -1)
     {
       struct uploaded_tp *uploaded_tps = NULL;
-      struct uploaded_tsv *uploaded_tsvs = NULL;
 
       if (current_trace_status ()->running)
        printf_filtered (_("Trace is already running on the target.\n"));
 
-      /* Get trace state variables first, they may be checked when
-        parsing uploaded commands.  */
-
-      remote_upload_trace_state_variables (&uploaded_tsvs);
-
-      merge_uploaded_trace_state_variables (&uploaded_tsvs);
-
       remote_upload_tracepoints (&uploaded_tps);
 
       merge_uploaded_tracepoints (&uploaded_tps);
     }
 
+  /* The thread and inferior lists are now synchronized with the
+     target, our symbols have been relocated, and we're merged the
+     target's tracepoints with ours.  We're done with basic start
+     up.  */
+  rs->starting_up = 0;
+
   /* If breakpoints are global, insert them now.  */
-  if (gdbarch_has_global_breakpoints (target_gdbarch)
+  if (gdbarch_has_global_breakpoints (target_gdbarch ())
       && breakpoints_always_inserted_mode ())
     insert_breakpoints ();
 }
@@ -3436,7 +3662,7 @@ init_all_packet_configs (void)
 /* Symbol look-up.  */
 
 static void
-remote_check_symbols (struct objfile *objfile)
+remote_check_symbols (void)
 {
   struct remote_state *rs = get_remote_state ();
   char *msg, *reply, *tmp;
@@ -3479,12 +3705,12 @@ remote_check_symbols (struct objfile *objfile)
        xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
       else
        {
-         int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
+         int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
          CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
 
          /* If this is a function address, return the start of code
             instead of any data function descriptor.  */
-         sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch,
+         sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
                                                         sym_addr,
                                                         &current_target);
 
@@ -3532,13 +3758,13 @@ remote_set_permissions (void)
 {
   struct remote_state *rs = get_remote_state ();
 
-  sprintf (rs->buf, "QAllow:"
-          "WriteReg:%x;WriteMem:%x;"
-          "InsertBreak:%x;InsertTrace:%x;"
-          "InsertFastTrace:%x;Stop:%x",
-          may_write_registers, may_write_memory,
-          may_insert_breakpoints, may_insert_tracepoints,
-          may_insert_fast_tracepoints, may_stop);
+  xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
+            "WriteReg:%x;WriteMem:%x;"
+            "InsertBreak:%x;InsertTrace:%x;"
+            "InsertFastTrace:%x;Stop:%x",
+            may_write_registers, may_write_memory,
+            may_insert_breakpoints, may_insert_tracepoints,
+            may_insert_fast_tracepoints, may_stop);
   putpkt (rs->buf);
   getpkt (&rs->buf, &rs->buf_size, 0);
 
@@ -3659,6 +3885,26 @@ remote_cond_tracepoint_feature (const struct protocol_feature *feature,
   rs->cond_tracepoints = (support == PACKET_ENABLE);
 }
 
+static void
+remote_cond_breakpoint_feature (const struct protocol_feature *feature,
+                               enum packet_support support,
+                               const char *value)
+{
+  struct remote_state *rs = get_remote_state ();
+
+  rs->cond_breakpoints = (support == PACKET_ENABLE);
+}
+
+static void
+remote_breakpoint_commands_feature (const struct protocol_feature *feature,
+                                   enum packet_support support,
+                                   const char *value)
+{
+  struct remote_state *rs = get_remote_state ();
+
+  rs->breakpoint_commands = (support == PACKET_ENABLE);
+}
+
 static void
 remote_fast_tracepoint_feature (const struct protocol_feature *feature,
                                enum packet_support support,
@@ -3679,6 +3925,16 @@ remote_static_tracepoint_feature (const struct protocol_feature *feature,
   rs->static_tracepoints = (support == PACKET_ENABLE);
 }
 
+static void
+remote_install_in_trace_feature (const struct protocol_feature *feature,
+                                enum packet_support support,
+                                const char *value)
+{
+  struct remote_state *rs = get_remote_state ();
+
+  rs->install_in_trace = (support == PACKET_ENABLE);
+}
+
 static void
 remote_disconnected_tracing_feature (const struct protocol_feature *feature,
                                     enum packet_support support,
@@ -3689,7 +3945,37 @@ remote_disconnected_tracing_feature (const struct protocol_feature *feature,
   rs->disconnected_tracing = (support == PACKET_ENABLE);
 }
 
-static struct protocol_feature remote_protocol_features[] = {
+static void
+remote_enable_disable_tracepoint_feature (const struct protocol_feature *feature,
+                                         enum packet_support support,
+                                         const char *value)
+{
+  struct remote_state *rs = get_remote_state ();
+
+  rs->enable_disable_tracepoints = (support == PACKET_ENABLE);
+}
+
+static void
+remote_string_tracing_feature (const struct protocol_feature *feature,
+                              enum packet_support support,
+                              const char *value)
+{
+  struct remote_state *rs = get_remote_state ();
+
+  rs->string_tracing = (support == PACKET_ENABLE);
+}
+
+static void
+remote_augmented_libraries_svr4_read_feature
+  (const struct protocol_feature *feature,
+   enum packet_support support, const char *value)
+{
+  struct remote_state *rs = get_remote_state ();
+
+  rs->augmented_libraries_svr4_read = (support == PACKET_ENABLE);
+}
+
+static const struct protocol_feature remote_protocol_features[] = {
   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
     PACKET_qXfer_auxv },
@@ -3697,6 +3983,10 @@ static struct protocol_feature remote_protocol_features[] = {
     PACKET_qXfer_features },
   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
     PACKET_qXfer_libraries },
+  { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
+    PACKET_qXfer_libraries_svr4 },
+  { "augmented-libraries-svr4-read", PACKET_DISABLE,
+    remote_augmented_libraries_svr4_read_feature, -1 },
   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
     PACKET_qXfer_memory_map },
   { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
@@ -3711,6 +4001,8 @@ static struct protocol_feature remote_protocol_features[] = {
     PACKET_qXfer_traceframe_info },
   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
     PACKET_QPassSignals },
+  { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
+    PACKET_QProgramSignals },
   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
     PACKET_QStartNoAckMode },
   { "multiprocess", PACKET_DISABLE, remote_multi_process_feature, -1 },
@@ -3721,10 +4013,16 @@ static struct protocol_feature remote_protocol_features[] = {
     PACKET_qXfer_siginfo_write },
   { "ConditionalTracepoints", PACKET_DISABLE, remote_cond_tracepoint_feature,
     PACKET_ConditionalTracepoints },
+  { "ConditionalBreakpoints", PACKET_DISABLE, remote_cond_breakpoint_feature,
+    PACKET_ConditionalBreakpoints },
+  { "BreakpointCommands", PACKET_DISABLE, remote_breakpoint_commands_feature,
+    PACKET_BreakpointCommands },
   { "FastTracepoints", PACKET_DISABLE, remote_fast_tracepoint_feature,
     PACKET_FastTracepoints },
   { "StaticTracepoints", PACKET_DISABLE, remote_static_tracepoint_feature,
     PACKET_StaticTracepoints },
+  {"InstallInTrace", PACKET_DISABLE, remote_install_in_trace_feature,
+   PACKET_InstallInTrace},
   { "DisconnectedTracing", PACKET_DISABLE, remote_disconnected_tracing_feature,
     -1 },
   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
@@ -3735,6 +4033,23 @@ static struct protocol_feature remote_protocol_features[] = {
     PACKET_TracepointSource },
   { "QAllow", PACKET_DISABLE, remote_supported_packet,
     PACKET_QAllow },
+  { "EnableDisableTracepoints", PACKET_DISABLE,
+    remote_enable_disable_tracepoint_feature, -1 },
+  { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
+    PACKET_qXfer_fdpic },
+  { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
+    PACKET_qXfer_uib },
+  { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
+    PACKET_QDisableRandomization },
+  { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
+  { "QTBuffer:size", PACKET_DISABLE,
+    remote_supported_packet, PACKET_QTBuffer_size},
+  { "tracenz", PACKET_DISABLE,
+    remote_string_tracing_feature, -1 },
+  { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
+  { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
+  { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
+    PACKET_qXfer_btrace }
 };
 
 static char *remote_support_xml;
@@ -3801,8 +4116,7 @@ remote_query_supported (void)
       char *q = NULL;
       struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
 
-      if (rs->extended)
-       q = remote_query_supported_append (q, "multiprocess+");
+      q = remote_query_supported_append (q, "multiprocess+");
 
       if (remote_support_xml)
        q = remote_query_supported_append (q, remote_support_xml);
@@ -3922,6 +4236,14 @@ remote_query_supported (void)
       }
 }
 
+/* Remove any of the remote.c targets from target stack.  Upper targets depend
+   on it so remove them first.  */
+
+static void
+remote_unpush_target (void)
+{
+  pop_all_targets_above (process_stratum - 1);
+}
 
 static void
 remote_open_1 (char *name, int from_tty,
@@ -3939,61 +4261,54 @@ remote_open_1 (char *name, int from_tty,
     wait_forever_enabled_p = 1;
 
   /* If we're connected to a running target, target_preopen will kill it.
-     But if we're connected to a target system with no running process,
-     then we will still be connected when it returns.  Ask this question
-     first, before target_preopen has a chance to kill anything.  */
-  if (remote_desc != NULL && !have_inferiors ())
-    {
-      if (!from_tty
-         || query (_("Already connected to a remote target.  Disconnect? ")))
-       pop_target ();
-      else
+     Ask this question first, before target_preopen has a chance to kill
+     anything.  */
+  if (rs->remote_desc != NULL && !have_inferiors ())
+    {
+      if (from_tty
+         && !query (_("Already connected to a remote target.  Disconnect? ")))
        error (_("Still connected."));
     }
 
+  /* Here the possibly existing remote target gets unpushed.  */
   target_preopen (from_tty);
 
-  unpush_target (target);
-
-  /* This time without a query.  If we were connected to an
-     extended-remote target and target_preopen killed the running
-     process, we may still be connected.  If we are starting "target
-     remote" now, the extended-remote target will not have been
-     removed by unpush_target.  */
-  if (remote_desc != NULL && !have_inferiors ())
-    pop_target ();
-
   /* Make sure we send the passed signals list the next time we resume.  */
-  xfree (last_pass_packet);
-  last_pass_packet = NULL;
+  xfree (rs->last_pass_packet);
+  rs->last_pass_packet = NULL;
+
+  /* Make sure we send the program signals list the next time we
+     resume.  */
+  xfree (rs->last_program_signals_packet);
+  rs->last_program_signals_packet = NULL;
 
   remote_fileio_reset ();
   reopen_exec_file ();
   reread_symbols ();
 
-  remote_desc = remote_serial_open (name);
-  if (!remote_desc)
+  rs->remote_desc = remote_serial_open (name);
+  if (!rs->remote_desc)
     perror_with_name (name);
 
   if (baud_rate != -1)
     {
-      if (serial_setbaudrate (remote_desc, baud_rate))
+      if (serial_setbaudrate (rs->remote_desc, baud_rate))
        {
          /* The requested speed could not be set.  Error out to
             top level after closing remote_desc.  Take care to
             set remote_desc to NULL to avoid closing remote_desc
             more than once.  */
-         serial_close (remote_desc);
-         remote_desc = NULL;
+         serial_close (rs->remote_desc);
+         rs->remote_desc = NULL;
          perror_with_name (name);
        }
     }
 
-  serial_raw (remote_desc);
+  serial_raw (rs->remote_desc);
 
   /* If there is something sitting in the buffer we might take it as a
      response to a command, which would be bad.  */
-  serial_flush_input (remote_desc);
+  serial_flush_input (rs->remote_desc);
 
   if (from_tty)
     {
@@ -4007,9 +4322,7 @@ remote_open_1 (char *name, int from_tty,
   remote_async_inferior_event_token
     = create_async_event_handler (remote_async_inferior_event_handler,
                                  NULL);
-  remote_async_get_pending_events_token
-    = create_async_event_handler (remote_async_get_pending_events_handler,
-                                 NULL);
+  rs->notif_state = remote_notif_state_allocate ();
 
   /* Reset the target state; these things will be queried either by
      remote_query_supported or as they are needed.  */
@@ -4023,13 +4336,13 @@ remote_open_1 (char *name, int from_tty,
   rs->waiting_for_stop_reply = 0;
   rs->ctrlc_pending_p = 0;
 
-  general_thread = not_sent_ptid;
-  continue_thread = not_sent_ptid;
-  remote_traceframe_number = -1;
+  rs->general_thread = not_sent_ptid;
+  rs->continue_thread = not_sent_ptid;
+  rs->remote_traceframe_number = -1;
 
   /* Probe for ability to use "ThreadInfo" query, as required.  */
-  use_threadinfo_query = 1;
-  use_threadextra_query = 1;
+  rs->use_threadinfo_query = 1;
+  rs->use_threadextra_query = 1;
 
   if (target_async_permitted)
     {
@@ -4078,8 +4391,8 @@ remote_open_1 (char *name, int from_tty,
       {
        /* Pop the partially set up target - unless something else did
           already before throwing the exception.  */
-       if (remote_desc != NULL)
-         pop_target ();
+       if (rs->remote_desc != NULL)
+         remote_unpush_target ();
        if (target_async_permitted)
          wait_forever_enabled_p = 1;
        throw_exception (ex);
@@ -4096,7 +4409,7 @@ remote_open_1 (char *name, int from_tty,
    die when it hits one.  */
 
 static void
-remote_detach_1 (char *args, int from_tty, int extended)
+remote_detach_1 (const char *args, int from_tty, int extended)
 {
   int pid = ptid_get_pid (inferior_ptid);
   struct remote_state *rs = get_remote_state ();
@@ -4107,9 +4420,19 @@ remote_detach_1 (char *args, int from_tty, int extended)
   if (!target_has_execution)
     error (_("No process to detach from."));
 
+  if (from_tty)
+    {
+      char *exec_file = get_exec_file (0);
+      if (exec_file == NULL)
+       exec_file = "";
+      printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
+                        target_pid_to_str (pid_to_ptid (pid)));
+      gdb_flush (gdb_stdout);
+    }
+
   /* Tell the remote target to detach.  */
   if (remote_multi_process_p (rs))
-    sprintf (rs->buf, "D;%x", pid);
+    xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
   else
     strcpy (rs->buf, "D");
 
@@ -4123,32 +4446,20 @@ remote_detach_1 (char *args, int from_tty, int extended)
   else
     error (_("Can't detach process."));
 
-  if (from_tty)
-    {
-      if (remote_multi_process_p (rs))
-       printf_filtered (_("Detached from remote %s.\n"),
-                        target_pid_to_str (pid_to_ptid (pid)));
-      else
-       {
-         if (extended)
-           puts_filtered (_("Detached from remote process.\n"));
-         else
-           puts_filtered (_("Ending remote debugging.\n"));
-       }
-    }
+  if (from_tty && !extended)
+    puts_filtered (_("Ending remote debugging.\n"));
 
-  discard_pending_stop_replies (pid);
   target_mourn_inferior ();
 }
 
 static void
-remote_detach (struct target_ops *ops, char *args, int from_tty)
+remote_detach (struct target_ops *ops, const char *args, int from_tty)
 {
   remote_detach_1 (args, from_tty, 0);
 }
 
 static void
-extended_remote_detach (struct target_ops *ops, char *args, int from_tty)
+extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
 {
   remote_detach_1 (args, from_tty, 1);
 }
@@ -4188,17 +4499,27 @@ extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
   if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
     error (_("This target does not support attaching to a process"));
 
-  sprintf (rs->buf, "vAttach;%x", pid);
+  if (from_tty)
+    {
+      char *exec_file = get_exec_file (0);
+
+      if (exec_file)
+       printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
+                          target_pid_to_str (pid_to_ptid (pid)));
+      else
+       printf_unfiltered (_("Attaching to %s\n"),
+                          target_pid_to_str (pid_to_ptid (pid)));
+
+      gdb_flush (gdb_stdout);
+    }
+
+  xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
   putpkt (rs->buf);
   getpkt (&rs->buf, &rs->buf_size, 0);
 
   if (packet_ok (rs->buf,
                 &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
     {
-      if (from_tty)
-       printf_unfiltered (_("Attached to %s\n"),
-                          target_pid_to_str (pid_to_ptid (pid)));
-
       if (!non_stop)
        {
          /* Save the reply for later.  */
@@ -4216,7 +4537,7 @@ extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
     error (_("Attaching to %s failed"),
           target_pid_to_str (pid_to_ptid (pid)));
 
-  set_current_inferior (remote_add_inferior (pid, 1));
+  set_current_inferior (remote_add_inferior (0, pid, 1));
 
   inferior_ptid = pid_to_ptid (pid);
 
@@ -4234,7 +4555,7 @@ extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
        inferior_ptid = pid_to_ptid (pid);
 
       /* Invalidate our notion of the remote current thread.  */
-      record_currthread (minus_one_ptid);
+      record_currthread (rs, minus_one_ptid);
     }
   else
     {
@@ -4256,14 +4577,10 @@ extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
 
       if (target_can_async_p ())
        {
-         struct stop_reply *stop_reply;
-         struct cleanup *old_chain;
+         struct notif_event *reply
+           =  remote_notif_parse (&notif_client_stop, wait_status);
 
-         stop_reply = stop_reply_xmalloc ();
-         old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
-         remote_parse_stop_reply (wait_status, stop_reply);
-         discard_cleanups (old_chain);
-         push_stop_reply (stop_reply);
+         push_stop_reply ((struct stop_reply *) reply);
 
          target_async (inferior_event_handler, 0);
        }
@@ -4284,68 +4601,6 @@ extended_remote_attach (struct target_ops *ops, char *args, int from_tty)
   extended_remote_attach_1 (ops, args, from_tty);
 }
 
-/* Convert hex digit A to a number.  */
-
-static int
-fromhex (int a)
-{
-  if (a >= '0' && a <= '9')
-    return a - '0';
-  else if (a >= 'a' && a <= 'f')
-    return a - 'a' + 10;
-  else if (a >= 'A' && a <= 'F')
-    return a - 'A' + 10;
-  else
-    error (_("Reply contains invalid hex digit %d"), a);
-}
-
-int
-hex2bin (const char *hex, gdb_byte *bin, int count)
-{
-  int i;
-
-  for (i = 0; i < count; i++)
-    {
-      if (hex[0] == 0 || hex[1] == 0)
-       {
-         /* Hex string is short, or of uneven length.
-            Return the count that has been converted so far.  */
-         return i;
-       }
-      *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
-      hex += 2;
-    }
-  return i;
-}
-
-/* Convert number NIB to a hex digit.  */
-
-static int
-tohex (int nib)
-{
-  if (nib < 10)
-    return '0' + nib;
-  else
-    return 'a' + nib - 10;
-}
-
-int
-bin2hex (const gdb_byte *bin, char *hex, int count)
-{
-  int i;
-
-  /* May use a length, or a nul-terminated string as input.  */
-  if (count == 0)
-    count = strlen ((char *) bin);
-
-  for (i = 0; i < count; i++)
-    {
-      *hex++ = tohex ((*bin >> 4) & 0xf);
-      *hex++ = tohex (*bin++ & 0xf);
-    }
-  *hex = 0;
-  return i;
-}
 \f
 /* Check for the availability of vCont.  This function should also check
    the response.  */
@@ -4370,7 +4625,8 @@ remote_vcont_probe (struct remote_state *rs)
       support_S = 0;
       support_c = 0;
       support_C = 0;
-      rs->support_vCont_t = 0;
+      rs->supports_vCont.t = 0;
+      rs->supports_vCont.r = 0;
       while (p && *p == ';')
        {
          p++;
@@ -4383,7 +4639,9 @@ remote_vcont_probe (struct remote_state *rs)
          else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
            support_C = 1;
          else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
-           rs->support_vCont_t = 1;
+           rs->supports_vCont.t = 1;
+         else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
+           rs->supports_vCont.r = 1;
 
          p = strchr (p, ';');
        }
@@ -4409,15 +4667,51 @@ remote_vcont_probe (struct remote_state *rs)
 
 static char *
 append_resumption (char *p, char *endp,
-                  ptid_t ptid, int step, enum target_signal siggnal)
+                  ptid_t ptid, int step, enum gdb_signal siggnal)
 {
   struct remote_state *rs = get_remote_state ();
 
-  if (step && siggnal != TARGET_SIGNAL_0)
+  if (step && siggnal != GDB_SIGNAL_0)
     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
+  else if (step
+          /* GDB is willing to range step.  */
+          && use_range_stepping
+          /* Target supports range stepping.  */
+          && rs->supports_vCont.r
+          /* We don't currently support range stepping multiple
+             threads with a wildcard (though the protocol allows it,
+             so stubs shouldn't make an active effort to forbid
+             it).  */
+          && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
+    {
+      struct thread_info *tp;
+
+      if (ptid_equal (ptid, minus_one_ptid))
+       {
+         /* If we don't know about the target thread's tid, then
+            we're resuming magic_null_ptid (see caller).  */
+         tp = find_thread_ptid (magic_null_ptid);
+       }
+      else
+       tp = find_thread_ptid (ptid);
+      gdb_assert (tp != NULL);
+
+      if (tp->control.may_range_step)
+       {
+         int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
+
+         p += xsnprintf (p, endp - p, ";r%s,%s",
+                         phex_nz (tp->control.step_range_start,
+                                  addr_size),
+                         phex_nz (tp->control.step_range_end,
+                                  addr_size));
+       }
+      else
+       p += xsnprintf (p, endp - p, ";s");
+    }
   else if (step)
     p += xsnprintf (p, endp - p, ";s");
-  else if (siggnal != TARGET_SIGNAL_0)
+  else if (siggnal != GDB_SIGNAL_0)
     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
   else
     p += xsnprintf (p, endp - p, ";c");
@@ -4441,6 +4735,28 @@ append_resumption (char *p, char *endp,
   return p;
 }
 
+/* Append a vCont continue-with-signal action for threads that have a
+   non-zero stop signal.  */
+
+static char *
+append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
+{
+  struct thread_info *thread;
+
+  ALL_THREADS (thread)
+    if (ptid_match (thread->ptid, ptid)
+       && !ptid_equal (inferior_ptid, thread->ptid)
+       && thread->suspend.stop_signal != GDB_SIGNAL_0
+       && signal_pass_state (thread->suspend.stop_signal))
+      {
+       p = append_resumption (p, endp, thread->ptid,
+                              0, thread->suspend.stop_signal);
+       thread->suspend.stop_signal = GDB_SIGNAL_0;
+      }
+
+  return p;
+}
+
 /* Resume the remote inferior by using a "vCont" packet.  The thread
    to be resumed is PTID; STEP and SIGGNAL indicate whether the
    resumed thread should be single-stepped and/or signalled.  If PTID
@@ -4452,7 +4768,7 @@ append_resumption (char *p, char *endp,
    moment.  */
 
 static int
-remote_vcont_resume (ptid_t ptid, int step, enum target_signal siggnal)
+remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
 {
   struct remote_state *rs = get_remote_state ();
   char *p;
@@ -4487,14 +4803,18 @@ remote_vcont_resume (ptid_t ptid, int step, enum target_signal siggnal)
         process), with preference for INFERIOR_PTID.  This assumes
         inferior_ptid belongs to the set of all threads we are about
         to resume.  */
-      if (step || siggnal != TARGET_SIGNAL_0)
+      if (step || siggnal != GDB_SIGNAL_0)
        {
          /* Step inferior_ptid, with or without signal.  */
          p = append_resumption (p, endp, inferior_ptid, step, siggnal);
        }
 
+      /* Also pass down any pending signaled resumption for other
+        threads not the current.  */
+      p = append_pending_thread_resumptions (p, endp, ptid);
+
       /* And continue others without a signal.  */
-      append_resumption (p, endp, ptid, /*step=*/ 0, TARGET_SIGNAL_0);
+      append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
     }
   else
     {
@@ -4520,19 +4840,24 @@ remote_vcont_resume (ptid_t ptid, int step, enum target_signal siggnal)
 
 /* Tell the remote machine to resume.  */
 
-static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
-
-static int last_sent_step;
-
 static void
 remote_resume (struct target_ops *ops,
-              ptid_t ptid, int step, enum target_signal siggnal)
+              ptid_t ptid, int step, enum gdb_signal siggnal)
 {
   struct remote_state *rs = get_remote_state ();
   char *buf;
 
-  last_sent_signal = siggnal;
-  last_sent_step = step;
+  /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
+     (explained in remote-notif.c:handle_notification) so
+     remote_notif_process is not called.  We need find a place where
+     it is safe to start a 'vNotif' sequence.  It is good to do it
+     before resuming inferior, because inferior was stopped and no RSP
+     traffic at that moment.  */
+  if (!non_stop)
+    remote_notif_process (rs->notif_state, &notif_client_stop);
+
+  rs->last_sent_signal = siggnal;
+  rs->last_sent_step = step;
 
   /* The vCont packet doesn't need to specify threads via Hc.  */
   /* No reverse support (yet) for vCont.  */
@@ -4551,7 +4876,7 @@ remote_resume (struct target_ops *ops,
   if (execution_direction == EXEC_REVERSE)
     {
       /* We don't pass signals to the target in reverse exec mode.  */
-      if (info_verbose && siggnal != TARGET_SIGNAL_0)
+      if (info_verbose && siggnal != GDB_SIGNAL_0)
        warning (_(" - Can't pass signal %d to target in reverse: ignored."),
                 siggnal);
 
@@ -4564,7 +4889,7 @@ remote_resume (struct target_ops *ops,
 
       strcpy (buf, step ? "bs" : "bc");
     }
-  else if (siggnal != TARGET_SIGNAL_0)
+  else if (siggnal != GDB_SIGNAL_0)
     {
       buf[0] = step ? 'S' : 'C';
       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
@@ -4602,27 +4927,27 @@ remote_resume (struct target_ops *ops,
 /* Set up the signal handler for SIGINT, while the target is
    executing, ovewriting the 'regular' SIGINT signal handler.  */
 static void
-initialize_sigint_signal_handler (void)
+async_initialize_sigint_signal_handler (void)
 {
-  signal (SIGINT, handle_remote_sigint);
+  signal (SIGINT, async_handle_remote_sigint);
 }
 
 /* Signal handler for SIGINT, while the target is executing.  */
 static void
-handle_remote_sigint (int sig)
+async_handle_remote_sigint (int sig)
 {
-  signal (sig, handle_remote_sigint_twice);
-  mark_async_signal_handler_wrapper (sigint_remote_token);
+  signal (sig, async_handle_remote_sigint_twice);
+  mark_async_signal_handler (async_sigint_remote_token);
 }
 
 /* Signal handler for SIGINT, installed after SIGINT has already been
    sent once.  It will take effect the second time that the user sends
    a ^C.  */
 static void
-handle_remote_sigint_twice (int sig)
+async_handle_remote_sigint_twice (int sig)
 {
-  signal (sig, handle_remote_sigint);
-  mark_async_signal_handler_wrapper (sigint_remote_twice_token);
+  signal (sig, async_handle_remote_sigint);
+  mark_async_signal_handler (async_sigint_remote_twice_token);
 }
 
 /* Perform the real interruption of the target execution, in response
@@ -4631,18 +4956,18 @@ static void
 async_remote_interrupt (gdb_client_data arg)
 {
   if (remote_debug)
-    fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
+    fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
 
   target_stop (inferior_ptid);
 }
 
 /* Perform interrupt, if the first attempt did not succeed.  Just give
    up on the target alltogether.  */
-void
+static void
 async_remote_interrupt_twice (gdb_client_data arg)
 {
   if (remote_debug)
-    fprintf_unfiltered (gdb_stdlog, "remote_interrupt_twice called\n");
+    fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
 
   interrupt_query ();
 }
@@ -4650,7 +4975,7 @@ async_remote_interrupt_twice (gdb_client_data arg)
 /* Reinstall the usual SIGINT handlers, after the target has
    stopped.  */
 static void
-cleanup_sigint_signal_handler (void *dummy)
+async_cleanup_sigint_signal_handler (void *dummy)
 {
   signal (SIGINT, handle_sigint);
 }
@@ -4665,22 +4990,22 @@ static void (*ofunc) (int);
    response from the target (it didn't stop when the user requested it),
    we ask the user if he'd like to detach from the target.  */
 static void
-remote_interrupt (int signo)
+sync_remote_interrupt (int signo)
 {
   /* If this doesn't work, try more severe steps.  */
-  signal (signo, remote_interrupt_twice);
+  signal (signo, sync_remote_interrupt_twice);
 
-  gdb_call_async_signal_handler (sigint_remote_token, 1);
+  gdb_call_async_signal_handler (async_sigint_remote_token, 1);
 }
 
 /* The user typed ^C twice.  */
 
 static void
-remote_interrupt_twice (int signo)
+sync_remote_interrupt_twice (int signo)
 {
   signal (signo, ofunc);
-  gdb_call_async_signal_handler (sigint_remote_twice_token, 1);
-  signal (signo, remote_interrupt);
+  gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
+  signal (signo, sync_remote_interrupt);
 }
 
 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
@@ -4697,7 +5022,7 @@ remote_stop_ns (ptid_t ptid)
   if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
     remote_vcont_probe (rs);
 
-  if (!rs->support_vCont_t)
+  if (!rs->supports_vCont.t)
     error (_("Remote server does not support stopping threads"));
 
   if (ptid_equal (ptid, minus_one_ptid)
@@ -4760,7 +5085,7 @@ remote_stop_as (ptid_t ptid)
    will eventually end up here.  */
 
 static void
-remote_stop (ptid_t ptid)
+remote_stop (struct target_ops *self, ptid_t ptid)
 {
   if (remote_debug)
     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
@@ -4781,15 +5106,15 @@ interrupt_query (void)
   if (target_can_async_p ())
     {
       signal (SIGINT, handle_sigint);
-      deprecated_throw_reason (RETURN_QUIT);
+      quit ();
     }
   else
     {
       if (query (_("Interrupted while waiting for the program.\n\
 Give up (and stop debugging it)? ")))
        {
-         pop_target ();
-         deprecated_throw_reason (RETURN_QUIT);
+         remote_unpush_target ();
+         quit ();
        }
     }
 
@@ -4802,7 +5127,7 @@ Give up (and stop debugging it)? ")))
    is required.  */
 
 static void
-remote_terminal_inferior (void)
+remote_terminal_inferior (struct target_ops *self)
 {
   if (!target_async_permitted)
     /* Nothing to do.  */
@@ -4818,14 +5143,14 @@ remote_terminal_inferior (void)
     return;
   delete_file_handler (input_fd);
   remote_async_terminal_ours_p = 0;
-  initialize_sigint_signal_handler ();
+  async_initialize_sigint_signal_handler ();
   /* NOTE: At this point we could also register our selves as the
      recipient of all input.  Any characters typed could then be
      passed on down to the target.  */
 }
 
 static void
-remote_terminal_ours (void)
+remote_terminal_ours (struct target_ops *self)
 {
   if (!target_async_permitted)
     /* Nothing to do.  */
@@ -4834,7 +5159,7 @@ remote_terminal_ours (void)
   /* See FIXME in remote_terminal_inferior.  */
   if (remote_async_terminal_ours_p)
     return;
-  cleanup_sigint_signal_handler (NULL);
+  async_cleanup_sigint_signal_handler (NULL);
   add_file_handler (input_fd, stdin_event_handler, 0);
   remote_async_terminal_ours_p = 1;
 }
@@ -4853,8 +5178,8 @@ remote_console_output (char *msg)
       tb[1] = 0;
       fputs_unfiltered (tb, gdb_stdtarg);
     }
-    gdb_flush (gdb_stdtarg);
-  }
+  gdb_flush (gdb_stdtarg);
+}
 
 typedef struct cached_reg
 {
@@ -4864,92 +5189,254 @@ typedef struct cached_reg
 
 DEF_VEC_O(cached_reg_t);
 
-struct stop_reply
+typedef struct stop_reply
 {
-  struct stop_reply *next;
+  struct notif_event base;
 
+  /* The identifier of the thread about this event  */
   ptid_t ptid;
 
+  /* The remote state this event is associated with.  When the remote
+     connection, represented by a remote_state object, is closed,
+     all the associated stop_reply events should be released.  */
+  struct remote_state *rs;
+
   struct target_waitstatus ws;
 
+  /* Expedited registers.  This makes remote debugging a bit more
+     efficient for those targets that provide critical registers as
+     part of their normal status mechanism (as another roundtrip to
+     fetch them is avoided).  */
   VEC(cached_reg_t) *regcache;
 
   int stopped_by_watchpoint_p;
   CORE_ADDR watch_data_address;
 
-  int solibs_changed;
-  int replay_event;
-
   int core;
-};
+} *stop_reply_p;
 
-/* The list of already fetched and acknowledged stop events.  */
-static struct stop_reply *stop_reply_queue;
+DECLARE_QUEUE_P (stop_reply_p);
+DEFINE_QUEUE_P (stop_reply_p);
+/* The list of already fetched and acknowledged stop events.  This
+   queue is used for notification Stop, and other notifications
+   don't need queue for their events, because the notification events
+   of Stop can't be consumed immediately, so that events should be
+   queued first, and be consumed by remote_wait_{ns,as} one per
+   time.  Other notifications can consume their events immediately,
+   so queue is not needed for them.  */
+static QUEUE (stop_reply_p) *stop_reply_queue;
 
-static struct stop_reply *
-stop_reply_xmalloc (void)
+static void
+stop_reply_xfree (struct stop_reply *r)
 {
-  struct stop_reply *r = XMALLOC (struct stop_reply);
+  notif_event_xfree ((struct notif_event *) r);
+}
 
-  r->next = NULL;
-  return r;
+static void
+remote_notif_stop_parse (struct notif_client *self, char *buf,
+                        struct notif_event *event)
+{
+  remote_parse_stop_reply (buf, (struct stop_reply *) event);
 }
 
 static void
-stop_reply_xfree (struct stop_reply *r)
+remote_notif_stop_ack (struct notif_client *self, char *buf,
+                      struct notif_event *event)
+{
+  struct stop_reply *stop_reply = (struct stop_reply *) event;
+
+  /* acknowledge */
+  putpkt ((char *) self->ack_command);
+
+  if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
+      /* We got an unknown stop reply.  */
+      error (_("Unknown stop reply"));
+
+  push_stop_reply (stop_reply);
+}
+
+static int
+remote_notif_stop_can_get_pending_events (struct notif_client *self)
+{
+  /* We can't get pending events in remote_notif_process for
+     notification stop, and we have to do this in remote_wait_ns
+     instead.  If we fetch all queued events from stub, remote stub
+     may exit and we have no chance to process them back in
+     remote_wait_ns.  */
+  mark_async_event_handler (remote_async_inferior_event_token);
+  return 0;
+}
+
+static void
+stop_reply_dtr (struct notif_event *event)
+{
+  struct stop_reply *r = (struct stop_reply *) event;
+
+  VEC_free (cached_reg_t, r->regcache);
+}
+
+static struct notif_event *
+remote_notif_stop_alloc_reply (void)
+{
+  struct notif_event *r
+    = (struct notif_event *) XNEW (struct stop_reply);
+
+  r->dtr = stop_reply_dtr;
+
+  return r;
+}
+
+/* A client of notification Stop.  */
+
+struct notif_client notif_client_stop =
 {
-  if (r != NULL)
+  "Stop",
+  "vStopped",
+  remote_notif_stop_parse,
+  remote_notif_stop_ack,
+  remote_notif_stop_can_get_pending_events,
+  remote_notif_stop_alloc_reply,
+  REMOTE_NOTIF_STOP,
+};
+
+/* A parameter to pass data in and out.  */
+
+struct queue_iter_param
+{
+  void *input;
+  struct stop_reply *output;
+};
+
+/* Remove stop replies in the queue if its pid is equal to the given
+   inferior's pid.  */
+
+static int
+remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
+                               QUEUE_ITER (stop_reply_p) *iter,
+                               stop_reply_p event,
+                               void *data)
+{
+  struct queue_iter_param *param = data;
+  struct inferior *inf = param->input;
+
+  if (ptid_get_pid (event->ptid) == inf->pid)
     {
-      VEC_free (cached_reg_t, r->regcache);
-      xfree (r);
+      stop_reply_xfree (event);
+      QUEUE_remove_elem (stop_reply_p, q, iter);
     }
+
+  return 1;
 }
 
-/* Discard all pending stop replies of inferior PID.  If PID is -1,
-   discard everything.  */
+/* Discard all pending stop replies of inferior INF.  */
 
 static void
-discard_pending_stop_replies (int pid)
+discard_pending_stop_replies (struct inferior *inf)
 {
-  struct stop_reply *prev = NULL, *reply, *next;
+  int i;
+  struct queue_iter_param param;
+  struct stop_reply *reply;
+  struct remote_state *rs = get_remote_state ();
+  struct remote_notif_state *rns = rs->notif_state;
+
+  /* This function can be notified when an inferior exists.  When the
+     target is not remote, the notification state is NULL.  */
+  if (rs->remote_desc == NULL)
+    return;
+
+  reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
 
   /* Discard the in-flight notification.  */
-  if (pending_stop_reply != NULL
-      && (pid == -1
-         || ptid_get_pid (pending_stop_reply->ptid) == pid))
+  if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
     {
-      stop_reply_xfree (pending_stop_reply);
-      pending_stop_reply = NULL;
+      stop_reply_xfree (reply);
+      rns->pending_event[notif_client_stop.id] = NULL;
     }
 
+  param.input = inf;
+  param.output = NULL;
   /* Discard the stop replies we have already pulled with
      vStopped.  */
-  for (reply = stop_reply_queue; reply; reply = next)
-    {
-      next = reply->next;
-      if (pid == -1
-         || ptid_get_pid (reply->ptid) == pid)
-       {
-         if (reply == stop_reply_queue)
-           stop_reply_queue = reply->next;
-         else
-           prev->next = reply->next;
+  QUEUE_iterate (stop_reply_p, stop_reply_queue,
+                remove_stop_reply_for_inferior, &param);
+}
 
-         stop_reply_xfree (reply);
-       }
-      else
-       prev = reply;
+/* If its remote state is equal to the given remote state,
+   remove EVENT from the stop reply queue.  */
+
+static int
+remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
+                                  QUEUE_ITER (stop_reply_p) *iter,
+                                  stop_reply_p event,
+                                  void *data)
+{
+  struct queue_iter_param *param = data;
+  struct remote_state *rs = param->input;
+
+  if (event->rs == rs)
+    {
+      stop_reply_xfree (event);
+      QUEUE_remove_elem (stop_reply_p, q, iter);
     }
+
+  return 1;
 }
 
-/* Cleanup wrapper.  */
+/* Discard the stop replies for RS in stop_reply_queue.  */
 
 static void
-do_stop_reply_xfree (void *arg)
+discard_pending_stop_replies_in_queue (struct remote_state *rs)
+{
+  struct queue_iter_param param;
+
+  param.input = rs;
+  param.output = NULL;
+  /* Discard the stop replies we have already pulled with
+     vStopped.  */
+  QUEUE_iterate (stop_reply_p, stop_reply_queue,
+                remove_stop_reply_of_remote_state, &param);
+}
+
+/* A parameter to pass data in and out.  */
+
+static int
+remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
+                                  QUEUE_ITER (stop_reply_p) *iter,
+                                  stop_reply_p event,
+                                  void *data)
+{
+  struct queue_iter_param *param = data;
+  ptid_t *ptid = param->input;
+
+  if (ptid_match (event->ptid, *ptid))
+    {
+      param->output = event;
+      QUEUE_remove_elem (stop_reply_p, q, iter);
+      return 0;
+    }
+
+  return 1;
+}
+
+/* Remove the first reply in 'stop_reply_queue' which matches
+   PTID.  */
+
+static struct stop_reply *
+remote_notif_remove_queued_reply (ptid_t ptid)
 {
-  struct stop_reply *r = arg;
+  struct queue_iter_param param;
+
+  param.input = &ptid;
+  param.output = NULL;
 
-  stop_reply_xfree (r);
+  QUEUE_iterate (stop_reply_p, stop_reply_queue,
+                remote_notif_remove_once_on_match, &param);
+  if (notif_debug)
+    fprintf_unfiltered (gdb_stdlog,
+                       "notif: discard queued event: 'Stop' in %s\n",
+                       target_pid_to_str (ptid));
+
+  return param.output;
 }
 
 /* Look for a queued stop reply belonging to PTID.  If one is found,
@@ -4960,29 +5447,13 @@ do_stop_reply_xfree (void *arg)
 static struct stop_reply *
 queued_stop_reply (ptid_t ptid)
 {
-  struct stop_reply *it;
-  struct stop_reply **it_link;
-
-  it = stop_reply_queue;
-  it_link = &stop_reply_queue;
-  while (it)
-    {
-      if (ptid_match (it->ptid, ptid))
-       {
-         *it_link = it->next;
-         it->next = NULL;
-         break;
-       }
+  struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
 
-      it_link = &it->next;
-      it = *it_link;
-    }
-
-  if (stop_reply_queue)
+  if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
     /* There's still at least an event left.  */
     mark_async_event_handler (remote_async_inferior_event_token);
 
-  return it;
+  return r;
 }
 
 /* Push a fully parsed stop reply in the stop reply queue.  Since we
@@ -4992,38 +5463,37 @@ queued_stop_reply (ptid_t ptid)
 static void
 push_stop_reply (struct stop_reply *new_event)
 {
-  struct stop_reply *event;
-
-  if (stop_reply_queue)
-    {
-      for (event = stop_reply_queue;
-          event && event->next;
-          event = event->next)
-       ;
+  QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
 
-      event->next = new_event;
-    }
-  else
-    stop_reply_queue = new_event;
+  if (notif_debug)
+    fprintf_unfiltered (gdb_stdlog,
+                       "notif: push 'Stop' %s to queue %d\n",
+                       target_pid_to_str (new_event->ptid),
+                       QUEUE_length (stop_reply_p,
+                                     stop_reply_queue));
 
   mark_async_event_handler (remote_async_inferior_event_token);
 }
 
-/* Returns true if we have a stop reply for PTID.  */
-
 static int
-peek_stop_reply (ptid_t ptid)
+stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
+                             QUEUE_ITER (stop_reply_p) *iter,
+                             struct stop_reply *event,
+                             void *data)
 {
-  struct stop_reply *it;
+  ptid_t *ptid = data;
 
-  for (it = stop_reply_queue; it; it = it->next)
-    if (ptid_equal (ptid, it->ptid))
-      {
-       if (it->ws.kind == TARGET_WAITKIND_STOPPED)
-         return 1;
-      }
+  return !(ptid_equal (*ptid, event->ptid)
+          && event->ws.kind == TARGET_WAITKIND_STOPPED);
+}
 
-  return 0;
+/* Returns true if we have a stop reply for PTID.  */
+
+static int
+peek_stop_reply (ptid_t ptid)
+{
+  return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
+                        stop_reply_match_ptid_and_ws, &ptid);
 }
 
 /* Parse the stop reply in BUF.  Either the function succeeds, and the
@@ -5037,10 +5507,9 @@ remote_parse_stop_reply (char *buf, struct stop_reply *event)
   char *p;
 
   event->ptid = null_ptid;
+  event->rs = get_remote_state ();
   event->ws.kind = TARGET_WAITKIND_IGNORE;
   event->ws.value.integer = 0;
-  event->solibs_changed = 0;
-  event->replay_event = 0;
   event->stopped_by_watchpoint_p = 0;
   event->regcache = NULL;
   event->core = -1;
@@ -5104,15 +5573,14 @@ Packet: '%s'\n"),
                  while (*p_temp && *p_temp != ';')
                    p_temp++;
 
-                 event->solibs_changed = 1;
+                 event->ws.kind = TARGET_WAITKIND_LOADED;
                  p = p_temp;
                }
              else if (strncmp (p, "replaylog", p1 - p) == 0)
                {
-                 /* NO_HISTORY event.
-                    p1 will indicate "begin" or "end", but
-                    it makes no difference for now, so ignore it.  */
-                 event->replay_event = 1;
+                 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
+                 /* p1 will indicate "begin" or "end", but it makes
+                    no difference for now, so ignore it.  */
                  p_temp = strchr (p1 + 1, ';');
                  if (p_temp)
                    p = p_temp;
@@ -5153,10 +5621,10 @@ Packet: '%s'\n"),
              cached_reg.num = reg->regnum;
 
              fieldsize = hex2bin (p, cached_reg.data,
-                                  register_size (target_gdbarch,
+                                  register_size (target_gdbarch (),
                                                  reg->regnum));
              p += 2 * fieldsize;
-             if (fieldsize < register_size (target_gdbarch,
+             if (fieldsize < register_size (target_gdbarch (),
                                             reg->regnum))
                warning (_("Remote reply is too short: %s"), buf);
 
@@ -5168,18 +5636,22 @@ Packet: '%s'\n"),
                   buf, p);
          ++p;
        }
+
+      if (event->ws.kind != TARGET_WAITKIND_IGNORE)
+       break;
+
       /* fall through */
     case 'S':          /* Old style status, just signal only.  */
-      if (event->solibs_changed)
-       event->ws.kind = TARGET_WAITKIND_LOADED;
-      else if (event->replay_event)
-       event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
-      else
-       {
-         event->ws.kind = TARGET_WAITKIND_STOPPED;
-         event->ws.value.sig = (enum target_signal)
-           (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
-       }
+      {
+       int sig;
+
+       event->ws.kind = TARGET_WAITKIND_STOPPED;
+       sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
+       if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
+         event->ws.value.sig = (enum gdb_signal) sig;
+       else
+         event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
+      }
       break;
     case 'W':          /* Target exited.  */
     case 'X':
@@ -5203,7 +5675,10 @@ Packet: '%s'\n"),
          {
            /* The remote process exited with a signal.  */
            event->ws.kind = TARGET_WAITKIND_SIGNALLED;
-           event->ws.value.sig = (enum target_signal) value;
+           if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
+             event->ws.value.sig = (enum gdb_signal) value;
+           else
+             event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
          }
 
        /* If no process is specified, assume inferior_ptid.  */
@@ -5239,13 +5714,14 @@ Packet: '%s'\n"),
     error (_("No process or thread specified in stop reply: %s"), buf);
 }
 
-/* When the stub wants to tell GDB about a new stop reply, it sends a
-   stop notification (%Stop).  Those can come it at any time, hence,
-   we have to make sure that any pending putpkt/getpkt sequence we're
-   making is finished, before querying the stub for more events with
-   vStopped.  E.g., if we started a vStopped sequence immediatelly
-   upon receiving the %Stop notification, something like this could
-   happen:
+/* When the stub wants to tell GDB about a new notification reply, it
+   sends a notification (%Stop, for example).  Those can come it at
+   any time, hence, we have to make sure that any pending
+   putpkt/getpkt sequence we're making is finished, before querying
+   the stub for more events with the corresponding ack command
+   (vStopped, for example).  E.g., if we started a vStopped sequence
+   immediately upon receiving the notification, something like this
+   could happen:
 
     1.1) --> Hg 1
     1.2) <-- OK
@@ -5257,7 +5733,7 @@ Packet: '%s'\n"),
    Obviously, the reply in step #1.6 would be unexpected to a vStopped
    query.
 
-   To solve this, whenever we parse a %Stop notification sucessfully,
+   To solve this, whenever we parse a %Stop notification successfully,
    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
    doing whatever we were doing:
 
@@ -5280,19 +5756,21 @@ Packet: '%s'\n"),
     2.9) --> OK
 */
 
-static void
-remote_get_pending_stop_replies (void)
+void
+remote_notif_get_pending_events (struct notif_client *nc)
 {
   struct remote_state *rs = get_remote_state ();
 
-  if (pending_stop_reply)
+  if (rs->notif_state->pending_event[nc->id] != NULL)
     {
-      /* acknowledge */
-      putpkt ("vStopped");
+      if (notif_debug)
+       fprintf_unfiltered (gdb_stdlog,
+                           "notif: process: '%s' ack pending event\n",
+                           nc->name);
 
-      /* Now we can rely on it.         */
-      push_stop_reply (pending_stop_reply);
-      pending_stop_reply = NULL;
+      /* acknowledge */
+      nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
+      rs->notif_state->pending_event[nc->id] = NULL;
 
       while (1)
        {
@@ -5300,31 +5778,18 @@ remote_get_pending_stop_replies (void)
          if (strcmp (rs->buf, "OK") == 0)
            break;
          else
-           {
-             struct cleanup *old_chain;
-             struct stop_reply *stop_reply = stop_reply_xmalloc ();
-
-             old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
-             remote_parse_stop_reply (rs->buf, stop_reply);
-
-             /* acknowledge */
-             putpkt ("vStopped");
-
-             if (stop_reply->ws.kind != TARGET_WAITKIND_IGNORE)
-               {
-                 /* Now we can rely on it.  */
-                 discard_cleanups (old_chain);
-                 push_stop_reply (stop_reply);
-               }
-             else
-               /* We got an unknown stop reply.  */
-               do_cleanups (old_chain);
-           }
+           remote_notif_ack (nc, rs->buf);
        }
     }
+  else
+    {
+      if (notif_debug)
+       fprintf_unfiltered (gdb_stdlog,
+                           "notif: process: '%s' no pending reply\n",
+                           nc->name);
+    }
 }
 
-
 /* Called when it is decided that STOP_REPLY holds the info of the
    event that is to be returned to the core.  This function always
    destroys STOP_REPLY.  */
@@ -5346,11 +5811,13 @@ process_stop_reply (struct stop_reply *stop_reply,
   if (status->kind != TARGET_WAITKIND_EXITED
       && status->kind != TARGET_WAITKIND_SIGNALLED)
     {
+      struct remote_state *rs = get_remote_state ();
+
       /* Expedited registers.  */
       if (stop_reply->regcache)
        {
          struct regcache *regcache
-           = get_thread_arch_regcache (ptid, target_gdbarch);
+           = get_thread_arch_regcache (ptid, target_gdbarch ());
          cached_reg_t *reg;
          int ix;
 
@@ -5361,8 +5828,8 @@ process_stop_reply (struct stop_reply *stop_reply,
          VEC_free (cached_reg_t, stop_reply->regcache);
        }
 
-      remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
-      remote_watch_data_address = stop_reply->watch_data_address;
+      rs->remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
+      rs->remote_watch_data_address = stop_reply->watch_data_address;
 
       remote_notice_new_inferior (ptid, 0);
       demand_private_info (ptid)->core = stop_reply->core;
@@ -5380,15 +5847,16 @@ remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
   struct remote_state *rs = get_remote_state ();
   struct stop_reply *stop_reply;
   int ret;
+  int is_notif = 0;
 
   /* If in non-stop mode, get out of getpkt even if a
      notification is received. */
 
   ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
-                             0 /* forever */);
+                             0 /* forever */, &is_notif);
   while (1)
     {
-      if (ret != -1)
+      if (ret != -1 && !is_notif)
        switch (rs->buf[0])
          {
          case 'E':             /* Error of some sort.  */
@@ -5407,8 +5875,8 @@ remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
 
       /* Acknowledge a pending stop reply that may have arrived in the
         mean time.  */
-      if (pending_stop_reply != NULL)
-       remote_get_pending_stop_replies ();
+      if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
+       remote_notif_get_pending_events (&notif_client_stop);
 
       /* If indeed we noticed a stop reply, we're done.  */
       stop_reply = queued_stop_reply (ptid);
@@ -5425,7 +5893,7 @@ remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
 
       /* Otherwise do a blocking wait.  */
       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
-                                 1 /* forever */);
+                                 1 /* forever */, &is_notif);
     }
 }
 
@@ -5455,16 +5923,17 @@ remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
   else
     {
       int ret;
+      int is_notif;
 
       if (!target_is_async_p ())
        {
-         ofunc = signal (SIGINT, remote_interrupt);
+         ofunc = signal (SIGINT, sync_remote_interrupt);
          /* If the user hit C-c before this packet, or between packets,
             pretend that it was hit right here.  */
-         if (quit_flag)
+         if (check_quit_flag ())
            {
-             quit_flag = 0;
-             remote_interrupt (SIGINT);
+             clear_quit_flag ();
+             sync_remote_interrupt (SIGINT);
            }
        }
 
@@ -5472,14 +5941,21 @@ remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
         _never_ wait for ever -> test on target_is_async_p().
         However, before we do that we need to ensure that the caller
         knows how to take the target into/out of async mode.  */
-      ret = getpkt_sane (&rs->buf, &rs->buf_size, wait_forever_enabled_p);
+      ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
+                                 wait_forever_enabled_p, &is_notif);
+
       if (!target_is_async_p ())
        signal (SIGINT, ofunc);
+
+      /* GDB gets a notification.  Return to core as this event is
+        not interesting.  */
+      if (ret != -1 && is_notif)
+       return minus_one_ptid;
     }
 
   buf = rs->buf;
 
-  remote_stopped_by_watchpoint_p = 0;
+  rs->remote_stopped_by_watchpoint_p = 0;
 
   /* We got something.  */
   rs->waiting_for_stop_reply = 0;
@@ -5496,7 +5972,7 @@ remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
         not?  Not is more likely, so report a stop.  */
       warning (_("Remote failure reply: %s"), buf);
       status->kind = TARGET_WAITKIND_STOPPED;
-      status->value.sig = TARGET_SIGNAL_0;
+      status->value.sig = GDB_SIGNAL_0;
       break;
     case 'F':          /* File-I/O request.  */
       remote_fileio_request (buf, rs->ctrlc_pending_p);
@@ -5504,13 +5980,10 @@ remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
       break;
     case 'T': case 'S': case 'X': case 'W':
       {
-       struct stop_reply *stop_reply;
-       struct cleanup *old_chain;
+       struct stop_reply *stop_reply
+         = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
+                                                     rs->buf);
 
-       stop_reply = stop_reply_xmalloc ();
-       old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
-       remote_parse_stop_reply (buf, stop_reply);
-       discard_cleanups (old_chain);
        event_ptid = process_stop_reply (stop_reply, status);
        break;
       }
@@ -5522,18 +5995,18 @@ remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
 
       break;
     case '\0':
-      if (last_sent_signal != TARGET_SIGNAL_0)
+      if (rs->last_sent_signal != GDB_SIGNAL_0)
        {
          /* Zero length reply means that we tried 'S' or 'C' and the
             remote system doesn't support it.  */
          target_terminal_ours_for_output ();
          printf_filtered
            ("Can't send signals to this remote system.  %s not sent.\n",
-            target_signal_to_name (last_sent_signal));
-         last_sent_signal = TARGET_SIGNAL_0;
+            gdb_signal_to_name (rs->last_sent_signal));
+         rs->last_sent_signal = GDB_SIGNAL_0;
          target_terminal_inferior ();
 
-         strcpy ((char *) buf, last_sent_step ? "s" : "c");
+         strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
          putpkt ((char *) buf);
 
          /* We just told the target to resume, so a stop reply is in
@@ -5562,13 +6035,13 @@ remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
           && status->kind != TARGET_WAITKIND_SIGNALLED)
     {
       if (!ptid_equal (event_ptid, null_ptid))
-       record_currthread (event_ptid);
+       record_currthread (rs, event_ptid);
       else
        event_ptid = inferior_ptid;
     }
   else
     /* A process exit.  Invalidate our notion of current thread.  */
-    record_currthread (minus_one_ptid);
+    record_currthread (rs, minus_one_ptid);
 
   return event_ptid;
 }
@@ -5591,7 +6064,7 @@ remote_wait (struct target_ops *ops,
     {
       /* If there are are events left in the queue tell the event loop
         to return here.  */
-      if (stop_reply_queue)
+      if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
        mark_async_event_handler (remote_async_inferior_event_token);
     }
 
@@ -5666,7 +6139,7 @@ send_g_packet (void)
   struct remote_state *rs = get_remote_state ();
   int buf_len;
 
-  sprintf (rs->buf, "g");
+  xsnprintf (rs->buf, get_remote_packet_size (), "g");
   remote_send (&rs->buf, &rs->buf_size);
 
   /* We can get out of synch in various cases.  If the first character
@@ -5796,12 +6269,13 @@ static void
 set_remote_traceframe (void)
 {
   int newnum;
+  struct remote_state *rs = get_remote_state ();
 
-  if (remote_traceframe_number == get_traceframe_number ())
+  if (rs->remote_traceframe_number == get_traceframe_number ())
     return;
 
   /* Avoid recursion, remote_trace_find calls us again.  */
-  remote_traceframe_number = get_traceframe_number ();
+  rs->remote_traceframe_number = get_traceframe_number ();
 
   newnum = target_trace_find (tfind_number,
                              get_traceframe_number (), 0, 0, NULL);
@@ -5863,7 +6337,7 @@ remote_fetch_registers (struct target_ops *ops,
    first.  */
 
 static void
-remote_prepare_to_store (struct regcache *regcache)
+remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
 {
   struct remote_arch_state *rsa = get_remote_arch_state ();
   int i;
@@ -6060,11 +6534,11 @@ hexnumnstr (char *buf, ULONGEST num, int width)
 static CORE_ADDR
 remote_address_masked (CORE_ADDR addr)
 {
-  int address_size = remote_address_size;
+  unsigned int address_size = remote_address_size;
 
   /* If "remoteaddresssize" was not set, default to target address size.  */
   if (!address_size)
-    address_size = gdbarch_addr_bit (target_gdbarch);
+    address_size = gdbarch_addr_bit (target_gdbarch ());
 
   if (address_size > 0
       && address_size < (sizeof (ULONGEST) * 8))
@@ -6079,91 +6553,6 @@ remote_address_masked (CORE_ADDR addr)
   return addr;
 }
 
-/* Convert BUFFER, binary data at least LEN bytes long, into escaped
-   binary data in OUT_BUF.  Set *OUT_LEN to the length of the data
-   encoded in OUT_BUF, and return the number of bytes in OUT_BUF
-   (which may be more than *OUT_LEN due to escape characters).  The
-   total number of bytes in the output buffer will be at most
-   OUT_MAXLEN.  */
-
-static int
-remote_escape_output (const gdb_byte *buffer, int len,
-                     gdb_byte *out_buf, int *out_len,
-                     int out_maxlen)
-{
-  int input_index, output_index;
-
-  output_index = 0;
-  for (input_index = 0; input_index < len; input_index++)
-    {
-      gdb_byte b = buffer[input_index];
-
-      if (b == '$' || b == '#' || b == '}')
-       {
-         /* These must be escaped.  */
-         if (output_index + 2 > out_maxlen)
-           break;
-         out_buf[output_index++] = '}';
-         out_buf[output_index++] = b ^ 0x20;
-       }
-      else
-       {
-         if (output_index + 1 > out_maxlen)
-           break;
-         out_buf[output_index++] = b;
-       }
-    }
-
-  *out_len = input_index;
-  return output_index;
-}
-
-/* Convert BUFFER, escaped data LEN bytes long, into binary data
-   in OUT_BUF.  Return the number of bytes written to OUT_BUF.
-   Raise an error if the total number of bytes exceeds OUT_MAXLEN.
-
-   This function reverses remote_escape_output.  It allows more
-   escaped characters than that function does, in particular because
-   '*' must be escaped to avoid the run-length encoding processing
-   in reading packets.  */
-
-static int
-remote_unescape_input (const gdb_byte *buffer, int len,
-                      gdb_byte *out_buf, int out_maxlen)
-{
-  int input_index, output_index;
-  int escaped;
-
-  output_index = 0;
-  escaped = 0;
-  for (input_index = 0; input_index < len; input_index++)
-    {
-      gdb_byte b = buffer[input_index];
-
-      if (output_index + 1 > out_maxlen)
-       {
-         warning (_("Received too much data from remote target;"
-                    " ignoring overflow."));
-         return output_index;
-       }
-
-      if (escaped)
-       {
-         out_buf[output_index++] = b ^ 0x20;
-         escaped = 0;
-       }
-      else if (b == '}')
-       escaped = 1;
-      else
-       out_buf[output_index++] = b;
-    }
-
-  if (escaped)
-    error (_("Unmatched escape character in target response."));
-
-  return output_index;
-}
-
 /* Determine whether the remote target supports binary downloading.
    This is accomplished by sending a no-op memory write of zero length
    to the target at the specified address. It does not suffice to send
@@ -6213,7 +6602,7 @@ check_binary_download (CORE_ADDR addr)
          {
            if (remote_debug)
              fprintf_unfiltered (gdb_stdlog,
-                                 "binary downloading suppported by target\n");
+                                 "binary downloading supported by target\n");
            remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
          }
        break;
@@ -6238,13 +6627,15 @@ check_binary_download (CORE_ADDR addr)
    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
    are omitted.
 
-   Returns the number of bytes transferred, or 0 (setting errno) for
-   error.  Only transfer a single packet.  */
+   Return the transferred status, error or OK (an
+   'enum target_xfer_status' value).  Save the number of bytes
+   transferred in *XFERED_LEN.  Only transfer a single packet.  */
 
-static int
+static enum target_xfer_status
 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
-                       const gdb_byte *myaddr, int len,
-                       char packet_format, int use_length)
+                       const gdb_byte *myaddr, ULONGEST len,
+                       ULONGEST *xfered_len, char packet_format,
+                       int use_length)
 {
   struct remote_state *rs = get_remote_state ();
   char *p;
@@ -6260,8 +6651,8 @@ remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
     internal_error (__FILE__, __LINE__,
                    _("remote_write_bytes_aux: bad packet format"));
 
-  if (len <= 0)
-    return 0;
+  if (len == 0)
+    return TARGET_XFER_EOF;
 
   payload_size = get_memory_write_packet_size ();
 
@@ -6305,7 +6696,7 @@ remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
 
   if (todo <= 0)
     internal_error (__FILE__, __LINE__,
-                   _("minumum packet size too small to write data"));
+                   _("minimum packet size too small to write data"));
 
   /* If we already need another packet, then try to align the end
      of this packet to a useful boundary.  */
@@ -6338,8 +6729,8 @@ remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
       /* Binary mode.  Send target system values byte by byte, in
         increasing byte addresses.  Only escape certain critical
         characters.  */
-      payload_length = remote_escape_output (myaddr, todo, p, &nr_bytes,
-                                            payload_size);
+      payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
+                                            &nr_bytes, payload_size);
 
       /* If not all TODO bytes fit, then we'll need another packet.  Make
         a second try to keep the end of the packet aligned.  Don't do
@@ -6352,7 +6743,7 @@ remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
                          - memaddr);
          if (new_nr_bytes != nr_bytes)
            payload_length = remote_escape_output (myaddr, new_nr_bytes,
-                                                  p, &nr_bytes,
+                                                  (gdb_byte *) p, &nr_bytes,
                                                   payload_size);
        }
 
@@ -6380,18 +6771,12 @@ remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
   getpkt (&rs->buf, &rs->buf_size, 0);
 
   if (rs->buf[0] == 'E')
-    {
-      /* There is no correspondance between what the remote protocol
-        uses for errors and errno codes.  We would like a cleaner way
-        of representing errors (big enough to include errno codes,
-        bfd_error codes, and others).  But for now just return EIO.  */
-      errno = EIO;
-      return 0;
-    }
+    return TARGET_XFER_E_IO;
 
   /* Return NR_BYTES, not TODO, in case escape chars caused us to send
      fewer bytes than we'd planned.  */
-  return nr_bytes;
+  *xfered_len = (ULONGEST) nr_bytes;
+  return TARGET_XFER_OK;
 }
 
 /* Write memory data directly to the remote machine.
@@ -6400,11 +6785,13 @@ remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
    MYADDR is the address of the buffer in our space.
    LEN is the number of bytes.
 
-   Returns number of bytes transferred, or 0 (setting errno) for
-   error.  Only transfer a single packet.  */
+   Return the transferred status, error or OK (an
+   'enum target_xfer_status' value).  Save the number of bytes
+   transferred in *XFERED_LEN.  Only transfer a single packet.  */
 
-static int
-remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
+static enum target_xfer_status
+remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
+                   ULONGEST *xfered_len)
 {
   char *packet_format = 0;
 
@@ -6427,7 +6814,8 @@ remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
     }
 
   return remote_write_bytes_aux (packet_format,
-                                memaddr, myaddr, len, packet_format[0], 1);
+                                memaddr, myaddr, len, xfered_len,
+                                packet_format[0], 1);
 }
 
 /* Read memory data directly from the remote machine.
@@ -6436,10 +6824,13 @@ remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
    MYADDR is the address of the buffer in our space.
    LEN is the number of bytes.
 
-   Returns number of bytes transferred, or 0 for error.  */
+   Return the transferred status, error or OK (an
+   'enum target_xfer_status' value).  Save the number of bytes
+   transferred in *XFERED_LEN.  */
 
-static int
-remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
+static enum target_xfer_status
+remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len,
+                  ULONGEST *xfered_len)
 {
   struct remote_state *rs = get_remote_state ();
   int max_buf_size;            /* Max size of packet output buffer.  */
@@ -6447,7 +6838,7 @@ remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
   int todo;
   int i;
 
-  if (len <= 0)
+  if (len == 0)
     return 0;
 
   max_buf_size = get_memory_read_packet_size ();
@@ -6470,91 +6861,17 @@ remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
   if (rs->buf[0] == 'E'
       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
       && rs->buf[3] == '\0')
-    {
-      /* There is no correspondance between what the remote protocol
-        uses for errors and errno codes.  We would like a cleaner way
-        of representing errors (big enough to include errno codes,
-        bfd_error codes, and others).  But for now just return
-        EIO.  */
-      errno = EIO;
-      return 0;
-    }
+    return TARGET_XFER_E_IO;
   /* Reply describes memory byte by byte, each byte encoded as two hex
      characters.  */
   p = rs->buf;
   i = hex2bin (p, myaddr, todo);
   /* Return what we have.  Let higher layers handle partial reads.  */
-  return i;
-}
-\f
-
-/* Remote notification handler.  */
-
-static void
-handle_notification (char *buf, size_t length)
-{
-  if (strncmp (buf, "Stop:", 5) == 0)
-    {
-      if (pending_stop_reply)
-       {
-         /* We've already parsed the in-flight stop-reply, but the
-            stub for some reason thought we didn't, possibly due to
-            timeout on its side.  Just ignore it.  */
-         if (remote_debug)
-           fprintf_unfiltered (gdb_stdlog, "ignoring resent notification\n");
-       }
-      else
-       {
-         struct cleanup *old_chain;
-         struct stop_reply *reply = stop_reply_xmalloc ();
-
-         old_chain = make_cleanup (do_stop_reply_xfree, reply);
-
-         remote_parse_stop_reply (buf + 5, reply);
-
-         discard_cleanups (old_chain);
-
-         /* Be careful to only set it after parsing, since an error
-            may be thrown then.  */
-         pending_stop_reply = reply;
-
-         /* Notify the event loop there's a stop reply to acknowledge
-            and that there may be more events to fetch.  */
-         mark_async_event_handler (remote_async_get_pending_events_token);
-
-         if (remote_debug)
-           fprintf_unfiltered (gdb_stdlog, "stop notification captured\n");
-       }
-    }
-  else
-    /* We ignore notifications we don't recognize, for compatibility
-       with newer stubs.  */
-    ;
+  *xfered_len = (ULONGEST) i;
+  return TARGET_XFER_OK;
 }
 
 \f
-/* Read or write LEN bytes from inferior memory at MEMADDR,
-   transferring to or from debugger address BUFFER.  Write to inferior
-   if SHOULD_WRITE is nonzero.  Returns length of data written or
-   read; 0 for error.  TARGET is unused.  */
-
-static int
-remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
-                   int should_write, struct mem_attrib *attrib,
-                   struct target_ops *target)
-{
-  int res;
-
-  set_remote_traceframe ();
-  set_general_thread (inferior_ptid);
-
-  if (should_write)
-    res = remote_write_bytes (mem_addr, buffer, mem_len);
-  else
-    res = remote_read_bytes (mem_addr, buffer, mem_len);
-
-  return res;
-}
 
 /* Sends a packet with content determined by the printf format string
    FORMAT and the remaining arguments, then gets the reply.  Returns
@@ -6599,7 +6916,7 @@ static void
 remote_flash_erase (struct target_ops *ops,
                     ULONGEST address, LONGEST length)
 {
-  int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
+  int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
   int saved_remote_timeout = remote_timeout;
   enum packet_result ret;
   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
@@ -6623,18 +6940,19 @@ remote_flash_erase (struct target_ops *ops,
   do_cleanups (back_to);
 }
 
-static LONGEST
-remote_flash_write (struct target_ops *ops,
-                    ULONGEST address, LONGEST length,
-                    const gdb_byte *data)
+static enum target_xfer_status
+remote_flash_write (struct target_ops *ops, ULONGEST address,
+                   ULONGEST length, ULONGEST *xfered_len,
+                   const gdb_byte *data)
 {
   int saved_remote_timeout = remote_timeout;
-  int ret;
+  enum target_xfer_status ret;
   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
-                                          &saved_remote_timeout);
+                                         &saved_remote_timeout);
 
   remote_timeout = remote_flash_timeout;
-  ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
+  ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length,
+                               xfered_len,'X', 0);
   do_cleanups (back_to);
 
   return ret;
@@ -6672,14 +6990,31 @@ remote_files_info (struct target_ops *ignore)
 /* Stuff for dealing with the packets which are part of this protocol.
    See comment at top of file for details.  */
 
+/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
+   error to higher layers.  Called when a serial error is detected.
+   The exception message is STRING, followed by a colon and a blank,
+   the system error message for errno at function entry and final dot
+   for output compatibility with throw_perror_with_name.  */
+
+static void
+unpush_and_perror (const char *string)
+{
+  int saved_errno = errno;
+
+  remote_unpush_target ();
+  throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
+              safe_strerror (saved_errno));
+}
+
 /* Read a single character from the remote end.  */
 
 static int
 readchar (int timeout)
 {
   int ch;
+  struct remote_state *rs = get_remote_state ();
 
-  ch = serial_readchar (remote_desc, timeout);
+  ch = serial_readchar (rs->remote_desc, timeout);
 
   if (ch >= 0)
     return ch;
@@ -6687,13 +7022,12 @@ readchar (int timeout)
   switch ((enum serial_rc) ch)
     {
     case SERIAL_EOF:
-      pop_target ();
-      error (_("Remote connection closed"));
+      remote_unpush_target ();
+      throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
       /* no return */
     case SERIAL_ERROR:
-      pop_target ();
-      perror_with_name (_("Remote communication error.  "
-                         "Target disconnected."));
+      unpush_and_perror (_("Remote communication error.  "
+                          "Target disconnected."));
       /* no return */
     case SERIAL_TIMEOUT:
       break;
@@ -6701,6 +7035,21 @@ readchar (int timeout)
   return ch;
 }
 
+/* Wrapper for serial_write that closes the target and throws if
+   writing fails.  */
+
+static void
+remote_serial_write (const char *str, int len)
+{
+  struct remote_state *rs = get_remote_state ();
+
+  if (serial_write (rs->remote_desc, str, len))
+    {
+      unpush_and_perror (_("Remote communication error.  "
+                          "Target disconnected."));
+    }
+}
+
 /* Send the command in *BUF to the remote machine, and read the reply
    into *BUF.  Report an error if we get an error reply.  Resize
    *BUF using xrealloc if necessary to hold the result, and update
@@ -6772,6 +7121,7 @@ putpkt_binary (char *buf, int cnt)
   int ch;
   int tcount = 0;
   char *p;
+  char *message;
 
   /* Catch cases like trying to read memory or listing threads while
      we're waiting for a stop reply.  The remote server wouldn't be
@@ -6820,8 +7170,7 @@ putpkt_binary (char *buf, int cnt)
          gdb_flush (gdb_stdlog);
          do_cleanups (old_chain);
        }
-      if (serial_write (remote_desc, buf2, p - buf2))
-       perror_with_name (_("putpkt: write failed"));
+      remote_serial_write (buf2, p - buf2);
 
       /* If this is a no acks version of the remote protocol, send the
         packet and move on.  */
@@ -6876,7 +7225,7 @@ putpkt_binary (char *buf, int cnt)
                   doesn't get retransmitted when we resend this
                   packet.  */
                skip_frame ();
-               serial_write (remote_desc, "+", 1);
+               remote_serial_write ("+", 1);
                continue;       /* Now, go look for +.  */
              }
 
@@ -6903,7 +7252,7 @@ putpkt_binary (char *buf, int cnt)
                                            str);
                        do_cleanups (old_chain);
                      }
-                   handle_notification (rs->buf, val);
+                   handle_notification (rs->notif_state, rs->buf);
                    /* We're in sync now, rewait for the ack.  */
                    tcount = 0;
                  }
@@ -7154,11 +7503,13 @@ getpkt (char **buf,
    0, this function is allowed to time out gracefully and return an
    indication of this to the caller.  Otherwise return the number of
    bytes read.  If EXPECTING_NOTIF, consider receiving a notification
-   enough reason to return to the caller.  */
+   enough reason to return to the caller.  *IS_NOTIF is an output
+   boolean that indicates whether *BUF holds a notification or not
+   (a regular packet).  */
 
 static int
 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
-                       int expecting_notif)
+                       int expecting_notif, int *is_notif)
 {
   struct remote_state *rs = get_remote_state ();
   int c;
@@ -7186,7 +7537,7 @@ getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
      we get a packet.  */
   for (;;)
     {
-      /* If we get a timeout or bad checksm, retry up to MAX_TRIES
+      /* If we get a timeout or bad checksum, retry up to MAX_TRIES
         times.  */
       for (tries = 1; tries <= MAX_TRIES; tries++)
        {
@@ -7212,8 +7563,10 @@ getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
              if (forever)      /* Watchdog went off?  Kill the target.  */
                {
                  QUIT;
-                 pop_target ();
-                 error (_("Watchdog timeout has expired.  Target detached."));
+                 remote_unpush_target ();
+                 throw_error (TARGET_CLOSE_ERROR,
+                              _("Watchdog timeout has expired.  "
+                                "Target detached."));
                }
              if (remote_debug)
                fputs_filtered ("Timed out.\n", gdb_stdlog);
@@ -7227,7 +7580,7 @@ getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
                break;
            }
 
-         serial_write (remote_desc, "-", 1);
+         remote_serial_write ("-", 1);
        }
 
       if (tries > MAX_TRIES)
@@ -7238,7 +7591,7 @@ getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
 
          /* Skip the ack char if we're in no-ack mode.  */
          if (!rs->noack_mode)
-           serial_write (remote_desc, "+", 1);
+           remote_serial_write ("+", 1);
          return -1;
        }
 
@@ -7258,7 +7611,9 @@ getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
 
          /* Skip the ack char if we're in no-ack mode.  */
          if (!rs->noack_mode)
-           serial_write (remote_desc, "+", 1);
+           remote_serial_write ("+", 1);
+         if (is_notif != NULL)
+           *is_notif = 0;
          return val;
        }
 
@@ -7280,13 +7635,15 @@ getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
                                  str);
              do_cleanups (old_chain);
            }
+         if (is_notif != NULL)
+           *is_notif = 1;
 
-         handle_notification (*buf, val);
+         handle_notification (rs->notif_state, *buf);
 
          /* Notifications require no acknowledgement.  */
 
          if (expecting_notif)
-           return -1;
+           return val;
        }
     }
 }
@@ -7294,25 +7651,51 @@ getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
 static int
 getpkt_sane (char **buf, long *sizeof_buf, int forever)
 {
-  return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0);
+  return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
 }
 
 static int
-getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever)
+getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
+                     int *is_notif)
 {
-  return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1);
+  return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
+                                is_notif);
 }
 
 \f
 static void
 remote_kill (struct target_ops *ops)
 {
-  /* Use catch_errors so the user can quit from gdb even when we
+  volatile struct gdb_exception ex;
+
+  /* Catch errors so the user can quit from gdb even when we
      aren't on speaking terms with the remote system.  */
-  catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
+  TRY_CATCH (ex, RETURN_MASK_ERROR)
+    {
+      putpkt ("k");
+    }
+  if (ex.reason < 0)
+    {
+      if (ex.error == TARGET_CLOSE_ERROR)
+       {
+         /* If we got an (EOF) error that caused the target
+            to go away, then we're done, that's what we wanted.
+            "k" is susceptible to cause a premature EOF, given
+            that the remote server isn't actually required to
+            reply to "k", and it can happen that it doesn't
+            even get to reply ACK to the "k".  */
+         return;
+       }
+
+       /* Otherwise, something went wrong.  We didn't actually kill
+          the target.  Just propagate the exception, and let the
+          user or higher layers decide what to do.  */
+       throw_exception (ex);
+    }
 
-  /* Don't wait for it to die.  I'm not really sure it matters whether
-     we do or not.  For the existing stubs, kill is a noop.  */
+  /* We've killed the remote end, we get to mourn it.  Since this is
+     target remote, single-process, mourning the inferior also
+     unpushes remote_ops.  */
   target_mourn_inferior ();
 }
 
@@ -7323,7 +7706,7 @@ remote_vkill (int pid, struct remote_state *rs)
     return -1;
 
   /* Tell the remote target to detach.  */
-  sprintf (rs->buf, "vKill;%x", pid);
+  xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
   putpkt (rs->buf);
   getpkt (&rs->buf, &rs->buf_size, 0);
 
@@ -7344,7 +7727,7 @@ extended_remote_kill (struct target_ops *ops)
   struct remote_state *rs = get_remote_state ();
 
   res = remote_vkill (pid, rs);
-  if (res == -1 && !remote_multi_process_p (rs))
+  if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
     {
       /* Don't try 'k' on a multi-process aware stub -- it has no way
         to specify the pid.  */
@@ -7392,9 +7775,6 @@ extended_remote_mourn_1 (struct target_ops *target)
      connected.  */
   rs->waiting_for_stop_reply = 0;
 
-  /* We're no longer interested in these events.  */
-  discard_pending_stop_replies (ptid_get_pid (inferior_ptid));
-
   /* If the current general thread belonged to the process we just
      detached from or has exited, the remote side current general
      thread becomes undefined.  Considering a case like this:
@@ -7418,7 +7798,7 @@ extended_remote_mourn_1 (struct target_ops *target)
 
      To keep things simple, we always invalidate our notion of the
      current thread.  */
-  record_currthread (minus_one_ptid);
+  record_currthread (rs, minus_one_ptid);
 
   /* Unlike "target remote", we do not want to unpush the target; then
      the next time the user says "run", we won't be connected.  */
@@ -7453,6 +7833,29 @@ extended_remote_mourn (struct target_ops *ops)
   extended_remote_mourn_1 (ops);
 }
 
+static int
+extended_remote_supports_disable_randomization (struct target_ops *self)
+{
+  return (remote_protocol_packets[PACKET_QDisableRandomization].support
+         == PACKET_ENABLE);
+}
+
+static void
+extended_remote_disable_randomization (int val)
+{
+  struct remote_state *rs = get_remote_state ();
+  char *reply;
+
+  xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
+            val);
+  putpkt (rs->buf);
+  reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
+  if (*reply == '\0')
+    error (_("Target does not support QDisableRandomization."));
+  if (strcmp (reply, "OK") != 0)
+    error (_("Bogus QDisableRandomization reply from target: %s"), reply);
+}
+
 static int
 extended_remote_run (char *args)
 {
@@ -7469,7 +7872,8 @@ extended_remote_run (char *args)
 
   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
     error (_("Remote file name too long for run packet"));
-  len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
+  len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
+                     strlen (remote_exec_file));
 
   gdb_assert (args != NULL);
   if (*args)
@@ -7485,7 +7889,8 @@ extended_remote_run (char *args)
          if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
            error (_("Argument list too long for run packet"));
          rs->buf[len++] = ';';
-         len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
+         len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
+                             strlen (argv[i]));
        }
       do_cleanups (back_to);
     }
@@ -7497,7 +7902,7 @@ extended_remote_run (char *args)
 
   if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
     {
-      /* We have a wait response; we don't need it, though.  All is well.  */
+      /* We have a wait response.  All is well.  */
       return 0;
     }
   else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
@@ -7521,16 +7926,26 @@ extended_remote_run (char *args)
    environment.  */
 
 static void
-extended_remote_create_inferior_1 (char *exec_file, char *args,
-                                  char **env, int from_tty)
+extended_remote_create_inferior (struct target_ops *ops,
+                                char *exec_file, char *args,
+                                char **env, int from_tty)
 {
+  int run_worked;
+  char *stop_reply;
+  struct remote_state *rs = get_remote_state ();
+
   /* If running asynchronously, register the target file descriptor
      with the event loop.  */
   if (target_can_async_p ())
     target_async (inferior_event_handler, 0);
 
+  /* Disable address space randomization if requested (and supported).  */
+  if (extended_remote_supports_disable_randomization (ops))
+    extended_remote_disable_randomization (disable_randomization);
+
   /* Now restart the remote server.  */
-  if (extended_remote_run (args) == -1)
+  run_worked = extended_remote_run (args) != -1;
+  if (!run_worked)
     {
       /* vRun was not supported.  Fail if we need it to do what the
         user requested.  */
@@ -7552,34 +7967,87 @@ extended_remote_create_inferior_1 (char *exec_file, char *args,
       init_wait_for_inferior ();
     }
 
-  /* Now mark the inferior as running before we do anything else.  */
-  inferior_ptid = magic_null_ptid;
-
-  /* Now, if we have thread information, update inferior_ptid.  */
-  inferior_ptid = remote_current_thread (inferior_ptid);
-
-  remote_add_inferior (ptid_get_pid (inferior_ptid), 0);
-  add_thread_silent (inferior_ptid);
+  /* vRun's success return is a stop reply.  */
+  stop_reply = run_worked ? rs->buf : NULL;
+  add_current_inferior_and_thread (stop_reply);
 
   /* Get updated offsets, if the stub uses qOffsets.  */
   get_offsets ();
 }
+\f
+
+/* Given a location's target info BP_TGT and the packet buffer BUF,  output
+   the list of conditions (in agent expression bytecode format), if any, the
+   target needs to evaluate.  The output is placed into the packet buffer
+   started from BUF and ended at BUF_END.  */
+
+static int
+remote_add_target_side_condition (struct gdbarch *gdbarch,
+                                 struct bp_target_info *bp_tgt, char *buf,
+                                 char *buf_end)
+{
+  struct agent_expr *aexpr = NULL;
+  int i, ix;
+  char *pkt;
+  char *buf_start = buf;
+
+  if (VEC_empty (agent_expr_p, bp_tgt->conditions))
+    return 0;
+
+  buf += strlen (buf);
+  xsnprintf (buf, buf_end - buf, "%s", ";");
+  buf++;
+
+  /* Send conditions to the target and free the vector.  */
+  for (ix = 0;
+       VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
+       ix++)
+    {
+      xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
+      buf += strlen (buf);
+      for (i = 0; i < aexpr->len; ++i)
+       buf = pack_hex_byte (buf, aexpr->buf[i]);
+      *buf = '\0';
+    }
+  return 0;
+}
 
 static void
-extended_remote_create_inferior (struct target_ops *ops, 
-                                char *exec_file, char *args,
-                                char **env, int from_tty)
+remote_add_target_side_commands (struct gdbarch *gdbarch,
+                                struct bp_target_info *bp_tgt, char *buf)
 {
-  extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
+  struct agent_expr *aexpr = NULL;
+  int i, ix;
+
+  if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
+    return;
+
+  buf += strlen (buf);
+
+  sprintf (buf, ";cmds:%x,", bp_tgt->persist);
+  buf += strlen (buf);
+
+  /* Concatenate all the agent expressions that are commands into the
+     cmds parameter.  */
+  for (ix = 0;
+       VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
+       ix++)
+    {
+      sprintf (buf, "X%x,", aexpr->len);
+      buf += strlen (buf);
+      for (i = 0; i < aexpr->len; ++i)
+       buf = pack_hex_byte (buf, aexpr->buf[i]);
+      *buf = '\0';
+    }
 }
-\f
 
 /* Insert a breakpoint.  On targets that have software breakpoint
    support, we ask the remote target to do the work; on targets
    which don't, we insert a traditional memory breakpoint.  */
 
 static int
-remote_insert_breakpoint (struct gdbarch *gdbarch,
+remote_insert_breakpoint (struct target_ops *ops,
+                         struct gdbarch *gdbarch,
                          struct bp_target_info *bp_tgt)
 {
   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
@@ -7591,20 +8059,33 @@ remote_insert_breakpoint (struct gdbarch *gdbarch,
     {
       CORE_ADDR addr = bp_tgt->placed_address;
       struct remote_state *rs;
-      char *p;
+      char *p, *endbuf;
       int bpsize;
+      struct condition_list *cond = NULL;
+
+      /* Make sure the remote is pointing at the right process, if
+        necessary.  */
+      if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
+       set_general_process ();
 
       gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
 
       rs = get_remote_state ();
       p = rs->buf;
+      endbuf = rs->buf + get_remote_packet_size ();
 
       *(p++) = 'Z';
       *(p++) = '0';
       *(p++) = ',';
       addr = (ULONGEST) remote_address_masked (addr);
       p += hexnumstr (p, addr);
-      sprintf (p, ",%d", bpsize);
+      xsnprintf (p, endbuf - p, ",%d", bpsize);
+
+      if (remote_supports_cond_breakpoints (ops))
+       remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
+
+      if (remote_can_run_breakpoint_commands (ops))
+       remote_add_target_side_commands (gdbarch, bp_tgt, p);
 
       putpkt (rs->buf);
       getpkt (&rs->buf, &rs->buf_size, 0);
@@ -7622,11 +8103,18 @@ remote_insert_breakpoint (struct gdbarch *gdbarch,
        }
     }
 
-  return memory_insert_breakpoint (gdbarch, bp_tgt);
+  /* If this breakpoint has target-side commands but this stub doesn't
+     support Z0 packets, throw error.  */
+  if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
+    throw_error (NOT_SUPPORTED_ERROR, _("\
+Target doesn't support breakpoints that have target side commands."));
+
+  return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
 }
 
 static int
-remote_remove_breakpoint (struct gdbarch *gdbarch,
+remote_remove_breakpoint (struct target_ops *ops,
+                         struct gdbarch *gdbarch,
                          struct bp_target_info *bp_tgt)
 {
   CORE_ADDR addr = bp_tgt->placed_address;
@@ -7635,6 +8123,12 @@ remote_remove_breakpoint (struct gdbarch *gdbarch,
   if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
     {
       char *p = rs->buf;
+      char *endbuf = rs->buf + get_remote_packet_size ();
+
+      /* Make sure the remote is pointing at the right process, if
+        necessary.  */
+      if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
+       set_general_process ();
 
       *(p++) = 'z';
       *(p++) = '0';
@@ -7642,7 +8136,7 @@ remote_remove_breakpoint (struct gdbarch *gdbarch,
 
       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
       p += hexnumstr (p, addr);
-      sprintf (p, ",%d", bp_tgt->placed_size);
+      xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
 
       putpkt (rs->buf);
       getpkt (&rs->buf, &rs->buf_size, 0);
@@ -7650,7 +8144,7 @@ remote_remove_breakpoint (struct gdbarch *gdbarch,
       return (rs->buf[0] == 'E');
     }
 
-  return memory_remove_breakpoint (gdbarch, bp_tgt);
+  return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
 }
 
 static int
@@ -7674,21 +8168,28 @@ watchpoint_to_Z_packet (int type)
 }
 
 static int
-remote_insert_watchpoint (CORE_ADDR addr, int len, int type,
+remote_insert_watchpoint (struct target_ops *self,
+                         CORE_ADDR addr, int len, int type,
                          struct expression *cond)
 {
   struct remote_state *rs = get_remote_state ();
+  char *endbuf = rs->buf + get_remote_packet_size ();
   char *p;
   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
 
   if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
     return 1;
 
-  sprintf (rs->buf, "Z%x,", packet);
+  /* Make sure the remote is pointing at the right process, if
+     necessary.  */
+  if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
+    set_general_process ();
+
+  xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
   p = strchr (rs->buf, '\0');
   addr = remote_address_masked (addr);
   p += hexnumstr (p, (ULONGEST) addr);
-  sprintf (p, ",%x", len);
+  xsnprintf (p, endbuf - p, ",%x", len);
 
   putpkt (rs->buf);
   getpkt (&rs->buf, &rs->buf_size, 0);
@@ -7706,23 +8207,39 @@ remote_insert_watchpoint (CORE_ADDR addr, int len, int type,
                  _("remote_insert_watchpoint: reached end of function"));
 }
 
+static int
+remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
+                                    CORE_ADDR start, int length)
+{
+  CORE_ADDR diff = remote_address_masked (addr - start);
+
+  return diff < length;
+}
+
 
 static int
-remote_remove_watchpoint (CORE_ADDR addr, int len, int type,
+remote_remove_watchpoint (struct target_ops *self,
+                         CORE_ADDR addr, int len, int type,
                          struct expression *cond)
 {
   struct remote_state *rs = get_remote_state ();
+  char *endbuf = rs->buf + get_remote_packet_size ();
   char *p;
   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
 
   if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
     return -1;
 
-  sprintf (rs->buf, "z%x,", packet);
+  /* Make sure the remote is pointing at the right process, if
+     necessary.  */
+  if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
+    set_general_process ();
+
+  xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
   p = strchr (rs->buf, '\0');
   addr = remote_address_masked (addr);
   p += hexnumstr (p, (ULONGEST) addr);
-  sprintf (p, ",%x", len);
+  xsnprintf (p, endbuf - p, ",%x", len);
   putpkt (rs->buf);
   getpkt (&rs->buf, &rs->buf_size, 0);
 
@@ -7740,10 +8257,26 @@ remote_remove_watchpoint (CORE_ADDR addr, int len, int type,
 
 
 int remote_hw_watchpoint_limit = -1;
+int remote_hw_watchpoint_length_limit = -1;
 int remote_hw_breakpoint_limit = -1;
 
 static int
-remote_check_watch_resources (int type, int cnt, int ot)
+remote_region_ok_for_hw_watchpoint (struct target_ops *self,
+                                   CORE_ADDR addr, int len)
+{
+  if (remote_hw_watchpoint_length_limit == 0)
+    return 0;
+  else if (remote_hw_watchpoint_length_limit < 0)
+    return 1;
+  else if (len <= remote_hw_watchpoint_length_limit)
+    return 1;
+  else
+    return 0;
+}
+
+static int
+remote_check_watch_resources (struct target_ops *self,
+                             int type, int cnt, int ot)
 {
   if (type == bp_hardware_breakpoint)
     {
@@ -7769,19 +8302,22 @@ remote_check_watch_resources (int type, int cnt, int ot)
 }
 
 static int
-remote_stopped_by_watchpoint (void)
+remote_stopped_by_watchpoint (struct target_ops *ops)
 {
-  return remote_stopped_by_watchpoint_p;
+  struct remote_state *rs = get_remote_state ();
+
+  return rs->remote_stopped_by_watchpoint_p;
 }
 
 static int
 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
 {
+  struct remote_state *rs = get_remote_state ();
   int rc = 0;
 
-  if (remote_stopped_by_watchpoint ())
+  if (remote_stopped_by_watchpoint (target))
     {
-      *addr_p = remote_watch_data_address;
+      *addr_p = rs->remote_watch_data_address;
       rc = 1;
     }
 
@@ -7790,12 +8326,13 @@ remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
 
 
 static int
-remote_insert_hw_breakpoint (struct gdbarch *gdbarch,
+remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
                             struct bp_target_info *bp_tgt)
 {
   CORE_ADDR addr;
   struct remote_state *rs;
-  char *p;
+  char *p, *endbuf;
+  char *message;
 
   /* The length field should be set to the size of a breakpoint
      instruction, even though we aren't inserting one ourselves.  */
@@ -7806,8 +8343,14 @@ remote_insert_hw_breakpoint (struct gdbarch *gdbarch,
   if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
     return -1;
 
+  /* Make sure the remote is pointing at the right process, if
+     necessary.  */
+  if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
+    set_general_process ();
+
   rs = get_remote_state ();
   p = rs->buf;
+  endbuf = rs->buf + get_remote_packet_size ();
 
   *(p++) = 'Z';
   *(p++) = '1';
@@ -7815,7 +8358,13 @@ remote_insert_hw_breakpoint (struct gdbarch *gdbarch,
 
   addr = remote_address_masked (bp_tgt->placed_address);
   p += hexnumstr (p, (ULONGEST) addr);
-  sprintf (p, ",%x", bp_tgt->placed_size);
+  xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
+
+  if (remote_supports_cond_breakpoints (self))
+    remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
+
+  if (remote_can_run_breakpoint_commands (self))
+    remote_add_target_side_commands (gdbarch, bp_tgt, p);
 
   putpkt (rs->buf);
   getpkt (&rs->buf, &rs->buf_size, 0);
@@ -7823,6 +8372,13 @@ remote_insert_hw_breakpoint (struct gdbarch *gdbarch,
   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
     {
     case PACKET_ERROR:
+      if (rs->buf[1] == '.')
+        {
+          message = strchr (rs->buf + 2, '.');
+          if (message)
+            error (_("Remote failure reply: %s"), message + 1);
+        }
+      return -1;
     case PACKET_UNKNOWN:
       return -1;
     case PACKET_OK:
@@ -7834,23 +8390,29 @@ remote_insert_hw_breakpoint (struct gdbarch *gdbarch,
 
 
 static int
-remote_remove_hw_breakpoint (struct gdbarch *gdbarch,
+remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
                             struct bp_target_info *bp_tgt)
 {
   CORE_ADDR addr;
   struct remote_state *rs = get_remote_state ();
   char *p = rs->buf;
+  char *endbuf = rs->buf + get_remote_packet_size ();
 
   if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
     return -1;
 
+  /* Make sure the remote is pointing at the right process, if
+     necessary.  */
+  if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
+    set_general_process ();
+
   *(p++) = 'z';
   *(p++) = '1';
   *(p++) = ',';
 
   addr = remote_address_masked (bp_tgt->placed_address);
   p += hexnumstr (p, (ULONGEST) addr);
-  sprintf (p, ",%x", bp_tgt->placed_size);
+  xsnprintf (p, endbuf  - p, ",%x", bp_tgt->placed_size);
 
   putpkt (rs->buf);
   getpkt (&rs->buf, &rs->buf_size, 0);
@@ -7867,46 +8429,19 @@ remote_remove_hw_breakpoint (struct gdbarch *gdbarch,
                  _("remote_remove_hw_breakpoint: reached end of function"));
 }
 
-/* Table used by the crc32 function to calcuate the checksum.  */
-
-static unsigned long crc32_table[256] =
-{0, 0};
+/* Verify memory using the "qCRC:" request.  */
 
-static unsigned long
-crc32 (const unsigned char *buf, int len, unsigned int crc)
-{
-  if (!crc32_table[1])
-    {
-      /* Initialize the CRC table and the decoding table.  */
-      int i, j;
-      unsigned int c;
-
-      for (i = 0; i < 256; i++)
-       {
-         for (c = i << 24, j = 8; j > 0; --j)
-           c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
-         crc32_table[i] = c;
-       }
-    }
-
-  while (len--)
-    {
-      crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
-      buf++;
-    }
-  return crc;
-}
-
-/* Verify memory using the "qCRC:" request.  */
-
-static int
-remote_verify_memory (struct target_ops *ops,
-                     const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
+static int
+remote_verify_memory (struct target_ops *ops,
+                     const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
 {
   struct remote_state *rs = get_remote_state ();
   unsigned long host_crc, target_crc;
   char *tmp;
 
+  /* Make sure the remote is pointing at the right process.  */
+  set_general_process ();
+
   /* FIXME: assumes lma can fit into long.  */
   xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
             (long) lma, (long) size);
@@ -7914,7 +8449,7 @@ remote_verify_memory (struct target_ops *ops,
 
   /* Be clever; compute the host_crc before waiting for target
      reply.  */
-  host_crc = crc32 (data, size, 0xffffffff);
+  host_crc = xcrc32 (data, size, 0xffffffff);
 
   getpkt (&rs->buf, &rs->buf_size, 0);
   if (rs->buf[0] == 'E')
@@ -7940,7 +8475,7 @@ compare_sections_command (char *args, int from_tty)
 {
   asection *s;
   struct cleanup *old_chain;
-  char *sectdata;
+  gdb_byte *sectdata;
   const char *sectname;
   bfd_size_type size;
   bfd_vma lma;
@@ -7951,6 +8486,9 @@ compare_sections_command (char *args, int from_tty)
   if (!exec_bfd)
     error (_("command cannot be used without an exec file"));
 
+  /* Make sure the remote is pointing at the right process.  */
+  set_general_process ();
+
   for (s = exec_bfd->sections; s; s = s->next)
     {
       if (!(s->flags & SEC_LOAD))
@@ -7975,12 +8513,12 @@ compare_sections_command (char *args, int from_tty)
 
       if (res == -1)
        error (_("target memory fault, section %s, range %s -- %s"), sectname,
-              paddress (target_gdbarch, lma),
-              paddress (target_gdbarch, lma + size));
+              paddress (target_gdbarch (), lma),
+              paddress (target_gdbarch (), lma + size));
 
       printf_filtered ("Section %s, range %s -- %s: ", sectname,
-                      paddress (target_gdbarch, lma),
-                      paddress (target_gdbarch, lma + size));
+                      paddress (target_gdbarch (), lma),
+                      paddress (target_gdbarch (), lma + size));
       if (res)
        printf_filtered ("matched.\n");
       else
@@ -8002,10 +8540,10 @@ the loaded file\n"));
    into remote target.  The number of bytes written to the remote
    target is returned, or -1 for error.  */
 
-static LONGEST
+static enum target_xfer_status
 remote_write_qxfer (struct target_ops *ops, const char *object_name,
                     const char *annex, const gdb_byte *writebuf, 
-                    ULONGEST offset, LONGEST len, 
+                    ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
                     struct packet_config *packet)
 {
   int i, buf_len;
@@ -8014,7 +8552,7 @@ remote_write_qxfer (struct target_ops *ops, const char *object_name,
   int max_size = get_memory_write_packet_size (); 
 
   if (packet->support == PACKET_DISABLE)
-    return -1;
+    return TARGET_XFER_E_IO;
 
   /* Insert header.  */
   i = snprintf (rs->buf, max_size, 
@@ -8025,15 +8563,17 @@ remote_write_qxfer (struct target_ops *ops, const char *object_name,
 
   /* Escape as much data as fits into rs->buf.  */
   buf_len = remote_escape_output 
-    (writebuf, len, (rs->buf + i), &max_size, max_size);
+    (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
 
   if (putpkt_binary (rs->buf, i + buf_len) < 0
       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
       || packet_ok (rs->buf, packet) != PACKET_OK)
-    return -1;
+    return TARGET_XFER_E_IO;
 
   unpack_varlen_hex (rs->buf, &n);
-  return n;
+
+  *xfered_len = n;
+  return TARGET_XFER_OK;
 }
 
 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
@@ -8043,37 +8583,35 @@ remote_write_qxfer (struct target_ops *ops, const char *object_name,
    EOF.  PACKET is checked and updated to indicate whether the remote
    target supports this object.  */
 
-static LONGEST
+static enum target_xfer_status
 remote_read_qxfer (struct target_ops *ops, const char *object_name,
                   const char *annex,
                   gdb_byte *readbuf, ULONGEST offset, LONGEST len,
+                  ULONGEST *xfered_len,
                   struct packet_config *packet)
 {
-  static char *finished_object;
-  static char *finished_annex;
-  static ULONGEST finished_offset;
-
   struct remote_state *rs = get_remote_state ();
   LONGEST i, n, packet_len;
 
   if (packet->support == PACKET_DISABLE)
-    return -1;
+    return TARGET_XFER_E_IO;
 
   /* Check whether we've cached an end-of-object packet that matches
      this request.  */
-  if (finished_object)
+  if (rs->finished_object)
     {
-      if (strcmp (object_name, finished_object) == 0
-         && strcmp (annex ? annex : "", finished_annex) == 0
-         && offset == finished_offset)
-       return 0;
+      if (strcmp (object_name, rs->finished_object) == 0
+         && strcmp (annex ? annex : "", rs->finished_annex) == 0
+         && offset == rs->finished_offset)
+       return TARGET_XFER_EOF;
+
 
       /* Otherwise, we're now reading something different.  Discard
         the cache.  */
-      xfree (finished_object);
-      xfree (finished_annex);
-      finished_object = NULL;
-      finished_annex = NULL;
+      xfree (rs->finished_object);
+      xfree (rs->finished_annex);
+      rs->finished_object = NULL;
+      rs->finished_annex = NULL;
     }
 
   /* Request only enough to fit in a single packet.  The actual data
@@ -8087,12 +8625,12 @@ remote_read_qxfer (struct target_ops *ops, const char *object_name,
            phex_nz (n, sizeof n));
   i = putpkt (rs->buf);
   if (i < 0)
-    return -1;
+    return TARGET_XFER_E_IO;
 
   rs->buf[0] = '\0';
   packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
-    return -1;
+    return TARGET_XFER_E_IO;
 
   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
     error (_("Unknown remote qXfer reply: %s"), rs->buf);
@@ -8104,25 +8642,33 @@ remote_read_qxfer (struct target_ops *ops, const char *object_name,
     error (_("Remote qXfer reply contained no data."));
 
   /* Got some data.  */
-  i = remote_unescape_input (rs->buf + 1, packet_len - 1, readbuf, n);
+  i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
+                            packet_len - 1, readbuf, n);
 
   /* 'l' is an EOF marker, possibly including a final block of data,
      or possibly empty.  If we have the final block of a non-empty
      object, record this fact to bypass a subsequent partial read.  */
   if (rs->buf[0] == 'l' && offset + i > 0)
     {
-      finished_object = xstrdup (object_name);
-      finished_annex = xstrdup (annex ? annex : "");
-      finished_offset = offset + i;
+      rs->finished_object = xstrdup (object_name);
+      rs->finished_annex = xstrdup (annex ? annex : "");
+      rs->finished_offset = offset + i;
     }
 
-  return i;
+  if (i == 0)
+    return TARGET_XFER_EOF;
+  else
+    {
+      *xfered_len = i;
+      return TARGET_XFER_OK;
+    }
 }
 
-static LONGEST
+static enum target_xfer_status
 remote_xfer_partial (struct target_ops *ops, enum target_object object,
                     const char *annex, gdb_byte *readbuf,
-                    const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
+                    const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
+                    ULONGEST *xfered_len)
 {
   struct remote_state *rs;
   int i;
@@ -8137,27 +8683,16 @@ remote_xfer_partial (struct target_ops *ops, enum target_object object,
   /* Handle memory using the standard memory routines.  */
   if (object == TARGET_OBJECT_MEMORY)
     {
-      int xfered;
-
-      errno = 0;
-
       /* If the remote target is connected but not running, we should
         pass this request down to a lower stratum (e.g. the executable
         file).  */
       if (!target_has_execution)
-       return 0;
+       return TARGET_XFER_EOF;
 
       if (writebuf != NULL)
-       xfered = remote_write_bytes (offset, writebuf, len);
-      else
-       xfered = remote_read_bytes (offset, readbuf, len);
-
-      if (xfered > 0)
-       return xfered;
-      else if (xfered == 0 && errno == 0)
-       return 0;
+       return remote_write_bytes (offset, writebuf, len, xfered_len);
       else
-       return -1;
+       return remote_read_bytes (offset, readbuf, len, xfered_len);
     }
 
   /* Handle SPU memory using qxfer packets.  */
@@ -8165,12 +8700,12 @@ remote_xfer_partial (struct target_ops *ops, enum target_object object,
     {
       if (readbuf)
        return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
-                                 &remote_protocol_packets
-                                   [PACKET_qXfer_spu_read]);
+                                 xfered_len, &remote_protocol_packets
+                                 [PACKET_qXfer_spu_read]);
       else
        return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
-                                  &remote_protocol_packets
-                                    [PACKET_qXfer_spu_write]);
+                                  xfered_len, &remote_protocol_packets
+                                  [PACKET_qXfer_spu_write]);
     }
 
   /* Handle extra signal info using qxfer packets.  */
@@ -8178,11 +8713,11 @@ remote_xfer_partial (struct target_ops *ops, enum target_object object,
     {
       if (readbuf)
        return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
-                                 &remote_protocol_packets
+                                 xfered_len, &remote_protocol_packets
                                  [PACKET_qXfer_siginfo_read]);
       else
        return remote_write_qxfer (ops, "siginfo", annex,
-                                  writebuf, offset, len,
+                                  writebuf, offset, len, xfered_len,
                                   &remote_protocol_packets
                                   [PACKET_qXfer_siginfo_write]);
     }
@@ -8191,11 +8726,11 @@ remote_xfer_partial (struct target_ops *ops, enum target_object object,
     {
       if (readbuf)
        return remote_read_qxfer (ops, "statictrace", annex,
-                                 readbuf, offset, len,
+                                 readbuf, offset, len, xfered_len,
                                  &remote_protocol_packets
                                  [PACKET_qXfer_statictrace_read]);
       else
-       return -1;
+       return TARGET_XFER_E_IO;
     }
 
   /* Only handle flash writes.  */
@@ -8206,17 +8741,11 @@ remote_xfer_partial (struct target_ops *ops, enum target_object object,
       switch (object)
        {
        case TARGET_OBJECT_FLASH:
-         xfered = remote_flash_write (ops, offset, len, writebuf);
-
-         if (xfered > 0)
-           return xfered;
-         else if (xfered == 0 && errno == 0)
-           return 0;
-         else
-           return -1;
+         return remote_flash_write (ops, offset, len, xfered_len,
+                                    writebuf);
 
        default:
-         return -1;
+         return TARGET_XFER_E_IO;
        }
     }
 
@@ -8231,42 +8760,66 @@ remote_xfer_partial (struct target_ops *ops, enum target_object object,
     case TARGET_OBJECT_AUXV:
       gdb_assert (annex == NULL);
       return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
+                               xfered_len,
                                &remote_protocol_packets[PACKET_qXfer_auxv]);
 
     case TARGET_OBJECT_AVAILABLE_FEATURES:
       return remote_read_qxfer
-       (ops, "features", annex, readbuf, offset, len,
+       (ops, "features", annex, readbuf, offset, len, xfered_len,
         &remote_protocol_packets[PACKET_qXfer_features]);
 
     case TARGET_OBJECT_LIBRARIES:
       return remote_read_qxfer
-       (ops, "libraries", annex, readbuf, offset, len,
+       (ops, "libraries", annex, readbuf, offset, len, xfered_len,
         &remote_protocol_packets[PACKET_qXfer_libraries]);
 
+    case TARGET_OBJECT_LIBRARIES_SVR4:
+      return remote_read_qxfer
+       (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
+        &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
+
     case TARGET_OBJECT_MEMORY_MAP:
       gdb_assert (annex == NULL);
       return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
+                                xfered_len,
                                &remote_protocol_packets[PACKET_qXfer_memory_map]);
 
     case TARGET_OBJECT_OSDATA:
       /* Should only get here if we're connected.  */
-      gdb_assert (remote_desc);
+      gdb_assert (rs->remote_desc);
       return remote_read_qxfer
-       (ops, "osdata", annex, readbuf, offset, len,
+       (ops, "osdata", annex, readbuf, offset, len, xfered_len,
         &remote_protocol_packets[PACKET_qXfer_osdata]);
 
     case TARGET_OBJECT_THREADS:
       gdb_assert (annex == NULL);
       return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
+                               xfered_len,
                                &remote_protocol_packets[PACKET_qXfer_threads]);
 
     case TARGET_OBJECT_TRACEFRAME_INFO:
       gdb_assert (annex == NULL);
       return remote_read_qxfer
-       (ops, "traceframe-info", annex, readbuf, offset, len,
+       (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
         &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
+
+    case TARGET_OBJECT_FDPIC:
+      return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
+                               xfered_len,
+                               &remote_protocol_packets[PACKET_qXfer_fdpic]);
+
+    case TARGET_OBJECT_OPENVMS_UIB:
+      return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
+                               xfered_len,
+                               &remote_protocol_packets[PACKET_qXfer_uib]);
+
+    case TARGET_OBJECT_BTRACE:
+      return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
+                               xfered_len,
+        &remote_protocol_packets[PACKET_qXfer_btrace]);
+
     default:
-      return -1;
+      return TARGET_XFER_E_IO;
     }
 
   /* Note: a zero OFFSET and LEN can be used to query the minimum
@@ -8276,11 +8829,11 @@ remote_xfer_partial (struct target_ops *ops, enum target_object object,
   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
      large enough let the caller deal with it.  */
   if (len < get_remote_packet_size ())
-    return -1;
+    return TARGET_XFER_E_IO;
   len = get_remote_packet_size ();
 
   /* Except for querying the minimum buffer size, target must be open.  */
-  if (!remote_desc)
+  if (!rs->remote_desc)
     error (_("remote query is only available after target open"));
 
   gdb_assert (annex != NULL);
@@ -8308,12 +8861,13 @@ remote_xfer_partial (struct target_ops *ops, enum target_object object,
 
   i = putpkt (rs->buf);
   if (i < 0)
-    return i;
+    return TARGET_XFER_E_IO;
 
   getpkt (&rs->buf, &rs->buf_size, 0);
   strcpy ((char *) readbuf, rs->buf);
 
-  return strlen ((char *) readbuf);
+  *xfered_len = strlen ((char *) readbuf);
+  return TARGET_XFER_OK;
 }
 
 static int
@@ -8322,7 +8876,7 @@ remote_search_memory (struct target_ops* ops,
                      const gdb_byte *pattern, ULONGEST pattern_len,
                      CORE_ADDR *found_addrp)
 {
-  int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
+  int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
   struct remote_state *rs = get_remote_state ();
   int max_size = get_memory_write_packet_size ();
   struct packet_config *packet =
@@ -8358,6 +8912,9 @@ remote_search_memory (struct target_ops* ops,
                                   pattern, pattern_len, found_addrp);
     }
 
+  /* Make sure the remote is pointing at the right process.  */
+  set_general_process ();
+
   /* Insert header.  */
   i = snprintf (rs->buf, max_size, 
                "qSearch:memory:%s;%s;",
@@ -8367,7 +8924,7 @@ remote_search_memory (struct target_ops* ops,
 
   /* Escape as much data as fits into rs->buf.  */
   escaped_pattern_len =
-    remote_escape_output (pattern, pattern_len, (rs->buf + i),
+    remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
                          &used_pattern_len, max_size);
 
   /* Bail if the pattern is too large.  */
@@ -8405,13 +8962,13 @@ remote_search_memory (struct target_ops* ops,
 }
 
 static void
-remote_rcmd (char *command,
+remote_rcmd (struct target_ops *self, char *command,
             struct ui_file *outbuf)
 {
   struct remote_state *rs = get_remote_state ();
   char *p = rs->buf;
 
-  if (!remote_desc)
+  if (!rs->remote_desc)
     error (_("remote rcmd is only available after target open"));
 
   /* Send a NULL command across as an empty command.  */
@@ -8427,7 +8984,7 @@ remote_rcmd (char *command,
     error (_("\"monitor\" command ``%s'' is too long."), command);
 
   /* Encode the actual command.  */
-  bin2hex ((gdb_byte *) command, p, 0);
+  bin2hex ((gdb_byte *) command, p, strlen (command));
 
   if (putpkt (rs->buf) < 0)
     error (_("Communication problem with target."));
@@ -8438,8 +8995,17 @@ remote_rcmd (char *command,
       char *buf;
 
       /* XXX - see also remote_get_noisy_reply().  */
+      QUIT;                    /* Allow user to bail out with ^C.  */
       rs->buf[0] = '\0';
-      getpkt (&rs->buf, &rs->buf_size, 0);
+      if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
+        { 
+          /* Timeout.  Continue to (try to) read responses.
+             This is better than stopping with an error, assuming the stub
+             is still executing the (long) monitor command.
+             If needed, the user can interrupt gdb using C-c, obtaining
+             an effect similar to stop on timeout.  */
+          continue;
+        }
       buf = rs->buf;
       if (buf[0] == '\0')
        error (_("Target does not support this command."));
@@ -8488,7 +9054,7 @@ packet_command (char *args, int from_tty)
 {
   struct remote_state *rs = get_remote_state ();
 
-  if (!remote_desc)
+  if (!rs->remote_desc)
     error (_("command can only be used with remote target"));
 
   if (!args)
@@ -8662,7 +9228,9 @@ remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
   static char buf[64];
   struct remote_state *rs = get_remote_state ();
 
-  if (ptid_is_pid (ptid))
+  if (ptid_equal (ptid, null_ptid))
+    return normal_pid_to_str (ptid);
+  else if (ptid_is_pid (ptid))
     {
       /* Printing an inferior target id.  */
 
@@ -8687,7 +9255,7 @@ remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
     {
       if (ptid_equal (magic_null_ptid, ptid))
        xsnprintf (buf, sizeof buf, "Thread <main>");
-      else if (remote_multi_process_p (rs))
+      else if (rs->extended && remote_multi_process_p (rs))
        xsnprintf (buf, sizeof buf, "Thread %d.%ld",
                   ptid_get_pid (ptid), ptid_get_tid (ptid));
       else
@@ -8748,7 +9316,7 @@ remote_get_thread_local_address (struct target_ops *ops,
 /* Provide thread local base, i.e. Thread Information Block address.
    Returns 1 if ptid is found and thread_local_base is non zero.  */
 
-int
+static int
 remote_get_tib_address (ptid_t ptid, CORE_ADDR *addr)
 {
   if (remote_protocol_packets[PACKET_qGetTIBAddr].support != PACKET_DISABLE)
@@ -8845,7 +9413,7 @@ static int
 remote_read_description_p (struct target_ops *target)
 {
   struct remote_g_packet_data *data
-    = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
+    = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
 
   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
     return 1;
@@ -8857,7 +9425,7 @@ static const struct target_desc *
 remote_read_description (struct target_ops *target)
 {
   struct remote_g_packet_data *data
-    = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
+    = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
 
   /* Do not try this during initial connection, when we do not know
      whether there is a running but stopped thread.  */
@@ -9026,7 +9594,7 @@ remote_hostio_send_command (int command_bytes, int which_packet,
   int ret, bytes_read;
   char *attachment_tmp;
 
-  if (!remote_desc
+  if (!rs->remote_desc
       || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
     {
       *remote_errno = FILEIO_ENOSYS;
@@ -9087,7 +9655,8 @@ remote_hostio_send_command (int command_bytes, int which_packet,
    *REMOTE_ERRNO).  */
 
 static int
-remote_hostio_open (const char *filename, int flags, int mode,
+remote_hostio_open (struct target_ops *self,
+                   const char *filename, int flags, int mode,
                    int *remote_errno)
 {
   struct remote_state *rs = get_remote_state ();
@@ -9114,7 +9683,8 @@ remote_hostio_open (const char *filename, int flags, int mode,
    set *REMOTE_ERRNO).  */
 
 static int
-remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
+remote_hostio_pwrite (struct target_ops *self,
+                     int fd, const gdb_byte *write_buf, int len,
                      ULONGEST offset, int *remote_errno)
 {
   struct remote_state *rs = get_remote_state ();
@@ -9130,7 +9700,7 @@ remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
   remote_buffer_add_int (&p, &left, offset);
   remote_buffer_add_string (&p, &left, ",");
 
-  p += remote_escape_output (write_buf, len, p, &out_len,
+  p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
                             get_remote_packet_size () - (p - rs->buf));
 
   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
@@ -9142,7 +9712,8 @@ remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
    set *REMOTE_ERRNO).  */
 
 static int
-remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
+remote_hostio_pread (struct target_ops *self,
+                    int fd, gdb_byte *read_buf, int len,
                     ULONGEST offset, int *remote_errno)
 {
   struct remote_state *rs = get_remote_state ();
@@ -9169,7 +9740,7 @@ remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
   if (ret < 0)
     return ret;
 
-  read_len = remote_unescape_input (attachment, attachment_len,
+  read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
                                    read_buf, len);
   if (read_len != ret)
     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
@@ -9214,6 +9785,44 @@ remote_hostio_unlink (const char *filename, int *remote_errno)
                                     remote_errno, NULL, NULL);
 }
 
+/* Read value of symbolic link FILENAME on the remote target.  Return
+   a null-terminated string allocated via xmalloc, or NULL if an error
+   occurs (and set *REMOTE_ERRNO).  */
+
+static char *
+remote_hostio_readlink (const char *filename, int *remote_errno)
+{
+  struct remote_state *rs = get_remote_state ();
+  char *p = rs->buf;
+  char *attachment;
+  int left = get_remote_packet_size ();
+  int len, attachment_len;
+  int read_len;
+  char *ret;
+
+  remote_buffer_add_string (&p, &left, "vFile:readlink:");
+
+  remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
+                          strlen (filename));
+
+  len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
+                                   remote_errno, &attachment,
+                                   &attachment_len);
+
+  if (len < 0)
+    return NULL;
+
+  ret = xmalloc (len + 1);
+
+  read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
+                                   (gdb_byte *) ret, len);
+  if (read_len != len)
+    error (_("Readlink returned %d, but %d bytes."), len, read_len);
+
+  ret[len] = '\0';
+  return ret;
+}
+
 static int
 remote_fileio_errno_to_host (int errnum)
 {
@@ -9295,7 +9904,8 @@ remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
 
   gdb_assert (remote_filename_p (filename));
 
-  fd = remote_hostio_open (filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
+  fd = remote_hostio_open (find_target_at (process_stratum),
+                          filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
   if (fd == -1)
     {
       errno = remote_fileio_errno_to_host (remote_errno);
@@ -9320,7 +9930,8 @@ remote_bfd_iovec_close (struct bfd *abfd, void *stream)
      connection was already torn down.  */
   remote_hostio_close (fd, &remote_errno);
 
-  return 1;
+  /* Zero means success.  */
+  return 0;
 }
 
 static file_ptr
@@ -9334,7 +9945,8 @@ remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
   pos = 0;
   while (nbytes > pos)
     {
-      bytes = remote_hostio_pread (fd, (char *)buf + pos, nbytes - pos,
+      bytes = remote_hostio_pread (find_target_at (process_stratum),
+                                  fd, (gdb_byte *) buf + pos, nbytes - pos,
                                   offset + pos, &remote_errno);
       if (bytes == 0)
         /* Success, but no bytes, means end-of-file.  */
@@ -9363,17 +9975,21 @@ remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
 int
 remote_filename_p (const char *filename)
 {
-  return strncmp (filename, "remote:", 7) == 0;
+  return strncmp (filename,
+                 REMOTE_SYSROOT_PREFIX,
+                 sizeof (REMOTE_SYSROOT_PREFIX) - 1) == 0;
 }
 
 bfd *
 remote_bfd_open (const char *remote_file, const char *target)
 {
-  return bfd_openr_iovec (remote_file, target,
-                         remote_bfd_iovec_open, NULL,
-                         remote_bfd_iovec_pread,
-                         remote_bfd_iovec_close,
-                         remote_bfd_iovec_stat);
+  bfd *abfd = gdb_bfd_openr_iovec (remote_file, target,
+                                  remote_bfd_iovec_open, NULL,
+                                  remote_bfd_iovec_pread,
+                                  remote_bfd_iovec_close,
+                                  remote_bfd_iovec_stat);
+
+  return abfd;
 }
 
 void
@@ -9386,16 +10002,18 @@ remote_file_put (const char *local_file, const char *remote_file, int from_tty)
   int bytes_in_buffer;
   int saw_eof;
   ULONGEST offset;
+  struct remote_state *rs = get_remote_state ();
 
-  if (!remote_desc)
+  if (!rs->remote_desc)
     error (_("command can only be used with remote target"));
 
-  file = fopen (local_file, "rb");
+  file = gdb_fopen_cloexec (local_file, "rb");
   if (file == NULL)
     perror_with_name (local_file);
   back_to = make_cleanup_fclose (file);
 
-  fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
+  fd = remote_hostio_open (find_target_at (process_stratum),
+                          remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
                                         | FILEIO_O_TRUNC),
                           0700, &remote_errno);
   if (fd == -1)
@@ -9439,7 +10057,8 @@ remote_file_put (const char *local_file, const char *remote_file, int from_tty)
       bytes += bytes_in_buffer;
       bytes_in_buffer = 0;
 
-      retcode = remote_hostio_pwrite (fd, buffer, bytes,
+      retcode = remote_hostio_pwrite (find_target_at (process_stratum),
+                                     fd, buffer, bytes,
                                      offset, &remote_errno);
 
       if (retcode < 0)
@@ -9474,15 +10093,17 @@ remote_file_get (const char *remote_file, const char *local_file, int from_tty)
   FILE *file;
   gdb_byte *buffer;
   ULONGEST offset;
+  struct remote_state *rs = get_remote_state ();
 
-  if (!remote_desc)
+  if (!rs->remote_desc)
     error (_("command can only be used with remote target"));
 
-  fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
+  fd = remote_hostio_open (find_target_at (process_stratum),
+                          remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
   if (fd == -1)
     remote_hostio_error (remote_errno);
 
-  file = fopen (local_file, "wb");
+  file = gdb_fopen_cloexec (local_file, "wb");
   if (file == NULL)
     perror_with_name (local_file);
   back_to = make_cleanup_fclose (file);
@@ -9498,7 +10119,8 @@ remote_file_get (const char *remote_file, const char *local_file, int from_tty)
   offset = 0;
   while (1)
     {
-      bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
+      bytes = remote_hostio_pread (find_target_at (process_stratum),
+                                  fd, buffer, io_size, offset, &remote_errno);
       if (bytes == 0)
        /* Success, but no bytes, means end-of-file.  */
        break;
@@ -9525,8 +10147,9 @@ void
 remote_file_delete (const char *remote_file, int from_tty)
 {
   int retcode, remote_errno;
+  struct remote_state *rs = get_remote_state ();
 
-  if (!remote_desc)
+  if (!rs->remote_desc)
     error (_("command can only be used with remote target"));
 
   retcode = remote_hostio_unlink (remote_file, &remote_errno);
@@ -9601,7 +10224,7 @@ remote_command (char *args, int from_tty)
 }
 
 static int
-remote_can_execute_reverse (void)
+remote_can_execute_reverse (struct target_ops *self)
 {
   if (remote_protocol_packets[PACKET_bs].support == PACKET_ENABLE
       || remote_protocol_packets[PACKET_bc].support == PACKET_ENABLE)
@@ -9611,20 +10234,31 @@ remote_can_execute_reverse (void)
 }
 
 static int
-remote_supports_non_stop (void)
+remote_supports_non_stop (struct target_ops *self)
 {
   return 1;
 }
 
 static int
-remote_supports_multi_process (void)
+remote_supports_disable_randomization (struct target_ops *self)
+{
+  /* Only supported in extended mode.  */
+  return 0;
+}
+
+static int
+remote_supports_multi_process (struct target_ops *self)
 {
   struct remote_state *rs = get_remote_state ();
 
-  return remote_multi_process_p (rs);
+  /* Only extended-remote handles being attached to multiple
+     processes, even though plain remote can use the multi-process
+     thread id extensions, so that GDB knows the target process's
+     PID.  */
+  return rs->extended && remote_multi_process_p (rs);
 }
 
-int
+static int
 remote_supports_cond_tracepoints (void)
 {
   struct remote_state *rs = get_remote_state ();
@@ -9632,7 +10266,15 @@ remote_supports_cond_tracepoints (void)
   return rs->cond_tracepoints;
 }
 
-int
+static int
+remote_supports_cond_breakpoints (struct target_ops *self)
+{
+  struct remote_state *rs = get_remote_state ();
+
+  return rs->cond_breakpoints;
+}
+
+static int
 remote_supports_fast_tracepoints (void)
 {
   struct remote_state *rs = get_remote_state ();
@@ -9648,6 +10290,38 @@ remote_supports_static_tracepoints (void)
   return rs->static_tracepoints;
 }
 
+static int
+remote_supports_install_in_trace (void)
+{
+  struct remote_state *rs = get_remote_state ();
+
+  return rs->install_in_trace;
+}
+
+static int
+remote_supports_enable_disable_tracepoint (struct target_ops *self)
+{
+  struct remote_state *rs = get_remote_state ();
+
+  return rs->enable_disable_tracepoints;
+}
+
+static int
+remote_supports_string_tracing (struct target_ops *self)
+{
+  struct remote_state *rs = get_remote_state ();
+
+  return rs->string_tracing;
+}
+
+static int
+remote_can_run_breakpoint_commands (struct target_ops *self)
+{
+  struct remote_state *rs = get_remote_state ();
+
+  return rs->breakpoint_commands;
+}
+
 static void
 remote_trace_init (void)
 {
@@ -9720,12 +10394,13 @@ remote_download_command_source (int num, ULONGEST addr,
 }
 
 static void
-remote_download_tracepoint (struct breakpoint *t)
+remote_download_tracepoint (struct bp_location *loc)
 {
-  struct bp_location *loc;
+#define BUF_SIZE 2048
+
   CORE_ADDR tpaddr;
   char addrbuf[40];
-  char buf[2048];
+  char buf[BUF_SIZE];
   char **tdp_actions;
   char **stepping_actions;
   int ndx;
@@ -9733,182 +10408,209 @@ remote_download_tracepoint (struct breakpoint *t)
   struct agent_expr *aexpr;
   struct cleanup *aexpr_chain = NULL;
   char *pkt;
-
-  /* Iterate over all the tracepoint locations.  It's up to the target to
-     notice multiple tracepoint packets with the same number but different
-     addresses, and treat them as multiple locations.  */
-  for (loc = t->loc; loc; loc = loc->next)
-    {
-      encode_actions (t, loc, &tdp_actions, &stepping_actions);
-      old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
-                               tdp_actions);
-      (void) make_cleanup (free_actions_list_cleanup_wrapper,
-                          stepping_actions);
-
-      tpaddr = loc->address;
-      sprintf_vma (addrbuf, tpaddr);
-      sprintf (buf, "QTDP:%x:%s:%c:%lx:%x", t->number, 
-              addrbuf, /* address */
-              (t->enable_state == bp_enabled ? 'E' : 'D'),
-              t->step_count, t->pass_count);
-      /* Fast tracepoints are mostly handled by the target, but we can
-        tell the target how big of an instruction block should be moved
-        around.  */
-      if (t->type == bp_fast_tracepoint)
+  struct breakpoint *b = loc->owner;
+  struct tracepoint *t = (struct tracepoint *) b;
+
+  encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
+  old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
+                           tdp_actions);
+  (void) make_cleanup (free_actions_list_cleanup_wrapper,
+                      stepping_actions);
+
+  tpaddr = loc->address;
+  sprintf_vma (addrbuf, tpaddr);
+  xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
+            addrbuf, /* address */
+            (b->enable_state == bp_enabled ? 'E' : 'D'),
+            t->step_count, t->pass_count);
+  /* Fast tracepoints are mostly handled by the target, but we can
+     tell the target how big of an instruction block should be moved
+     around.  */
+  if (b->type == bp_fast_tracepoint)
+    {
+      /* Only test for support at download time; we may not know
+        target capabilities at definition time.  */
+      if (remote_supports_fast_tracepoints ())
        {
-         /* Only test for support at download time; we may not know
-            target capabilities at definition time.  */
-         if (remote_supports_fast_tracepoints ())
-           {
-             int isize;
+         int isize;
 
-             if (gdbarch_fast_tracepoint_valid_at (target_gdbarch,
-                                                   tpaddr, &isize, NULL))
-               sprintf (buf + strlen (buf), ":F%x", isize);
-             else
-               /* If it passed validation at definition but fails now,
-                  something is very wrong.  */
-               internal_error (__FILE__, __LINE__,
-                               _("Fast tracepoint not "
-                                 "valid during download"));
-           }
+         if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
+                                               tpaddr, &isize, NULL))
+           xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
+                      isize);
          else
-           /* Fast tracepoints are functionally identical to regular
-              tracepoints, so don't take lack of support as a reason to
-              give up on the trace run.  */
-           warning (_("Target does not support fast tracepoints, "
-                      "downloading %d as regular tracepoint"), t->number);
+           /* If it passed validation at definition but fails now,
+              something is very wrong.  */
+           internal_error (__FILE__, __LINE__,
+                           _("Fast tracepoint not "
+                             "valid during download"));
        }
-      else if (t->type == bp_static_tracepoint)
+      else
+       /* Fast tracepoints are functionally identical to regular
+          tracepoints, so don't take lack of support as a reason to
+          give up on the trace run.  */
+       warning (_("Target does not support fast tracepoints, "
+                  "downloading %d as regular tracepoint"), b->number);
+    }
+  else if (b->type == bp_static_tracepoint)
+    {
+      /* Only test for support at download time; we may not know
+        target capabilities at definition time.  */
+      if (remote_supports_static_tracepoints ())
        {
-         /* Only test for support at download time; we may not know
-            target capabilities at definition time.  */
-         if (remote_supports_static_tracepoints ())
-           {
-             struct static_tracepoint_marker marker;
+         struct static_tracepoint_marker marker;
 
-             if (target_static_tracepoint_marker_at (tpaddr, &marker))
-               strcat (buf, ":S");
-             else
-               error (_("Static tracepoint not valid during download"));
-           }
+         if (target_static_tracepoint_marker_at (tpaddr, &marker))
+           strcat (buf, ":S");
          else
-           /* Fast tracepoints are functionally identical to regular
-              tracepoints, so don't take lack of support as a reason
-              to give up on the trace run.  */
-           error (_("Target does not support static tracepoints"));
+           error (_("Static tracepoint not valid during download"));
        }
-      /* If the tracepoint has a conditional, make it into an agent
-        expression and append to the definition.  */
-      if (loc->cond)
+      else
+       /* Fast tracepoints are functionally identical to regular
+          tracepoints, so don't take lack of support as a reason
+          to give up on the trace run.  */
+       error (_("Target does not support static tracepoints"));
+    }
+  /* If the tracepoint has a conditional, make it into an agent
+     expression and append to the definition.  */
+  if (loc->cond)
+    {
+      /* Only test support at download time, we may not know target
+        capabilities at definition time.  */
+      if (remote_supports_cond_tracepoints ())
        {
-         /* Only test support at download time, we may not know target
-            capabilities at definition time.  */
-         if (remote_supports_cond_tracepoints ())
-           {
-             aexpr = gen_eval_for_expr (tpaddr, loc->cond);
-             aexpr_chain = make_cleanup_free_agent_expr (aexpr);
-             sprintf (buf + strlen (buf), ":X%x,", aexpr->len);
-             pkt = buf + strlen (buf);
-             for (ndx = 0; ndx < aexpr->len; ++ndx)
-               pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
-             *pkt = '\0';
-             do_cleanups (aexpr_chain);
-           }
-         else
-           warning (_("Target does not support conditional tracepoints, "
-                      "ignoring tp %d cond"), t->number);
+         aexpr = gen_eval_for_expr (tpaddr, loc->cond);
+         aexpr_chain = make_cleanup_free_agent_expr (aexpr);
+         xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
+                    aexpr->len);
+         pkt = buf + strlen (buf);
+         for (ndx = 0; ndx < aexpr->len; ++ndx)
+           pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
+         *pkt = '\0';
+         do_cleanups (aexpr_chain);
        }
+      else
+       warning (_("Target does not support conditional tracepoints, "
+                  "ignoring tp %d cond"), b->number);
+    }
 
-  if (t->commands || *default_collect)
-       strcat (buf, "-");
-      putpkt (buf);
-      remote_get_noisy_reply (&target_buf, &target_buf_size);
-      if (strcmp (target_buf, "OK"))
-       error (_("Target does not support tracepoints."));
+  if (b->commands || *default_collect)
+    strcat (buf, "-");
+  putpkt (buf);
+  remote_get_noisy_reply (&target_buf, &target_buf_size);
+  if (strcmp (target_buf, "OK"))
+    error (_("Target does not support tracepoints."));
 
-      /* do_single_steps (t); */
-      if (tdp_actions)
+  /* do_single_steps (t); */
+  if (tdp_actions)
+    {
+      for (ndx = 0; tdp_actions[ndx]; ndx++)
        {
-         for (ndx = 0; tdp_actions[ndx]; ndx++)
-           {
-             QUIT;     /* Allow user to bail out with ^C.  */
-             sprintf (buf, "QTDP:-%x:%s:%s%c",
-                      t->number, addrbuf, /* address */
-                      tdp_actions[ndx],
-                      ((tdp_actions[ndx + 1] || stepping_actions)
-                       ? '-' : 0));
-             putpkt (buf);
-             remote_get_noisy_reply (&target_buf,
-                                     &target_buf_size);
-             if (strcmp (target_buf, "OK"))
-               error (_("Error on target while setting tracepoints."));
-           }
+         QUIT; /* Allow user to bail out with ^C.  */
+         xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
+                    b->number, addrbuf, /* address */
+                    tdp_actions[ndx],
+                    ((tdp_actions[ndx + 1] || stepping_actions)
+                     ? '-' : 0));
+         putpkt (buf);
+         remote_get_noisy_reply (&target_buf,
+                                 &target_buf_size);
+         if (strcmp (target_buf, "OK"))
+           error (_("Error on target while setting tracepoints."));
        }
-      if (stepping_actions)
+    }
+  if (stepping_actions)
+    {
+      for (ndx = 0; stepping_actions[ndx]; ndx++)
        {
-         for (ndx = 0; stepping_actions[ndx]; ndx++)
-           {
-             QUIT;     /* Allow user to bail out with ^C.  */
-             sprintf (buf, "QTDP:-%x:%s:%s%s%s",
-                      t->number, addrbuf, /* address */
-                      ((ndx == 0) ? "S" : ""),
-                      stepping_actions[ndx],
-                      (stepping_actions[ndx + 1] ? "-" : ""));
-             putpkt (buf);
-             remote_get_noisy_reply (&target_buf,
-                                     &target_buf_size);
-             if (strcmp (target_buf, "OK"))
-               error (_("Error on target while setting tracepoints."));
-           }
+         QUIT; /* Allow user to bail out with ^C.  */
+         xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
+                    b->number, addrbuf, /* address */
+                    ((ndx == 0) ? "S" : ""),
+                    stepping_actions[ndx],
+                    (stepping_actions[ndx + 1] ? "-" : ""));
+         putpkt (buf);
+         remote_get_noisy_reply (&target_buf,
+                                 &target_buf_size);
+         if (strcmp (target_buf, "OK"))
+           error (_("Error on target while setting tracepoints."));
        }
+    }
 
-      if (remote_protocol_packets[PACKET_TracepointSource].support
-         == PACKET_ENABLE)
+  if (remote_protocol_packets[PACKET_TracepointSource].support
+      == PACKET_ENABLE)
+    {
+      if (b->addr_string)
        {
-         if (t->addr_string)
-           {
-             strcpy (buf, "QTDPsrc:");
-             encode_source_string (t->number, loc->address,
-                                   "at", t->addr_string, buf + strlen (buf),
-                                   2048 - strlen (buf));
+         strcpy (buf, "QTDPsrc:");
+         encode_source_string (b->number, loc->address,
+                               "at", b->addr_string, buf + strlen (buf),
+                               2048 - strlen (buf));
 
-             putpkt (buf);
-             remote_get_noisy_reply (&target_buf, &target_buf_size);
-             if (strcmp (target_buf, "OK"))
-               warning (_("Target does not support source download."));
-           }
-         if (t->cond_string)
-           {
-             strcpy (buf, "QTDPsrc:");
-             encode_source_string (t->number, loc->address,
-                                   "cond", t->cond_string, buf + strlen (buf),
-                                   2048 - strlen (buf));
-             putpkt (buf);
-             remote_get_noisy_reply (&target_buf, &target_buf_size);
-             if (strcmp (target_buf, "OK"))
-               warning (_("Target does not support source download."));
-           }
-         remote_download_command_source (t->number, loc->address,
-                                         breakpoint_commands (t));
+         putpkt (buf);
+         remote_get_noisy_reply (&target_buf, &target_buf_size);
+         if (strcmp (target_buf, "OK"))
+           warning (_("Target does not support source download."));
        }
-
-      do_cleanups (old_chain);
+      if (b->cond_string)
+       {
+         strcpy (buf, "QTDPsrc:");
+         encode_source_string (b->number, loc->address,
+                               "cond", b->cond_string, buf + strlen (buf),
+                               2048 - strlen (buf));
+         putpkt (buf);
+         remote_get_noisy_reply (&target_buf, &target_buf_size);
+         if (strcmp (target_buf, "OK"))
+           warning (_("Target does not support source download."));
+       }
+      remote_download_command_source (b->number, loc->address,
+                                     breakpoint_commands (b));
     }
+
+  do_cleanups (old_chain);
 }
 
+static int
+remote_can_download_tracepoint (void)
+{
+  struct remote_state *rs = get_remote_state ();
+  struct trace_status *ts;
+  int status;
+
+  /* Don't try to install tracepoints until we've relocated our
+     symbols, and fetched and merged the target's tracepoint list with
+     ours.  */
+  if (rs->starting_up)
+    return 0;
+
+  ts = current_trace_status ();
+  status = remote_get_trace_status (ts);
+
+  if (status == -1 || !ts->running_known || !ts->running)
+    return 0;
+
+  /* If we are in a tracing experiment, but remote stub doesn't support
+     installing tracepoint in trace, we have to return.  */
+  if (!remote_supports_install_in_trace ())
+    return 0;
+
+  return 1;
+}
+
+
 static void
 remote_download_trace_state_variable (struct trace_state_variable *tsv)
 {
   struct remote_state *rs = get_remote_state ();
   char *p;
 
-  sprintf (rs->buf, "QTDV:%x:%s:%x:",
-          tsv->number, phex ((ULONGEST) tsv->initial_value, 8), tsv->builtin);
+  xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
+            tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
+            tsv->builtin);
   p = rs->buf + strlen (rs->buf);
   if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
     error (_("Trace state variable name too long for tsv definition packet"));
-  p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, 0);
+  p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
   *p++ = '\0';
   putpkt (rs->buf);
   remote_get_noisy_reply (&target_buf, &target_buf_size);
@@ -9918,21 +10620,59 @@ remote_download_trace_state_variable (struct trace_state_variable *tsv)
     error (_("Error on target while downloading trace state variable."));
 }
 
+static void
+remote_enable_tracepoint (struct bp_location *location)
+{
+  struct remote_state *rs = get_remote_state ();
+  char addr_buf[40];
+
+  sprintf_vma (addr_buf, location->address);
+  xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
+            location->owner->number, addr_buf);
+  putpkt (rs->buf);
+  remote_get_noisy_reply (&rs->buf, &rs->buf_size);
+  if (*rs->buf == '\0')
+    error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
+  if (strcmp (rs->buf, "OK") != 0)
+    error (_("Error on target while enabling tracepoint."));
+}
+
+static void
+remote_disable_tracepoint (struct bp_location *location)
+{
+  struct remote_state *rs = get_remote_state ();
+  char addr_buf[40];
+
+  sprintf_vma (addr_buf, location->address);
+  xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
+            location->owner->number, addr_buf);
+  putpkt (rs->buf);
+  remote_get_noisy_reply (&rs->buf, &rs->buf_size);
+  if (*rs->buf == '\0')
+    error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
+  if (strcmp (rs->buf, "OK") != 0)
+    error (_("Error on target while disabling tracepoint."));
+}
+
 static void
 remote_trace_set_readonly_regions (void)
 {
   asection *s;
+  bfd *abfd = NULL;
   bfd_size_type size;
   bfd_vma vma;
   int anysecs = 0;
+  int offset = 0;
 
   if (!exec_bfd)
     return;                    /* No information to give.  */
 
   strcpy (target_buf, "QTro");
+  offset = strlen (target_buf);
   for (s = exec_bfd->sections; s; s = s->next)
     {
       char tmp1[40], tmp2[40];
+      int sec_length;
 
       if ((s->flags & SEC_LOAD) == 0 ||
       /*  (s->flags & SEC_CODE) == 0 || */
@@ -9940,12 +10680,22 @@ remote_trace_set_readonly_regions (void)
        continue;
 
       anysecs = 1;
-      vma = bfd_get_section_vma (,s);
+      vma = bfd_get_section_vma (abfd, s);
       size = bfd_get_section_size (s);
       sprintf_vma (tmp1, vma);
       sprintf_vma (tmp2, vma + size);
-      sprintf (target_buf + strlen (target_buf), 
-              ":%s,%s", tmp1, tmp2);
+      sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
+      if (offset + sec_length + 1 > target_buf_size)
+       {
+         if (remote_protocol_packets[PACKET_qXfer_traceframe_info].support
+             != PACKET_ENABLE)
+           warning (_("\
+Too many sections for read-only sections definition packet."));
+         break;
+       }
+      xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
+                tmp1, tmp2);
+      offset += sec_length;
     }
   if (anysecs)
     {
@@ -9968,36 +10718,100 @@ remote_trace_start (void)
 static int
 remote_get_trace_status (struct trace_status *ts)
 {
-  char *p;
+  /* Initialize it just to avoid a GCC false warning.  */
+  char *p = NULL;
   /* FIXME we need to get register block size some other way.  */
   extern int trace_regblock_size;
+  volatile struct gdb_exception ex;
+  enum packet_result result;
+
+  if (remote_protocol_packets[PACKET_qTStatus].support == PACKET_DISABLE)
+    return -1;
 
   trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
 
   putpkt ("qTStatus");
-  p = remote_get_noisy_reply (&target_buf, &target_buf_size);
+
+  TRY_CATCH (ex, RETURN_MASK_ERROR)
+    {
+      p = remote_get_noisy_reply (&target_buf, &target_buf_size);
+    }
+  if (ex.reason < 0)
+    {
+      if (ex.error != TARGET_CLOSE_ERROR)
+       {
+         exception_fprintf (gdb_stderr, ex, "qTStatus: ");
+         return -1;
+       }
+      throw_exception (ex);
+    }
+
+  result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
 
   /* If the remote target doesn't do tracing, flag it.  */
-  if (*p == '\0')
+  if (result == PACKET_UNKNOWN)
     return -1;
 
   /* We're working with a live target.  */
-  ts->from_file = 0;
-
-  /* Set some defaults.  */
-  ts->running_known = 0;
-  ts->stop_reason = trace_stop_reason_unknown;
-  ts->traceframe_count = -1;
-  ts->buffer_free = 0;
+  ts->filename = NULL;
 
   if (*p++ != 'T')
     error (_("Bogus trace status reply from target: %s"), target_buf);
 
+  /* Function 'parse_trace_status' sets default value of each field of
+     'ts' at first, so we don't have to do it here.  */
   parse_trace_status (p, ts);
 
   return ts->running;
 }
 
+static void
+remote_get_tracepoint_status (struct breakpoint *bp,
+                             struct uploaded_tp *utp)
+{
+  struct remote_state *rs = get_remote_state ();
+  char *reply;
+  struct bp_location *loc;
+  struct tracepoint *tp = (struct tracepoint *) bp;
+  size_t size = get_remote_packet_size ();
+
+  if (tp)
+    {
+      tp->base.hit_count = 0;
+      tp->traceframe_usage = 0;
+      for (loc = tp->base.loc; loc; loc = loc->next)
+       {
+         /* If the tracepoint was never downloaded, don't go asking for
+            any status.  */
+         if (tp->number_on_target == 0)
+           continue;
+         xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
+                    phex_nz (loc->address, 0));
+         putpkt (rs->buf);
+         reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
+         if (reply && *reply)
+           {
+             if (*reply == 'V')
+               parse_tracepoint_status (reply + 1, bp, utp);
+           }
+       }
+    }
+  else if (utp)
+    {
+      utp->hit_count = 0;
+      utp->traceframe_usage = 0;
+      xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
+                phex_nz (utp->addr, 0));
+      putpkt (rs->buf);
+      reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
+      if (reply && *reply)
+       {
+         if (*reply == 'V')
+           parse_tracepoint_status (reply + 1, bp, utp);
+       }
+    }
+}
+
 static void
 remote_trace_stop (void)
 {
@@ -10011,10 +10825,11 @@ remote_trace_stop (void)
 
 static int
 remote_trace_find (enum trace_find_type type, int num,
-                  ULONGEST addr1, ULONGEST addr2,
+                  CORE_ADDR addr1, CORE_ADDR addr2,
                   int *tpp)
 {
   struct remote_state *rs = get_remote_state ();
+  char *endbuf = rs->buf + get_remote_packet_size ();
   char *p, *reply;
   int target_frameno = -1, target_tracept = -1;
 
@@ -10030,26 +10845,28 @@ remote_trace_find (enum trace_find_type type, int num,
   switch (type)
     {
     case tfind_number:
-      sprintf (p, "%x", num);
+      xsnprintf (p, endbuf - p, "%x", num);
       break;
     case tfind_pc:
-      sprintf (p, "pc:%s", phex_nz (addr1, 0));
+      xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
       break;
     case tfind_tp:
-      sprintf (p, "tdp:%x", num);
+      xsnprintf (p, endbuf - p, "tdp:%x", num);
       break;
     case tfind_range:
-      sprintf (p, "range:%s:%s", phex_nz (addr1, 0), phex_nz (addr2, 0));
+      xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
+                phex_nz (addr2, 0));
       break;
     case tfind_outside:
-      sprintf (p, "outside:%s:%s", phex_nz (addr1, 0), phex_nz (addr2, 0));
+      xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
+                phex_nz (addr2, 0));
       break;
     default:
       error (_("Unknown trace find type %d"), type);
     }
 
   putpkt (rs->buf);
-  reply = remote_get_noisy_reply (&(rs->buf), &sizeof_pkt);
+  reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
   if (*reply == '\0')
     error (_("Target does not support this command."));
 
@@ -10084,7 +10901,7 @@ remote_trace_find (enum trace_find_type type, int num,
   if (tpp)
     *tpp = target_tracept;
 
-  remote_traceframe_number = target_frameno;
+  rs->remote_traceframe_number = target_frameno;
   return target_frameno;
 }
 
@@ -10097,7 +10914,7 @@ remote_get_trace_state_variable_value (int tsvnum, LONGEST *val)
 
   set_remote_traceframe ();
 
-  sprintf (rs->buf, "qTV:%x", tsvnum);
+  xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
   putpkt (rs->buf);
   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
   if (reply && *reply)
@@ -10123,11 +10940,11 @@ remote_save_trace_data (const char *filename)
   p += strlen (p);
   if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
     error (_("Remote file name too long for trace save packet"));
-  p += 2 * bin2hex ((gdb_byte *) filename, p, 0);
+  p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
   *p++ = '\0';
   putpkt (rs->buf);
   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
-  if (*reply != '\0')
+  if (*reply == '\0')
     error (_("Target does not support this command."));
   if (strcmp (reply, "OK") != 0)
     error (_("Bogus reply from target: %s"), reply);
@@ -10186,7 +11003,7 @@ remote_set_disconnected_tracing (int val)
     {
       char *reply;
 
-      sprintf (rs->buf, "QTDisconnected:%x", val);
+      xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
       putpkt (rs->buf);
       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
       if (*reply == '\0')
@@ -10214,7 +11031,7 @@ remote_set_circular_trace_buffer (int val)
   struct remote_state *rs = get_remote_state ();
   char *reply;
 
-  sprintf (rs->buf, "QTBuffer:circular:%x", val);
+  xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
   putpkt (rs->buf);
   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
   if (*reply == '\0')
@@ -10228,6 +11045,11 @@ remote_traceframe_info (void)
 {
   char *text;
 
+  /* If current traceframe is not selected, don't bother the remote
+     stub.  */
+  if (get_traceframe_number () < 0)
+    return NULL;
+
   text = target_read_stralloc (&current_target,
                               TARGET_OBJECT_TRACEFRAME_INFO, NULL);
   if (text != NULL)
@@ -10243,6 +11065,309 @@ remote_traceframe_info (void)
   return NULL;
 }
 
+/* Handle the qTMinFTPILen packet.  Returns the minimum length of
+   instruction on which a fast tracepoint may be placed.  Returns -1
+   if the packet is not supported, and 0 if the minimum instruction
+   length is unknown.  */
+
+static int
+remote_get_min_fast_tracepoint_insn_len (void)
+{
+  struct remote_state *rs = get_remote_state ();
+  char *reply;
+
+  /* If we're not debugging a process yet, the IPA can't be
+     loaded.  */
+  if (!target_has_execution)
+    return 0;
+
+  /* Make sure the remote is pointing at the right process.  */
+  set_general_process ();
+
+  xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
+  putpkt (rs->buf);
+  reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
+  if (*reply == '\0')
+    return -1;
+  else
+    {
+      ULONGEST min_insn_len;
+
+      unpack_varlen_hex (reply, &min_insn_len);
+
+      return (int) min_insn_len;
+    }
+}
+
+static void
+remote_set_trace_buffer_size (LONGEST val)
+{
+  if (remote_protocol_packets[PACKET_QTBuffer_size].support
+      != PACKET_DISABLE)
+    {
+      struct remote_state *rs = get_remote_state ();
+      char *buf = rs->buf;
+      char *endbuf = rs->buf + get_remote_packet_size ();
+      enum packet_result result;
+
+      gdb_assert (val >= 0 || val == -1);
+      buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
+      /* Send -1 as literal "-1" to avoid host size dependency.  */
+      if (val < 0)
+       {
+         *buf++ = '-';
+          buf += hexnumstr (buf, (ULONGEST) -val);
+       }
+      else
+       buf += hexnumstr (buf, (ULONGEST) val);
+
+      putpkt (rs->buf);
+      remote_get_noisy_reply (&rs->buf, &rs->buf_size);
+      result = packet_ok (rs->buf,
+                 &remote_protocol_packets[PACKET_QTBuffer_size]);
+
+      if (result != PACKET_OK)
+       warning (_("Bogus reply from target: %s"), rs->buf);
+    }
+}
+
+static int
+remote_set_trace_notes (const char *user, const char *notes,
+                       const char *stop_notes)
+{
+  struct remote_state *rs = get_remote_state ();
+  char *reply;
+  char *buf = rs->buf;
+  char *endbuf = rs->buf + get_remote_packet_size ();
+  int nbytes;
+
+  buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
+  if (user)
+    {
+      buf += xsnprintf (buf, endbuf - buf, "user:");
+      nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
+      buf += 2 * nbytes;
+      *buf++ = ';';
+    }
+  if (notes)
+    {
+      buf += xsnprintf (buf, endbuf - buf, "notes:");
+      nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
+      buf += 2 * nbytes;
+      *buf++ = ';';
+    }
+  if (stop_notes)
+    {
+      buf += xsnprintf (buf, endbuf - buf, "tstop:");
+      nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
+      buf += 2 * nbytes;
+      *buf++ = ';';
+    }
+  /* Ensure the buffer is terminated.  */
+  *buf = '\0';
+
+  putpkt (rs->buf);
+  reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
+  if (*reply == '\0')
+    return 0;
+
+  if (strcmp (reply, "OK") != 0)
+    error (_("Bogus reply from target: %s"), reply);
+
+  return 1;
+}
+
+static int
+remote_use_agent (int use)
+{
+  if (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE)
+    {
+      struct remote_state *rs = get_remote_state ();
+
+      /* If the stub supports QAgent.  */
+      xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
+      putpkt (rs->buf);
+      getpkt (&rs->buf, &rs->buf_size, 0);
+
+      if (strcmp (rs->buf, "OK") == 0)
+       {
+         use_agent = use;
+         return 1;
+       }
+    }
+
+  return 0;
+}
+
+static int
+remote_can_use_agent (void)
+{
+  return (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE);
+}
+
+struct btrace_target_info
+{
+  /* The ptid of the traced thread.  */
+  ptid_t ptid;
+};
+
+/* Check whether the target supports branch tracing.  */
+
+static int
+remote_supports_btrace (struct target_ops *self)
+{
+  if (remote_protocol_packets[PACKET_Qbtrace_off].support != PACKET_ENABLE)
+    return 0;
+  if (remote_protocol_packets[PACKET_Qbtrace_bts].support != PACKET_ENABLE)
+    return 0;
+  if (remote_protocol_packets[PACKET_qXfer_btrace].support != PACKET_ENABLE)
+    return 0;
+
+  return 1;
+}
+
+/* Enable branch tracing.  */
+
+static struct btrace_target_info *
+remote_enable_btrace (ptid_t ptid)
+{
+  struct btrace_target_info *tinfo = NULL;
+  struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
+  struct remote_state *rs = get_remote_state ();
+  char *buf = rs->buf;
+  char *endbuf = rs->buf + get_remote_packet_size ();
+
+  if (packet->support != PACKET_ENABLE)
+    error (_("Target does not support branch tracing."));
+
+  set_general_thread (ptid);
+
+  buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
+  putpkt (rs->buf);
+  getpkt (&rs->buf, &rs->buf_size, 0);
+
+  if (packet_ok (rs->buf, packet) == PACKET_ERROR)
+    {
+      if (rs->buf[0] == 'E' && rs->buf[1] == '.')
+       error (_("Could not enable branch tracing for %s: %s"),
+              target_pid_to_str (ptid), rs->buf + 2);
+      else
+       error (_("Could not enable branch tracing for %s."),
+              target_pid_to_str (ptid));
+    }
+
+  tinfo = xzalloc (sizeof (*tinfo));
+  tinfo->ptid = ptid;
+
+  return tinfo;
+}
+
+/* Disable branch tracing.  */
+
+static void
+remote_disable_btrace (struct btrace_target_info *tinfo)
+{
+  struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
+  struct remote_state *rs = get_remote_state ();
+  char *buf = rs->buf;
+  char *endbuf = rs->buf + get_remote_packet_size ();
+
+  if (packet->support != PACKET_ENABLE)
+    error (_("Target does not support branch tracing."));
+
+  set_general_thread (tinfo->ptid);
+
+  buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
+  putpkt (rs->buf);
+  getpkt (&rs->buf, &rs->buf_size, 0);
+
+  if (packet_ok (rs->buf, packet) == PACKET_ERROR)
+    {
+      if (rs->buf[0] == 'E' && rs->buf[1] == '.')
+       error (_("Could not disable branch tracing for %s: %s"),
+              target_pid_to_str (tinfo->ptid), rs->buf + 2);
+      else
+       error (_("Could not disable branch tracing for %s."),
+              target_pid_to_str (tinfo->ptid));
+    }
+
+  xfree (tinfo);
+}
+
+/* Teardown branch tracing.  */
+
+static void
+remote_teardown_btrace (struct btrace_target_info *tinfo)
+{
+  /* We must not talk to the target during teardown.  */
+  xfree (tinfo);
+}
+
+/* Read the branch trace.  */
+
+static enum btrace_error
+remote_read_btrace (VEC (btrace_block_s) **btrace,
+                   struct btrace_target_info *tinfo,
+                   enum btrace_read_type type)
+{
+  struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
+  struct remote_state *rs = get_remote_state ();
+  struct cleanup *cleanup;
+  const char *annex;
+  char *xml;
+
+  if (packet->support != PACKET_ENABLE)
+    error (_("Target does not support branch tracing."));
+
+#if !defined(HAVE_LIBEXPAT)
+  error (_("Cannot process branch tracing result. XML parsing not supported."));
+#endif
+
+  switch (type)
+    {
+    case BTRACE_READ_ALL:
+      annex = "all";
+      break;
+    case BTRACE_READ_NEW:
+      annex = "new";
+      break;
+    case BTRACE_READ_DELTA:
+      annex = "delta";
+      break;
+    default:
+      internal_error (__FILE__, __LINE__,
+                     _("Bad branch tracing read type: %u."),
+                     (unsigned int) type);
+    }
+
+  xml = target_read_stralloc (&current_target,
+                              TARGET_OBJECT_BTRACE, annex);
+  if (xml == NULL)
+    return BTRACE_ERR_UNKNOWN;
+
+  cleanup = make_cleanup (xfree, xml);
+  *btrace = parse_xml_btrace (xml);
+  do_cleanups (cleanup);
+
+  return BTRACE_ERR_NONE;
+}
+
+static int
+remote_augmented_libraries_svr4_read (void)
+{
+  struct remote_state *rs = get_remote_state ();
+
+  return rs->augmented_libraries_svr4_read;
+}
+
+/* Implementation of to_load.  */
+
+static void
+remote_load (struct target_ops *self, char *name, int from_tty)
+{
+  generic_load (name, from_tty);
+}
+
 static void
 init_remote_ops (void)
 {
@@ -10261,21 +11386,25 @@ Specify the serial device it is connected to\n\
   remote_ops.to_fetch_registers = remote_fetch_registers;
   remote_ops.to_store_registers = remote_store_registers;
   remote_ops.to_prepare_to_store = remote_prepare_to_store;
-  remote_ops.deprecated_xfer_memory = remote_xfer_memory;
   remote_ops.to_files_info = remote_files_info;
   remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
   remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
   remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
   remote_ops.to_stopped_data_address = remote_stopped_data_address;
+  remote_ops.to_watchpoint_addr_within_range =
+    remote_watchpoint_addr_within_range;
   remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
   remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
   remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
+  remote_ops.to_region_ok_for_hw_watchpoint
+     = remote_region_ok_for_hw_watchpoint;
   remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
   remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
   remote_ops.to_kill = remote_kill;
-  remote_ops.to_load = generic_load;
+  remote_ops.to_load = remote_load;
   remote_ops.to_mourn_inferior = remote_mourn;
   remote_ops.to_pass_signals = remote_pass_signals;
+  remote_ops.to_program_signals = remote_program_signals;
   remote_ops.to_thread_alive = remote_thread_alive;
   remote_ops.to_find_new_threads = remote_threads_info;
   remote_ops.to_pid_to_str = remote_pid_to_str;
@@ -10303,18 +11432,33 @@ Specify the serial device it is connected to\n\
   remote_ops.to_can_async_p = remote_can_async_p;
   remote_ops.to_is_async_p = remote_is_async_p;
   remote_ops.to_async = remote_async;
-  remote_ops.to_async_mask = remote_async_mask;
   remote_ops.to_terminal_inferior = remote_terminal_inferior;
   remote_ops.to_terminal_ours = remote_terminal_ours;
   remote_ops.to_supports_non_stop = remote_supports_non_stop;
   remote_ops.to_supports_multi_process = remote_supports_multi_process;
+  remote_ops.to_supports_disable_randomization
+    = remote_supports_disable_randomization;
+  remote_ops.to_fileio_open = remote_hostio_open;
+  remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
+  remote_ops.to_fileio_pread = remote_hostio_pread;
+  remote_ops.to_fileio_close = remote_hostio_close;
+  remote_ops.to_fileio_unlink = remote_hostio_unlink;
+  remote_ops.to_fileio_readlink = remote_hostio_readlink;
+  remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
+  remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
+  remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
+  remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
   remote_ops.to_trace_init = remote_trace_init;
   remote_ops.to_download_tracepoint = remote_download_tracepoint;
+  remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
   remote_ops.to_download_trace_state_variable
     = remote_download_trace_state_variable;
+  remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
+  remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
   remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
   remote_ops.to_trace_start = remote_trace_start;
   remote_ops.to_get_trace_status = remote_get_trace_status;
+  remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
   remote_ops.to_trace_stop = remote_trace_stop;
   remote_ops.to_trace_find = remote_trace_find;
   remote_ops.to_get_trace_state_variable_value
@@ -10324,8 +11468,11 @@ Specify the serial device it is connected to\n\
   remote_ops.to_upload_trace_state_variables
     = remote_upload_trace_state_variables;
   remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
+  remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
   remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
   remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
+  remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
+  remote_ops.to_set_trace_notes = remote_set_trace_notes;
   remote_ops.to_core_of_thread = remote_core_of_thread;
   remote_ops.to_verify_memory = remote_verify_memory;
   remote_ops.to_get_tib_address = remote_get_tib_address;
@@ -10335,6 +11482,15 @@ Specify the serial device it is connected to\n\
   remote_ops.to_static_tracepoint_markers_by_strid
     = remote_static_tracepoint_markers_by_strid;
   remote_ops.to_traceframe_info = remote_traceframe_info;
+  remote_ops.to_use_agent = remote_use_agent;
+  remote_ops.to_can_use_agent = remote_can_use_agent;
+  remote_ops.to_supports_btrace = remote_supports_btrace;
+  remote_ops.to_enable_btrace = remote_enable_btrace;
+  remote_ops.to_disable_btrace = remote_disable_btrace;
+  remote_ops.to_teardown_btrace = remote_teardown_btrace;
+  remote_ops.to_read_btrace = remote_read_btrace;
+  remote_ops.to_augmented_libraries_svr4_read =
+    remote_augmented_libraries_svr4_read;
 }
 
 /* Set up the extended remote vector by making a copy of the standard
@@ -10357,45 +11513,50 @@ Specify the serial device it is connected to (e.g. /dev/ttya).";
   extended_remote_ops.to_detach = extended_remote_detach;
   extended_remote_ops.to_attach = extended_remote_attach;
   extended_remote_ops.to_kill = extended_remote_kill;
+  extended_remote_ops.to_supports_disable_randomization
+    = extended_remote_supports_disable_randomization;
 }
 
 static int
-remote_can_async_p (void)
+remote_can_async_p (struct target_ops *ops)
 {
+  struct remote_state *rs = get_remote_state ();
+
   if (!target_async_permitted)
     /* We only enable async when the user specifically asks for it.  */
     return 0;
 
   /* We're async whenever the serial device is.  */
-  return remote_async_mask_value && serial_can_async_p (remote_desc);
+  return serial_can_async_p (rs->remote_desc);
 }
 
 static int
-remote_is_async_p (void)
+remote_is_async_p (struct target_ops *ops)
 {
+  struct remote_state *rs = get_remote_state ();
+
   if (!target_async_permitted)
     /* We only enable async when the user specifically asks for it.  */
     return 0;
 
   /* We're async whenever the serial device is.  */
-  return remote_async_mask_value && serial_is_async_p (remote_desc);
+  return serial_is_async_p (rs->remote_desc);
 }
 
 /* Pass the SERIAL event on and up to the client.  One day this code
    will be able to delay notifying the client of an event until the
    point where an entire packet has been received.  */
 
-static void (*async_client_callback) (enum inferior_event_type event_type,
-                                     void *context);
-static void *async_client_context;
 static serial_event_ftype remote_async_serial_handler;
 
 static void
 remote_async_serial_handler (struct serial *scb, void *context)
 {
+  struct remote_state *rs = context;
+
   /* Don't propogate error information up to the client.  Instead let
      the client find out about the error by querying the target.  */
-  async_client_callback (INF_REG_EVENT, async_client_context);
+  rs->async_client_callback (INF_REG_EVENT, rs->async_client_context);
 }
 
 static void
@@ -10405,36 +11566,21 @@ remote_async_inferior_event_handler (gdb_client_data data)
 }
 
 static void
-remote_async_get_pending_events_handler (gdb_client_data data)
-{
-  remote_get_pending_stop_replies ();
-}
-
-static void
-remote_async (void (*callback) (enum inferior_event_type event_type,
-                               void *context), void *context)
+remote_async (struct target_ops *ops,
+             void (*callback) (enum inferior_event_type event_type,
+                               void *context),
+             void *context)
 {
-  if (remote_async_mask_value == 0)
-    internal_error (__FILE__, __LINE__,
-                   _("Calling remote_async when async is masked"));
+  struct remote_state *rs = get_remote_state ();
 
   if (callback != NULL)
     {
-      serial_async (remote_desc, remote_async_serial_handler, NULL);
-      async_client_callback = callback;
-      async_client_context = context;
+      serial_async (rs->remote_desc, remote_async_serial_handler, rs);
+      rs->async_client_callback = callback;
+      rs->async_client_context = context;
     }
   else
-    serial_async (remote_desc, NULL, NULL);
-}
-
-static int
-remote_async_mask (int new_mask)
-{
-  int curr_mask = remote_async_mask_value;
-
-  remote_async_mask_value = new_mask;
-  return curr_mask;
+    serial_async (rs->remote_desc, NULL, NULL);
 }
 
 static void
@@ -10450,6 +11596,7 @@ show_remote_cmd (char *args, int from_tty)
      the redundant "show remote Z-packet" and the legacy aliases.  */
   struct cleanup *showlist_chain;
   struct cmd_list_element *list = remote_show_cmdlist;
+  struct ui_out *uiout = current_uiout;
 
   showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
   for (; list != NULL; list = list->next)
@@ -10467,7 +11614,7 @@ show_remote_cmd (char *args, int from_tty)
        ui_out_field_string (uiout, "name", list->name);
        ui_out_text (uiout, ":  ");
        if (list->type == show_cmd)
-         do_setshow_command ((char *) NULL, from_tty, list);
+         do_show_command ((char *) NULL, from_tty, list);
        else
          cmd_func (list, NULL, from_tty);
        /* Close the tuple.  */
@@ -10483,8 +11630,10 @@ show_remote_cmd (char *args, int from_tty)
 static void
 remote_new_objfile (struct objfile *objfile)
 {
-  if (remote_desc != 0)                /* Have a remote connection.  */
-    remote_check_symbols (objfile);
+  struct remote_state *rs = get_remote_state ();
+
+  if (rs->remote_desc != 0)            /* Have a remote connection.  */
+    remote_check_symbols ();
 }
 
 /* Pull all the tracepoints defined on the target and create local
@@ -10534,12 +11683,50 @@ remote_upload_trace_state_variables (struct uploaded_tsv **utsvp)
   return 0;
 }
 
+/* The "set/show range-stepping" show hook.  */
+
+static void
+show_range_stepping (struct ui_file *file, int from_tty,
+                    struct cmd_list_element *c,
+                    const char *value)
+{
+  fprintf_filtered (file,
+                   _("Debugger's willingness to use range stepping "
+                     "is %s.\n"), value);
+}
+
+/* The "set/show range-stepping" set hook.  */
+
+static void
+set_range_stepping (char *ignore_args, int from_tty,
+                   struct cmd_list_element *c)
+{
+  struct remote_state *rs = get_remote_state ();
+
+  /* Whene enabling, check whether range stepping is actually
+     supported by the target, and warn if not.  */
+  if (use_range_stepping)
+    {
+      if (rs->remote_desc != NULL)
+       {
+         if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
+           remote_vcont_probe (rs);
+
+         if (remote_protocol_packets[PACKET_vCont].support == PACKET_ENABLE
+             && rs->supports_vCont.r)
+           return;
+       }
+
+      warning (_("Range stepping is not supported by the current target"));
+    }
+}
+
 void
 _initialize_remote (void)
 {
   struct remote_state *rs;
   struct cmd_list_element *cmd;
-  char *cmd_name;
+  const char *cmd_name;
 
   /* architecture specific data */
   remote_gdbarch_data_handle =
@@ -10549,11 +11736,8 @@ _initialize_remote (void)
 
   /* Initialize the per-target state.  At the moment there is only one
      of these, not one per target.  Only one target is active at a
-     time.  The default buffer size is unimportant; it will be expanded
-     whenever a larger buffer is needed.  */
-  rs = get_remote_state_raw ();
-  rs->buf_size = 400;
-  rs->buf = xmalloc (rs->buf_size);
+     time.  */
+  remote_state = new_remote_state ();
 
   init_remote_ops ();
   add_target (&remote_ops);
@@ -10563,17 +11747,21 @@ _initialize_remote (void)
 
   /* Hook into new objfile notification.  */
   observer_attach_new_objfile (remote_new_objfile);
+  /* We're no longer interested in notification events of an inferior
+     when it exits.  */
+  observer_attach_inferior_exit (discard_pending_stop_replies);
 
   /* Set up signal handlers.  */
-  sigint_remote_token =
+  async_sigint_remote_token =
     create_async_signal_handler (async_remote_interrupt, NULL);
-  sigint_remote_twice_token =
-    create_async_signal_handler (inferior_event_handler_wrapper, NULL);
+  async_sigint_remote_twice_token =
+    create_async_signal_handler (async_remote_interrupt_twice, NULL);
 
 #if 0
   init_remote_threadtests ();
 #endif
 
+  stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
   /* set/show remote ...  */
 
   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
@@ -10676,6 +11864,15 @@ Specify a negative limit for unlimited."),
                                           number of target hardware
                                           watchpoints is %s.  */
                            &remote_set_cmdlist, &remote_show_cmdlist);
+  add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
+                           &remote_hw_watchpoint_length_limit, _("\
+Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
+Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
+Specify a negative limit for unlimited."),
+                           NULL, NULL, /* FIXME: i18n: The maximum
+                                           length (in bytes) of a target
+                                           hardware watchpoint is %s.  */
+                           &remote_set_cmdlist, &remote_show_cmdlist);
   add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
                            &remote_hw_breakpoint_limit, _("\
 Set the maximum number of target hardware breakpoints."), _("\
@@ -10686,13 +11883,13 @@ Specify a negative limit for unlimited."),
                                           breakpoints is %s.  */
                            &remote_set_cmdlist, &remote_show_cmdlist);
 
-  add_setshow_integer_cmd ("remoteaddresssize", class_obscure,
-                          &remote_address_size, _("\
+  add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
+                            &remote_address_size, _("\
 Set the maximum size of the address (in bits) in a memory packet."), _("\
 Show the maximum size of the address (in bits) in a memory packet."), NULL,
-                          NULL,
-                          NULL, /* FIXME: i18n: */
-                          &setlist, &showlist);
+                            NULL,
+                            NULL, /* FIXME: i18n: */
+                            &setlist, &showlist);
 
   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
                         "X", "binary-download", 1);
@@ -10703,6 +11900,9 @@ Show the maximum size of the address (in bits) in a memory packet."), NULL,
   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
                         "QPassSignals", "pass-signals", 0);
 
+  add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
+                        "QProgramSignals", "program-signals", 0);
+
   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
                         "qSymbol", "symbol-lookup", 0);
 
@@ -10736,6 +11936,9 @@ Show the maximum size of the address (in bits) in a memory packet."), NULL,
   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
                         "qXfer:libraries:read", "library-info", 0);
 
+  add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
+                        "qXfer:libraries-svr4:read", "library-info-svr4", 0);
+
   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
                         "qXfer:memory-map:read", "memory-map", 0);
 
@@ -10759,7 +11962,10 @@ Show the maximum size of the address (in bits) in a memory packet."), NULL,
 
   add_packet_config_cmd
     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
-     "qXfer:trace-frame-info:read", "traceframe-info", 0);
+     "qXfer:traceframe-info:read", "traceframe-info", 0);
+
+  add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
+                        "qXfer:uib:read", "unwind-info-block", 0);
 
   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
                         "qGetTLSAddr", "get-thread-local-storage-address",
@@ -10781,6 +11987,9 @@ Show the maximum size of the address (in bits) in a memory packet."), NULL,
   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
                         "qSearch:memory", "search-memory", 0);
 
+  add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
+                        "qTStatus", "trace-status", 0);
+
   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
                         "vFile:open", "hostio-open", 0);
 
@@ -10796,6 +12005,9 @@ Show the maximum size of the address (in bits) in a memory packet."), NULL,
   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
                         "vFile:unlink", "hostio-unlink", 0);
 
+  add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
+                        "vFile:readlink", "hostio-readlink", 0);
+
   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
                         "vAttach", "attach", 0);
 
@@ -10814,6 +12026,15 @@ Show the maximum size of the address (in bits) in a memory packet."), NULL,
   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
                         "ConditionalTracepoints",
                         "conditional-tracepoints", 0);
+
+  add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
+                        "ConditionalBreakpoints",
+                        "conditional-breakpoints", 0);
+
+  add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
+                        "BreakpointCommands",
+                        "breakpoint-commands", 0);
+
   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
                         "FastTracepoints", "fast-tracepoints", 0);
 
@@ -10826,9 +12047,33 @@ Show the maximum size of the address (in bits) in a memory packet."), NULL,
   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
                         "StaticTracepoints", "static-tracepoints", 0);
 
+  add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
+                        "InstallInTrace", "install-in-trace", 0);
+
   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
                          "qXfer:statictrace:read", "read-sdata-object", 0);
 
+  add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
+                        "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
+
+  add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
+                        "QDisableRandomization", "disable-randomization", 0);
+
+  add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
+                        "QAgent", "agent", 0);
+
+  add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
+                        "QTBuffer:size", "trace-buffer-size", 0);
+
+  add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
+       "Qbtrace:off", "disable-btrace", 0);
+
+  add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
+       "Qbtrace:bts", "enable-btrace", 0);
+
+  add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
+       "qXfer:btrace", "read-btrace", 0);
+
   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
      Z sub-packet has its own set and show commands, but users may
      have sets to this variable in their .gdbinit files (or in their
@@ -10870,6 +12115,20 @@ Set the remote pathname for \"run\""), _("\
 Show the remote pathname for \"run\""), NULL, NULL, NULL,
                                   &remote_set_cmdlist, &remote_show_cmdlist);
 
+  add_setshow_boolean_cmd ("range-stepping", class_run,
+                          &use_range_stepping, _("\
+Enable or disable range stepping."), _("\
+Show whether target-assisted range stepping is enabled."), _("\
+If on, and the target supports it, when stepping a source line, GDB\n\
+tells the target to step the corresponding range of addresses itself instead\n\
+of issuing multiple single-steps.  This speeds up source level\n\
+stepping.  If off, GDB always issues single-steps, even if range\n\
+stepping is supported by the target.  The default is on."),
+                          set_range_stepping,
+                          show_range_stepping,
+                          &setlist,
+                          &showlist);
+
   /* Eventually initialize fileio.  See fileio.c */
   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
 
This page took 0.110031 seconds and 4 git commands to generate.