Identify remote fork event support
[external/binutils.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3    Copyright (C) 1988-2015 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 /* See the GDB User Guide for details of the GDB remote protocol.  */
21
22 #include "defs.h"
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "bfd.h"
28 #include "symfile.h"
29 #include "target.h"
30 /*#include "terminal.h" */
31 #include "gdbcmd.h"
32 #include "objfiles.h"
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
35 #include "remote.h"
36 #include "remote-notif.h"
37 #include "regcache.h"
38 #include "value.h"
39 #include "observer.h"
40 #include "solib.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
44 #include "gdb_bfd.h"
45 #include "filestuff.h"
46 #include "rsp-low.h"
47
48 #include <sys/time.h>
49
50 #include "event-loop.h"
51 #include "event-top.h"
52 #include "inf-loop.h"
53
54 #include <signal.h>
55 #include "serial.h"
56
57 #include "gdbcore.h" /* for exec_bfd */
58
59 #include "remote-fileio.h"
60 #include "gdb/fileio.h"
61 #include <sys/stat.h>
62 #include "xml-support.h"
63
64 #include "memory-map.h"
65
66 #include "tracepoint.h"
67 #include "ax.h"
68 #include "ax-gdb.h"
69 #include "agent.h"
70 #include "btrace.h"
71
72 /* Temp hacks for tracepoint encoding migration.  */
73 static char *target_buf;
74 static long target_buf_size;
75
76 /* The size to align memory write packets, when practical.  The protocol
77    does not guarantee any alignment, and gdb will generate short
78    writes and unaligned writes, but even as a best-effort attempt this
79    can improve bulk transfers.  For instance, if a write is misaligned
80    relative to the target's data bus, the stub may need to make an extra
81    round trip fetching data from the target.  This doesn't make a
82    huge difference, but it's easy to do, so we try to be helpful.
83
84    The alignment chosen is arbitrary; usually data bus width is
85    important here, not the possibly larger cache line size.  */
86 enum { REMOTE_ALIGN_WRITES = 16 };
87
88 /* Prototypes for local functions.  */
89 static void async_cleanup_sigint_signal_handler (void *dummy);
90 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
91 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
92                                  int forever, int *is_notif);
93
94 static void async_handle_remote_sigint (int);
95 static void async_handle_remote_sigint_twice (int);
96
97 static void remote_files_info (struct target_ops *ignore);
98
99 static void remote_prepare_to_store (struct target_ops *self,
100                                      struct regcache *regcache);
101
102 static void remote_open_1 (const char *, int, struct target_ops *,
103                            int extended_p);
104
105 static void remote_close (struct target_ops *self);
106
107 static void remote_mourn (struct target_ops *ops);
108
109 static void extended_remote_restart (void);
110
111 static void extended_remote_mourn (struct target_ops *);
112
113 static void remote_send (char **buf, long *sizeof_buf_p);
114
115 static int readchar (int timeout);
116
117 static void remote_serial_write (const char *str, int len);
118
119 static void remote_kill (struct target_ops *ops);
120
121 static int remote_can_async_p (struct target_ops *);
122
123 static int remote_is_async_p (struct target_ops *);
124
125 static void remote_async (struct target_ops *ops, int enable);
126
127 static void sync_remote_interrupt_twice (int signo);
128
129 static void interrupt_query (void);
130
131 static void set_general_thread (struct ptid ptid);
132 static void set_continue_thread (struct ptid ptid);
133
134 static void get_offsets (void);
135
136 static void skip_frame (void);
137
138 static long read_frame (char **buf_p, long *sizeof_buf);
139
140 static int hexnumlen (ULONGEST num);
141
142 static void init_remote_ops (void);
143
144 static void init_extended_remote_ops (void);
145
146 static void remote_stop (struct target_ops *self, ptid_t);
147
148 static int stubhex (int ch);
149
150 static int hexnumstr (char *, ULONGEST);
151
152 static int hexnumnstr (char *, ULONGEST, int);
153
154 static CORE_ADDR remote_address_masked (CORE_ADDR);
155
156 static void print_packet (const char *);
157
158 static void compare_sections_command (char *, int);
159
160 static void packet_command (char *, int);
161
162 static int stub_unpack_int (char *buff, int fieldlength);
163
164 static ptid_t remote_current_thread (ptid_t oldptid);
165
166 static int putpkt_binary (const char *buf, int cnt);
167
168 static void check_binary_download (CORE_ADDR addr);
169
170 struct packet_config;
171
172 static void show_packet_config_cmd (struct packet_config *config);
173
174 static void show_remote_protocol_packet_cmd (struct ui_file *file,
175                                              int from_tty,
176                                              struct cmd_list_element *c,
177                                              const char *value);
178
179 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
180 static ptid_t read_ptid (char *buf, char **obuf);
181
182 static void remote_set_permissions (struct target_ops *self);
183
184 struct remote_state;
185 static int remote_get_trace_status (struct target_ops *self,
186                                     struct trace_status *ts);
187
188 static int remote_upload_tracepoints (struct target_ops *self,
189                                       struct uploaded_tp **utpp);
190
191 static int remote_upload_trace_state_variables (struct target_ops *self,
192                                                 struct uploaded_tsv **utsvp);
193   
194 static void remote_query_supported (void);
195
196 static void remote_check_symbols (void);
197
198 void _initialize_remote (void);
199
200 struct stop_reply;
201 static void stop_reply_xfree (struct stop_reply *);
202 static void remote_parse_stop_reply (char *, struct stop_reply *);
203 static void push_stop_reply (struct stop_reply *);
204 static void discard_pending_stop_replies_in_queue (struct remote_state *);
205 static int peek_stop_reply (ptid_t ptid);
206
207 static void remote_async_inferior_event_handler (gdb_client_data);
208
209 static void remote_terminal_ours (struct target_ops *self);
210
211 static int remote_read_description_p (struct target_ops *target);
212
213 static void remote_console_output (char *msg);
214
215 static int remote_supports_cond_breakpoints (struct target_ops *self);
216
217 static int remote_can_run_breakpoint_commands (struct target_ops *self);
218
219 static void remote_btrace_reset (void);
220
221 /* For "remote".  */
222
223 static struct cmd_list_element *remote_cmdlist;
224
225 /* For "set remote" and "show remote".  */
226
227 static struct cmd_list_element *remote_set_cmdlist;
228 static struct cmd_list_element *remote_show_cmdlist;
229
230 /* Stub vCont actions support.
231
232    Each field is a boolean flag indicating whether the stub reports
233    support for the corresponding action.  */
234
235 struct vCont_action_support
236 {
237   /* vCont;t */
238   int t;
239
240   /* vCont;r */
241   int r;
242 };
243
244 /* Controls whether GDB is willing to use range stepping.  */
245
246 static int use_range_stepping = 1;
247
248 #define OPAQUETHREADBYTES 8
249
250 /* a 64 bit opaque identifier */
251 typedef unsigned char threadref[OPAQUETHREADBYTES];
252
253 /* About this many threadisds fit in a packet.  */
254
255 #define MAXTHREADLISTRESULTS 32
256
257 /* Description of the remote protocol state for the currently
258    connected target.  This is per-target state, and independent of the
259    selected architecture.  */
260
261 struct remote_state
262 {
263   /* A buffer to use for incoming packets, and its current size.  The
264      buffer is grown dynamically for larger incoming packets.
265      Outgoing packets may also be constructed in this buffer.
266      BUF_SIZE is always at least REMOTE_PACKET_SIZE;
267      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
268      packets.  */
269   char *buf;
270   long buf_size;
271
272   /* True if we're going through initial connection setup (finding out
273      about the remote side's threads, relocating symbols, etc.).  */
274   int starting_up;
275
276   /* If we negotiated packet size explicitly (and thus can bypass
277      heuristics for the largest packet size that will not overflow
278      a buffer in the stub), this will be set to that packet size.
279      Otherwise zero, meaning to use the guessed size.  */
280   long explicit_packet_size;
281
282   /* remote_wait is normally called when the target is running and
283      waits for a stop reply packet.  But sometimes we need to call it
284      when the target is already stopped.  We can send a "?" packet
285      and have remote_wait read the response.  Or, if we already have
286      the response, we can stash it in BUF and tell remote_wait to
287      skip calling getpkt.  This flag is set when BUF contains a
288      stop reply packet and the target is not waiting.  */
289   int cached_wait_status;
290
291   /* True, if in no ack mode.  That is, neither GDB nor the stub will
292      expect acks from each other.  The connection is assumed to be
293      reliable.  */
294   int noack_mode;
295
296   /* True if we're connected in extended remote mode.  */
297   int extended;
298
299   /* True if we resumed the target and we're waiting for the target to
300      stop.  In the mean time, we can't start another command/query.
301      The remote server wouldn't be ready to process it, so we'd
302      timeout waiting for a reply that would never come and eventually
303      we'd close the connection.  This can happen in asynchronous mode
304      because we allow GDB commands while the target is running.  */
305   int waiting_for_stop_reply;
306
307   /* The status of the stub support for the various vCont actions.  */
308   struct vCont_action_support supports_vCont;
309
310   /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
311      responded to that.  */
312   int ctrlc_pending_p;
313
314   /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
315      remote_open knows that we don't have a file open when the program
316      starts.  */
317   struct serial *remote_desc;
318
319   /* These are the threads which we last sent to the remote system.  The
320      TID member will be -1 for all or -2 for not sent yet.  */
321   ptid_t general_thread;
322   ptid_t continue_thread;
323
324   /* This is the traceframe which we last selected on the remote system.
325      It will be -1 if no traceframe is selected.  */
326   int remote_traceframe_number;
327
328   char *last_pass_packet;
329
330   /* The last QProgramSignals packet sent to the target.  We bypass
331      sending a new program signals list down to the target if the new
332      packet is exactly the same as the last we sent.  IOW, we only let
333      the target know about program signals list changes.  */
334   char *last_program_signals_packet;
335
336   enum gdb_signal last_sent_signal;
337
338   int last_sent_step;
339
340   char *finished_object;
341   char *finished_annex;
342   ULONGEST finished_offset;
343
344   /* Should we try the 'ThreadInfo' query packet?
345
346      This variable (NOT available to the user: auto-detect only!)
347      determines whether GDB will use the new, simpler "ThreadInfo"
348      query or the older, more complex syntax for thread queries.
349      This is an auto-detect variable (set to true at each connect,
350      and set to false when the target fails to recognize it).  */
351   int use_threadinfo_query;
352   int use_threadextra_query;
353
354   /* This is set to the data address of the access causing the target
355      to stop for a watchpoint.  */
356   CORE_ADDR remote_watch_data_address;
357
358   /* Whether the target stopped for a breakpoint/watchpoint.  */
359   enum target_stop_reason stop_reason;
360
361   threadref echo_nextthread;
362   threadref nextthread;
363   threadref resultthreadlist[MAXTHREADLISTRESULTS];
364
365   /* The state of remote notification.  */
366   struct remote_notif_state *notif_state;
367
368   /* The branch trace configuration.  */
369   struct btrace_config btrace_config;
370 };
371
372 /* Private data that we'll store in (struct thread_info)->private.  */
373 struct private_thread_info
374 {
375   char *extra;
376   int core;
377 };
378
379 static void
380 free_private_thread_info (struct private_thread_info *info)
381 {
382   xfree (info->extra);
383   xfree (info);
384 }
385
386 /* This data could be associated with a target, but we do not always
387    have access to the current target when we need it, so for now it is
388    static.  This will be fine for as long as only one target is in use
389    at a time.  */
390 static struct remote_state *remote_state;
391
392 static struct remote_state *
393 get_remote_state_raw (void)
394 {
395   return remote_state;
396 }
397
398 /* Allocate a new struct remote_state with xmalloc, initialize it, and
399    return it.  */
400
401 static struct remote_state *
402 new_remote_state (void)
403 {
404   struct remote_state *result = XCNEW (struct remote_state);
405
406   /* The default buffer size is unimportant; it will be expanded
407      whenever a larger buffer is needed. */
408   result->buf_size = 400;
409   result->buf = xmalloc (result->buf_size);
410   result->remote_traceframe_number = -1;
411   result->last_sent_signal = GDB_SIGNAL_0;
412
413   return result;
414 }
415
416 /* Description of the remote protocol for a given architecture.  */
417
418 struct packet_reg
419 {
420   long offset; /* Offset into G packet.  */
421   long regnum; /* GDB's internal register number.  */
422   LONGEST pnum; /* Remote protocol register number.  */
423   int in_g_packet; /* Always part of G packet.  */
424   /* long size in bytes;  == register_size (target_gdbarch (), regnum);
425      at present.  */
426   /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
427      at present.  */
428 };
429
430 struct remote_arch_state
431 {
432   /* Description of the remote protocol registers.  */
433   long sizeof_g_packet;
434
435   /* Description of the remote protocol registers indexed by REGNUM
436      (making an array gdbarch_num_regs in size).  */
437   struct packet_reg *regs;
438
439   /* This is the size (in chars) of the first response to the ``g''
440      packet.  It is used as a heuristic when determining the maximum
441      size of memory-read and memory-write packets.  A target will
442      typically only reserve a buffer large enough to hold the ``g''
443      packet.  The size does not include packet overhead (headers and
444      trailers).  */
445   long actual_register_packet_size;
446
447   /* This is the maximum size (in chars) of a non read/write packet.
448      It is also used as a cap on the size of read/write packets.  */
449   long remote_packet_size;
450 };
451
452 /* Utility: generate error from an incoming stub packet.  */
453 static void
454 trace_error (char *buf)
455 {
456   if (*buf++ != 'E')
457     return;                     /* not an error msg */
458   switch (*buf)
459     {
460     case '1':                   /* malformed packet error */
461       if (*++buf == '0')        /*   general case: */
462         error (_("remote.c: error in outgoing packet."));
463       else
464         error (_("remote.c: error in outgoing packet at field #%ld."),
465                strtol (buf, NULL, 16));
466     default:
467       error (_("Target returns error code '%s'."), buf);
468     }
469 }
470
471 /* Utility: wait for reply from stub, while accepting "O" packets.  */
472 static char *
473 remote_get_noisy_reply (char **buf_p,
474                         long *sizeof_buf)
475 {
476   do                            /* Loop on reply from remote stub.  */
477     {
478       char *buf;
479
480       QUIT;                     /* Allow user to bail out with ^C.  */
481       getpkt (buf_p, sizeof_buf, 0);
482       buf = *buf_p;
483       if (buf[0] == 'E')
484         trace_error (buf);
485       else if (startswith (buf, "qRelocInsn:"))
486         {
487           ULONGEST ul;
488           CORE_ADDR from, to, org_to;
489           char *p, *pp;
490           int adjusted_size = 0;
491           int relocated = 0;
492
493           p = buf + strlen ("qRelocInsn:");
494           pp = unpack_varlen_hex (p, &ul);
495           if (*pp != ';')
496             error (_("invalid qRelocInsn packet: %s"), buf);
497           from = ul;
498
499           p = pp + 1;
500           unpack_varlen_hex (p, &ul);
501           to = ul;
502
503           org_to = to;
504
505           TRY
506             {
507               gdbarch_relocate_instruction (target_gdbarch (), &to, from);
508               relocated = 1;
509             }
510           CATCH (ex, RETURN_MASK_ALL)
511             {
512               if (ex.error == MEMORY_ERROR)
513                 {
514                   /* Propagate memory errors silently back to the
515                      target.  The stub may have limited the range of
516                      addresses we can write to, for example.  */
517                 }
518               else
519                 {
520                   /* Something unexpectedly bad happened.  Be verbose
521                      so we can tell what, and propagate the error back
522                      to the stub, so it doesn't get stuck waiting for
523                      a response.  */
524                   exception_fprintf (gdb_stderr, ex,
525                                      _("warning: relocating instruction: "));
526                 }
527               putpkt ("E01");
528             }
529           END_CATCH
530
531           if (relocated)
532             {
533               adjusted_size = to - org_to;
534
535               xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
536               putpkt (buf);
537             }
538         }
539       else if (buf[0] == 'O' && buf[1] != 'K')
540         remote_console_output (buf + 1);        /* 'O' message from stub */
541       else
542         return buf;             /* Here's the actual reply.  */
543     }
544   while (1);
545 }
546
547 /* Handle for retreving the remote protocol data from gdbarch.  */
548 static struct gdbarch_data *remote_gdbarch_data_handle;
549
550 static struct remote_arch_state *
551 get_remote_arch_state (void)
552 {
553   return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
554 }
555
556 /* Fetch the global remote target state.  */
557
558 static struct remote_state *
559 get_remote_state (void)
560 {
561   /* Make sure that the remote architecture state has been
562      initialized, because doing so might reallocate rs->buf.  Any
563      function which calls getpkt also needs to be mindful of changes
564      to rs->buf, but this call limits the number of places which run
565      into trouble.  */
566   get_remote_arch_state ();
567
568   return get_remote_state_raw ();
569 }
570
571 static int
572 compare_pnums (const void *lhs_, const void *rhs_)
573 {
574   const struct packet_reg * const *lhs = lhs_;
575   const struct packet_reg * const *rhs = rhs_;
576
577   if ((*lhs)->pnum < (*rhs)->pnum)
578     return -1;
579   else if ((*lhs)->pnum == (*rhs)->pnum)
580     return 0;
581   else
582     return 1;
583 }
584
585 static int
586 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
587 {
588   int regnum, num_remote_regs, offset;
589   struct packet_reg **remote_regs;
590
591   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
592     {
593       struct packet_reg *r = &regs[regnum];
594
595       if (register_size (gdbarch, regnum) == 0)
596         /* Do not try to fetch zero-sized (placeholder) registers.  */
597         r->pnum = -1;
598       else
599         r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
600
601       r->regnum = regnum;
602     }
603
604   /* Define the g/G packet format as the contents of each register
605      with a remote protocol number, in order of ascending protocol
606      number.  */
607
608   remote_regs = alloca (gdbarch_num_regs (gdbarch)
609                         * sizeof (struct packet_reg *));
610   for (num_remote_regs = 0, regnum = 0;
611        regnum < gdbarch_num_regs (gdbarch);
612        regnum++)
613     if (regs[regnum].pnum != -1)
614       remote_regs[num_remote_regs++] = &regs[regnum];
615
616   qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
617          compare_pnums);
618
619   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
620     {
621       remote_regs[regnum]->in_g_packet = 1;
622       remote_regs[regnum]->offset = offset;
623       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
624     }
625
626   return offset;
627 }
628
629 /* Given the architecture described by GDBARCH, return the remote
630    protocol register's number and the register's offset in the g/G
631    packets of GDB register REGNUM, in PNUM and POFFSET respectively.
632    If the target does not have a mapping for REGNUM, return false,
633    otherwise, return true.  */
634
635 int
636 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
637                                    int *pnum, int *poffset)
638 {
639   int sizeof_g_packet;
640   struct packet_reg *regs;
641   struct cleanup *old_chain;
642
643   gdb_assert (regnum < gdbarch_num_regs (gdbarch));
644
645   regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
646   old_chain = make_cleanup (xfree, regs);
647
648   sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
649
650   *pnum = regs[regnum].pnum;
651   *poffset = regs[regnum].offset;
652
653   do_cleanups (old_chain);
654
655   return *pnum != -1;
656 }
657
658 static void *
659 init_remote_state (struct gdbarch *gdbarch)
660 {
661   struct remote_state *rs = get_remote_state_raw ();
662   struct remote_arch_state *rsa;
663
664   rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
665
666   /* Use the architecture to build a regnum<->pnum table, which will be
667      1:1 unless a feature set specifies otherwise.  */
668   rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
669                                       gdbarch_num_regs (gdbarch),
670                                       struct packet_reg);
671
672   /* Record the maximum possible size of the g packet - it may turn out
673      to be smaller.  */
674   rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
675
676   /* Default maximum number of characters in a packet body.  Many
677      remote stubs have a hardwired buffer size of 400 bytes
678      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
679      as the maximum packet-size to ensure that the packet and an extra
680      NUL character can always fit in the buffer.  This stops GDB
681      trashing stubs that try to squeeze an extra NUL into what is
682      already a full buffer (As of 1999-12-04 that was most stubs).  */
683   rsa->remote_packet_size = 400 - 1;
684
685   /* This one is filled in when a ``g'' packet is received.  */
686   rsa->actual_register_packet_size = 0;
687
688   /* Should rsa->sizeof_g_packet needs more space than the
689      default, adjust the size accordingly.  Remember that each byte is
690      encoded as two characters.  32 is the overhead for the packet
691      header / footer.  NOTE: cagney/1999-10-26: I suspect that 8
692      (``$NN:G...#NN'') is a better guess, the below has been padded a
693      little.  */
694   if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
695     rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
696
697   /* Make sure that the packet buffer is plenty big enough for
698      this architecture.  */
699   if (rs->buf_size < rsa->remote_packet_size)
700     {
701       rs->buf_size = 2 * rsa->remote_packet_size;
702       rs->buf = xrealloc (rs->buf, rs->buf_size);
703     }
704
705   return rsa;
706 }
707
708 /* Return the current allowed size of a remote packet.  This is
709    inferred from the current architecture, and should be used to
710    limit the length of outgoing packets.  */
711 static long
712 get_remote_packet_size (void)
713 {
714   struct remote_state *rs = get_remote_state ();
715   struct remote_arch_state *rsa = get_remote_arch_state ();
716
717   if (rs->explicit_packet_size)
718     return rs->explicit_packet_size;
719
720   return rsa->remote_packet_size;
721 }
722
723 static struct packet_reg *
724 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
725 {
726   if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
727     return NULL;
728   else
729     {
730       struct packet_reg *r = &rsa->regs[regnum];
731
732       gdb_assert (r->regnum == regnum);
733       return r;
734     }
735 }
736
737 static struct packet_reg *
738 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
739 {
740   int i;
741
742   for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
743     {
744       struct packet_reg *r = &rsa->regs[i];
745
746       if (r->pnum == pnum)
747         return r;
748     }
749   return NULL;
750 }
751
752 static struct target_ops remote_ops;
753
754 static struct target_ops extended_remote_ops;
755
756 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
757    ``forever'' still use the normal timeout mechanism.  This is
758    currently used by the ASYNC code to guarentee that target reads
759    during the initial connect always time-out.  Once getpkt has been
760    modified to return a timeout indication and, in turn
761    remote_wait()/wait_for_inferior() have gained a timeout parameter
762    this can go away.  */
763 static int wait_forever_enabled_p = 1;
764
765 /* Allow the user to specify what sequence to send to the remote
766    when he requests a program interruption: Although ^C is usually
767    what remote systems expect (this is the default, here), it is
768    sometimes preferable to send a break.  On other systems such
769    as the Linux kernel, a break followed by g, which is Magic SysRq g
770    is required in order to interrupt the execution.  */
771 const char interrupt_sequence_control_c[] = "Ctrl-C";
772 const char interrupt_sequence_break[] = "BREAK";
773 const char interrupt_sequence_break_g[] = "BREAK-g";
774 static const char *const interrupt_sequence_modes[] =
775   {
776     interrupt_sequence_control_c,
777     interrupt_sequence_break,
778     interrupt_sequence_break_g,
779     NULL
780   };
781 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
782
783 static void
784 show_interrupt_sequence (struct ui_file *file, int from_tty,
785                          struct cmd_list_element *c,
786                          const char *value)
787 {
788   if (interrupt_sequence_mode == interrupt_sequence_control_c)
789     fprintf_filtered (file,
790                       _("Send the ASCII ETX character (Ctrl-c) "
791                         "to the remote target to interrupt the "
792                         "execution of the program.\n"));
793   else if (interrupt_sequence_mode == interrupt_sequence_break)
794     fprintf_filtered (file,
795                       _("send a break signal to the remote target "
796                         "to interrupt the execution of the program.\n"));
797   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
798     fprintf_filtered (file,
799                       _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
800                         "the remote target to interrupt the execution "
801                         "of Linux kernel.\n"));
802   else
803     internal_error (__FILE__, __LINE__,
804                     _("Invalid value for interrupt_sequence_mode: %s."),
805                     interrupt_sequence_mode);
806 }
807
808 /* This boolean variable specifies whether interrupt_sequence is sent
809    to the remote target when gdb connects to it.
810    This is mostly needed when you debug the Linux kernel: The Linux kernel
811    expects BREAK g which is Magic SysRq g for connecting gdb.  */
812 static int interrupt_on_connect = 0;
813
814 /* This variable is used to implement the "set/show remotebreak" commands.
815    Since these commands are now deprecated in favor of "set/show remote
816    interrupt-sequence", it no longer has any effect on the code.  */
817 static int remote_break;
818
819 static void
820 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
821 {
822   if (remote_break)
823     interrupt_sequence_mode = interrupt_sequence_break;
824   else
825     interrupt_sequence_mode = interrupt_sequence_control_c;
826 }
827
828 static void
829 show_remotebreak (struct ui_file *file, int from_tty,
830                   struct cmd_list_element *c,
831                   const char *value)
832 {
833 }
834
835 /* This variable sets the number of bits in an address that are to be
836    sent in a memory ("M" or "m") packet.  Normally, after stripping
837    leading zeros, the entire address would be sent.  This variable
838    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
839    initial implementation of remote.c restricted the address sent in
840    memory packets to ``host::sizeof long'' bytes - (typically 32
841    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
842    address was never sent.  Since fixing this bug may cause a break in
843    some remote targets this variable is principly provided to
844    facilitate backward compatibility.  */
845
846 static unsigned int remote_address_size;
847
848 /* Temporary to track who currently owns the terminal.  See
849    remote_terminal_* for more details.  */
850
851 static int remote_async_terminal_ours_p;
852
853 /* The executable file to use for "run" on the remote side.  */
854
855 static char *remote_exec_file = "";
856
857 \f
858 /* User configurable variables for the number of characters in a
859    memory read/write packet.  MIN (rsa->remote_packet_size,
860    rsa->sizeof_g_packet) is the default.  Some targets need smaller
861    values (fifo overruns, et.al.) and some users need larger values
862    (speed up transfers).  The variables ``preferred_*'' (the user
863    request), ``current_*'' (what was actually set) and ``forced_*''
864    (Positive - a soft limit, negative - a hard limit).  */
865
866 struct memory_packet_config
867 {
868   char *name;
869   long size;
870   int fixed_p;
871 };
872
873 /* Compute the current size of a read/write packet.  Since this makes
874    use of ``actual_register_packet_size'' the computation is dynamic.  */
875
876 static long
877 get_memory_packet_size (struct memory_packet_config *config)
878 {
879   struct remote_state *rs = get_remote_state ();
880   struct remote_arch_state *rsa = get_remote_arch_state ();
881
882   /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
883      law?) that some hosts don't cope very well with large alloca()
884      calls.  Eventually the alloca() code will be replaced by calls to
885      xmalloc() and make_cleanups() allowing this restriction to either
886      be lifted or removed.  */
887 #ifndef MAX_REMOTE_PACKET_SIZE
888 #define MAX_REMOTE_PACKET_SIZE 16384
889 #endif
890   /* NOTE: 20 ensures we can write at least one byte.  */
891 #ifndef MIN_REMOTE_PACKET_SIZE
892 #define MIN_REMOTE_PACKET_SIZE 20
893 #endif
894   long what_they_get;
895   if (config->fixed_p)
896     {
897       if (config->size <= 0)
898         what_they_get = MAX_REMOTE_PACKET_SIZE;
899       else
900         what_they_get = config->size;
901     }
902   else
903     {
904       what_they_get = get_remote_packet_size ();
905       /* Limit the packet to the size specified by the user.  */
906       if (config->size > 0
907           && what_they_get > config->size)
908         what_they_get = config->size;
909
910       /* Limit it to the size of the targets ``g'' response unless we have
911          permission from the stub to use a larger packet size.  */
912       if (rs->explicit_packet_size == 0
913           && rsa->actual_register_packet_size > 0
914           && what_they_get > rsa->actual_register_packet_size)
915         what_they_get = rsa->actual_register_packet_size;
916     }
917   if (what_they_get > MAX_REMOTE_PACKET_SIZE)
918     what_they_get = MAX_REMOTE_PACKET_SIZE;
919   if (what_they_get < MIN_REMOTE_PACKET_SIZE)
920     what_they_get = MIN_REMOTE_PACKET_SIZE;
921
922   /* Make sure there is room in the global buffer for this packet
923      (including its trailing NUL byte).  */
924   if (rs->buf_size < what_they_get + 1)
925     {
926       rs->buf_size = 2 * what_they_get;
927       rs->buf = xrealloc (rs->buf, 2 * what_they_get);
928     }
929
930   return what_they_get;
931 }
932
933 /* Update the size of a read/write packet.  If they user wants
934    something really big then do a sanity check.  */
935
936 static void
937 set_memory_packet_size (char *args, struct memory_packet_config *config)
938 {
939   int fixed_p = config->fixed_p;
940   long size = config->size;
941
942   if (args == NULL)
943     error (_("Argument required (integer, `fixed' or `limited')."));
944   else if (strcmp (args, "hard") == 0
945       || strcmp (args, "fixed") == 0)
946     fixed_p = 1;
947   else if (strcmp (args, "soft") == 0
948            || strcmp (args, "limit") == 0)
949     fixed_p = 0;
950   else
951     {
952       char *end;
953
954       size = strtoul (args, &end, 0);
955       if (args == end)
956         error (_("Invalid %s (bad syntax)."), config->name);
957 #if 0
958       /* Instead of explicitly capping the size of a packet to
959          MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
960          instead allowed to set the size to something arbitrarily
961          large.  */
962       if (size > MAX_REMOTE_PACKET_SIZE)
963         error (_("Invalid %s (too large)."), config->name);
964 #endif
965     }
966   /* Extra checks?  */
967   if (fixed_p && !config->fixed_p)
968     {
969       if (! query (_("The target may not be able to correctly handle a %s\n"
970                    "of %ld bytes. Change the packet size? "),
971                    config->name, size))
972         error (_("Packet size not changed."));
973     }
974   /* Update the config.  */
975   config->fixed_p = fixed_p;
976   config->size = size;
977 }
978
979 static void
980 show_memory_packet_size (struct memory_packet_config *config)
981 {
982   printf_filtered (_("The %s is %ld. "), config->name, config->size);
983   if (config->fixed_p)
984     printf_filtered (_("Packets are fixed at %ld bytes.\n"),
985                      get_memory_packet_size (config));
986   else
987     printf_filtered (_("Packets are limited to %ld bytes.\n"),
988                      get_memory_packet_size (config));
989 }
990
991 static struct memory_packet_config memory_write_packet_config =
992 {
993   "memory-write-packet-size",
994 };
995
996 static void
997 set_memory_write_packet_size (char *args, int from_tty)
998 {
999   set_memory_packet_size (args, &memory_write_packet_config);
1000 }
1001
1002 static void
1003 show_memory_write_packet_size (char *args, int from_tty)
1004 {
1005   show_memory_packet_size (&memory_write_packet_config);
1006 }
1007
1008 static long
1009 get_memory_write_packet_size (void)
1010 {
1011   return get_memory_packet_size (&memory_write_packet_config);
1012 }
1013
1014 static struct memory_packet_config memory_read_packet_config =
1015 {
1016   "memory-read-packet-size",
1017 };
1018
1019 static void
1020 set_memory_read_packet_size (char *args, int from_tty)
1021 {
1022   set_memory_packet_size (args, &memory_read_packet_config);
1023 }
1024
1025 static void
1026 show_memory_read_packet_size (char *args, int from_tty)
1027 {
1028   show_memory_packet_size (&memory_read_packet_config);
1029 }
1030
1031 static long
1032 get_memory_read_packet_size (void)
1033 {
1034   long size = get_memory_packet_size (&memory_read_packet_config);
1035
1036   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1037      extra buffer size argument before the memory read size can be
1038      increased beyond this.  */
1039   if (size > get_remote_packet_size ())
1040     size = get_remote_packet_size ();
1041   return size;
1042 }
1043
1044 \f
1045 /* Generic configuration support for packets the stub optionally
1046    supports.  Allows the user to specify the use of the packet as well
1047    as allowing GDB to auto-detect support in the remote stub.  */
1048
1049 enum packet_support
1050   {
1051     PACKET_SUPPORT_UNKNOWN = 0,
1052     PACKET_ENABLE,
1053     PACKET_DISABLE
1054   };
1055
1056 struct packet_config
1057   {
1058     const char *name;
1059     const char *title;
1060
1061     /* If auto, GDB auto-detects support for this packet or feature,
1062        either through qSupported, or by trying the packet and looking
1063        at the response.  If true, GDB assumes the target supports this
1064        packet.  If false, the packet is disabled.  Configs that don't
1065        have an associated command always have this set to auto.  */
1066     enum auto_boolean detect;
1067
1068     /* Does the target support this packet?  */
1069     enum packet_support support;
1070   };
1071
1072 /* Analyze a packet's return value and update the packet config
1073    accordingly.  */
1074
1075 enum packet_result
1076 {
1077   PACKET_ERROR,
1078   PACKET_OK,
1079   PACKET_UNKNOWN
1080 };
1081
1082 static enum packet_support packet_config_support (struct packet_config *config);
1083 static enum packet_support packet_support (int packet);
1084
1085 static void
1086 show_packet_config_cmd (struct packet_config *config)
1087 {
1088   char *support = "internal-error";
1089
1090   switch (packet_config_support (config))
1091     {
1092     case PACKET_ENABLE:
1093       support = "enabled";
1094       break;
1095     case PACKET_DISABLE:
1096       support = "disabled";
1097       break;
1098     case PACKET_SUPPORT_UNKNOWN:
1099       support = "unknown";
1100       break;
1101     }
1102   switch (config->detect)
1103     {
1104     case AUTO_BOOLEAN_AUTO:
1105       printf_filtered (_("Support for the `%s' packet "
1106                          "is auto-detected, currently %s.\n"),
1107                        config->name, support);
1108       break;
1109     case AUTO_BOOLEAN_TRUE:
1110     case AUTO_BOOLEAN_FALSE:
1111       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1112                        config->name, support);
1113       break;
1114     }
1115 }
1116
1117 static void
1118 add_packet_config_cmd (struct packet_config *config, const char *name,
1119                        const char *title, int legacy)
1120 {
1121   char *set_doc;
1122   char *show_doc;
1123   char *cmd_name;
1124
1125   config->name = name;
1126   config->title = title;
1127   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1128                         name, title);
1129   show_doc = xstrprintf ("Show current use of remote "
1130                          "protocol `%s' (%s) packet",
1131                          name, title);
1132   /* set/show TITLE-packet {auto,on,off} */
1133   cmd_name = xstrprintf ("%s-packet", title);
1134   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1135                                 &config->detect, set_doc,
1136                                 show_doc, NULL, /* help_doc */
1137                                 NULL,
1138                                 show_remote_protocol_packet_cmd,
1139                                 &remote_set_cmdlist, &remote_show_cmdlist);
1140   /* The command code copies the documentation strings.  */
1141   xfree (set_doc);
1142   xfree (show_doc);
1143   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
1144   if (legacy)
1145     {
1146       char *legacy_name;
1147
1148       legacy_name = xstrprintf ("%s-packet", name);
1149       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1150                      &remote_set_cmdlist);
1151       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1152                      &remote_show_cmdlist);
1153     }
1154 }
1155
1156 static enum packet_result
1157 packet_check_result (const char *buf)
1158 {
1159   if (buf[0] != '\0')
1160     {
1161       /* The stub recognized the packet request.  Check that the
1162          operation succeeded.  */
1163       if (buf[0] == 'E'
1164           && isxdigit (buf[1]) && isxdigit (buf[2])
1165           && buf[3] == '\0')
1166         /* "Enn"  - definitly an error.  */
1167         return PACKET_ERROR;
1168
1169       /* Always treat "E." as an error.  This will be used for
1170          more verbose error messages, such as E.memtypes.  */
1171       if (buf[0] == 'E' && buf[1] == '.')
1172         return PACKET_ERROR;
1173
1174       /* The packet may or may not be OK.  Just assume it is.  */
1175       return PACKET_OK;
1176     }
1177   else
1178     /* The stub does not support the packet.  */
1179     return PACKET_UNKNOWN;
1180 }
1181
1182 static enum packet_result
1183 packet_ok (const char *buf, struct packet_config *config)
1184 {
1185   enum packet_result result;
1186
1187   if (config->detect != AUTO_BOOLEAN_TRUE
1188       && config->support == PACKET_DISABLE)
1189     internal_error (__FILE__, __LINE__,
1190                     _("packet_ok: attempt to use a disabled packet"));
1191
1192   result = packet_check_result (buf);
1193   switch (result)
1194     {
1195     case PACKET_OK:
1196     case PACKET_ERROR:
1197       /* The stub recognized the packet request.  */
1198       if (config->support == PACKET_SUPPORT_UNKNOWN)
1199         {
1200           if (remote_debug)
1201             fprintf_unfiltered (gdb_stdlog,
1202                                 "Packet %s (%s) is supported\n",
1203                                 config->name, config->title);
1204           config->support = PACKET_ENABLE;
1205         }
1206       break;
1207     case PACKET_UNKNOWN:
1208       /* The stub does not support the packet.  */
1209       if (config->detect == AUTO_BOOLEAN_AUTO
1210           && config->support == PACKET_ENABLE)
1211         {
1212           /* If the stub previously indicated that the packet was
1213              supported then there is a protocol error.  */
1214           error (_("Protocol error: %s (%s) conflicting enabled responses."),
1215                  config->name, config->title);
1216         }
1217       else if (config->detect == AUTO_BOOLEAN_TRUE)
1218         {
1219           /* The user set it wrong.  */
1220           error (_("Enabled packet %s (%s) not recognized by stub"),
1221                  config->name, config->title);
1222         }
1223
1224       if (remote_debug)
1225         fprintf_unfiltered (gdb_stdlog,
1226                             "Packet %s (%s) is NOT supported\n",
1227                             config->name, config->title);
1228       config->support = PACKET_DISABLE;
1229       break;
1230     }
1231
1232   return result;
1233 }
1234
1235 enum {
1236   PACKET_vCont = 0,
1237   PACKET_X,
1238   PACKET_qSymbol,
1239   PACKET_P,
1240   PACKET_p,
1241   PACKET_Z0,
1242   PACKET_Z1,
1243   PACKET_Z2,
1244   PACKET_Z3,
1245   PACKET_Z4,
1246   PACKET_vFile_open,
1247   PACKET_vFile_pread,
1248   PACKET_vFile_pwrite,
1249   PACKET_vFile_close,
1250   PACKET_vFile_unlink,
1251   PACKET_vFile_readlink,
1252   PACKET_vFile_fstat,
1253   PACKET_qXfer_auxv,
1254   PACKET_qXfer_features,
1255   PACKET_qXfer_exec_file,
1256   PACKET_qXfer_libraries,
1257   PACKET_qXfer_libraries_svr4,
1258   PACKET_qXfer_memory_map,
1259   PACKET_qXfer_spu_read,
1260   PACKET_qXfer_spu_write,
1261   PACKET_qXfer_osdata,
1262   PACKET_qXfer_threads,
1263   PACKET_qXfer_statictrace_read,
1264   PACKET_qXfer_traceframe_info,
1265   PACKET_qXfer_uib,
1266   PACKET_qGetTIBAddr,
1267   PACKET_qGetTLSAddr,
1268   PACKET_qSupported,
1269   PACKET_qTStatus,
1270   PACKET_QPassSignals,
1271   PACKET_QProgramSignals,
1272   PACKET_qCRC,
1273   PACKET_qSearch_memory,
1274   PACKET_vAttach,
1275   PACKET_vRun,
1276   PACKET_QStartNoAckMode,
1277   PACKET_vKill,
1278   PACKET_qXfer_siginfo_read,
1279   PACKET_qXfer_siginfo_write,
1280   PACKET_qAttached,
1281
1282   /* Support for conditional tracepoints.  */
1283   PACKET_ConditionalTracepoints,
1284
1285   /* Support for target-side breakpoint conditions.  */
1286   PACKET_ConditionalBreakpoints,
1287
1288   /* Support for target-side breakpoint commands.  */
1289   PACKET_BreakpointCommands,
1290
1291   /* Support for fast tracepoints.  */
1292   PACKET_FastTracepoints,
1293
1294   /* Support for static tracepoints.  */
1295   PACKET_StaticTracepoints,
1296
1297   /* Support for installing tracepoints while a trace experiment is
1298      running.  */
1299   PACKET_InstallInTrace,
1300
1301   PACKET_bc,
1302   PACKET_bs,
1303   PACKET_TracepointSource,
1304   PACKET_QAllow,
1305   PACKET_qXfer_fdpic,
1306   PACKET_QDisableRandomization,
1307   PACKET_QAgent,
1308   PACKET_QTBuffer_size,
1309   PACKET_Qbtrace_off,
1310   PACKET_Qbtrace_bts,
1311   PACKET_qXfer_btrace,
1312
1313   /* Support for the QNonStop packet.  */
1314   PACKET_QNonStop,
1315
1316   /* Support for multi-process extensions.  */
1317   PACKET_multiprocess_feature,
1318
1319   /* Support for enabling and disabling tracepoints while a trace
1320      experiment is running.  */
1321   PACKET_EnableDisableTracepoints_feature,
1322
1323   /* Support for collecting strings using the tracenz bytecode.  */
1324   PACKET_tracenz_feature,
1325
1326   /* Support for continuing to run a trace experiment while GDB is
1327      disconnected.  */
1328   PACKET_DisconnectedTracing_feature,
1329
1330   /* Support for qXfer:libraries-svr4:read with a non-empty annex.  */
1331   PACKET_augmented_libraries_svr4_read_feature,
1332
1333   /* Support for the qXfer:btrace-conf:read packet.  */
1334   PACKET_qXfer_btrace_conf,
1335
1336   /* Support for the Qbtrace-conf:bts:size packet.  */
1337   PACKET_Qbtrace_conf_bts_size,
1338
1339   /* Support for swbreak+ feature.  */
1340   PACKET_swbreak_feature,
1341
1342   /* Support for hwbreak+ feature.  */
1343   PACKET_hwbreak_feature,
1344
1345   /* Support for fork events.  */
1346   PACKET_fork_event_feature,
1347
1348   /* Support for vfork events.  */
1349   PACKET_vfork_event_feature,
1350
1351   PACKET_MAX
1352 };
1353
1354 static struct packet_config remote_protocol_packets[PACKET_MAX];
1355
1356 /* Returns the packet's corresponding "set remote foo-packet" command
1357    state.  See struct packet_config for more details.  */
1358
1359 static enum auto_boolean
1360 packet_set_cmd_state (int packet)
1361 {
1362   return remote_protocol_packets[packet].detect;
1363 }
1364
1365 /* Returns whether a given packet or feature is supported.  This takes
1366    into account the state of the corresponding "set remote foo-packet"
1367    command, which may be used to bypass auto-detection.  */
1368
1369 static enum packet_support
1370 packet_config_support (struct packet_config *config)
1371 {
1372   switch (config->detect)
1373     {
1374     case AUTO_BOOLEAN_TRUE:
1375       return PACKET_ENABLE;
1376     case AUTO_BOOLEAN_FALSE:
1377       return PACKET_DISABLE;
1378     case AUTO_BOOLEAN_AUTO:
1379       return config->support;
1380     default:
1381       gdb_assert_not_reached (_("bad switch"));
1382     }
1383 }
1384
1385 /* Same as packet_config_support, but takes the packet's enum value as
1386    argument.  */
1387
1388 static enum packet_support
1389 packet_support (int packet)
1390 {
1391   struct packet_config *config = &remote_protocol_packets[packet];
1392
1393   return packet_config_support (config);
1394 }
1395
1396 static void
1397 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1398                                  struct cmd_list_element *c,
1399                                  const char *value)
1400 {
1401   struct packet_config *packet;
1402
1403   for (packet = remote_protocol_packets;
1404        packet < &remote_protocol_packets[PACKET_MAX];
1405        packet++)
1406     {
1407       if (&packet->detect == c->var)
1408         {
1409           show_packet_config_cmd (packet);
1410           return;
1411         }
1412     }
1413   internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1414                   c->name);
1415 }
1416
1417 /* Should we try one of the 'Z' requests?  */
1418
1419 enum Z_packet_type
1420 {
1421   Z_PACKET_SOFTWARE_BP,
1422   Z_PACKET_HARDWARE_BP,
1423   Z_PACKET_WRITE_WP,
1424   Z_PACKET_READ_WP,
1425   Z_PACKET_ACCESS_WP,
1426   NR_Z_PACKET_TYPES
1427 };
1428
1429 /* For compatibility with older distributions.  Provide a ``set remote
1430    Z-packet ...'' command that updates all the Z packet types.  */
1431
1432 static enum auto_boolean remote_Z_packet_detect;
1433
1434 static void
1435 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1436                                   struct cmd_list_element *c)
1437 {
1438   int i;
1439
1440   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1441     remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1442 }
1443
1444 static void
1445 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1446                                    struct cmd_list_element *c,
1447                                    const char *value)
1448 {
1449   int i;
1450
1451   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1452     {
1453       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1454     }
1455 }
1456
1457 /* Returns true if the multi-process extensions are in effect.  */
1458
1459 static int
1460 remote_multi_process_p (struct remote_state *rs)
1461 {
1462   return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1463 }
1464
1465 /* Tokens for use by the asynchronous signal handlers for SIGINT.  */
1466 static struct async_signal_handler *async_sigint_remote_twice_token;
1467 static struct async_signal_handler *async_sigint_remote_token;
1468
1469 \f
1470 /* Asynchronous signal handle registered as event loop source for
1471    when we have pending events ready to be passed to the core.  */
1472
1473 static struct async_event_handler *remote_async_inferior_event_token;
1474
1475 \f
1476
1477 static ptid_t magic_null_ptid;
1478 static ptid_t not_sent_ptid;
1479 static ptid_t any_thread_ptid;
1480
1481 /* Find out if the stub attached to PID (and hence GDB should offer to
1482    detach instead of killing it when bailing out).  */
1483
1484 static int
1485 remote_query_attached (int pid)
1486 {
1487   struct remote_state *rs = get_remote_state ();
1488   size_t size = get_remote_packet_size ();
1489
1490   if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1491     return 0;
1492
1493   if (remote_multi_process_p (rs))
1494     xsnprintf (rs->buf, size, "qAttached:%x", pid);
1495   else
1496     xsnprintf (rs->buf, size, "qAttached");
1497
1498   putpkt (rs->buf);
1499   getpkt (&rs->buf, &rs->buf_size, 0);
1500
1501   switch (packet_ok (rs->buf,
1502                      &remote_protocol_packets[PACKET_qAttached]))
1503     {
1504     case PACKET_OK:
1505       if (strcmp (rs->buf, "1") == 0)
1506         return 1;
1507       break;
1508     case PACKET_ERROR:
1509       warning (_("Remote failure reply: %s"), rs->buf);
1510       break;
1511     case PACKET_UNKNOWN:
1512       break;
1513     }
1514
1515   return 0;
1516 }
1517
1518 /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
1519    has been invented by GDB, instead of reported by the target.  Since
1520    we can be connected to a remote system before before knowing about
1521    any inferior, mark the target with execution when we find the first
1522    inferior.  If ATTACHED is 1, then we had just attached to this
1523    inferior.  If it is 0, then we just created this inferior.  If it
1524    is -1, then try querying the remote stub to find out if it had
1525    attached to the inferior or not.  If TRY_OPEN_EXEC is true then
1526    attempt to open this inferior's executable as the main executable
1527    if no main executable is open already.  */
1528
1529 static struct inferior *
1530 remote_add_inferior (int fake_pid_p, int pid, int attached,
1531                      int try_open_exec)
1532 {
1533   struct inferior *inf;
1534
1535   /* Check whether this process we're learning about is to be
1536      considered attached, or if is to be considered to have been
1537      spawned by the stub.  */
1538   if (attached == -1)
1539     attached = remote_query_attached (pid);
1540
1541   if (gdbarch_has_global_solist (target_gdbarch ()))
1542     {
1543       /* If the target shares code across all inferiors, then every
1544          attach adds a new inferior.  */
1545       inf = add_inferior (pid);
1546
1547       /* ... and every inferior is bound to the same program space.
1548          However, each inferior may still have its own address
1549          space.  */
1550       inf->aspace = maybe_new_address_space ();
1551       inf->pspace = current_program_space;
1552     }
1553   else
1554     {
1555       /* In the traditional debugging scenario, there's a 1-1 match
1556          between program/address spaces.  We simply bind the inferior
1557          to the program space's address space.  */
1558       inf = current_inferior ();
1559       inferior_appeared (inf, pid);
1560     }
1561
1562   inf->attach_flag = attached;
1563   inf->fake_pid_p = fake_pid_p;
1564
1565   /* If no main executable is currently open then attempt to
1566      open the file that was executed to create this inferior.  */
1567   if (try_open_exec && get_exec_file (0) == NULL)
1568     exec_file_locate_attach (pid, 1);
1569
1570   return inf;
1571 }
1572
1573 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
1574    according to RUNNING.  */
1575
1576 static void
1577 remote_add_thread (ptid_t ptid, int running)
1578 {
1579   struct remote_state *rs = get_remote_state ();
1580
1581   /* GDB historically didn't pull threads in the initial connection
1582      setup.  If the remote target doesn't even have a concept of
1583      threads (e.g., a bare-metal target), even if internally we
1584      consider that a single-threaded target, mentioning a new thread
1585      might be confusing to the user.  Be silent then, preserving the
1586      age old behavior.  */
1587   if (rs->starting_up)
1588     add_thread_silent (ptid);
1589   else
1590     add_thread (ptid);
1591
1592   set_executing (ptid, running);
1593   set_running (ptid, running);
1594 }
1595
1596 /* Come here when we learn about a thread id from the remote target.
1597    It may be the first time we hear about such thread, so take the
1598    opportunity to add it to GDB's thread list.  In case this is the
1599    first time we're noticing its corresponding inferior, add it to
1600    GDB's inferior list as well.  */
1601
1602 static void
1603 remote_notice_new_inferior (ptid_t currthread, int running)
1604 {
1605   /* If this is a new thread, add it to GDB's thread list.
1606      If we leave it up to WFI to do this, bad things will happen.  */
1607
1608   if (in_thread_list (currthread) && is_exited (currthread))
1609     {
1610       /* We're seeing an event on a thread id we knew had exited.
1611          This has to be a new thread reusing the old id.  Add it.  */
1612       remote_add_thread (currthread, running);
1613       return;
1614     }
1615
1616   if (!in_thread_list (currthread))
1617     {
1618       struct inferior *inf = NULL;
1619       int pid = ptid_get_pid (currthread);
1620
1621       if (ptid_is_pid (inferior_ptid)
1622           && pid == ptid_get_pid (inferior_ptid))
1623         {
1624           /* inferior_ptid has no thread member yet.  This can happen
1625              with the vAttach -> remote_wait,"TAAthread:" path if the
1626              stub doesn't support qC.  This is the first stop reported
1627              after an attach, so this is the main thread.  Update the
1628              ptid in the thread list.  */
1629           if (in_thread_list (pid_to_ptid (pid)))
1630             thread_change_ptid (inferior_ptid, currthread);
1631           else
1632             {
1633               remote_add_thread (currthread, running);
1634               inferior_ptid = currthread;
1635             }
1636           return;
1637         }
1638
1639       if (ptid_equal (magic_null_ptid, inferior_ptid))
1640         {
1641           /* inferior_ptid is not set yet.  This can happen with the
1642              vRun -> remote_wait,"TAAthread:" path if the stub
1643              doesn't support qC.  This is the first stop reported
1644              after an attach, so this is the main thread.  Update the
1645              ptid in the thread list.  */
1646           thread_change_ptid (inferior_ptid, currthread);
1647           return;
1648         }
1649
1650       /* When connecting to a target remote, or to a target
1651          extended-remote which already was debugging an inferior, we
1652          may not know about it yet.  Add it before adding its child
1653          thread, so notifications are emitted in a sensible order.  */
1654       if (!in_inferior_list (ptid_get_pid (currthread)))
1655         {
1656           struct remote_state *rs = get_remote_state ();
1657           int fake_pid_p = !remote_multi_process_p (rs);
1658
1659           inf = remote_add_inferior (fake_pid_p,
1660                                      ptid_get_pid (currthread), -1, 1);
1661         }
1662
1663       /* This is really a new thread.  Add it.  */
1664       remote_add_thread (currthread, running);
1665
1666       /* If we found a new inferior, let the common code do whatever
1667          it needs to with it (e.g., read shared libraries, insert
1668          breakpoints), unless we're just setting up an all-stop
1669          connection.  */
1670       if (inf != NULL)
1671         {
1672           struct remote_state *rs = get_remote_state ();
1673
1674           if (non_stop || !rs->starting_up)
1675             notice_new_inferior (currthread, running, 0);
1676         }
1677     }
1678 }
1679
1680 /* Return the private thread data, creating it if necessary.  */
1681
1682 static struct private_thread_info *
1683 demand_private_info (ptid_t ptid)
1684 {
1685   struct thread_info *info = find_thread_ptid (ptid);
1686
1687   gdb_assert (info);
1688
1689   if (!info->priv)
1690     {
1691       info->priv = xmalloc (sizeof (*(info->priv)));
1692       info->private_dtor = free_private_thread_info;
1693       info->priv->core = -1;
1694       info->priv->extra = 0;
1695     }
1696
1697   return info->priv;
1698 }
1699
1700 /* Call this function as a result of
1701    1) A halt indication (T packet) containing a thread id
1702    2) A direct query of currthread
1703    3) Successful execution of set thread */
1704
1705 static void
1706 record_currthread (struct remote_state *rs, ptid_t currthread)
1707 {
1708   rs->general_thread = currthread;
1709 }
1710
1711 /* If 'QPassSignals' is supported, tell the remote stub what signals
1712    it can simply pass through to the inferior without reporting.  */
1713
1714 static void
1715 remote_pass_signals (struct target_ops *self,
1716                      int numsigs, unsigned char *pass_signals)
1717 {
1718   if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1719     {
1720       char *pass_packet, *p;
1721       int count = 0, i;
1722       struct remote_state *rs = get_remote_state ();
1723
1724       gdb_assert (numsigs < 256);
1725       for (i = 0; i < numsigs; i++)
1726         {
1727           if (pass_signals[i])
1728             count++;
1729         }
1730       pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1731       strcpy (pass_packet, "QPassSignals:");
1732       p = pass_packet + strlen (pass_packet);
1733       for (i = 0; i < numsigs; i++)
1734         {
1735           if (pass_signals[i])
1736             {
1737               if (i >= 16)
1738                 *p++ = tohex (i >> 4);
1739               *p++ = tohex (i & 15);
1740               if (count)
1741                 *p++ = ';';
1742               else
1743                 break;
1744               count--;
1745             }
1746         }
1747       *p = 0;
1748       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1749         {
1750           putpkt (pass_packet);
1751           getpkt (&rs->buf, &rs->buf_size, 0);
1752           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1753           if (rs->last_pass_packet)
1754             xfree (rs->last_pass_packet);
1755           rs->last_pass_packet = pass_packet;
1756         }
1757       else
1758         xfree (pass_packet);
1759     }
1760 }
1761
1762 /* If 'QProgramSignals' is supported, tell the remote stub what
1763    signals it should pass through to the inferior when detaching.  */
1764
1765 static void
1766 remote_program_signals (struct target_ops *self,
1767                         int numsigs, unsigned char *signals)
1768 {
1769   if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
1770     {
1771       char *packet, *p;
1772       int count = 0, i;
1773       struct remote_state *rs = get_remote_state ();
1774
1775       gdb_assert (numsigs < 256);
1776       for (i = 0; i < numsigs; i++)
1777         {
1778           if (signals[i])
1779             count++;
1780         }
1781       packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1782       strcpy (packet, "QProgramSignals:");
1783       p = packet + strlen (packet);
1784       for (i = 0; i < numsigs; i++)
1785         {
1786           if (signal_pass_state (i))
1787             {
1788               if (i >= 16)
1789                 *p++ = tohex (i >> 4);
1790               *p++ = tohex (i & 15);
1791               if (count)
1792                 *p++ = ';';
1793               else
1794                 break;
1795               count--;
1796             }
1797         }
1798       *p = 0;
1799       if (!rs->last_program_signals_packet
1800           || strcmp (rs->last_program_signals_packet, packet) != 0)
1801         {
1802           putpkt (packet);
1803           getpkt (&rs->buf, &rs->buf_size, 0);
1804           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
1805           xfree (rs->last_program_signals_packet);
1806           rs->last_program_signals_packet = packet;
1807         }
1808       else
1809         xfree (packet);
1810     }
1811 }
1812
1813 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
1814    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1815    thread.  If GEN is set, set the general thread, if not, then set
1816    the step/continue thread.  */
1817 static void
1818 set_thread (struct ptid ptid, int gen)
1819 {
1820   struct remote_state *rs = get_remote_state ();
1821   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
1822   char *buf = rs->buf;
1823   char *endbuf = rs->buf + get_remote_packet_size ();
1824
1825   if (ptid_equal (state, ptid))
1826     return;
1827
1828   *buf++ = 'H';
1829   *buf++ = gen ? 'g' : 'c';
1830   if (ptid_equal (ptid, magic_null_ptid))
1831     xsnprintf (buf, endbuf - buf, "0");
1832   else if (ptid_equal (ptid, any_thread_ptid))
1833     xsnprintf (buf, endbuf - buf, "0");
1834   else if (ptid_equal (ptid, minus_one_ptid))
1835     xsnprintf (buf, endbuf - buf, "-1");
1836   else
1837     write_ptid (buf, endbuf, ptid);
1838   putpkt (rs->buf);
1839   getpkt (&rs->buf, &rs->buf_size, 0);
1840   if (gen)
1841     rs->general_thread = ptid;
1842   else
1843     rs->continue_thread = ptid;
1844 }
1845
1846 static void
1847 set_general_thread (struct ptid ptid)
1848 {
1849   set_thread (ptid, 1);
1850 }
1851
1852 static void
1853 set_continue_thread (struct ptid ptid)
1854 {
1855   set_thread (ptid, 0);
1856 }
1857
1858 /* Change the remote current process.  Which thread within the process
1859    ends up selected isn't important, as long as it is the same process
1860    as what INFERIOR_PTID points to.
1861
1862    This comes from that fact that there is no explicit notion of
1863    "selected process" in the protocol.  The selected process for
1864    general operations is the process the selected general thread
1865    belongs to.  */
1866
1867 static void
1868 set_general_process (void)
1869 {
1870   struct remote_state *rs = get_remote_state ();
1871
1872   /* If the remote can't handle multiple processes, don't bother.  */
1873   if (!rs->extended || !remote_multi_process_p (rs))
1874     return;
1875
1876   /* We only need to change the remote current thread if it's pointing
1877      at some other process.  */
1878   if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
1879     set_general_thread (inferior_ptid);
1880 }
1881
1882 \f
1883 /* Return nonzero if this is the main thread that we made up ourselves
1884    to model non-threaded targets as single-threaded.  */
1885
1886 static int
1887 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
1888 {
1889   struct remote_state *rs = get_remote_state ();
1890   char *p, *endp;
1891
1892   if (ptid_equal (ptid, magic_null_ptid))
1893     /* The main thread is always alive.  */
1894     return 1;
1895
1896   if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
1897     /* The main thread is always alive.  This can happen after a
1898        vAttach, if the remote side doesn't support
1899        multi-threading.  */
1900     return 1;
1901
1902   return 0;
1903 }
1904
1905 /* Return nonzero if the thread PTID is still alive on the remote
1906    system.  */
1907
1908 static int
1909 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1910 {
1911   struct remote_state *rs = get_remote_state ();
1912   char *p, *endp;
1913
1914   /* Check if this is a thread that we made up ourselves to model
1915      non-threaded targets as single-threaded.  */
1916   if (remote_thread_always_alive (ops, ptid))
1917     return 1;
1918
1919   p = rs->buf;
1920   endp = rs->buf + get_remote_packet_size ();
1921
1922   *p++ = 'T';
1923   write_ptid (p, endp, ptid);
1924
1925   putpkt (rs->buf);
1926   getpkt (&rs->buf, &rs->buf_size, 0);
1927   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1928 }
1929
1930 /* About these extended threadlist and threadinfo packets.  They are
1931    variable length packets but, the fields within them are often fixed
1932    length.  They are redundent enough to send over UDP as is the
1933    remote protocol in general.  There is a matching unit test module
1934    in libstub.  */
1935
1936 /* WARNING: This threadref data structure comes from the remote O.S.,
1937    libstub protocol encoding, and remote.c.  It is not particularly
1938    changable.  */
1939
1940 /* Right now, the internal structure is int. We want it to be bigger.
1941    Plan to fix this.  */
1942
1943 typedef int gdb_threadref;      /* Internal GDB thread reference.  */
1944
1945 /* gdb_ext_thread_info is an internal GDB data structure which is
1946    equivalent to the reply of the remote threadinfo packet.  */
1947
1948 struct gdb_ext_thread_info
1949   {
1950     threadref threadid;         /* External form of thread reference.  */
1951     int active;                 /* Has state interesting to GDB?
1952                                    regs, stack.  */
1953     char display[256];          /* Brief state display, name,
1954                                    blocked/suspended.  */
1955     char shortname[32];         /* To be used to name threads.  */
1956     char more_display[256];     /* Long info, statistics, queue depth,
1957                                    whatever.  */
1958   };
1959
1960 /* The volume of remote transfers can be limited by submitting
1961    a mask containing bits specifying the desired information.
1962    Use a union of these values as the 'selection' parameter to
1963    get_thread_info.  FIXME: Make these TAG names more thread specific.  */
1964
1965 #define TAG_THREADID 1
1966 #define TAG_EXISTS 2
1967 #define TAG_DISPLAY 4
1968 #define TAG_THREADNAME 8
1969 #define TAG_MOREDISPLAY 16
1970
1971 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1972
1973 static char *unpack_nibble (char *buf, int *val);
1974
1975 static char *unpack_byte (char *buf, int *value);
1976
1977 static char *pack_int (char *buf, int value);
1978
1979 static char *unpack_int (char *buf, int *value);
1980
1981 static char *unpack_string (char *src, char *dest, int length);
1982
1983 static char *pack_threadid (char *pkt, threadref *id);
1984
1985 static char *unpack_threadid (char *inbuf, threadref *id);
1986
1987 void int_to_threadref (threadref *id, int value);
1988
1989 static int threadref_to_int (threadref *ref);
1990
1991 static void copy_threadref (threadref *dest, threadref *src);
1992
1993 static int threadmatch (threadref *dest, threadref *src);
1994
1995 static char *pack_threadinfo_request (char *pkt, int mode,
1996                                       threadref *id);
1997
1998 static int remote_unpack_thread_info_response (char *pkt,
1999                                                threadref *expectedref,
2000                                                struct gdb_ext_thread_info
2001                                                *info);
2002
2003
2004 static int remote_get_threadinfo (threadref *threadid,
2005                                   int fieldset, /*TAG mask */
2006                                   struct gdb_ext_thread_info *info);
2007
2008 static char *pack_threadlist_request (char *pkt, int startflag,
2009                                       int threadcount,
2010                                       threadref *nextthread);
2011
2012 static int parse_threadlist_response (char *pkt,
2013                                       int result_limit,
2014                                       threadref *original_echo,
2015                                       threadref *resultlist,
2016                                       int *doneflag);
2017
2018 static int remote_get_threadlist (int startflag,
2019                                   threadref *nextthread,
2020                                   int result_limit,
2021                                   int *done,
2022                                   int *result_count,
2023                                   threadref *threadlist);
2024
2025 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2026
2027 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2028                                        void *context, int looplimit);
2029
2030 static int remote_newthread_step (threadref *ref, void *context);
2031
2032
2033 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
2034    buffer we're allowed to write to.  Returns
2035    BUF+CHARACTERS_WRITTEN.  */
2036
2037 static char *
2038 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2039 {
2040   int pid, tid;
2041   struct remote_state *rs = get_remote_state ();
2042
2043   if (remote_multi_process_p (rs))
2044     {
2045       pid = ptid_get_pid (ptid);
2046       if (pid < 0)
2047         buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2048       else
2049         buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2050     }
2051   tid = ptid_get_lwp (ptid);
2052   if (tid < 0)
2053     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2054   else
2055     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2056
2057   return buf;
2058 }
2059
2060 /* Extract a PTID from BUF.  If non-null, OBUF is set to the to one
2061    passed the last parsed char.  Returns null_ptid on error.  */
2062
2063 static ptid_t
2064 read_ptid (char *buf, char **obuf)
2065 {
2066   char *p = buf;
2067   char *pp;
2068   ULONGEST pid = 0, tid = 0;
2069
2070   if (*p == 'p')
2071     {
2072       /* Multi-process ptid.  */
2073       pp = unpack_varlen_hex (p + 1, &pid);
2074       if (*pp != '.')
2075         error (_("invalid remote ptid: %s"), p);
2076
2077       p = pp;
2078       pp = unpack_varlen_hex (p + 1, &tid);
2079       if (obuf)
2080         *obuf = pp;
2081       return ptid_build (pid, tid, 0);
2082     }
2083
2084   /* No multi-process.  Just a tid.  */
2085   pp = unpack_varlen_hex (p, &tid);
2086
2087   /* Since the stub is not sending a process id, then default to
2088      what's in inferior_ptid, unless it's null at this point.  If so,
2089      then since there's no way to know the pid of the reported
2090      threads, use the magic number.  */
2091   if (ptid_equal (inferior_ptid, null_ptid))
2092     pid = ptid_get_pid (magic_null_ptid);
2093   else
2094     pid = ptid_get_pid (inferior_ptid);
2095
2096   if (obuf)
2097     *obuf = pp;
2098   return ptid_build (pid, tid, 0);
2099 }
2100
2101 static int
2102 stubhex (int ch)
2103 {
2104   if (ch >= 'a' && ch <= 'f')
2105     return ch - 'a' + 10;
2106   if (ch >= '0' && ch <= '9')
2107     return ch - '0';
2108   if (ch >= 'A' && ch <= 'F')
2109     return ch - 'A' + 10;
2110   return -1;
2111 }
2112
2113 static int
2114 stub_unpack_int (char *buff, int fieldlength)
2115 {
2116   int nibble;
2117   int retval = 0;
2118
2119   while (fieldlength)
2120     {
2121       nibble = stubhex (*buff++);
2122       retval |= nibble;
2123       fieldlength--;
2124       if (fieldlength)
2125         retval = retval << 4;
2126     }
2127   return retval;
2128 }
2129
2130 static char *
2131 unpack_nibble (char *buf, int *val)
2132 {
2133   *val = fromhex (*buf++);
2134   return buf;
2135 }
2136
2137 static char *
2138 unpack_byte (char *buf, int *value)
2139 {
2140   *value = stub_unpack_int (buf, 2);
2141   return buf + 2;
2142 }
2143
2144 static char *
2145 pack_int (char *buf, int value)
2146 {
2147   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2148   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2149   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2150   buf = pack_hex_byte (buf, (value & 0xff));
2151   return buf;
2152 }
2153
2154 static char *
2155 unpack_int (char *buf, int *value)
2156 {
2157   *value = stub_unpack_int (buf, 8);
2158   return buf + 8;
2159 }
2160
2161 #if 0                   /* Currently unused, uncomment when needed.  */
2162 static char *pack_string (char *pkt, char *string);
2163
2164 static char *
2165 pack_string (char *pkt, char *string)
2166 {
2167   char ch;
2168   int len;
2169
2170   len = strlen (string);
2171   if (len > 200)
2172     len = 200;          /* Bigger than most GDB packets, junk???  */
2173   pkt = pack_hex_byte (pkt, len);
2174   while (len-- > 0)
2175     {
2176       ch = *string++;
2177       if ((ch == '\0') || (ch == '#'))
2178         ch = '*';               /* Protect encapsulation.  */
2179       *pkt++ = ch;
2180     }
2181   return pkt;
2182 }
2183 #endif /* 0 (unused) */
2184
2185 static char *
2186 unpack_string (char *src, char *dest, int length)
2187 {
2188   while (length--)
2189     *dest++ = *src++;
2190   *dest = '\0';
2191   return src;
2192 }
2193
2194 static char *
2195 pack_threadid (char *pkt, threadref *id)
2196 {
2197   char *limit;
2198   unsigned char *altid;
2199
2200   altid = (unsigned char *) id;
2201   limit = pkt + BUF_THREAD_ID_SIZE;
2202   while (pkt < limit)
2203     pkt = pack_hex_byte (pkt, *altid++);
2204   return pkt;
2205 }
2206
2207
2208 static char *
2209 unpack_threadid (char *inbuf, threadref *id)
2210 {
2211   char *altref;
2212   char *limit = inbuf + BUF_THREAD_ID_SIZE;
2213   int x, y;
2214
2215   altref = (char *) id;
2216
2217   while (inbuf < limit)
2218     {
2219       x = stubhex (*inbuf++);
2220       y = stubhex (*inbuf++);
2221       *altref++ = (x << 4) | y;
2222     }
2223   return inbuf;
2224 }
2225
2226 /* Externally, threadrefs are 64 bits but internally, they are still
2227    ints.  This is due to a mismatch of specifications.  We would like
2228    to use 64bit thread references internally.  This is an adapter
2229    function.  */
2230
2231 void
2232 int_to_threadref (threadref *id, int value)
2233 {
2234   unsigned char *scan;
2235
2236   scan = (unsigned char *) id;
2237   {
2238     int i = 4;
2239     while (i--)
2240       *scan++ = 0;
2241   }
2242   *scan++ = (value >> 24) & 0xff;
2243   *scan++ = (value >> 16) & 0xff;
2244   *scan++ = (value >> 8) & 0xff;
2245   *scan++ = (value & 0xff);
2246 }
2247
2248 static int
2249 threadref_to_int (threadref *ref)
2250 {
2251   int i, value = 0;
2252   unsigned char *scan;
2253
2254   scan = *ref;
2255   scan += 4;
2256   i = 4;
2257   while (i-- > 0)
2258     value = (value << 8) | ((*scan++) & 0xff);
2259   return value;
2260 }
2261
2262 static void
2263 copy_threadref (threadref *dest, threadref *src)
2264 {
2265   int i;
2266   unsigned char *csrc, *cdest;
2267
2268   csrc = (unsigned char *) src;
2269   cdest = (unsigned char *) dest;
2270   i = 8;
2271   while (i--)
2272     *cdest++ = *csrc++;
2273 }
2274
2275 static int
2276 threadmatch (threadref *dest, threadref *src)
2277 {
2278   /* Things are broken right now, so just assume we got a match.  */
2279 #if 0
2280   unsigned char *srcp, *destp;
2281   int i, result;
2282   srcp = (char *) src;
2283   destp = (char *) dest;
2284
2285   result = 1;
2286   while (i-- > 0)
2287     result &= (*srcp++ == *destp++) ? 1 : 0;
2288   return result;
2289 #endif
2290   return 1;
2291 }
2292
2293 /*
2294    threadid:1,        # always request threadid
2295    context_exists:2,
2296    display:4,
2297    unique_name:8,
2298    more_display:16
2299  */
2300
2301 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
2302
2303 static char *
2304 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2305 {
2306   *pkt++ = 'q';                         /* Info Query */
2307   *pkt++ = 'P';                         /* process or thread info */
2308   pkt = pack_int (pkt, mode);           /* mode */
2309   pkt = pack_threadid (pkt, id);        /* threadid */
2310   *pkt = '\0';                          /* terminate */
2311   return pkt;
2312 }
2313
2314 /* These values tag the fields in a thread info response packet.  */
2315 /* Tagging the fields allows us to request specific fields and to
2316    add more fields as time goes by.  */
2317
2318 #define TAG_THREADID 1          /* Echo the thread identifier.  */
2319 #define TAG_EXISTS 2            /* Is this process defined enough to
2320                                    fetch registers and its stack?  */
2321 #define TAG_DISPLAY 4           /* A short thing maybe to put on a window */
2322 #define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is.  */
2323 #define TAG_MOREDISPLAY 16      /* Whatever the kernel wants to say about
2324                                    the process.  */
2325
2326 static int
2327 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2328                                     struct gdb_ext_thread_info *info)
2329 {
2330   struct remote_state *rs = get_remote_state ();
2331   int mask, length;
2332   int tag;
2333   threadref ref;
2334   char *limit = pkt + rs->buf_size; /* Plausible parsing limit.  */
2335   int retval = 1;
2336
2337   /* info->threadid = 0; FIXME: implement zero_threadref.  */
2338   info->active = 0;
2339   info->display[0] = '\0';
2340   info->shortname[0] = '\0';
2341   info->more_display[0] = '\0';
2342
2343   /* Assume the characters indicating the packet type have been
2344      stripped.  */
2345   pkt = unpack_int (pkt, &mask);        /* arg mask */
2346   pkt = unpack_threadid (pkt, &ref);
2347
2348   if (mask == 0)
2349     warning (_("Incomplete response to threadinfo request."));
2350   if (!threadmatch (&ref, expectedref))
2351     {                   /* This is an answer to a different request.  */
2352       warning (_("ERROR RMT Thread info mismatch."));
2353       return 0;
2354     }
2355   copy_threadref (&info->threadid, &ref);
2356
2357   /* Loop on tagged fields , try to bail if somthing goes wrong.  */
2358
2359   /* Packets are terminated with nulls.  */
2360   while ((pkt < limit) && mask && *pkt)
2361     {
2362       pkt = unpack_int (pkt, &tag);     /* tag */
2363       pkt = unpack_byte (pkt, &length); /* length */
2364       if (!(tag & mask))                /* Tags out of synch with mask.  */
2365         {
2366           warning (_("ERROR RMT: threadinfo tag mismatch."));
2367           retval = 0;
2368           break;
2369         }
2370       if (tag == TAG_THREADID)
2371         {
2372           if (length != 16)
2373             {
2374               warning (_("ERROR RMT: length of threadid is not 16."));
2375               retval = 0;
2376               break;
2377             }
2378           pkt = unpack_threadid (pkt, &ref);
2379           mask = mask & ~TAG_THREADID;
2380           continue;
2381         }
2382       if (tag == TAG_EXISTS)
2383         {
2384           info->active = stub_unpack_int (pkt, length);
2385           pkt += length;
2386           mask = mask & ~(TAG_EXISTS);
2387           if (length > 8)
2388             {
2389               warning (_("ERROR RMT: 'exists' length too long."));
2390               retval = 0;
2391               break;
2392             }
2393           continue;
2394         }
2395       if (tag == TAG_THREADNAME)
2396         {
2397           pkt = unpack_string (pkt, &info->shortname[0], length);
2398           mask = mask & ~TAG_THREADNAME;
2399           continue;
2400         }
2401       if (tag == TAG_DISPLAY)
2402         {
2403           pkt = unpack_string (pkt, &info->display[0], length);
2404           mask = mask & ~TAG_DISPLAY;
2405           continue;
2406         }
2407       if (tag == TAG_MOREDISPLAY)
2408         {
2409           pkt = unpack_string (pkt, &info->more_display[0], length);
2410           mask = mask & ~TAG_MOREDISPLAY;
2411           continue;
2412         }
2413       warning (_("ERROR RMT: unknown thread info tag."));
2414       break;                    /* Not a tag we know about.  */
2415     }
2416   return retval;
2417 }
2418
2419 static int
2420 remote_get_threadinfo (threadref *threadid, int fieldset,       /* TAG mask */
2421                        struct gdb_ext_thread_info *info)
2422 {
2423   struct remote_state *rs = get_remote_state ();
2424   int result;
2425
2426   pack_threadinfo_request (rs->buf, fieldset, threadid);
2427   putpkt (rs->buf);
2428   getpkt (&rs->buf, &rs->buf_size, 0);
2429
2430   if (rs->buf[0] == '\0')
2431     return 0;
2432
2433   result = remote_unpack_thread_info_response (rs->buf + 2,
2434                                                threadid, info);
2435   return result;
2436 }
2437
2438 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
2439
2440 static char *
2441 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2442                          threadref *nextthread)
2443 {
2444   *pkt++ = 'q';                 /* info query packet */
2445   *pkt++ = 'L';                 /* Process LIST or threadLIST request */
2446   pkt = pack_nibble (pkt, startflag);           /* initflag 1 bytes */
2447   pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
2448   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
2449   *pkt = '\0';
2450   return pkt;
2451 }
2452
2453 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2454
2455 static int
2456 parse_threadlist_response (char *pkt, int result_limit,
2457                            threadref *original_echo, threadref *resultlist,
2458                            int *doneflag)
2459 {
2460   struct remote_state *rs = get_remote_state ();
2461   char *limit;
2462   int count, resultcount, done;
2463
2464   resultcount = 0;
2465   /* Assume the 'q' and 'M chars have been stripped.  */
2466   limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2467   /* done parse past here */
2468   pkt = unpack_byte (pkt, &count);      /* count field */
2469   pkt = unpack_nibble (pkt, &done);
2470   /* The first threadid is the argument threadid.  */
2471   pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
2472   while ((count-- > 0) && (pkt < limit))
2473     {
2474       pkt = unpack_threadid (pkt, resultlist++);
2475       if (resultcount++ >= result_limit)
2476         break;
2477     }
2478   if (doneflag)
2479     *doneflag = done;
2480   return resultcount;
2481 }
2482
2483 /* Fetch the next batch of threads from the remote.  Returns -1 if the
2484    qL packet is not supported, 0 on error and 1 on success.  */
2485
2486 static int
2487 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2488                        int *done, int *result_count, threadref *threadlist)
2489 {
2490   struct remote_state *rs = get_remote_state ();
2491   int result = 1;
2492
2493   /* Trancate result limit to be smaller than the packet size.  */
2494   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2495       >= get_remote_packet_size ())
2496     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2497
2498   pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2499   putpkt (rs->buf);
2500   getpkt (&rs->buf, &rs->buf_size, 0);
2501   if (*rs->buf == '\0')
2502     {
2503       /* Packet not supported.  */
2504       return -1;
2505     }
2506
2507   *result_count =
2508     parse_threadlist_response (rs->buf + 2, result_limit,
2509                                &rs->echo_nextthread, threadlist, done);
2510
2511   if (!threadmatch (&rs->echo_nextthread, nextthread))
2512     {
2513       /* FIXME: This is a good reason to drop the packet.  */
2514       /* Possably, there is a duplicate response.  */
2515       /* Possabilities :
2516          retransmit immediatly - race conditions
2517          retransmit after timeout - yes
2518          exit
2519          wait for packet, then exit
2520        */
2521       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2522       return 0;                 /* I choose simply exiting.  */
2523     }
2524   if (*result_count <= 0)
2525     {
2526       if (*done != 1)
2527         {
2528           warning (_("RMT ERROR : failed to get remote thread list."));
2529           result = 0;
2530         }
2531       return result;            /* break; */
2532     }
2533   if (*result_count > result_limit)
2534     {
2535       *result_count = 0;
2536       warning (_("RMT ERROR: threadlist response longer than requested."));
2537       return 0;
2538     }
2539   return result;
2540 }
2541
2542 /* Fetch the list of remote threads, with the qL packet, and call
2543    STEPFUNCTION for each thread found.  Stops iterating and returns 1
2544    if STEPFUNCTION returns true.  Stops iterating and returns 0 if the
2545    STEPFUNCTION returns false.  If the packet is not supported,
2546    returns -1.  */
2547
2548 static int
2549 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2550                             int looplimit)
2551 {
2552   struct remote_state *rs = get_remote_state ();
2553   int done, i, result_count;
2554   int startflag = 1;
2555   int result = 1;
2556   int loopcount = 0;
2557
2558   done = 0;
2559   while (!done)
2560     {
2561       if (loopcount++ > looplimit)
2562         {
2563           result = 0;
2564           warning (_("Remote fetch threadlist -infinite loop-."));
2565           break;
2566         }
2567       result = remote_get_threadlist (startflag, &rs->nextthread,
2568                                       MAXTHREADLISTRESULTS,
2569                                       &done, &result_count,
2570                                       rs->resultthreadlist);
2571       if (result <= 0)
2572         break;
2573       /* Clear for later iterations.  */
2574       startflag = 0;
2575       /* Setup to resume next batch of thread references, set nextthread.  */
2576       if (result_count >= 1)
2577         copy_threadref (&rs->nextthread,
2578                         &rs->resultthreadlist[result_count - 1]);
2579       i = 0;
2580       while (result_count--)
2581         {
2582           if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2583             {
2584               result = 0;
2585               break;
2586             }
2587         }
2588     }
2589   return result;
2590 }
2591
2592 /* A thread found on the remote target.  */
2593
2594 typedef struct thread_item
2595 {
2596   /* The thread's PTID.  */
2597   ptid_t ptid;
2598
2599   /* The thread's extra info.  May be NULL.  */
2600   char *extra;
2601
2602   /* The core the thread was running on.  -1 if not known.  */
2603   int core;
2604 } thread_item_t;
2605 DEF_VEC_O(thread_item_t);
2606
2607 /* Context passed around to the various methods listing remote
2608    threads.  As new threads are found, they're added to the ITEMS
2609    vector.  */
2610
2611 struct threads_listing_context
2612 {
2613   /* The threads found on the remote target.  */
2614   VEC (thread_item_t) *items;
2615 };
2616
2617 /* Discard the contents of the constructed thread listing context.  */
2618
2619 static void
2620 clear_threads_listing_context (void *p)
2621 {
2622   struct threads_listing_context *context = p;
2623   int i;
2624   struct thread_item *item;
2625
2626   for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2627     xfree (item->extra);
2628
2629   VEC_free (thread_item_t, context->items);
2630 }
2631
2632 static int
2633 remote_newthread_step (threadref *ref, void *data)
2634 {
2635   struct threads_listing_context *context = data;
2636   struct thread_item item;
2637   int pid = ptid_get_pid (inferior_ptid);
2638
2639   item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2640   item.core = -1;
2641   item.extra = NULL;
2642
2643   VEC_safe_push (thread_item_t, context->items, &item);
2644
2645   return 1;                     /* continue iterator */
2646 }
2647
2648 #define CRAZY_MAX_THREADS 1000
2649
2650 static ptid_t
2651 remote_current_thread (ptid_t oldpid)
2652 {
2653   struct remote_state *rs = get_remote_state ();
2654
2655   putpkt ("qC");
2656   getpkt (&rs->buf, &rs->buf_size, 0);
2657   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2658     return read_ptid (&rs->buf[2], NULL);
2659   else
2660     return oldpid;
2661 }
2662
2663 /* List remote threads using the deprecated qL packet.  */
2664
2665 static int
2666 remote_get_threads_with_ql (struct target_ops *ops,
2667                             struct threads_listing_context *context)
2668 {
2669   if (remote_threadlist_iterator (remote_newthread_step, context,
2670                                   CRAZY_MAX_THREADS) >= 0)
2671     return 1;
2672
2673   return 0;
2674 }
2675
2676 #if defined(HAVE_LIBEXPAT)
2677
2678 static void
2679 start_thread (struct gdb_xml_parser *parser,
2680               const struct gdb_xml_element *element,
2681               void *user_data, VEC(gdb_xml_value_s) *attributes)
2682 {
2683   struct threads_listing_context *data = user_data;
2684
2685   struct thread_item item;
2686   char *id;
2687   struct gdb_xml_value *attr;
2688
2689   id = xml_find_attribute (attributes, "id")->value;
2690   item.ptid = read_ptid (id, NULL);
2691
2692   attr = xml_find_attribute (attributes, "core");
2693   if (attr != NULL)
2694     item.core = *(ULONGEST *) attr->value;
2695   else
2696     item.core = -1;
2697
2698   item.extra = 0;
2699
2700   VEC_safe_push (thread_item_t, data->items, &item);
2701 }
2702
2703 static void
2704 end_thread (struct gdb_xml_parser *parser,
2705             const struct gdb_xml_element *element,
2706             void *user_data, const char *body_text)
2707 {
2708   struct threads_listing_context *data = user_data;
2709
2710   if (body_text && *body_text)
2711     VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2712 }
2713
2714 const struct gdb_xml_attribute thread_attributes[] = {
2715   { "id", GDB_XML_AF_NONE, NULL, NULL },
2716   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2717   { NULL, GDB_XML_AF_NONE, NULL, NULL }
2718 };
2719
2720 const struct gdb_xml_element thread_children[] = {
2721   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2722 };
2723
2724 const struct gdb_xml_element threads_children[] = {
2725   { "thread", thread_attributes, thread_children,
2726     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2727     start_thread, end_thread },
2728   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2729 };
2730
2731 const struct gdb_xml_element threads_elements[] = {
2732   { "threads", NULL, threads_children,
2733     GDB_XML_EF_NONE, NULL, NULL },
2734   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2735 };
2736
2737 #endif
2738
2739 /* List remote threads using qXfer:threads:read.  */
2740
2741 static int
2742 remote_get_threads_with_qxfer (struct target_ops *ops,
2743                                struct threads_listing_context *context)
2744 {
2745 #if defined(HAVE_LIBEXPAT)
2746   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
2747     {
2748       char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
2749       struct cleanup *back_to = make_cleanup (xfree, xml);
2750
2751       if (xml != NULL && *xml != '\0')
2752         {
2753           gdb_xml_parse_quick (_("threads"), "threads.dtd",
2754                                threads_elements, xml, context);
2755         }
2756
2757       do_cleanups (back_to);
2758       return 1;
2759     }
2760 #endif
2761
2762   return 0;
2763 }
2764
2765 /* List remote threads using qfThreadInfo/qsThreadInfo.  */
2766
2767 static int
2768 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
2769                                      struct threads_listing_context *context)
2770 {
2771   struct remote_state *rs = get_remote_state ();
2772
2773   if (rs->use_threadinfo_query)
2774     {
2775       char *bufp;
2776
2777       putpkt ("qfThreadInfo");
2778       getpkt (&rs->buf, &rs->buf_size, 0);
2779       bufp = rs->buf;
2780       if (bufp[0] != '\0')              /* q packet recognized */
2781         {
2782           while (*bufp++ == 'm')        /* reply contains one or more TID */
2783             {
2784               do
2785                 {
2786                   struct thread_item item;
2787
2788                   item.ptid = read_ptid (bufp, &bufp);
2789                   item.core = -1;
2790                   item.extra = NULL;
2791
2792                   VEC_safe_push (thread_item_t, context->items, &item);
2793                 }
2794               while (*bufp++ == ',');   /* comma-separated list */
2795               putpkt ("qsThreadInfo");
2796               getpkt (&rs->buf, &rs->buf_size, 0);
2797               bufp = rs->buf;
2798             }
2799           return 1;
2800         }
2801       else
2802         {
2803           /* Packet not recognized.  */
2804           rs->use_threadinfo_query = 0;
2805         }
2806     }
2807
2808   return 0;
2809 }
2810
2811 /* Implement the to_update_thread_list function for the remote
2812    targets.  */
2813
2814 static void
2815 remote_update_thread_list (struct target_ops *ops)
2816 {
2817   struct remote_state *rs = get_remote_state ();
2818   struct threads_listing_context context;
2819   struct cleanup *old_chain;
2820   int got_list = 0;
2821
2822   context.items = NULL;
2823   old_chain = make_cleanup (clear_threads_listing_context, &context);
2824
2825   /* We have a few different mechanisms to fetch the thread list.  Try
2826      them all, starting with the most preferred one first, falling
2827      back to older methods.  */
2828   if (remote_get_threads_with_qxfer (ops, &context)
2829       || remote_get_threads_with_qthreadinfo (ops, &context)
2830       || remote_get_threads_with_ql (ops, &context))
2831     {
2832       int i;
2833       struct thread_item *item;
2834       struct thread_info *tp, *tmp;
2835
2836       got_list = 1;
2837
2838       if (VEC_empty (thread_item_t, context.items)
2839           && remote_thread_always_alive (ops, inferior_ptid))
2840         {
2841           /* Some targets don't really support threads, but still
2842              reply an (empty) thread list in response to the thread
2843              listing packets, instead of replying "packet not
2844              supported".  Exit early so we don't delete the main
2845              thread.  */
2846           do_cleanups (old_chain);
2847           return;
2848         }
2849
2850       /* CONTEXT now holds the current thread list on the remote
2851          target end.  Delete GDB-side threads no longer found on the
2852          target.  */
2853       ALL_THREADS_SAFE (tp, tmp)
2854         {
2855           for (i = 0;
2856                VEC_iterate (thread_item_t, context.items, i, item);
2857                ++i)
2858             {
2859               if (ptid_equal (item->ptid, tp->ptid))
2860                 break;
2861             }
2862
2863           if (i == VEC_length (thread_item_t, context.items))
2864             {
2865               /* Not found.  */
2866               delete_thread (tp->ptid);
2867             }
2868         }
2869
2870       /* And now add threads we don't know about yet to our list.  */
2871       for (i = 0;
2872            VEC_iterate (thread_item_t, context.items, i, item);
2873            ++i)
2874         {
2875           if (!ptid_equal (item->ptid, null_ptid))
2876             {
2877               struct private_thread_info *info;
2878               /* In non-stop mode, we assume new found threads are
2879                  running until proven otherwise with a stop reply.  In
2880                  all-stop, we can only get here if all threads are
2881                  stopped.  */
2882               int running = non_stop ? 1 : 0;
2883
2884               remote_notice_new_inferior (item->ptid, running);
2885
2886               info = demand_private_info (item->ptid);
2887               info->core = item->core;
2888               info->extra = item->extra;
2889               item->extra = NULL;
2890             }
2891         }
2892     }
2893
2894   if (!got_list)
2895     {
2896       /* If no thread listing method is supported, then query whether
2897          each known thread is alive, one by one, with the T packet.
2898          If the target doesn't support threads at all, then this is a
2899          no-op.  See remote_thread_alive.  */
2900       prune_threads ();
2901     }
2902
2903   do_cleanups (old_chain);
2904 }
2905
2906 /*
2907  * Collect a descriptive string about the given thread.
2908  * The target may say anything it wants to about the thread
2909  * (typically info about its blocked / runnable state, name, etc.).
2910  * This string will appear in the info threads display.
2911  *
2912  * Optional: targets are not required to implement this function.
2913  */
2914
2915 static char *
2916 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
2917 {
2918   struct remote_state *rs = get_remote_state ();
2919   int result;
2920   int set;
2921   threadref id;
2922   struct gdb_ext_thread_info threadinfo;
2923   static char display_buf[100]; /* arbitrary...  */
2924   int n = 0;                    /* position in display_buf */
2925
2926   if (rs->remote_desc == 0)             /* paranoia */
2927     internal_error (__FILE__, __LINE__,
2928                     _("remote_threads_extra_info"));
2929
2930   if (ptid_equal (tp->ptid, magic_null_ptid)
2931       || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
2932     /* This is the main thread which was added by GDB.  The remote
2933        server doesn't know about it.  */
2934     return NULL;
2935
2936   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
2937     {
2938       struct thread_info *info = find_thread_ptid (tp->ptid);
2939
2940       if (info && info->priv)
2941         return info->priv->extra;
2942       else
2943         return NULL;
2944     }
2945
2946   if (rs->use_threadextra_query)
2947     {
2948       char *b = rs->buf;
2949       char *endb = rs->buf + get_remote_packet_size ();
2950
2951       xsnprintf (b, endb - b, "qThreadExtraInfo,");
2952       b += strlen (b);
2953       write_ptid (b, endb, tp->ptid);
2954
2955       putpkt (rs->buf);
2956       getpkt (&rs->buf, &rs->buf_size, 0);
2957       if (rs->buf[0] != 0)
2958         {
2959           n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2960           result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2961           display_buf [result] = '\0';
2962           return display_buf;
2963         }
2964     }
2965
2966   /* If the above query fails, fall back to the old method.  */
2967   rs->use_threadextra_query = 0;
2968   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2969     | TAG_MOREDISPLAY | TAG_DISPLAY;
2970   int_to_threadref (&id, ptid_get_lwp (tp->ptid));
2971   if (remote_get_threadinfo (&id, set, &threadinfo))
2972     if (threadinfo.active)
2973       {
2974         if (*threadinfo.shortname)
2975           n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2976                           " Name: %s,", threadinfo.shortname);
2977         if (*threadinfo.display)
2978           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2979                           " State: %s,", threadinfo.display);
2980         if (*threadinfo.more_display)
2981           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2982                           " Priority: %s", threadinfo.more_display);
2983
2984         if (n > 0)
2985           {
2986             /* For purely cosmetic reasons, clear up trailing commas.  */
2987             if (',' == display_buf[n-1])
2988               display_buf[n-1] = ' ';
2989             return display_buf;
2990           }
2991       }
2992   return NULL;
2993 }
2994 \f
2995
2996 static int
2997 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
2998                                     struct static_tracepoint_marker *marker)
2999 {
3000   struct remote_state *rs = get_remote_state ();
3001   char *p = rs->buf;
3002
3003   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3004   p += strlen (p);
3005   p += hexnumstr (p, addr);
3006   putpkt (rs->buf);
3007   getpkt (&rs->buf, &rs->buf_size, 0);
3008   p = rs->buf;
3009
3010   if (*p == 'E')
3011     error (_("Remote failure reply: %s"), p);
3012
3013   if (*p++ == 'm')
3014     {
3015       parse_static_tracepoint_marker_definition (p, &p, marker);
3016       return 1;
3017     }
3018
3019   return 0;
3020 }
3021
3022 static VEC(static_tracepoint_marker_p) *
3023 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3024                                            const char *strid)
3025 {
3026   struct remote_state *rs = get_remote_state ();
3027   VEC(static_tracepoint_marker_p) *markers = NULL;
3028   struct static_tracepoint_marker *marker = NULL;
3029   struct cleanup *old_chain;
3030   char *p;
3031
3032   /* Ask for a first packet of static tracepoint marker
3033      definition.  */
3034   putpkt ("qTfSTM");
3035   getpkt (&rs->buf, &rs->buf_size, 0);
3036   p = rs->buf;
3037   if (*p == 'E')
3038     error (_("Remote failure reply: %s"), p);
3039
3040   old_chain = make_cleanup (free_current_marker, &marker);
3041
3042   while (*p++ == 'm')
3043     {
3044       if (marker == NULL)
3045         marker = XCNEW (struct static_tracepoint_marker);
3046
3047       do
3048         {
3049           parse_static_tracepoint_marker_definition (p, &p, marker);
3050
3051           if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3052             {
3053               VEC_safe_push (static_tracepoint_marker_p,
3054                              markers, marker);
3055               marker = NULL;
3056             }
3057           else
3058             {
3059               release_static_tracepoint_marker (marker);
3060               memset (marker, 0, sizeof (*marker));
3061             }
3062         }
3063       while (*p++ == ',');      /* comma-separated list */
3064       /* Ask for another packet of static tracepoint definition.  */
3065       putpkt ("qTsSTM");
3066       getpkt (&rs->buf, &rs->buf_size, 0);
3067       p = rs->buf;
3068     }
3069
3070   do_cleanups (old_chain);
3071   return markers;
3072 }
3073
3074 \f
3075 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
3076
3077 static ptid_t
3078 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3079 {
3080   return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3081 }
3082 \f
3083
3084 /* Restart the remote side; this is an extended protocol operation.  */
3085
3086 static void
3087 extended_remote_restart (void)
3088 {
3089   struct remote_state *rs = get_remote_state ();
3090
3091   /* Send the restart command; for reasons I don't understand the
3092      remote side really expects a number after the "R".  */
3093   xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3094   putpkt (rs->buf);
3095
3096   remote_fileio_reset ();
3097 }
3098 \f
3099 /* Clean up connection to a remote debugger.  */
3100
3101 static void
3102 remote_close (struct target_ops *self)
3103 {
3104   struct remote_state *rs = get_remote_state ();
3105
3106   if (rs->remote_desc == NULL)
3107     return; /* already closed */
3108
3109   /* Make sure we leave stdin registered in the event loop, and we
3110      don't leave the async SIGINT signal handler installed.  */
3111   remote_terminal_ours (self);
3112
3113   serial_close (rs->remote_desc);
3114   rs->remote_desc = NULL;
3115
3116   /* We don't have a connection to the remote stub anymore.  Get rid
3117      of all the inferiors and their threads we were controlling.
3118      Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3119      will be unable to find the thread corresponding to (pid, 0, 0).  */
3120   inferior_ptid = null_ptid;
3121   discard_all_inferiors ();
3122
3123   /* We are closing the remote target, so we should discard
3124      everything of this target.  */
3125   discard_pending_stop_replies_in_queue (rs);
3126
3127   if (remote_async_inferior_event_token)
3128     delete_async_event_handler (&remote_async_inferior_event_token);
3129
3130   remote_notif_state_xfree (rs->notif_state);
3131
3132   trace_reset_local_state ();
3133 }
3134
3135 /* Query the remote side for the text, data and bss offsets.  */
3136
3137 static void
3138 get_offsets (void)
3139 {
3140   struct remote_state *rs = get_remote_state ();
3141   char *buf;
3142   char *ptr;
3143   int lose, num_segments = 0, do_sections, do_segments;
3144   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3145   struct section_offsets *offs;
3146   struct symfile_segment_data *data;
3147
3148   if (symfile_objfile == NULL)
3149     return;
3150
3151   putpkt ("qOffsets");
3152   getpkt (&rs->buf, &rs->buf_size, 0);
3153   buf = rs->buf;
3154
3155   if (buf[0] == '\000')
3156     return;                     /* Return silently.  Stub doesn't support
3157                                    this command.  */
3158   if (buf[0] == 'E')
3159     {
3160       warning (_("Remote failure reply: %s"), buf);
3161       return;
3162     }
3163
3164   /* Pick up each field in turn.  This used to be done with scanf, but
3165      scanf will make trouble if CORE_ADDR size doesn't match
3166      conversion directives correctly.  The following code will work
3167      with any size of CORE_ADDR.  */
3168   text_addr = data_addr = bss_addr = 0;
3169   ptr = buf;
3170   lose = 0;
3171
3172   if (startswith (ptr, "Text="))
3173     {
3174       ptr += 5;
3175       /* Don't use strtol, could lose on big values.  */
3176       while (*ptr && *ptr != ';')
3177         text_addr = (text_addr << 4) + fromhex (*ptr++);
3178
3179       if (startswith (ptr, ";Data="))
3180         {
3181           ptr += 6;
3182           while (*ptr && *ptr != ';')
3183             data_addr = (data_addr << 4) + fromhex (*ptr++);
3184         }
3185       else
3186         lose = 1;
3187
3188       if (!lose && startswith (ptr, ";Bss="))
3189         {
3190           ptr += 5;
3191           while (*ptr && *ptr != ';')
3192             bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3193
3194           if (bss_addr != data_addr)
3195             warning (_("Target reported unsupported offsets: %s"), buf);
3196         }
3197       else
3198         lose = 1;
3199     }
3200   else if (startswith (ptr, "TextSeg="))
3201     {
3202       ptr += 8;
3203       /* Don't use strtol, could lose on big values.  */
3204       while (*ptr && *ptr != ';')
3205         text_addr = (text_addr << 4) + fromhex (*ptr++);
3206       num_segments = 1;
3207
3208       if (startswith (ptr, ";DataSeg="))
3209         {
3210           ptr += 9;
3211           while (*ptr && *ptr != ';')
3212             data_addr = (data_addr << 4) + fromhex (*ptr++);
3213           num_segments++;
3214         }
3215     }
3216   else
3217     lose = 1;
3218
3219   if (lose)
3220     error (_("Malformed response to offset query, %s"), buf);
3221   else if (*ptr != '\0')
3222     warning (_("Target reported unsupported offsets: %s"), buf);
3223
3224   offs = ((struct section_offsets *)
3225           alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3226   memcpy (offs, symfile_objfile->section_offsets,
3227           SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3228
3229   data = get_symfile_segment_data (symfile_objfile->obfd);
3230   do_segments = (data != NULL);
3231   do_sections = num_segments == 0;
3232
3233   if (num_segments > 0)
3234     {
3235       segments[0] = text_addr;
3236       segments[1] = data_addr;
3237     }
3238   /* If we have two segments, we can still try to relocate everything
3239      by assuming that the .text and .data offsets apply to the whole
3240      text and data segments.  Convert the offsets given in the packet
3241      to base addresses for symfile_map_offsets_to_segments.  */
3242   else if (data && data->num_segments == 2)
3243     {
3244       segments[0] = data->segment_bases[0] + text_addr;
3245       segments[1] = data->segment_bases[1] + data_addr;
3246       num_segments = 2;
3247     }
3248   /* If the object file has only one segment, assume that it is text
3249      rather than data; main programs with no writable data are rare,
3250      but programs with no code are useless.  Of course the code might
3251      have ended up in the data segment... to detect that we would need
3252      the permissions here.  */
3253   else if (data && data->num_segments == 1)
3254     {
3255       segments[0] = data->segment_bases[0] + text_addr;
3256       num_segments = 1;
3257     }
3258   /* There's no way to relocate by segment.  */
3259   else
3260     do_segments = 0;
3261
3262   if (do_segments)
3263     {
3264       int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3265                                                  offs, num_segments, segments);
3266
3267       if (ret == 0 && !do_sections)
3268         error (_("Can not handle qOffsets TextSeg "
3269                  "response with this symbol file"));
3270
3271       if (ret > 0)
3272         do_sections = 0;
3273     }
3274
3275   if (data)
3276     free_symfile_segment_data (data);
3277
3278   if (do_sections)
3279     {
3280       offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3281
3282       /* This is a temporary kludge to force data and bss to use the
3283          same offsets because that's what nlmconv does now.  The real
3284          solution requires changes to the stub and remote.c that I
3285          don't have time to do right now.  */
3286
3287       offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3288       offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3289     }
3290
3291   objfile_relocate (symfile_objfile, offs);
3292 }
3293
3294 /* Callback for iterate_over_threads.  Set the STOP_REQUESTED flags in
3295    threads we know are stopped already.  This is used during the
3296    initial remote connection in non-stop mode --- threads that are
3297    reported as already being stopped are left stopped.  */
3298
3299 static int
3300 set_stop_requested_callback (struct thread_info *thread, void *data)
3301 {
3302   /* If we have a stop reply for this thread, it must be stopped.  */
3303   if (peek_stop_reply (thread->ptid))
3304     set_stop_requested (thread->ptid, 1);
3305
3306   return 0;
3307 }
3308
3309 /* Send interrupt_sequence to remote target.  */
3310 static void
3311 send_interrupt_sequence (void)
3312 {
3313   struct remote_state *rs = get_remote_state ();
3314
3315   if (interrupt_sequence_mode == interrupt_sequence_control_c)
3316     remote_serial_write ("\x03", 1);
3317   else if (interrupt_sequence_mode == interrupt_sequence_break)
3318     serial_send_break (rs->remote_desc);
3319   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3320     {
3321       serial_send_break (rs->remote_desc);
3322       remote_serial_write ("g", 1);
3323     }
3324   else
3325     internal_error (__FILE__, __LINE__,
3326                     _("Invalid value for interrupt_sequence_mode: %s."),
3327                     interrupt_sequence_mode);
3328 }
3329
3330
3331 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3332    and extract the PTID.  Returns NULL_PTID if not found.  */
3333
3334 static ptid_t
3335 stop_reply_extract_thread (char *stop_reply)
3336 {
3337   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3338     {
3339       char *p;
3340
3341       /* Txx r:val ; r:val (...)  */
3342       p = &stop_reply[3];
3343
3344       /* Look for "register" named "thread".  */
3345       while (*p != '\0')
3346         {
3347           char *p1;
3348
3349           p1 = strchr (p, ':');
3350           if (p1 == NULL)
3351             return null_ptid;
3352
3353           if (strncmp (p, "thread", p1 - p) == 0)
3354             return read_ptid (++p1, &p);
3355
3356           p1 = strchr (p, ';');
3357           if (p1 == NULL)
3358             return null_ptid;
3359           p1++;
3360
3361           p = p1;
3362         }
3363     }
3364
3365   return null_ptid;
3366 }
3367
3368 /* Determine the remote side's current thread.  If we have a stop
3369    reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3370    "thread" register we can extract the current thread from.  If not,
3371    ask the remote which is the current thread with qC.  The former
3372    method avoids a roundtrip.  */
3373
3374 static ptid_t
3375 get_current_thread (char *wait_status)
3376 {
3377   ptid_t ptid;
3378
3379   /* Note we don't use remote_parse_stop_reply as that makes use of
3380      the target architecture, which we haven't yet fully determined at
3381      this point.  */
3382   if (wait_status != NULL)
3383     ptid = stop_reply_extract_thread (wait_status);
3384   if (ptid_equal (ptid, null_ptid))
3385     ptid = remote_current_thread (inferior_ptid);
3386
3387   return ptid;
3388 }
3389
3390 /* Query the remote target for which is the current thread/process,
3391    add it to our tables, and update INFERIOR_PTID.  The caller is
3392    responsible for setting the state such that the remote end is ready
3393    to return the current thread.
3394
3395    This function is called after handling the '?' or 'vRun' packets,
3396    whose response is a stop reply from which we can also try
3397    extracting the thread.  If the target doesn't support the explicit
3398    qC query, we infer the current thread from that stop reply, passed
3399    in in WAIT_STATUS, which may be NULL.  */
3400
3401 static void
3402 add_current_inferior_and_thread (char *wait_status)
3403 {
3404   struct remote_state *rs = get_remote_state ();
3405   int fake_pid_p = 0;
3406   ptid_t ptid = null_ptid;
3407
3408   inferior_ptid = null_ptid;
3409
3410   /* Now, if we have thread information, update inferior_ptid.  */
3411   ptid = get_current_thread (wait_status);
3412
3413   if (!ptid_equal (ptid, null_ptid))
3414     {
3415       if (!remote_multi_process_p (rs))
3416         fake_pid_p = 1;
3417
3418       inferior_ptid = ptid;
3419     }
3420   else
3421     {
3422       /* Without this, some commands which require an active target
3423          (such as kill) won't work.  This variable serves (at least)
3424          double duty as both the pid of the target process (if it has
3425          such), and as a flag indicating that a target is active.  */
3426       inferior_ptid = magic_null_ptid;
3427       fake_pid_p = 1;
3428     }
3429
3430   remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3431
3432   /* Add the main thread.  */
3433   add_thread_silent (inferior_ptid);
3434 }
3435
3436 static void
3437 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3438 {
3439   struct remote_state *rs = get_remote_state ();
3440   struct packet_config *noack_config;
3441   char *wait_status = NULL;
3442
3443   immediate_quit++;             /* Allow user to interrupt it.  */
3444   QUIT;
3445
3446   if (interrupt_on_connect)
3447     send_interrupt_sequence ();
3448
3449   /* Ack any packet which the remote side has already sent.  */
3450   serial_write (rs->remote_desc, "+", 1);
3451
3452   /* Signal other parts that we're going through the initial setup,
3453      and so things may not be stable yet.  */
3454   rs->starting_up = 1;
3455
3456   /* The first packet we send to the target is the optional "supported
3457      packets" request.  If the target can answer this, it will tell us
3458      which later probes to skip.  */
3459   remote_query_supported ();
3460
3461   /* If the stub wants to get a QAllow, compose one and send it.  */
3462   if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
3463     remote_set_permissions (target);
3464
3465   /* Next, we possibly activate noack mode.
3466
3467      If the QStartNoAckMode packet configuration is set to AUTO,
3468      enable noack mode if the stub reported a wish for it with
3469      qSupported.
3470
3471      If set to TRUE, then enable noack mode even if the stub didn't
3472      report it in qSupported.  If the stub doesn't reply OK, the
3473      session ends with an error.
3474
3475      If FALSE, then don't activate noack mode, regardless of what the
3476      stub claimed should be the default with qSupported.  */
3477
3478   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3479   if (packet_config_support (noack_config) != PACKET_DISABLE)
3480     {
3481       putpkt ("QStartNoAckMode");
3482       getpkt (&rs->buf, &rs->buf_size, 0);
3483       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3484         rs->noack_mode = 1;
3485     }
3486
3487   if (extended_p)
3488     {
3489       /* Tell the remote that we are using the extended protocol.  */
3490       putpkt ("!");
3491       getpkt (&rs->buf, &rs->buf_size, 0);
3492     }
3493
3494   /* Let the target know which signals it is allowed to pass down to
3495      the program.  */
3496   update_signals_program_target ();
3497
3498   /* Next, if the target can specify a description, read it.  We do
3499      this before anything involving memory or registers.  */
3500   target_find_description ();
3501
3502   /* Next, now that we know something about the target, update the
3503      address spaces in the program spaces.  */
3504   update_address_spaces ();
3505
3506   /* On OSs where the list of libraries is global to all
3507      processes, we fetch them early.  */
3508   if (gdbarch_has_global_solist (target_gdbarch ()))
3509     solib_add (NULL, from_tty, target, auto_solib_add);
3510
3511   if (non_stop)
3512     {
3513       if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3514         error (_("Non-stop mode requested, but remote "
3515                  "does not support non-stop"));
3516
3517       putpkt ("QNonStop:1");
3518       getpkt (&rs->buf, &rs->buf_size, 0);
3519
3520       if (strcmp (rs->buf, "OK") != 0)
3521         error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3522
3523       /* Find about threads and processes the stub is already
3524          controlling.  We default to adding them in the running state.
3525          The '?' query below will then tell us about which threads are
3526          stopped.  */
3527       remote_update_thread_list (target);
3528     }
3529   else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
3530     {
3531       /* Don't assume that the stub can operate in all-stop mode.
3532          Request it explicitly.  */
3533       putpkt ("QNonStop:0");
3534       getpkt (&rs->buf, &rs->buf_size, 0);
3535
3536       if (strcmp (rs->buf, "OK") != 0)
3537         error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3538     }
3539
3540   /* Upload TSVs regardless of whether the target is running or not.  The
3541      remote stub, such as GDBserver, may have some predefined or builtin
3542      TSVs, even if the target is not running.  */
3543   if (remote_get_trace_status (target, current_trace_status ()) != -1)
3544     {
3545       struct uploaded_tsv *uploaded_tsvs = NULL;
3546
3547       remote_upload_trace_state_variables (target, &uploaded_tsvs);
3548       merge_uploaded_trace_state_variables (&uploaded_tsvs);
3549     }
3550
3551   /* Check whether the target is running now.  */
3552   putpkt ("?");
3553   getpkt (&rs->buf, &rs->buf_size, 0);
3554
3555   if (!non_stop)
3556     {
3557       ptid_t ptid;
3558       int fake_pid_p = 0;
3559       struct inferior *inf;
3560
3561       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3562         {
3563           if (!extended_p)
3564             error (_("The target is not running (try extended-remote?)"));
3565
3566           /* We're connected, but not running.  Drop out before we
3567              call start_remote.  */
3568           rs->starting_up = 0;
3569           return;
3570         }
3571       else
3572         {
3573           /* Save the reply for later.  */
3574           wait_status = alloca (strlen (rs->buf) + 1);
3575           strcpy (wait_status, rs->buf);
3576         }
3577
3578       /* Fetch thread list.  */
3579       target_update_thread_list ();
3580
3581       /* Let the stub know that we want it to return the thread.  */
3582       set_continue_thread (minus_one_ptid);
3583
3584       if (thread_count () == 0)
3585         {
3586           /* Target has no concept of threads at all.  GDB treats
3587              non-threaded target as single-threaded; add a main
3588              thread.  */
3589           add_current_inferior_and_thread (wait_status);
3590         }
3591       else
3592         {
3593           /* We have thread information; select the thread the target
3594              says should be current.  If we're reconnecting to a
3595              multi-threaded program, this will ideally be the thread
3596              that last reported an event before GDB disconnected.  */
3597           inferior_ptid = get_current_thread (wait_status);
3598           if (ptid_equal (inferior_ptid, null_ptid))
3599             {
3600               /* Odd... The target was able to list threads, but not
3601                  tell us which thread was current (no "thread"
3602                  register in T stop reply?).  Just pick the first
3603                  thread in the thread list then.  */
3604               inferior_ptid = thread_list->ptid;
3605             }
3606         }
3607
3608       /* init_wait_for_inferior should be called before get_offsets in order
3609          to manage `inserted' flag in bp loc in a correct state.
3610          breakpoint_init_inferior, called from init_wait_for_inferior, set
3611          `inserted' flag to 0, while before breakpoint_re_set, called from
3612          start_remote, set `inserted' flag to 1.  In the initialization of
3613          inferior, breakpoint_init_inferior should be called first, and then
3614          breakpoint_re_set can be called.  If this order is broken, state of
3615          `inserted' flag is wrong, and cause some problems on breakpoint
3616          manipulation.  */
3617       init_wait_for_inferior ();
3618
3619       get_offsets ();           /* Get text, data & bss offsets.  */
3620
3621       /* If we could not find a description using qXfer, and we know
3622          how to do it some other way, try again.  This is not
3623          supported for non-stop; it could be, but it is tricky if
3624          there are no stopped threads when we connect.  */
3625       if (remote_read_description_p (target)
3626           && gdbarch_target_desc (target_gdbarch ()) == NULL)
3627         {
3628           target_clear_description ();
3629           target_find_description ();
3630         }
3631
3632       /* Use the previously fetched status.  */
3633       gdb_assert (wait_status != NULL);
3634       strcpy (rs->buf, wait_status);
3635       rs->cached_wait_status = 1;
3636
3637       immediate_quit--;
3638       start_remote (from_tty); /* Initialize gdb process mechanisms.  */
3639     }
3640   else
3641     {
3642       /* Clear WFI global state.  Do this before finding about new
3643          threads and inferiors, and setting the current inferior.
3644          Otherwise we would clear the proceed status of the current
3645          inferior when we want its stop_soon state to be preserved
3646          (see notice_new_inferior).  */
3647       init_wait_for_inferior ();
3648
3649       /* In non-stop, we will either get an "OK", meaning that there
3650          are no stopped threads at this time; or, a regular stop
3651          reply.  In the latter case, there may be more than one thread
3652          stopped --- we pull them all out using the vStopped
3653          mechanism.  */
3654       if (strcmp (rs->buf, "OK") != 0)
3655         {
3656           struct notif_client *notif = &notif_client_stop;
3657
3658           /* remote_notif_get_pending_replies acks this one, and gets
3659              the rest out.  */
3660           rs->notif_state->pending_event[notif_client_stop.id]
3661             = remote_notif_parse (notif, rs->buf);
3662           remote_notif_get_pending_events (notif);
3663
3664           /* Make sure that threads that were stopped remain
3665              stopped.  */
3666           iterate_over_threads (set_stop_requested_callback, NULL);
3667         }
3668
3669       if (target_can_async_p ())
3670         target_async (1);
3671
3672       if (thread_count () == 0)
3673         {
3674           if (!extended_p)
3675             error (_("The target is not running (try extended-remote?)"));
3676
3677           /* We're connected, but not running.  Drop out before we
3678              call start_remote.  */
3679           rs->starting_up = 0;
3680           return;
3681         }
3682
3683       /* Let the stub know that we want it to return the thread.  */
3684
3685       /* Force the stub to choose a thread.  */
3686       set_general_thread (null_ptid);
3687
3688       /* Query it.  */
3689       inferior_ptid = remote_current_thread (minus_one_ptid);
3690       if (ptid_equal (inferior_ptid, minus_one_ptid))
3691         error (_("remote didn't report the current thread in non-stop mode"));
3692
3693       get_offsets ();           /* Get text, data & bss offsets.  */
3694
3695       /* In non-stop mode, any cached wait status will be stored in
3696          the stop reply queue.  */
3697       gdb_assert (wait_status == NULL);
3698
3699       /* Report all signals during attach/startup.  */
3700       remote_pass_signals (target, 0, NULL);
3701     }
3702
3703   /* If we connected to a live target, do some additional setup.  */
3704   if (target_has_execution)
3705     {
3706       if (symfile_objfile)      /* No use without a symbol-file.  */
3707         remote_check_symbols ();
3708     }
3709
3710   /* Possibly the target has been engaged in a trace run started
3711      previously; find out where things are at.  */
3712   if (remote_get_trace_status (target, current_trace_status ()) != -1)
3713     {
3714       struct uploaded_tp *uploaded_tps = NULL;
3715
3716       if (current_trace_status ()->running)
3717         printf_filtered (_("Trace is already running on the target.\n"));
3718
3719       remote_upload_tracepoints (target, &uploaded_tps);
3720
3721       merge_uploaded_tracepoints (&uploaded_tps);
3722     }
3723
3724   /* The thread and inferior lists are now synchronized with the
3725      target, our symbols have been relocated, and we're merged the
3726      target's tracepoints with ours.  We're done with basic start
3727      up.  */
3728   rs->starting_up = 0;
3729
3730   /* Maybe breakpoints are global and need to be inserted now.  */
3731   if (breakpoints_should_be_inserted_now ())
3732     insert_breakpoints ();
3733 }
3734
3735 /* Open a connection to a remote debugger.
3736    NAME is the filename used for communication.  */
3737
3738 static void
3739 remote_open (const char *name, int from_tty)
3740 {
3741   remote_open_1 (name, from_tty, &remote_ops, 0);
3742 }
3743
3744 /* Open a connection to a remote debugger using the extended
3745    remote gdb protocol.  NAME is the filename used for communication.  */
3746
3747 static void
3748 extended_remote_open (const char *name, int from_tty)
3749 {
3750   remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
3751 }
3752
3753 /* Reset all packets back to "unknown support".  Called when opening a
3754    new connection to a remote target.  */
3755
3756 static void
3757 reset_all_packet_configs_support (void)
3758 {
3759   int i;
3760
3761   for (i = 0; i < PACKET_MAX; i++)
3762     remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3763 }
3764
3765 /* Initialize all packet configs.  */
3766
3767 static void
3768 init_all_packet_configs (void)
3769 {
3770   int i;
3771
3772   for (i = 0; i < PACKET_MAX; i++)
3773     {
3774       remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
3775       remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3776     }
3777 }
3778
3779 /* Symbol look-up.  */
3780
3781 static void
3782 remote_check_symbols (void)
3783 {
3784   struct remote_state *rs = get_remote_state ();
3785   char *msg, *reply, *tmp;
3786   struct bound_minimal_symbol sym;
3787   int end;
3788
3789   /* The remote side has no concept of inferiors that aren't running
3790      yet, it only knows about running processes.  If we're connected
3791      but our current inferior is not running, we should not invite the
3792      remote target to request symbol lookups related to its
3793      (unrelated) current process.  */
3794   if (!target_has_execution)
3795     return;
3796
3797   if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
3798     return;
3799
3800   /* Make sure the remote is pointing at the right process.  Note
3801      there's no way to select "no process".  */
3802   set_general_process ();
3803
3804   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
3805      because we need both at the same time.  */
3806   msg = alloca (get_remote_packet_size ());
3807
3808   /* Invite target to request symbol lookups.  */
3809
3810   putpkt ("qSymbol::");
3811   getpkt (&rs->buf, &rs->buf_size, 0);
3812   packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
3813   reply = rs->buf;
3814
3815   while (startswith (reply, "qSymbol:"))
3816     {
3817       struct bound_minimal_symbol sym;
3818
3819       tmp = &reply[8];
3820       end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
3821       msg[end] = '\0';
3822       sym = lookup_minimal_symbol (msg, NULL, NULL);
3823       if (sym.minsym == NULL)
3824         xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
3825       else
3826         {
3827           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
3828           CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
3829
3830           /* If this is a function address, return the start of code
3831              instead of any data function descriptor.  */
3832           sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
3833                                                          sym_addr,
3834                                                          &current_target);
3835
3836           xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
3837                      phex_nz (sym_addr, addr_size), &reply[8]);
3838         }
3839   
3840       putpkt (msg);
3841       getpkt (&rs->buf, &rs->buf_size, 0);
3842       reply = rs->buf;
3843     }
3844 }
3845
3846 static struct serial *
3847 remote_serial_open (const char *name)
3848 {
3849   static int udp_warning = 0;
3850
3851   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
3852      of in ser-tcp.c, because it is the remote protocol assuming that the
3853      serial connection is reliable and not the serial connection promising
3854      to be.  */
3855   if (!udp_warning && startswith (name, "udp:"))
3856     {
3857       warning (_("The remote protocol may be unreliable over UDP.\n"
3858                  "Some events may be lost, rendering further debugging "
3859                  "impossible."));
3860       udp_warning = 1;
3861     }
3862
3863   return serial_open (name);
3864 }
3865
3866 /* Inform the target of our permission settings.  The permission flags
3867    work without this, but if the target knows the settings, it can do
3868    a couple things.  First, it can add its own check, to catch cases
3869    that somehow manage to get by the permissions checks in target
3870    methods.  Second, if the target is wired to disallow particular
3871    settings (for instance, a system in the field that is not set up to
3872    be able to stop at a breakpoint), it can object to any unavailable
3873    permissions.  */
3874
3875 void
3876 remote_set_permissions (struct target_ops *self)
3877 {
3878   struct remote_state *rs = get_remote_state ();
3879
3880   xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
3881              "WriteReg:%x;WriteMem:%x;"
3882              "InsertBreak:%x;InsertTrace:%x;"
3883              "InsertFastTrace:%x;Stop:%x",
3884              may_write_registers, may_write_memory,
3885              may_insert_breakpoints, may_insert_tracepoints,
3886              may_insert_fast_tracepoints, may_stop);
3887   putpkt (rs->buf);
3888   getpkt (&rs->buf, &rs->buf_size, 0);
3889
3890   /* If the target didn't like the packet, warn the user.  Do not try
3891      to undo the user's settings, that would just be maddening.  */
3892   if (strcmp (rs->buf, "OK") != 0)
3893     warning (_("Remote refused setting permissions with: %s"), rs->buf);
3894 }
3895
3896 /* This type describes each known response to the qSupported
3897    packet.  */
3898 struct protocol_feature
3899 {
3900   /* The name of this protocol feature.  */
3901   const char *name;
3902
3903   /* The default for this protocol feature.  */
3904   enum packet_support default_support;
3905
3906   /* The function to call when this feature is reported, or after
3907      qSupported processing if the feature is not supported.
3908      The first argument points to this structure.  The second
3909      argument indicates whether the packet requested support be
3910      enabled, disabled, or probed (or the default, if this function
3911      is being called at the end of processing and this feature was
3912      not reported).  The third argument may be NULL; if not NULL, it
3913      is a NUL-terminated string taken from the packet following
3914      this feature's name and an equals sign.  */
3915   void (*func) (const struct protocol_feature *, enum packet_support,
3916                 const char *);
3917
3918   /* The corresponding packet for this feature.  Only used if
3919      FUNC is remote_supported_packet.  */
3920   int packet;
3921 };
3922
3923 static void
3924 remote_supported_packet (const struct protocol_feature *feature,
3925                          enum packet_support support,
3926                          const char *argument)
3927 {
3928   if (argument)
3929     {
3930       warning (_("Remote qSupported response supplied an unexpected value for"
3931                  " \"%s\"."), feature->name);
3932       return;
3933     }
3934
3935   remote_protocol_packets[feature->packet].support = support;
3936 }
3937
3938 static void
3939 remote_packet_size (const struct protocol_feature *feature,
3940                     enum packet_support support, const char *value)
3941 {
3942   struct remote_state *rs = get_remote_state ();
3943
3944   int packet_size;
3945   char *value_end;
3946
3947   if (support != PACKET_ENABLE)
3948     return;
3949
3950   if (value == NULL || *value == '\0')
3951     {
3952       warning (_("Remote target reported \"%s\" without a size."),
3953                feature->name);
3954       return;
3955     }
3956
3957   errno = 0;
3958   packet_size = strtol (value, &value_end, 16);
3959   if (errno != 0 || *value_end != '\0' || packet_size < 0)
3960     {
3961       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3962                feature->name, value);
3963       return;
3964     }
3965
3966   if (packet_size > MAX_REMOTE_PACKET_SIZE)
3967     {
3968       warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3969                packet_size, MAX_REMOTE_PACKET_SIZE);
3970       packet_size = MAX_REMOTE_PACKET_SIZE;
3971     }
3972
3973   /* Record the new maximum packet size.  */
3974   rs->explicit_packet_size = packet_size;
3975 }
3976
3977 static const struct protocol_feature remote_protocol_features[] = {
3978   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
3979   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
3980     PACKET_qXfer_auxv },
3981   { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
3982     PACKET_qXfer_exec_file },
3983   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3984     PACKET_qXfer_features },
3985   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3986     PACKET_qXfer_libraries },
3987   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
3988     PACKET_qXfer_libraries_svr4 },
3989   { "augmented-libraries-svr4-read", PACKET_DISABLE,
3990     remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
3991   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
3992     PACKET_qXfer_memory_map },
3993   { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3994     PACKET_qXfer_spu_read },
3995   { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3996     PACKET_qXfer_spu_write },
3997   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3998     PACKET_qXfer_osdata },
3999   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4000     PACKET_qXfer_threads },
4001   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4002     PACKET_qXfer_traceframe_info },
4003   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4004     PACKET_QPassSignals },
4005   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4006     PACKET_QProgramSignals },
4007   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4008     PACKET_QStartNoAckMode },
4009   { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4010     PACKET_multiprocess_feature },
4011   { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4012   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4013     PACKET_qXfer_siginfo_read },
4014   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4015     PACKET_qXfer_siginfo_write },
4016   { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4017     PACKET_ConditionalTracepoints },
4018   { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4019     PACKET_ConditionalBreakpoints },
4020   { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4021     PACKET_BreakpointCommands },
4022   { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4023     PACKET_FastTracepoints },
4024   { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4025     PACKET_StaticTracepoints },
4026   {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4027    PACKET_InstallInTrace},
4028   { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4029     PACKET_DisconnectedTracing_feature },
4030   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4031     PACKET_bc },
4032   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4033     PACKET_bs },
4034   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4035     PACKET_TracepointSource },
4036   { "QAllow", PACKET_DISABLE, remote_supported_packet,
4037     PACKET_QAllow },
4038   { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4039     PACKET_EnableDisableTracepoints_feature },
4040   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4041     PACKET_qXfer_fdpic },
4042   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4043     PACKET_qXfer_uib },
4044   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4045     PACKET_QDisableRandomization },
4046   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4047   { "QTBuffer:size", PACKET_DISABLE,
4048     remote_supported_packet, PACKET_QTBuffer_size},
4049   { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4050   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4051   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4052   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4053     PACKET_qXfer_btrace },
4054   { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4055     PACKET_qXfer_btrace_conf },
4056   { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4057     PACKET_Qbtrace_conf_bts_size },
4058   { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4059   { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4060   { "fork-events", PACKET_DISABLE, remote_supported_packet,
4061     PACKET_fork_event_feature },
4062   { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4063     PACKET_vfork_event_feature },
4064 };
4065
4066 static char *remote_support_xml;
4067
4068 /* Register string appended to "xmlRegisters=" in qSupported query.  */
4069
4070 void
4071 register_remote_support_xml (const char *xml)
4072 {
4073 #if defined(HAVE_LIBEXPAT)
4074   if (remote_support_xml == NULL)
4075     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4076   else
4077     {
4078       char *copy = xstrdup (remote_support_xml + 13);
4079       char *p = strtok (copy, ",");
4080
4081       do
4082         {
4083           if (strcmp (p, xml) == 0)
4084             {
4085               /* already there */
4086               xfree (copy);
4087               return;
4088             }
4089         }
4090       while ((p = strtok (NULL, ",")) != NULL);
4091       xfree (copy);
4092
4093       remote_support_xml = reconcat (remote_support_xml,
4094                                      remote_support_xml, ",", xml,
4095                                      (char *) NULL);
4096     }
4097 #endif
4098 }
4099
4100 static char *
4101 remote_query_supported_append (char *msg, const char *append)
4102 {
4103   if (msg)
4104     return reconcat (msg, msg, ";", append, (char *) NULL);
4105   else
4106     return xstrdup (append);
4107 }
4108
4109 static void
4110 remote_query_supported (void)
4111 {
4112   struct remote_state *rs = get_remote_state ();
4113   char *next;
4114   int i;
4115   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4116
4117   /* The packet support flags are handled differently for this packet
4118      than for most others.  We treat an error, a disabled packet, and
4119      an empty response identically: any features which must be reported
4120      to be used will be automatically disabled.  An empty buffer
4121      accomplishes this, since that is also the representation for a list
4122      containing no features.  */
4123
4124   rs->buf[0] = 0;
4125   if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4126     {
4127       char *q = NULL;
4128       struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4129
4130       q = remote_query_supported_append (q, "multiprocess+");
4131
4132       if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4133         q = remote_query_supported_append (q, "swbreak+");
4134       if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4135         q = remote_query_supported_append (q, "hwbreak+");
4136
4137       if (remote_support_xml)
4138         q = remote_query_supported_append (q, remote_support_xml);
4139
4140       q = remote_query_supported_append (q, "qRelocInsn+");
4141
4142       if (rs->extended)
4143         {
4144           if (packet_set_cmd_state (PACKET_fork_event_feature)
4145               != AUTO_BOOLEAN_FALSE)
4146             q = remote_query_supported_append (q, "fork-events+");
4147           if (packet_set_cmd_state (PACKET_vfork_event_feature)
4148               != AUTO_BOOLEAN_FALSE)
4149             q = remote_query_supported_append (q, "vfork-events+");
4150         }
4151
4152       q = reconcat (q, "qSupported:", q, (char *) NULL);
4153       putpkt (q);
4154
4155       do_cleanups (old_chain);
4156
4157       getpkt (&rs->buf, &rs->buf_size, 0);
4158
4159       /* If an error occured, warn, but do not return - just reset the
4160          buffer to empty and go on to disable features.  */
4161       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4162           == PACKET_ERROR)
4163         {
4164           warning (_("Remote failure reply: %s"), rs->buf);
4165           rs->buf[0] = 0;
4166         }
4167     }
4168
4169   memset (seen, 0, sizeof (seen));
4170
4171   next = rs->buf;
4172   while (*next)
4173     {
4174       enum packet_support is_supported;
4175       char *p, *end, *name_end, *value;
4176
4177       /* First separate out this item from the rest of the packet.  If
4178          there's another item after this, we overwrite the separator
4179          (terminated strings are much easier to work with).  */
4180       p = next;
4181       end = strchr (p, ';');
4182       if (end == NULL)
4183         {
4184           end = p + strlen (p);
4185           next = end;
4186         }
4187       else
4188         {
4189           *end = '\0';
4190           next = end + 1;
4191
4192           if (end == p)
4193             {
4194               warning (_("empty item in \"qSupported\" response"));
4195               continue;
4196             }
4197         }
4198
4199       name_end = strchr (p, '=');
4200       if (name_end)
4201         {
4202           /* This is a name=value entry.  */
4203           is_supported = PACKET_ENABLE;
4204           value = name_end + 1;
4205           *name_end = '\0';
4206         }
4207       else
4208         {
4209           value = NULL;
4210           switch (end[-1])
4211             {
4212             case '+':
4213               is_supported = PACKET_ENABLE;
4214               break;
4215
4216             case '-':
4217               is_supported = PACKET_DISABLE;
4218               break;
4219
4220             case '?':
4221               is_supported = PACKET_SUPPORT_UNKNOWN;
4222               break;
4223
4224             default:
4225               warning (_("unrecognized item \"%s\" "
4226                          "in \"qSupported\" response"), p);
4227               continue;
4228             }
4229           end[-1] = '\0';
4230         }
4231
4232       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4233         if (strcmp (remote_protocol_features[i].name, p) == 0)
4234           {
4235             const struct protocol_feature *feature;
4236
4237             seen[i] = 1;
4238             feature = &remote_protocol_features[i];
4239             feature->func (feature, is_supported, value);
4240             break;
4241           }
4242     }
4243
4244   /* If we increased the packet size, make sure to increase the global
4245      buffer size also.  We delay this until after parsing the entire
4246      qSupported packet, because this is the same buffer we were
4247      parsing.  */
4248   if (rs->buf_size < rs->explicit_packet_size)
4249     {
4250       rs->buf_size = rs->explicit_packet_size;
4251       rs->buf = xrealloc (rs->buf, rs->buf_size);
4252     }
4253
4254   /* Handle the defaults for unmentioned features.  */
4255   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4256     if (!seen[i])
4257       {
4258         const struct protocol_feature *feature;
4259
4260         feature = &remote_protocol_features[i];
4261         feature->func (feature, feature->default_support, NULL);
4262       }
4263 }
4264
4265 /* Remove any of the remote.c targets from target stack.  Upper targets depend
4266    on it so remove them first.  */
4267
4268 static void
4269 remote_unpush_target (void)
4270 {
4271   pop_all_targets_above (process_stratum - 1);
4272 }
4273
4274 static void
4275 remote_open_1 (const char *name, int from_tty,
4276                struct target_ops *target, int extended_p)
4277 {
4278   struct remote_state *rs = get_remote_state ();
4279
4280   if (name == 0)
4281     error (_("To open a remote debug connection, you need to specify what\n"
4282            "serial device is attached to the remote system\n"
4283            "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4284
4285   /* See FIXME above.  */
4286   if (!target_async_permitted)
4287     wait_forever_enabled_p = 1;
4288
4289   /* If we're connected to a running target, target_preopen will kill it.
4290      Ask this question first, before target_preopen has a chance to kill
4291      anything.  */
4292   if (rs->remote_desc != NULL && !have_inferiors ())
4293     {
4294       if (from_tty
4295           && !query (_("Already connected to a remote target.  Disconnect? ")))
4296         error (_("Still connected."));
4297     }
4298
4299   /* Here the possibly existing remote target gets unpushed.  */
4300   target_preopen (from_tty);
4301
4302   /* Make sure we send the passed signals list the next time we resume.  */
4303   xfree (rs->last_pass_packet);
4304   rs->last_pass_packet = NULL;
4305
4306   /* Make sure we send the program signals list the next time we
4307      resume.  */
4308   xfree (rs->last_program_signals_packet);
4309   rs->last_program_signals_packet = NULL;
4310
4311   remote_fileio_reset ();
4312   reopen_exec_file ();
4313   reread_symbols ();
4314
4315   rs->remote_desc = remote_serial_open (name);
4316   if (!rs->remote_desc)
4317     perror_with_name (name);
4318
4319   if (baud_rate != -1)
4320     {
4321       if (serial_setbaudrate (rs->remote_desc, baud_rate))
4322         {
4323           /* The requested speed could not be set.  Error out to
4324              top level after closing remote_desc.  Take care to
4325              set remote_desc to NULL to avoid closing remote_desc
4326              more than once.  */
4327           serial_close (rs->remote_desc);
4328           rs->remote_desc = NULL;
4329           perror_with_name (name);
4330         }
4331     }
4332
4333   serial_setparity (rs->remote_desc, serial_parity);
4334   serial_raw (rs->remote_desc);
4335
4336   /* If there is something sitting in the buffer we might take it as a
4337      response to a command, which would be bad.  */
4338   serial_flush_input (rs->remote_desc);
4339
4340   if (from_tty)
4341     {
4342       puts_filtered ("Remote debugging using ");
4343       puts_filtered (name);
4344       puts_filtered ("\n");
4345     }
4346   push_target (target);         /* Switch to using remote target now.  */
4347
4348   /* Register extra event sources in the event loop.  */
4349   remote_async_inferior_event_token
4350     = create_async_event_handler (remote_async_inferior_event_handler,
4351                                   NULL);
4352   rs->notif_state = remote_notif_state_allocate ();
4353
4354   /* Reset the target state; these things will be queried either by
4355      remote_query_supported or as they are needed.  */
4356   reset_all_packet_configs_support ();
4357   rs->cached_wait_status = 0;
4358   rs->explicit_packet_size = 0;
4359   rs->noack_mode = 0;
4360   rs->extended = extended_p;
4361   rs->waiting_for_stop_reply = 0;
4362   rs->ctrlc_pending_p = 0;
4363
4364   rs->general_thread = not_sent_ptid;
4365   rs->continue_thread = not_sent_ptid;
4366   rs->remote_traceframe_number = -1;
4367
4368   /* Probe for ability to use "ThreadInfo" query, as required.  */
4369   rs->use_threadinfo_query = 1;
4370   rs->use_threadextra_query = 1;
4371
4372   if (target_async_permitted)
4373     {
4374       /* With this target we start out by owning the terminal.  */
4375       remote_async_terminal_ours_p = 1;
4376
4377       /* FIXME: cagney/1999-09-23: During the initial connection it is
4378          assumed that the target is already ready and able to respond to
4379          requests.  Unfortunately remote_start_remote() eventually calls
4380          wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
4381          around this.  Eventually a mechanism that allows
4382          wait_for_inferior() to expect/get timeouts will be
4383          implemented.  */
4384       wait_forever_enabled_p = 0;
4385     }
4386
4387   /* First delete any symbols previously loaded from shared libraries.  */
4388   no_shared_libraries (NULL, 0);
4389
4390   /* Start afresh.  */
4391   init_thread_list ();
4392
4393   /* Start the remote connection.  If error() or QUIT, discard this
4394      target (we'd otherwise be in an inconsistent state) and then
4395      propogate the error on up the exception chain.  This ensures that
4396      the caller doesn't stumble along blindly assuming that the
4397      function succeeded.  The CLI doesn't have this problem but other
4398      UI's, such as MI do.
4399
4400      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4401      this function should return an error indication letting the
4402      caller restore the previous state.  Unfortunately the command
4403      ``target remote'' is directly wired to this function making that
4404      impossible.  On a positive note, the CLI side of this problem has
4405      been fixed - the function set_cmd_context() makes it possible for
4406      all the ``target ....'' commands to share a common callback
4407      function.  See cli-dump.c.  */
4408   {
4409
4410     TRY
4411       {
4412         remote_start_remote (from_tty, target, extended_p);
4413       }
4414     CATCH (ex, RETURN_MASK_ALL)
4415       {
4416         /* Pop the partially set up target - unless something else did
4417            already before throwing the exception.  */
4418         if (rs->remote_desc != NULL)
4419           remote_unpush_target ();
4420         if (target_async_permitted)
4421           wait_forever_enabled_p = 1;
4422         throw_exception (ex);
4423       }
4424     END_CATCH
4425   }
4426
4427   remote_btrace_reset ();
4428
4429   if (target_async_permitted)
4430     wait_forever_enabled_p = 1;
4431 }
4432
4433 /* This takes a program previously attached to and detaches it.  After
4434    this is done, GDB can be used to debug some other program.  We
4435    better not have left any breakpoints in the target program or it'll
4436    die when it hits one.  */
4437
4438 static void
4439 remote_detach_1 (const char *args, int from_tty, int extended)
4440 {
4441   int pid = ptid_get_pid (inferior_ptid);
4442   struct remote_state *rs = get_remote_state ();
4443
4444   if (args)
4445     error (_("Argument given to \"detach\" when remotely debugging."));
4446
4447   if (!target_has_execution)
4448     error (_("No process to detach from."));
4449
4450   if (from_tty)
4451     {
4452       char *exec_file = get_exec_file (0);
4453       if (exec_file == NULL)
4454         exec_file = "";
4455       printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4456                          target_pid_to_str (pid_to_ptid (pid)));
4457       gdb_flush (gdb_stdout);
4458     }
4459
4460   /* Tell the remote target to detach.  */
4461   if (remote_multi_process_p (rs))
4462     xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4463   else
4464     strcpy (rs->buf, "D");
4465
4466   putpkt (rs->buf);
4467   getpkt (&rs->buf, &rs->buf_size, 0);
4468
4469   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4470     ;
4471   else if (rs->buf[0] == '\0')
4472     error (_("Remote doesn't know how to detach"));
4473   else
4474     error (_("Can't detach process."));
4475
4476   if (from_tty && !extended)
4477     puts_filtered (_("Ending remote debugging.\n"));
4478
4479   target_mourn_inferior ();
4480 }
4481
4482 static void
4483 remote_detach (struct target_ops *ops, const char *args, int from_tty)
4484 {
4485   remote_detach_1 (args, from_tty, 0);
4486 }
4487
4488 static void
4489 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
4490 {
4491   remote_detach_1 (args, from_tty, 1);
4492 }
4493
4494 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
4495
4496 static void
4497 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
4498 {
4499   if (args)
4500     error (_("Argument given to \"disconnect\" when remotely debugging."));
4501
4502   /* Make sure we unpush even the extended remote targets; mourn
4503      won't do it.  So call remote_mourn directly instead of
4504      target_mourn_inferior.  */
4505   remote_mourn (target);
4506
4507   if (from_tty)
4508     puts_filtered ("Ending remote debugging.\n");
4509 }
4510
4511 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
4512    be chatty about it.  */
4513
4514 static void
4515 extended_remote_attach (struct target_ops *target, const char *args,
4516                         int from_tty)
4517 {
4518   struct remote_state *rs = get_remote_state ();
4519   int pid;
4520   char *wait_status = NULL;
4521
4522   pid = parse_pid_to_attach (args);
4523
4524   /* Remote PID can be freely equal to getpid, do not check it here the same
4525      way as in other targets.  */
4526
4527   if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
4528     error (_("This target does not support attaching to a process"));
4529
4530   if (from_tty)
4531     {
4532       char *exec_file = get_exec_file (0);
4533
4534       if (exec_file)
4535         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4536                            target_pid_to_str (pid_to_ptid (pid)));
4537       else
4538         printf_unfiltered (_("Attaching to %s\n"),
4539                            target_pid_to_str (pid_to_ptid (pid)));
4540
4541       gdb_flush (gdb_stdout);
4542     }
4543
4544   xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
4545   putpkt (rs->buf);
4546   getpkt (&rs->buf, &rs->buf_size, 0);
4547
4548   switch (packet_ok (rs->buf,
4549                      &remote_protocol_packets[PACKET_vAttach]))
4550     {
4551     case PACKET_OK:
4552       if (!non_stop)
4553         {
4554           /* Save the reply for later.  */
4555           wait_status = alloca (strlen (rs->buf) + 1);
4556           strcpy (wait_status, rs->buf);
4557         }
4558       else if (strcmp (rs->buf, "OK") != 0)
4559         error (_("Attaching to %s failed with: %s"),
4560                target_pid_to_str (pid_to_ptid (pid)),
4561                rs->buf);
4562       break;
4563     case PACKET_UNKNOWN:
4564       error (_("This target does not support attaching to a process"));
4565     default:
4566       error (_("Attaching to %s failed"),
4567              target_pid_to_str (pid_to_ptid (pid)));
4568     }
4569
4570   set_current_inferior (remote_add_inferior (0, pid, 1, 0));
4571
4572   inferior_ptid = pid_to_ptid (pid);
4573
4574   if (non_stop)
4575     {
4576       struct thread_info *thread;
4577
4578       /* Get list of threads.  */
4579       remote_update_thread_list (target);
4580
4581       thread = first_thread_of_process (pid);
4582       if (thread)
4583         inferior_ptid = thread->ptid;
4584       else
4585         inferior_ptid = pid_to_ptid (pid);
4586
4587       /* Invalidate our notion of the remote current thread.  */
4588       record_currthread (rs, minus_one_ptid);
4589     }
4590   else
4591     {
4592       /* Now, if we have thread information, update inferior_ptid.  */
4593       inferior_ptid = remote_current_thread (inferior_ptid);
4594
4595       /* Add the main thread to the thread list.  */
4596       add_thread_silent (inferior_ptid);
4597     }
4598
4599   /* Next, if the target can specify a description, read it.  We do
4600      this before anything involving memory or registers.  */
4601   target_find_description ();
4602
4603   if (!non_stop)
4604     {
4605       /* Use the previously fetched status.  */
4606       gdb_assert (wait_status != NULL);
4607
4608       if (target_can_async_p ())
4609         {
4610           struct notif_event *reply
4611             =  remote_notif_parse (&notif_client_stop, wait_status);
4612
4613           push_stop_reply ((struct stop_reply *) reply);
4614
4615           target_async (1);
4616         }
4617       else
4618         {
4619           gdb_assert (wait_status != NULL);
4620           strcpy (rs->buf, wait_status);
4621           rs->cached_wait_status = 1;
4622         }
4623     }
4624   else
4625     gdb_assert (wait_status == NULL);
4626 }
4627
4628 /* Implementation of the to_post_attach method.  */
4629
4630 static void
4631 extended_remote_post_attach (struct target_ops *ops, int pid)
4632 {
4633   /* In certain cases GDB might not have had the chance to start
4634      symbol lookup up until now.  This could happen if the debugged
4635      binary is not using shared libraries, the vsyscall page is not
4636      present (on Linux) and the binary itself hadn't changed since the
4637      debugging process was started.  */
4638   if (symfile_objfile != NULL)
4639     remote_check_symbols();
4640 }
4641
4642 \f
4643 /* Check for the availability of vCont.  This function should also check
4644    the response.  */
4645
4646 static void
4647 remote_vcont_probe (struct remote_state *rs)
4648 {
4649   char *buf;
4650
4651   strcpy (rs->buf, "vCont?");
4652   putpkt (rs->buf);
4653   getpkt (&rs->buf, &rs->buf_size, 0);
4654   buf = rs->buf;
4655
4656   /* Make sure that the features we assume are supported.  */
4657   if (startswith (buf, "vCont"))
4658     {
4659       char *p = &buf[5];
4660       int support_s, support_S, support_c, support_C;
4661
4662       support_s = 0;
4663       support_S = 0;
4664       support_c = 0;
4665       support_C = 0;
4666       rs->supports_vCont.t = 0;
4667       rs->supports_vCont.r = 0;
4668       while (p && *p == ';')
4669         {
4670           p++;
4671           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4672             support_s = 1;
4673           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4674             support_S = 1;
4675           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4676             support_c = 1;
4677           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4678             support_C = 1;
4679           else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4680             rs->supports_vCont.t = 1;
4681           else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4682             rs->supports_vCont.r = 1;
4683
4684           p = strchr (p, ';');
4685         }
4686
4687       /* If s, S, c, and C are not all supported, we can't use vCont.  Clearing
4688          BUF will make packet_ok disable the packet.  */
4689       if (!support_s || !support_S || !support_c || !support_C)
4690         buf[0] = 0;
4691     }
4692
4693   packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4694 }
4695
4696 /* Helper function for building "vCont" resumptions.  Write a
4697    resumption to P.  ENDP points to one-passed-the-end of the buffer
4698    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
4699    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4700    resumed thread should be single-stepped and/or signalled.  If PTID
4701    equals minus_one_ptid, then all threads are resumed; if PTID
4702    represents a process, then all threads of the process are resumed;
4703    the thread to be stepped and/or signalled is given in the global
4704    INFERIOR_PTID.  */
4705
4706 static char *
4707 append_resumption (char *p, char *endp,
4708                    ptid_t ptid, int step, enum gdb_signal siggnal)
4709 {
4710   struct remote_state *rs = get_remote_state ();
4711
4712   if (step && siggnal != GDB_SIGNAL_0)
4713     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
4714   else if (step
4715            /* GDB is willing to range step.  */
4716            && use_range_stepping
4717            /* Target supports range stepping.  */
4718            && rs->supports_vCont.r
4719            /* We don't currently support range stepping multiple
4720               threads with a wildcard (though the protocol allows it,
4721               so stubs shouldn't make an active effort to forbid
4722               it).  */
4723            && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4724     {
4725       struct thread_info *tp;
4726
4727       if (ptid_equal (ptid, minus_one_ptid))
4728         {
4729           /* If we don't know about the target thread's tid, then
4730              we're resuming magic_null_ptid (see caller).  */
4731           tp = find_thread_ptid (magic_null_ptid);
4732         }
4733       else
4734         tp = find_thread_ptid (ptid);
4735       gdb_assert (tp != NULL);
4736
4737       if (tp->control.may_range_step)
4738         {
4739           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4740
4741           p += xsnprintf (p, endp - p, ";r%s,%s",
4742                           phex_nz (tp->control.step_range_start,
4743                                    addr_size),
4744                           phex_nz (tp->control.step_range_end,
4745                                    addr_size));
4746         }
4747       else
4748         p += xsnprintf (p, endp - p, ";s");
4749     }
4750   else if (step)
4751     p += xsnprintf (p, endp - p, ";s");
4752   else if (siggnal != GDB_SIGNAL_0)
4753     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4754   else
4755     p += xsnprintf (p, endp - p, ";c");
4756
4757   if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4758     {
4759       ptid_t nptid;
4760
4761       /* All (-1) threads of process.  */
4762       nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
4763
4764       p += xsnprintf (p, endp - p, ":");
4765       p = write_ptid (p, endp, nptid);
4766     }
4767   else if (!ptid_equal (ptid, minus_one_ptid))
4768     {
4769       p += xsnprintf (p, endp - p, ":");
4770       p = write_ptid (p, endp, ptid);
4771     }
4772
4773   return p;
4774 }
4775
4776 /* Append a vCont continue-with-signal action for threads that have a
4777    non-zero stop signal.  */
4778
4779 static char *
4780 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4781 {
4782   struct thread_info *thread;
4783
4784   ALL_NON_EXITED_THREADS (thread)
4785     if (ptid_match (thread->ptid, ptid)
4786         && !ptid_equal (inferior_ptid, thread->ptid)
4787         && thread->suspend.stop_signal != GDB_SIGNAL_0)
4788       {
4789         p = append_resumption (p, endp, thread->ptid,
4790                                0, thread->suspend.stop_signal);
4791         thread->suspend.stop_signal = GDB_SIGNAL_0;
4792       }
4793
4794   return p;
4795 }
4796
4797 /* Resume the remote inferior by using a "vCont" packet.  The thread
4798    to be resumed is PTID; STEP and SIGGNAL indicate whether the
4799    resumed thread should be single-stepped and/or signalled.  If PTID
4800    equals minus_one_ptid, then all threads are resumed; the thread to
4801    be stepped and/or signalled is given in the global INFERIOR_PTID.
4802    This function returns non-zero iff it resumes the inferior.
4803
4804    This function issues a strict subset of all possible vCont commands at the
4805    moment.  */
4806
4807 static int
4808 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
4809 {
4810   struct remote_state *rs = get_remote_state ();
4811   char *p;
4812   char *endp;
4813
4814   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
4815     remote_vcont_probe (rs);
4816
4817   if (packet_support (PACKET_vCont) == PACKET_DISABLE)
4818     return 0;
4819
4820   p = rs->buf;
4821   endp = rs->buf + get_remote_packet_size ();
4822
4823   /* If we could generate a wider range of packets, we'd have to worry
4824      about overflowing BUF.  Should there be a generic
4825      "multi-part-packet" packet?  */
4826
4827   p += xsnprintf (p, endp - p, "vCont");
4828
4829   if (ptid_equal (ptid, magic_null_ptid))
4830     {
4831       /* MAGIC_NULL_PTID means that we don't have any active threads,
4832          so we don't have any TID numbers the inferior will
4833          understand.  Make sure to only send forms that do not specify
4834          a TID.  */
4835       append_resumption (p, endp, minus_one_ptid, step, siggnal);
4836     }
4837   else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
4838     {
4839       /* Resume all threads (of all processes, or of a single
4840          process), with preference for INFERIOR_PTID.  This assumes
4841          inferior_ptid belongs to the set of all threads we are about
4842          to resume.  */
4843       if (step || siggnal != GDB_SIGNAL_0)
4844         {
4845           /* Step inferior_ptid, with or without signal.  */
4846           p = append_resumption (p, endp, inferior_ptid, step, siggnal);
4847         }
4848
4849       /* Also pass down any pending signaled resumption for other
4850          threads not the current.  */
4851       p = append_pending_thread_resumptions (p, endp, ptid);
4852
4853       /* And continue others without a signal.  */
4854       append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
4855     }
4856   else
4857     {
4858       /* Scheduler locking; resume only PTID.  */
4859       append_resumption (p, endp, ptid, step, siggnal);
4860     }
4861
4862   gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4863   putpkt (rs->buf);
4864
4865   if (non_stop)
4866     {
4867       /* In non-stop, the stub replies to vCont with "OK".  The stop
4868          reply will be reported asynchronously by means of a `%Stop'
4869          notification.  */
4870       getpkt (&rs->buf, &rs->buf_size, 0);
4871       if (strcmp (rs->buf, "OK") != 0)
4872         error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4873     }
4874
4875   return 1;
4876 }
4877
4878 /* Tell the remote machine to resume.  */
4879
4880 static void
4881 remote_resume (struct target_ops *ops,
4882                ptid_t ptid, int step, enum gdb_signal siggnal)
4883 {
4884   struct remote_state *rs = get_remote_state ();
4885   char *buf;
4886
4887   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
4888      (explained in remote-notif.c:handle_notification) so
4889      remote_notif_process is not called.  We need find a place where
4890      it is safe to start a 'vNotif' sequence.  It is good to do it
4891      before resuming inferior, because inferior was stopped and no RSP
4892      traffic at that moment.  */
4893   if (!non_stop)
4894     remote_notif_process (rs->notif_state, &notif_client_stop);
4895
4896   rs->last_sent_signal = siggnal;
4897   rs->last_sent_step = step;
4898
4899   /* The vCont packet doesn't need to specify threads via Hc.  */
4900   /* No reverse support (yet) for vCont.  */
4901   if (execution_direction != EXEC_REVERSE)
4902     if (remote_vcont_resume (ptid, step, siggnal))
4903       goto done;
4904
4905   /* All other supported resume packets do use Hc, so set the continue
4906      thread.  */
4907   if (ptid_equal (ptid, minus_one_ptid))
4908     set_continue_thread (any_thread_ptid);
4909   else
4910     set_continue_thread (ptid);
4911
4912   buf = rs->buf;
4913   if (execution_direction == EXEC_REVERSE)
4914     {
4915       /* We don't pass signals to the target in reverse exec mode.  */
4916       if (info_verbose && siggnal != GDB_SIGNAL_0)
4917         warning (_(" - Can't pass signal %d to target in reverse: ignored."),
4918                  siggnal);
4919
4920       if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
4921         error (_("Remote reverse-step not supported."));
4922       if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
4923         error (_("Remote reverse-continue not supported."));
4924
4925       strcpy (buf, step ? "bs" : "bc");
4926     }
4927   else if (siggnal != GDB_SIGNAL_0)
4928     {
4929       buf[0] = step ? 'S' : 'C';
4930       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
4931       buf[2] = tohex (((int) siggnal) & 0xf);
4932       buf[3] = '\0';
4933     }
4934   else
4935     strcpy (buf, step ? "s" : "c");
4936
4937   putpkt (buf);
4938
4939  done:
4940   /* We are about to start executing the inferior, let's register it
4941      with the event loop.  NOTE: this is the one place where all the
4942      execution commands end up.  We could alternatively do this in each
4943      of the execution commands in infcmd.c.  */
4944   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4945      into infcmd.c in order to allow inferior function calls to work
4946      NOT asynchronously.  */
4947   if (target_can_async_p ())
4948     target_async (1);
4949
4950   /* We've just told the target to resume.  The remote server will
4951      wait for the inferior to stop, and then send a stop reply.  In
4952      the mean time, we can't start another command/query ourselves
4953      because the stub wouldn't be ready to process it.  This applies
4954      only to the base all-stop protocol, however.  In non-stop (which
4955      only supports vCont), the stub replies with an "OK", and is
4956      immediate able to process further serial input.  */
4957   if (!non_stop)
4958     rs->waiting_for_stop_reply = 1;
4959 }
4960 \f
4961
4962 /* Set up the signal handler for SIGINT, while the target is
4963    executing, ovewriting the 'regular' SIGINT signal handler.  */
4964 static void
4965 async_initialize_sigint_signal_handler (void)
4966 {
4967   signal (SIGINT, async_handle_remote_sigint);
4968 }
4969
4970 /* Signal handler for SIGINT, while the target is executing.  */
4971 static void
4972 async_handle_remote_sigint (int sig)
4973 {
4974   signal (sig, async_handle_remote_sigint_twice);
4975   /* Note we need to go through gdb_call_async_signal_handler in order
4976      to wake up the event loop on Windows.  */
4977   gdb_call_async_signal_handler (async_sigint_remote_token, 0);
4978 }
4979
4980 /* Signal handler for SIGINT, installed after SIGINT has already been
4981    sent once.  It will take effect the second time that the user sends
4982    a ^C.  */
4983 static void
4984 async_handle_remote_sigint_twice (int sig)
4985 {
4986   signal (sig, async_handle_remote_sigint);
4987   /* See note in async_handle_remote_sigint.  */
4988   gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
4989 }
4990
4991 /* Perform the real interruption of the target execution, in response
4992    to a ^C.  */
4993 static void
4994 async_remote_interrupt (gdb_client_data arg)
4995 {
4996   if (remote_debug)
4997     fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
4998
4999   target_stop (inferior_ptid);
5000 }
5001
5002 /* Perform interrupt, if the first attempt did not succeed.  Just give
5003    up on the target alltogether.  */
5004 static void
5005 async_remote_interrupt_twice (gdb_client_data arg)
5006 {
5007   if (remote_debug)
5008     fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5009
5010   interrupt_query ();
5011 }
5012
5013 /* Reinstall the usual SIGINT handlers, after the target has
5014    stopped.  */
5015 static void
5016 async_cleanup_sigint_signal_handler (void *dummy)
5017 {
5018   signal (SIGINT, handle_sigint);
5019 }
5020
5021 /* Send ^C to target to halt it.  Target will respond, and send us a
5022    packet.  */
5023 static void (*ofunc) (int);
5024
5025 /* The command line interface's stop routine.  This function is installed
5026    as a signal handler for SIGINT.  The first time a user requests a
5027    stop, we call remote_stop to send a break or ^C.  If there is no
5028    response from the target (it didn't stop when the user requested it),
5029    we ask the user if he'd like to detach from the target.  */
5030 static void
5031 sync_remote_interrupt (int signo)
5032 {
5033   /* If this doesn't work, try more severe steps.  */
5034   signal (signo, sync_remote_interrupt_twice);
5035
5036   gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5037 }
5038
5039 /* The user typed ^C twice.  */
5040
5041 static void
5042 sync_remote_interrupt_twice (int signo)
5043 {
5044   signal (signo, ofunc);
5045   gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5046   signal (signo, sync_remote_interrupt);
5047 }
5048
5049 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
5050    thread, all threads of a remote process, or all threads of all
5051    processes.  */
5052
5053 static void
5054 remote_stop_ns (ptid_t ptid)
5055 {
5056   struct remote_state *rs = get_remote_state ();
5057   char *p = rs->buf;
5058   char *endp = rs->buf + get_remote_packet_size ();
5059
5060   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5061     remote_vcont_probe (rs);
5062
5063   if (!rs->supports_vCont.t)
5064     error (_("Remote server does not support stopping threads"));
5065
5066   if (ptid_equal (ptid, minus_one_ptid)
5067       || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5068     p += xsnprintf (p, endp - p, "vCont;t");
5069   else
5070     {
5071       ptid_t nptid;
5072
5073       p += xsnprintf (p, endp - p, "vCont;t:");
5074
5075       if (ptid_is_pid (ptid))
5076           /* All (-1) threads of process.  */
5077         nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5078       else
5079         {
5080           /* Small optimization: if we already have a stop reply for
5081              this thread, no use in telling the stub we want this
5082              stopped.  */
5083           if (peek_stop_reply (ptid))
5084             return;
5085
5086           nptid = ptid;
5087         }
5088
5089       write_ptid (p, endp, nptid);
5090     }
5091
5092   /* In non-stop, we get an immediate OK reply.  The stop reply will
5093      come in asynchronously by notification.  */
5094   putpkt (rs->buf);
5095   getpkt (&rs->buf, &rs->buf_size, 0);
5096   if (strcmp (rs->buf, "OK") != 0)
5097     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5098 }
5099
5100 /* All-stop version of target_stop.  Sends a break or a ^C to stop the
5101    remote target.  It is undefined which thread of which process
5102    reports the stop.  */
5103
5104 static void
5105 remote_stop_as (ptid_t ptid)
5106 {
5107   struct remote_state *rs = get_remote_state ();
5108
5109   rs->ctrlc_pending_p = 1;
5110
5111   /* If the inferior is stopped already, but the core didn't know
5112      about it yet, just ignore the request.  The cached wait status
5113      will be collected in remote_wait.  */
5114   if (rs->cached_wait_status)
5115     return;
5116
5117   /* Send interrupt_sequence to remote target.  */
5118   send_interrupt_sequence ();
5119 }
5120
5121 /* This is the generic stop called via the target vector.  When a target
5122    interrupt is requested, either by the command line or the GUI, we
5123    will eventually end up here.  */
5124
5125 static void
5126 remote_stop (struct target_ops *self, ptid_t ptid)
5127 {
5128   if (remote_debug)
5129     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5130
5131   if (non_stop)
5132     remote_stop_ns (ptid);
5133   else
5134     remote_stop_as (ptid);
5135 }
5136
5137 /* Ask the user what to do when an interrupt is received.  */
5138
5139 static void
5140 interrupt_query (void)
5141 {
5142   target_terminal_ours ();
5143
5144   if (target_is_async_p ())
5145     {
5146       signal (SIGINT, handle_sigint);
5147       quit ();
5148     }
5149   else
5150     {
5151       if (query (_("Interrupted while waiting for the program.\n\
5152 Give up (and stop debugging it)? ")))
5153         {
5154           remote_unpush_target ();
5155           quit ();
5156         }
5157     }
5158
5159   target_terminal_inferior ();
5160 }
5161
5162 /* Enable/disable target terminal ownership.  Most targets can use
5163    terminal groups to control terminal ownership.  Remote targets are
5164    different in that explicit transfer of ownership to/from GDB/target
5165    is required.  */
5166
5167 static void
5168 remote_terminal_inferior (struct target_ops *self)
5169 {
5170   if (!target_async_permitted)
5171     /* Nothing to do.  */
5172     return;
5173
5174   /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5175      idempotent.  The event-loop GDB talking to an asynchronous target
5176      with a synchronous command calls this function from both
5177      event-top.c and infrun.c/infcmd.c.  Once GDB stops trying to
5178      transfer the terminal to the target when it shouldn't this guard
5179      can go away.  */
5180   if (!remote_async_terminal_ours_p)
5181     return;
5182   delete_file_handler (input_fd);
5183   remote_async_terminal_ours_p = 0;
5184   async_initialize_sigint_signal_handler ();
5185   /* NOTE: At this point we could also register our selves as the
5186      recipient of all input.  Any characters typed could then be
5187      passed on down to the target.  */
5188 }
5189
5190 static void
5191 remote_terminal_ours (struct target_ops *self)
5192 {
5193   if (!target_async_permitted)
5194     /* Nothing to do.  */
5195     return;
5196
5197   /* See FIXME in remote_terminal_inferior.  */
5198   if (remote_async_terminal_ours_p)
5199     return;
5200   async_cleanup_sigint_signal_handler (NULL);
5201   add_file_handler (input_fd, stdin_event_handler, 0);
5202   remote_async_terminal_ours_p = 1;
5203 }
5204
5205 static void
5206 remote_console_output (char *msg)
5207 {
5208   char *p;
5209
5210   for (p = msg; p[0] && p[1]; p += 2)
5211     {
5212       char tb[2];
5213       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5214
5215       tb[0] = c;
5216       tb[1] = 0;
5217       fputs_unfiltered (tb, gdb_stdtarg);
5218     }
5219   gdb_flush (gdb_stdtarg);
5220 }
5221
5222 typedef struct cached_reg
5223 {
5224   int num;
5225   gdb_byte data[MAX_REGISTER_SIZE];
5226 } cached_reg_t;
5227
5228 DEF_VEC_O(cached_reg_t);
5229
5230 typedef struct stop_reply
5231 {
5232   struct notif_event base;
5233
5234   /* The identifier of the thread about this event  */
5235   ptid_t ptid;
5236
5237   /* The remote state this event is associated with.  When the remote
5238      connection, represented by a remote_state object, is closed,
5239      all the associated stop_reply events should be released.  */
5240   struct remote_state *rs;
5241
5242   struct target_waitstatus ws;
5243
5244   /* Expedited registers.  This makes remote debugging a bit more
5245      efficient for those targets that provide critical registers as
5246      part of their normal status mechanism (as another roundtrip to
5247      fetch them is avoided).  */
5248   VEC(cached_reg_t) *regcache;
5249
5250   enum target_stop_reason stop_reason;
5251
5252   CORE_ADDR watch_data_address;
5253
5254   int core;
5255 } *stop_reply_p;
5256
5257 DECLARE_QUEUE_P (stop_reply_p);
5258 DEFINE_QUEUE_P (stop_reply_p);
5259 /* The list of already fetched and acknowledged stop events.  This
5260    queue is used for notification Stop, and other notifications
5261    don't need queue for their events, because the notification events
5262    of Stop can't be consumed immediately, so that events should be
5263    queued first, and be consumed by remote_wait_{ns,as} one per
5264    time.  Other notifications can consume their events immediately,
5265    so queue is not needed for them.  */
5266 static QUEUE (stop_reply_p) *stop_reply_queue;
5267
5268 static void
5269 stop_reply_xfree (struct stop_reply *r)
5270 {
5271   notif_event_xfree ((struct notif_event *) r);
5272 }
5273
5274 static void
5275 remote_notif_stop_parse (struct notif_client *self, char *buf,
5276                          struct notif_event *event)
5277 {
5278   remote_parse_stop_reply (buf, (struct stop_reply *) event);
5279 }
5280
5281 static void
5282 remote_notif_stop_ack (struct notif_client *self, char *buf,
5283                        struct notif_event *event)
5284 {
5285   struct stop_reply *stop_reply = (struct stop_reply *) event;
5286
5287   /* acknowledge */
5288   putpkt ((char *) self->ack_command);
5289
5290   if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5291       /* We got an unknown stop reply.  */
5292       error (_("Unknown stop reply"));
5293
5294   push_stop_reply (stop_reply);
5295 }
5296
5297 static int
5298 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5299 {
5300   /* We can't get pending events in remote_notif_process for
5301      notification stop, and we have to do this in remote_wait_ns
5302      instead.  If we fetch all queued events from stub, remote stub
5303      may exit and we have no chance to process them back in
5304      remote_wait_ns.  */
5305   mark_async_event_handler (remote_async_inferior_event_token);
5306   return 0;
5307 }
5308
5309 static void
5310 stop_reply_dtr (struct notif_event *event)
5311 {
5312   struct stop_reply *r = (struct stop_reply *) event;
5313
5314   VEC_free (cached_reg_t, r->regcache);
5315 }
5316
5317 static struct notif_event *
5318 remote_notif_stop_alloc_reply (void)
5319 {
5320   struct notif_event *r
5321     = (struct notif_event *) XNEW (struct stop_reply);
5322
5323   r->dtr = stop_reply_dtr;
5324
5325   return r;
5326 }
5327
5328 /* A client of notification Stop.  */
5329
5330 struct notif_client notif_client_stop =
5331 {
5332   "Stop",
5333   "vStopped",
5334   remote_notif_stop_parse,
5335   remote_notif_stop_ack,
5336   remote_notif_stop_can_get_pending_events,
5337   remote_notif_stop_alloc_reply,
5338   REMOTE_NOTIF_STOP,
5339 };
5340
5341 /* A parameter to pass data in and out.  */
5342
5343 struct queue_iter_param
5344 {
5345   void *input;
5346   struct stop_reply *output;
5347 };
5348
5349 /* Remove stop replies in the queue if its pid is equal to the given
5350    inferior's pid.  */
5351
5352 static int
5353 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5354                                 QUEUE_ITER (stop_reply_p) *iter,
5355                                 stop_reply_p event,
5356                                 void *data)
5357 {
5358   struct queue_iter_param *param = data;
5359   struct inferior *inf = param->input;
5360
5361   if (ptid_get_pid (event->ptid) == inf->pid)
5362     {
5363       stop_reply_xfree (event);
5364       QUEUE_remove_elem (stop_reply_p, q, iter);
5365     }
5366
5367   return 1;
5368 }
5369
5370 /* Discard all pending stop replies of inferior INF.  */
5371
5372 static void
5373 discard_pending_stop_replies (struct inferior *inf)
5374 {
5375   int i;
5376   struct queue_iter_param param;
5377   struct stop_reply *reply;
5378   struct remote_state *rs = get_remote_state ();
5379   struct remote_notif_state *rns = rs->notif_state;
5380
5381   /* This function can be notified when an inferior exists.  When the
5382      target is not remote, the notification state is NULL.  */
5383   if (rs->remote_desc == NULL)
5384     return;
5385
5386   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
5387
5388   /* Discard the in-flight notification.  */
5389   if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
5390     {
5391       stop_reply_xfree (reply);
5392       rns->pending_event[notif_client_stop.id] = NULL;
5393     }
5394
5395   param.input = inf;
5396   param.output = NULL;
5397   /* Discard the stop replies we have already pulled with
5398      vStopped.  */
5399   QUEUE_iterate (stop_reply_p, stop_reply_queue,
5400                  remove_stop_reply_for_inferior, &param);
5401 }
5402
5403 /* If its remote state is equal to the given remote state,
5404    remove EVENT from the stop reply queue.  */
5405
5406 static int
5407 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5408                                    QUEUE_ITER (stop_reply_p) *iter,
5409                                    stop_reply_p event,
5410                                    void *data)
5411 {
5412   struct queue_iter_param *param = data;
5413   struct remote_state *rs = param->input;
5414
5415   if (event->rs == rs)
5416     {
5417       stop_reply_xfree (event);
5418       QUEUE_remove_elem (stop_reply_p, q, iter);
5419     }
5420
5421   return 1;
5422 }
5423
5424 /* Discard the stop replies for RS in stop_reply_queue.  */
5425
5426 static void
5427 discard_pending_stop_replies_in_queue (struct remote_state *rs)
5428 {
5429   struct queue_iter_param param;
5430
5431   param.input = rs;
5432   param.output = NULL;
5433   /* Discard the stop replies we have already pulled with
5434      vStopped.  */
5435   QUEUE_iterate (stop_reply_p, stop_reply_queue,
5436                  remove_stop_reply_of_remote_state, &param);
5437 }
5438
5439 /* A parameter to pass data in and out.  */
5440
5441 static int
5442 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5443                                    QUEUE_ITER (stop_reply_p) *iter,
5444                                    stop_reply_p event,
5445                                    void *data)
5446 {
5447   struct queue_iter_param *param = data;
5448   ptid_t *ptid = param->input;
5449
5450   if (ptid_match (event->ptid, *ptid))
5451     {
5452       param->output = event;
5453       QUEUE_remove_elem (stop_reply_p, q, iter);
5454       return 0;
5455     }
5456
5457   return 1;
5458 }
5459
5460 /* Remove the first reply in 'stop_reply_queue' which matches
5461    PTID.  */
5462
5463 static struct stop_reply *
5464 remote_notif_remove_queued_reply (ptid_t ptid)
5465 {
5466   struct queue_iter_param param;
5467
5468   param.input = &ptid;
5469   param.output = NULL;
5470
5471   QUEUE_iterate (stop_reply_p, stop_reply_queue,
5472                  remote_notif_remove_once_on_match, &param);
5473   if (notif_debug)
5474     fprintf_unfiltered (gdb_stdlog,
5475                         "notif: discard queued event: 'Stop' in %s\n",
5476                         target_pid_to_str (ptid));
5477
5478   return param.output;
5479 }
5480
5481 /* Look for a queued stop reply belonging to PTID.  If one is found,
5482    remove it from the queue, and return it.  Returns NULL if none is
5483    found.  If there are still queued events left to process, tell the
5484    event loop to get back to target_wait soon.  */
5485
5486 static struct stop_reply *
5487 queued_stop_reply (ptid_t ptid)
5488 {
5489   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
5490
5491   if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
5492     /* There's still at least an event left.  */
5493     mark_async_event_handler (remote_async_inferior_event_token);
5494
5495   return r;
5496 }
5497
5498 /* Push a fully parsed stop reply in the stop reply queue.  Since we
5499    know that we now have at least one queued event left to pass to the
5500    core side, tell the event loop to get back to target_wait soon.  */
5501
5502 static void
5503 push_stop_reply (struct stop_reply *new_event)
5504 {
5505   QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
5506
5507   if (notif_debug)
5508     fprintf_unfiltered (gdb_stdlog,
5509                         "notif: push 'Stop' %s to queue %d\n",
5510                         target_pid_to_str (new_event->ptid),
5511                         QUEUE_length (stop_reply_p,
5512                                       stop_reply_queue));
5513
5514   mark_async_event_handler (remote_async_inferior_event_token);
5515 }
5516
5517 static int
5518 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5519                               QUEUE_ITER (stop_reply_p) *iter,
5520                               struct stop_reply *event,
5521                               void *data)
5522 {
5523   ptid_t *ptid = data;
5524
5525   return !(ptid_equal (*ptid, event->ptid)
5526            && event->ws.kind == TARGET_WAITKIND_STOPPED);
5527 }
5528
5529 /* Returns true if we have a stop reply for PTID.  */
5530
5531 static int
5532 peek_stop_reply (ptid_t ptid)
5533 {
5534   return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5535                          stop_reply_match_ptid_and_ws, &ptid);
5536 }
5537
5538 /* Skip PACKET until the next semi-colon (or end of string).  */
5539
5540 static char *
5541 skip_to_semicolon (char *p)
5542 {
5543   while (*p != '\0' && *p != ';')
5544     p++;
5545   return p;
5546 }
5547
5548 /* Parse the stop reply in BUF.  Either the function succeeds, and the
5549    result is stored in EVENT, or throws an error.  */
5550
5551 static void
5552 remote_parse_stop_reply (char *buf, struct stop_reply *event)
5553 {
5554   struct remote_arch_state *rsa = get_remote_arch_state ();
5555   ULONGEST addr;
5556   char *p;
5557
5558   event->ptid = null_ptid;
5559   event->rs = get_remote_state ();
5560   event->ws.kind = TARGET_WAITKIND_IGNORE;
5561   event->ws.value.integer = 0;
5562   event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5563   event->regcache = NULL;
5564   event->core = -1;
5565
5566   switch (buf[0])
5567     {
5568     case 'T':           /* Status with PC, SP, FP, ...  */
5569       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
5570       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
5571             ss = signal number
5572             n... = register number
5573             r... = register contents
5574       */
5575
5576       p = &buf[3];      /* after Txx */
5577       while (*p)
5578         {
5579           char *p1;
5580           int fieldsize;
5581
5582           p1 = strchr (p, ':');
5583           if (p1 == NULL)
5584             error (_("Malformed packet(a) (missing colon): %s\n\
5585 Packet: '%s'\n"),
5586                    p, buf);
5587           if (p == p1)
5588             error (_("Malformed packet(a) (missing register number): %s\n\
5589 Packet: '%s'\n"),
5590                    p, buf);
5591
5592           /* Some "registers" are actually extended stop information.
5593              Note if you're adding a new entry here: GDB 7.9 and
5594              earlier assume that all register "numbers" that start
5595              with an hex digit are real register numbers.  Make sure
5596              the server only sends such a packet if it knows the
5597              client understands it.  */
5598
5599           if (strncmp (p, "thread", p1 - p) == 0)
5600             event->ptid = read_ptid (++p1, &p);
5601           else if ((strncmp (p, "watch", p1 - p) == 0)
5602                    || (strncmp (p, "rwatch", p1 - p) == 0)
5603                    || (strncmp (p, "awatch", p1 - p) == 0))
5604             {
5605               event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
5606               p = unpack_varlen_hex (++p1, &addr);
5607               event->watch_data_address = (CORE_ADDR) addr;
5608             }
5609           else if (strncmp (p, "swbreak", p1 - p) == 0)
5610             {
5611               event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
5612
5613               /* Make sure the stub doesn't forget to indicate support
5614                  with qSupported.  */
5615               if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
5616                 error (_("Unexpected swbreak stop reason"));
5617
5618               /* The value part is documented as "must be empty",
5619                  though we ignore it, in case we ever decide to make
5620                  use of it in a backward compatible way.  */
5621               p = skip_to_semicolon (p1 + 1);
5622             }
5623           else if (strncmp (p, "hwbreak", p1 - p) == 0)
5624             {
5625               event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
5626
5627               /* Make sure the stub doesn't forget to indicate support
5628                  with qSupported.  */
5629               if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
5630                 error (_("Unexpected hwbreak stop reason"));
5631
5632               /* See above.  */
5633               p = skip_to_semicolon (p1 + 1);
5634             }
5635           else if (strncmp (p, "library", p1 - p) == 0)
5636             {
5637               event->ws.kind = TARGET_WAITKIND_LOADED;
5638               p = skip_to_semicolon (p1 + 1);
5639             }
5640           else if (strncmp (p, "replaylog", p1 - p) == 0)
5641             {
5642               event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5643               /* p1 will indicate "begin" or "end", but it makes
5644                  no difference for now, so ignore it.  */
5645               p = skip_to_semicolon (p1 + 1);
5646             }
5647           else if (strncmp (p, "core", p1 - p) == 0)
5648             {
5649               ULONGEST c;
5650
5651               p = unpack_varlen_hex (++p1, &c);
5652               event->core = c;
5653             }
5654           else
5655             {
5656               ULONGEST pnum;
5657               char *p_temp;
5658
5659               /* Maybe a real ``P'' register number.  */
5660               p_temp = unpack_varlen_hex (p, &pnum);
5661               /* If the first invalid character is the colon, we got a
5662                  register number.  Otherwise, it's an unknown stop
5663                  reason.  */
5664               if (p_temp == p1)
5665                 {
5666                   struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5667                   cached_reg_t cached_reg;
5668
5669                   if (reg == NULL)
5670                     error (_("Remote sent bad register number %s: %s\n\
5671 Packet: '%s'\n"),
5672                            hex_string (pnum), p, buf);
5673
5674                   cached_reg.num = reg->regnum;
5675
5676                   p = p1 + 1;
5677                   fieldsize = hex2bin (p, cached_reg.data,
5678                                        register_size (target_gdbarch (),
5679                                                       reg->regnum));
5680                   p += 2 * fieldsize;
5681                   if (fieldsize < register_size (target_gdbarch (),
5682                                                  reg->regnum))
5683                     warning (_("Remote reply is too short: %s"), buf);
5684
5685                   VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5686                 }
5687               else
5688                 {
5689                   /* Not a number.  Silently skip unknown optional
5690                      info.  */
5691                   p = skip_to_semicolon (p1 + 1);
5692                 }
5693             }
5694
5695           if (*p != ';')
5696             error (_("Remote register badly formatted: %s\nhere: %s"),
5697                    buf, p);
5698           ++p;
5699         }
5700
5701       if (event->ws.kind != TARGET_WAITKIND_IGNORE)
5702         break;
5703
5704       /* fall through */
5705     case 'S':           /* Old style status, just signal only.  */
5706       {
5707         int sig;
5708
5709         event->ws.kind = TARGET_WAITKIND_STOPPED;
5710         sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
5711         if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
5712           event->ws.value.sig = (enum gdb_signal) sig;
5713         else
5714           event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5715       }
5716       break;
5717     case 'W':           /* Target exited.  */
5718     case 'X':
5719       {
5720         char *p;
5721         int pid;
5722         ULONGEST value;
5723
5724         /* GDB used to accept only 2 hex chars here.  Stubs should
5725            only send more if they detect GDB supports multi-process
5726            support.  */
5727         p = unpack_varlen_hex (&buf[1], &value);
5728
5729         if (buf[0] == 'W')
5730           {
5731             /* The remote process exited.  */
5732             event->ws.kind = TARGET_WAITKIND_EXITED;
5733             event->ws.value.integer = value;
5734           }
5735         else
5736           {
5737             /* The remote process exited with a signal.  */
5738             event->ws.kind = TARGET_WAITKIND_SIGNALLED;
5739             if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
5740               event->ws.value.sig = (enum gdb_signal) value;
5741             else
5742               event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5743           }
5744
5745         /* If no process is specified, assume inferior_ptid.  */
5746         pid = ptid_get_pid (inferior_ptid);
5747         if (*p == '\0')
5748           ;
5749         else if (*p == ';')
5750           {
5751             p++;
5752
5753             if (*p == '\0')
5754               ;
5755             else if (startswith (p, "process:"))
5756               {
5757                 ULONGEST upid;
5758
5759                 p += sizeof ("process:") - 1;
5760                 unpack_varlen_hex (p, &upid);
5761                 pid = upid;
5762               }
5763             else
5764               error (_("unknown stop reply packet: %s"), buf);
5765           }
5766         else
5767           error (_("unknown stop reply packet: %s"), buf);
5768         event->ptid = pid_to_ptid (pid);
5769       }
5770       break;
5771     }
5772
5773   if (non_stop && ptid_equal (event->ptid, null_ptid))
5774     error (_("No process or thread specified in stop reply: %s"), buf);
5775 }
5776
5777 /* When the stub wants to tell GDB about a new notification reply, it
5778    sends a notification (%Stop, for example).  Those can come it at
5779    any time, hence, we have to make sure that any pending
5780    putpkt/getpkt sequence we're making is finished, before querying
5781    the stub for more events with the corresponding ack command
5782    (vStopped, for example).  E.g., if we started a vStopped sequence
5783    immediately upon receiving the notification, something like this
5784    could happen:
5785
5786     1.1) --> Hg 1
5787     1.2) <-- OK
5788     1.3) --> g
5789     1.4) <-- %Stop
5790     1.5) --> vStopped
5791     1.6) <-- (registers reply to step #1.3)
5792
5793    Obviously, the reply in step #1.6 would be unexpected to a vStopped
5794    query.
5795
5796    To solve this, whenever we parse a %Stop notification successfully,
5797    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5798    doing whatever we were doing:
5799
5800     2.1) --> Hg 1
5801     2.2) <-- OK
5802     2.3) --> g
5803     2.4) <-- %Stop
5804       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5805     2.5) <-- (registers reply to step #2.3)
5806
5807    Eventualy after step #2.5, we return to the event loop, which
5808    notices there's an event on the
5809    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5810    associated callback --- the function below.  At this point, we're
5811    always safe to start a vStopped sequence. :
5812
5813     2.6) --> vStopped
5814     2.7) <-- T05 thread:2
5815     2.8) --> vStopped
5816     2.9) --> OK
5817 */
5818
5819 void
5820 remote_notif_get_pending_events (struct notif_client *nc)
5821 {
5822   struct remote_state *rs = get_remote_state ();
5823
5824   if (rs->notif_state->pending_event[nc->id] != NULL)
5825     {
5826       if (notif_debug)
5827         fprintf_unfiltered (gdb_stdlog,
5828                             "notif: process: '%s' ack pending event\n",
5829                             nc->name);
5830
5831       /* acknowledge */
5832       nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
5833       rs->notif_state->pending_event[nc->id] = NULL;
5834
5835       while (1)
5836         {
5837           getpkt (&rs->buf, &rs->buf_size, 0);
5838           if (strcmp (rs->buf, "OK") == 0)
5839             break;
5840           else
5841             remote_notif_ack (nc, rs->buf);
5842         }
5843     }
5844   else
5845     {
5846       if (notif_debug)
5847         fprintf_unfiltered (gdb_stdlog,
5848                             "notif: process: '%s' no pending reply\n",
5849                             nc->name);
5850     }
5851 }
5852
5853 /* Called when it is decided that STOP_REPLY holds the info of the
5854    event that is to be returned to the core.  This function always
5855    destroys STOP_REPLY.  */
5856
5857 static ptid_t
5858 process_stop_reply (struct stop_reply *stop_reply,
5859                     struct target_waitstatus *status)
5860 {
5861   ptid_t ptid;
5862
5863   *status = stop_reply->ws;
5864   ptid = stop_reply->ptid;
5865
5866   /* If no thread/process was reported by the stub, assume the current
5867      inferior.  */
5868   if (ptid_equal (ptid, null_ptid))
5869     ptid = inferior_ptid;
5870
5871   if (status->kind != TARGET_WAITKIND_EXITED
5872       && status->kind != TARGET_WAITKIND_SIGNALLED)
5873     {
5874       struct remote_state *rs = get_remote_state ();
5875
5876       /* Expedited registers.  */
5877       if (stop_reply->regcache)
5878         {
5879           struct regcache *regcache
5880             = get_thread_arch_regcache (ptid, target_gdbarch ());
5881           cached_reg_t *reg;
5882           int ix;
5883
5884           for (ix = 0;
5885                VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5886                ix++)
5887             regcache_raw_supply (regcache, reg->num, reg->data);
5888           VEC_free (cached_reg_t, stop_reply->regcache);
5889         }
5890
5891       rs->stop_reason = stop_reply->stop_reason;
5892       rs->remote_watch_data_address = stop_reply->watch_data_address;
5893
5894       remote_notice_new_inferior (ptid, 0);
5895       demand_private_info (ptid)->core = stop_reply->core;
5896     }
5897
5898   stop_reply_xfree (stop_reply);
5899   return ptid;
5900 }
5901
5902 /* The non-stop mode version of target_wait.  */
5903
5904 static ptid_t
5905 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
5906 {
5907   struct remote_state *rs = get_remote_state ();
5908   struct stop_reply *stop_reply;
5909   int ret;
5910   int is_notif = 0;
5911
5912   /* If in non-stop mode, get out of getpkt even if a
5913      notification is received.  */
5914
5915   ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5916                               0 /* forever */, &is_notif);
5917   while (1)
5918     {
5919       if (ret != -1 && !is_notif)
5920         switch (rs->buf[0])
5921           {
5922           case 'E':             /* Error of some sort.  */
5923             /* We're out of sync with the target now.  Did it continue
5924                or not?  We can't tell which thread it was in non-stop,
5925                so just ignore this.  */
5926             warning (_("Remote failure reply: %s"), rs->buf);
5927             break;
5928           case 'O':             /* Console output.  */
5929             remote_console_output (rs->buf + 1);
5930             break;
5931           default:
5932             warning (_("Invalid remote reply: %s"), rs->buf);
5933             break;
5934           }
5935
5936       /* Acknowledge a pending stop reply that may have arrived in the
5937          mean time.  */
5938       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
5939         remote_notif_get_pending_events (&notif_client_stop);
5940
5941       /* If indeed we noticed a stop reply, we're done.  */
5942       stop_reply = queued_stop_reply (ptid);
5943       if (stop_reply != NULL)
5944         return process_stop_reply (stop_reply, status);
5945
5946       /* Still no event.  If we're just polling for an event, then
5947          return to the event loop.  */
5948       if (options & TARGET_WNOHANG)
5949         {
5950           status->kind = TARGET_WAITKIND_IGNORE;
5951           return minus_one_ptid;
5952         }
5953
5954       /* Otherwise do a blocking wait.  */
5955       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5956                                   1 /* forever */, &is_notif);
5957     }
5958 }
5959
5960 /* Wait until the remote machine stops, then return, storing status in
5961    STATUS just as `wait' would.  */
5962
5963 static ptid_t
5964 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
5965 {
5966   struct remote_state *rs = get_remote_state ();
5967   ptid_t event_ptid = null_ptid;
5968   char *buf;
5969   struct stop_reply *stop_reply;
5970
5971  again:
5972
5973   status->kind = TARGET_WAITKIND_IGNORE;
5974   status->value.integer = 0;
5975
5976   stop_reply = queued_stop_reply (ptid);
5977   if (stop_reply != NULL)
5978     return process_stop_reply (stop_reply, status);
5979
5980   if (rs->cached_wait_status)
5981     /* Use the cached wait status, but only once.  */
5982     rs->cached_wait_status = 0;
5983   else
5984     {
5985       int ret;
5986       int is_notif;
5987
5988       if (!target_is_async_p ())
5989         {
5990           ofunc = signal (SIGINT, sync_remote_interrupt);
5991           /* If the user hit C-c before this packet, or between packets,
5992              pretend that it was hit right here.  */
5993           if (check_quit_flag ())
5994             {
5995               clear_quit_flag ();
5996               sync_remote_interrupt (SIGINT);
5997             }
5998         }
5999
6000       /* FIXME: cagney/1999-09-27: If we're in async mode we should
6001          _never_ wait for ever -> test on target_is_async_p().
6002          However, before we do that we need to ensure that the caller
6003          knows how to take the target into/out of async mode.  */
6004       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6005                                   wait_forever_enabled_p, &is_notif);
6006
6007       if (!target_is_async_p ())
6008         signal (SIGINT, ofunc);
6009
6010       /* GDB gets a notification.  Return to core as this event is
6011          not interesting.  */
6012       if (ret != -1 && is_notif)
6013         return minus_one_ptid;
6014     }
6015
6016   buf = rs->buf;
6017
6018   rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6019
6020   /* We got something.  */
6021   rs->waiting_for_stop_reply = 0;
6022
6023   /* Assume that the target has acknowledged Ctrl-C unless we receive
6024      an 'F' or 'O' packet.  */
6025   if (buf[0] != 'F' && buf[0] != 'O')
6026     rs->ctrlc_pending_p = 0;
6027
6028   switch (buf[0])
6029     {
6030     case 'E':           /* Error of some sort.  */
6031       /* We're out of sync with the target now.  Did it continue or
6032          not?  Not is more likely, so report a stop.  */
6033       warning (_("Remote failure reply: %s"), buf);
6034       status->kind = TARGET_WAITKIND_STOPPED;
6035       status->value.sig = GDB_SIGNAL_0;
6036       break;
6037     case 'F':           /* File-I/O request.  */
6038       remote_fileio_request (buf, rs->ctrlc_pending_p);
6039       rs->ctrlc_pending_p = 0;
6040       break;
6041     case 'T': case 'S': case 'X': case 'W':
6042       {
6043         struct stop_reply *stop_reply
6044           = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6045                                                       rs->buf);
6046
6047         event_ptid = process_stop_reply (stop_reply, status);
6048         break;
6049       }
6050     case 'O':           /* Console output.  */
6051       remote_console_output (buf + 1);
6052
6053       /* The target didn't really stop; keep waiting.  */
6054       rs->waiting_for_stop_reply = 1;
6055
6056       break;
6057     case '\0':
6058       if (rs->last_sent_signal != GDB_SIGNAL_0)
6059         {
6060           /* Zero length reply means that we tried 'S' or 'C' and the
6061              remote system doesn't support it.  */
6062           target_terminal_ours_for_output ();
6063           printf_filtered
6064             ("Can't send signals to this remote system.  %s not sent.\n",
6065              gdb_signal_to_name (rs->last_sent_signal));
6066           rs->last_sent_signal = GDB_SIGNAL_0;
6067           target_terminal_inferior ();
6068
6069           strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6070           putpkt ((char *) buf);
6071
6072           /* We just told the target to resume, so a stop reply is in
6073              order.  */
6074           rs->waiting_for_stop_reply = 1;
6075           break;
6076         }
6077       /* else fallthrough */
6078     default:
6079       warning (_("Invalid remote reply: %s"), buf);
6080       /* Keep waiting.  */
6081       rs->waiting_for_stop_reply = 1;
6082       break;
6083     }
6084
6085   if (status->kind == TARGET_WAITKIND_IGNORE)
6086     {
6087       /* Nothing interesting happened.  If we're doing a non-blocking
6088          poll, we're done.  Otherwise, go back to waiting.  */
6089       if (options & TARGET_WNOHANG)
6090         return minus_one_ptid;
6091       else
6092         goto again;
6093     }
6094   else if (status->kind != TARGET_WAITKIND_EXITED
6095            && status->kind != TARGET_WAITKIND_SIGNALLED)
6096     {
6097       if (!ptid_equal (event_ptid, null_ptid))
6098         record_currthread (rs, event_ptid);
6099       else
6100         event_ptid = inferior_ptid;
6101     }
6102   else
6103     /* A process exit.  Invalidate our notion of current thread.  */
6104     record_currthread (rs, minus_one_ptid);
6105
6106   return event_ptid;
6107 }
6108
6109 /* Wait until the remote machine stops, then return, storing status in
6110    STATUS just as `wait' would.  */
6111
6112 static ptid_t
6113 remote_wait (struct target_ops *ops,
6114              ptid_t ptid, struct target_waitstatus *status, int options)
6115 {
6116   ptid_t event_ptid;
6117
6118   if (non_stop)
6119     event_ptid = remote_wait_ns (ptid, status, options);
6120   else
6121     event_ptid = remote_wait_as (ptid, status, options);
6122
6123   if (target_is_async_p ())
6124     {
6125       /* If there are are events left in the queue tell the event loop
6126          to return here.  */
6127       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6128         mark_async_event_handler (remote_async_inferior_event_token);
6129     }
6130
6131   return event_ptid;
6132 }
6133
6134 /* Fetch a single register using a 'p' packet.  */
6135
6136 static int
6137 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6138 {
6139   struct remote_state *rs = get_remote_state ();
6140   char *buf, *p;
6141   char regp[MAX_REGISTER_SIZE];
6142   int i;
6143
6144   if (packet_support (PACKET_p) == PACKET_DISABLE)
6145     return 0;
6146
6147   if (reg->pnum == -1)
6148     return 0;
6149
6150   p = rs->buf;
6151   *p++ = 'p';
6152   p += hexnumstr (p, reg->pnum);
6153   *p++ = '\0';
6154   putpkt (rs->buf);
6155   getpkt (&rs->buf, &rs->buf_size, 0);
6156
6157   buf = rs->buf;
6158
6159   switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6160     {
6161     case PACKET_OK:
6162       break;
6163     case PACKET_UNKNOWN:
6164       return 0;
6165     case PACKET_ERROR:
6166       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6167              gdbarch_register_name (get_regcache_arch (regcache), 
6168                                     reg->regnum), 
6169              buf);
6170     }
6171
6172   /* If this register is unfetchable, tell the regcache.  */
6173   if (buf[0] == 'x')
6174     {
6175       regcache_raw_supply (regcache, reg->regnum, NULL);
6176       return 1;
6177     }
6178
6179   /* Otherwise, parse and supply the value.  */
6180   p = buf;
6181   i = 0;
6182   while (p[0] != 0)
6183     {
6184       if (p[1] == 0)
6185         error (_("fetch_register_using_p: early buf termination"));
6186
6187       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6188       p += 2;
6189     }
6190   regcache_raw_supply (regcache, reg->regnum, regp);
6191   return 1;
6192 }
6193
6194 /* Fetch the registers included in the target's 'g' packet.  */
6195
6196 static int
6197 send_g_packet (void)
6198 {
6199   struct remote_state *rs = get_remote_state ();
6200   int buf_len;
6201
6202   xsnprintf (rs->buf, get_remote_packet_size (), "g");
6203   remote_send (&rs->buf, &rs->buf_size);
6204
6205   /* We can get out of synch in various cases.  If the first character
6206      in the buffer is not a hex character, assume that has happened
6207      and try to fetch another packet to read.  */
6208   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6209          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6210          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6211          && rs->buf[0] != 'x')  /* New: unavailable register value.  */
6212     {
6213       if (remote_debug)
6214         fprintf_unfiltered (gdb_stdlog,
6215                             "Bad register packet; fetching a new packet\n");
6216       getpkt (&rs->buf, &rs->buf_size, 0);
6217     }
6218
6219   buf_len = strlen (rs->buf);
6220
6221   /* Sanity check the received packet.  */
6222   if (buf_len % 2 != 0)
6223     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6224
6225   return buf_len / 2;
6226 }
6227
6228 static void
6229 process_g_packet (struct regcache *regcache)
6230 {
6231   struct gdbarch *gdbarch = get_regcache_arch (regcache);
6232   struct remote_state *rs = get_remote_state ();
6233   struct remote_arch_state *rsa = get_remote_arch_state ();
6234   int i, buf_len;
6235   char *p;
6236   char *regs;
6237
6238   buf_len = strlen (rs->buf);
6239
6240   /* Further sanity checks, with knowledge of the architecture.  */
6241   if (buf_len > 2 * rsa->sizeof_g_packet)
6242     error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6243
6244   /* Save the size of the packet sent to us by the target.  It is used
6245      as a heuristic when determining the max size of packets that the
6246      target can safely receive.  */
6247   if (rsa->actual_register_packet_size == 0)
6248     rsa->actual_register_packet_size = buf_len;
6249
6250   /* If this is smaller than we guessed the 'g' packet would be,
6251      update our records.  A 'g' reply that doesn't include a register's
6252      value implies either that the register is not available, or that
6253      the 'p' packet must be used.  */
6254   if (buf_len < 2 * rsa->sizeof_g_packet)
6255     {
6256       rsa->sizeof_g_packet = buf_len / 2;
6257
6258       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6259         {
6260           if (rsa->regs[i].pnum == -1)
6261             continue;
6262
6263           if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6264             rsa->regs[i].in_g_packet = 0;
6265           else
6266             rsa->regs[i].in_g_packet = 1;
6267         }
6268     }
6269
6270   regs = alloca (rsa->sizeof_g_packet);
6271
6272   /* Unimplemented registers read as all bits zero.  */
6273   memset (regs, 0, rsa->sizeof_g_packet);
6274
6275   /* Reply describes registers byte by byte, each byte encoded as two
6276      hex characters.  Suck them all up, then supply them to the
6277      register cacheing/storage mechanism.  */
6278
6279   p = rs->buf;
6280   for (i = 0; i < rsa->sizeof_g_packet; i++)
6281     {
6282       if (p[0] == 0 || p[1] == 0)
6283         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
6284         internal_error (__FILE__, __LINE__,
6285                         _("unexpected end of 'g' packet reply"));
6286
6287       if (p[0] == 'x' && p[1] == 'x')
6288         regs[i] = 0;            /* 'x' */
6289       else
6290         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6291       p += 2;
6292     }
6293
6294   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6295     {
6296       struct packet_reg *r = &rsa->regs[i];
6297
6298       if (r->in_g_packet)
6299         {
6300           if (r->offset * 2 >= strlen (rs->buf))
6301             /* This shouldn't happen - we adjusted in_g_packet above.  */
6302             internal_error (__FILE__, __LINE__,
6303                             _("unexpected end of 'g' packet reply"));
6304           else if (rs->buf[r->offset * 2] == 'x')
6305             {
6306               gdb_assert (r->offset * 2 < strlen (rs->buf));
6307               /* The register isn't available, mark it as such (at
6308                  the same time setting the value to zero).  */
6309               regcache_raw_supply (regcache, r->regnum, NULL);
6310             }
6311           else
6312             regcache_raw_supply (regcache, r->regnum,
6313                                  regs + r->offset);
6314         }
6315     }
6316 }
6317
6318 static void
6319 fetch_registers_using_g (struct regcache *regcache)
6320 {
6321   send_g_packet ();
6322   process_g_packet (regcache);
6323 }
6324
6325 /* Make the remote selected traceframe match GDB's selected
6326    traceframe.  */
6327
6328 static void
6329 set_remote_traceframe (void)
6330 {
6331   int newnum;
6332   struct remote_state *rs = get_remote_state ();
6333
6334   if (rs->remote_traceframe_number == get_traceframe_number ())
6335     return;
6336
6337   /* Avoid recursion, remote_trace_find calls us again.  */
6338   rs->remote_traceframe_number = get_traceframe_number ();
6339
6340   newnum = target_trace_find (tfind_number,
6341                               get_traceframe_number (), 0, 0, NULL);
6342
6343   /* Should not happen.  If it does, all bets are off.  */
6344   if (newnum != get_traceframe_number ())
6345     warning (_("could not set remote traceframe"));
6346 }
6347
6348 static void
6349 remote_fetch_registers (struct target_ops *ops,
6350                         struct regcache *regcache, int regnum)
6351 {
6352   struct remote_arch_state *rsa = get_remote_arch_state ();
6353   int i;
6354
6355   set_remote_traceframe ();
6356   set_general_thread (inferior_ptid);
6357
6358   if (regnum >= 0)
6359     {
6360       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6361
6362       gdb_assert (reg != NULL);
6363
6364       /* If this register might be in the 'g' packet, try that first -
6365          we are likely to read more than one register.  If this is the
6366          first 'g' packet, we might be overly optimistic about its
6367          contents, so fall back to 'p'.  */
6368       if (reg->in_g_packet)
6369         {
6370           fetch_registers_using_g (regcache);
6371           if (reg->in_g_packet)
6372             return;
6373         }
6374
6375       if (fetch_register_using_p (regcache, reg))
6376         return;
6377
6378       /* This register is not available.  */
6379       regcache_raw_supply (regcache, reg->regnum, NULL);
6380
6381       return;
6382     }
6383
6384   fetch_registers_using_g (regcache);
6385
6386   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6387     if (!rsa->regs[i].in_g_packet)
6388       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
6389         {
6390           /* This register is not available.  */
6391           regcache_raw_supply (regcache, i, NULL);
6392         }
6393 }
6394
6395 /* Prepare to store registers.  Since we may send them all (using a
6396    'G' request), we have to read out the ones we don't want to change
6397    first.  */
6398
6399 static void
6400 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
6401 {
6402   struct remote_arch_state *rsa = get_remote_arch_state ();
6403   int i;
6404   gdb_byte buf[MAX_REGISTER_SIZE];
6405
6406   /* Make sure the entire registers array is valid.  */
6407   switch (packet_support (PACKET_P))
6408     {
6409     case PACKET_DISABLE:
6410     case PACKET_SUPPORT_UNKNOWN:
6411       /* Make sure all the necessary registers are cached.  */
6412       for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6413         if (rsa->regs[i].in_g_packet)
6414           regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
6415       break;
6416     case PACKET_ENABLE:
6417       break;
6418     }
6419 }
6420
6421 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
6422    packet was not recognized.  */
6423
6424 static int
6425 store_register_using_P (const struct regcache *regcache, 
6426                         struct packet_reg *reg)
6427 {
6428   struct gdbarch *gdbarch = get_regcache_arch (regcache);
6429   struct remote_state *rs = get_remote_state ();
6430   /* Try storing a single register.  */
6431   char *buf = rs->buf;
6432   gdb_byte regp[MAX_REGISTER_SIZE];
6433   char *p;
6434
6435   if (packet_support (PACKET_P) == PACKET_DISABLE)
6436     return 0;
6437
6438   if (reg->pnum == -1)
6439     return 0;
6440
6441   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
6442   p = buf + strlen (buf);
6443   regcache_raw_collect (regcache, reg->regnum, regp);
6444   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
6445   putpkt (rs->buf);
6446   getpkt (&rs->buf, &rs->buf_size, 0);
6447
6448   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6449     {
6450     case PACKET_OK:
6451       return 1;
6452     case PACKET_ERROR:
6453       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6454              gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
6455     case PACKET_UNKNOWN:
6456       return 0;
6457     default:
6458       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6459     }
6460 }
6461
6462 /* Store register REGNUM, or all registers if REGNUM == -1, from the
6463    contents of the register cache buffer.  FIXME: ignores errors.  */
6464
6465 static void
6466 store_registers_using_G (const struct regcache *regcache)
6467 {
6468   struct remote_state *rs = get_remote_state ();
6469   struct remote_arch_state *rsa = get_remote_arch_state ();
6470   gdb_byte *regs;
6471   char *p;
6472
6473   /* Extract all the registers in the regcache copying them into a
6474      local buffer.  */
6475   {
6476     int i;
6477
6478     regs = alloca (rsa->sizeof_g_packet);
6479     memset (regs, 0, rsa->sizeof_g_packet);
6480     for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6481       {
6482         struct packet_reg *r = &rsa->regs[i];
6483
6484         if (r->in_g_packet)
6485           regcache_raw_collect (regcache, r->regnum, regs + r->offset);
6486       }
6487   }
6488
6489   /* Command describes registers byte by byte,
6490      each byte encoded as two hex characters.  */
6491   p = rs->buf;
6492   *p++ = 'G';
6493   /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6494      updated.  */
6495   bin2hex (regs, p, rsa->sizeof_g_packet);
6496   putpkt (rs->buf);
6497   getpkt (&rs->buf, &rs->buf_size, 0);
6498   if (packet_check_result (rs->buf) == PACKET_ERROR)
6499     error (_("Could not write registers; remote failure reply '%s'"), 
6500            rs->buf);
6501 }
6502
6503 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6504    of the register cache buffer.  FIXME: ignores errors.  */
6505
6506 static void
6507 remote_store_registers (struct target_ops *ops,
6508                         struct regcache *regcache, int regnum)
6509 {
6510   struct remote_arch_state *rsa = get_remote_arch_state ();
6511   int i;
6512
6513   set_remote_traceframe ();
6514   set_general_thread (inferior_ptid);
6515
6516   if (regnum >= 0)
6517     {
6518       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6519
6520       gdb_assert (reg != NULL);
6521
6522       /* Always prefer to store registers using the 'P' packet if
6523          possible; we often change only a small number of registers.
6524          Sometimes we change a larger number; we'd need help from a
6525          higher layer to know to use 'G'.  */
6526       if (store_register_using_P (regcache, reg))
6527         return;
6528
6529       /* For now, don't complain if we have no way to write the
6530          register.  GDB loses track of unavailable registers too
6531          easily.  Some day, this may be an error.  We don't have
6532          any way to read the register, either...  */
6533       if (!reg->in_g_packet)
6534         return;
6535
6536       store_registers_using_G (regcache);
6537       return;
6538     }
6539
6540   store_registers_using_G (regcache);
6541
6542   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6543     if (!rsa->regs[i].in_g_packet)
6544       if (!store_register_using_P (regcache, &rsa->regs[i]))
6545         /* See above for why we do not issue an error here.  */
6546         continue;
6547 }
6548 \f
6549
6550 /* Return the number of hex digits in num.  */
6551
6552 static int
6553 hexnumlen (ULONGEST num)
6554 {
6555   int i;
6556
6557   for (i = 0; num != 0; i++)
6558     num >>= 4;
6559
6560   return max (i, 1);
6561 }
6562
6563 /* Set BUF to the minimum number of hex digits representing NUM.  */
6564
6565 static int
6566 hexnumstr (char *buf, ULONGEST num)
6567 {
6568   int len = hexnumlen (num);
6569
6570   return hexnumnstr (buf, num, len);
6571 }
6572
6573
6574 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
6575
6576 static int
6577 hexnumnstr (char *buf, ULONGEST num, int width)
6578 {
6579   int i;
6580
6581   buf[width] = '\0';
6582
6583   for (i = width - 1; i >= 0; i--)
6584     {
6585       buf[i] = "0123456789abcdef"[(num & 0xf)];
6586       num >>= 4;
6587     }
6588
6589   return width;
6590 }
6591
6592 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
6593
6594 static CORE_ADDR
6595 remote_address_masked (CORE_ADDR addr)
6596 {
6597   unsigned int address_size = remote_address_size;
6598
6599   /* If "remoteaddresssize" was not set, default to target address size.  */
6600   if (!address_size)
6601     address_size = gdbarch_addr_bit (target_gdbarch ());
6602
6603   if (address_size > 0
6604       && address_size < (sizeof (ULONGEST) * 8))
6605     {
6606       /* Only create a mask when that mask can safely be constructed
6607          in a ULONGEST variable.  */
6608       ULONGEST mask = 1;
6609
6610       mask = (mask << address_size) - 1;
6611       addr &= mask;
6612     }
6613   return addr;
6614 }
6615
6616 /* Determine whether the remote target supports binary downloading.
6617    This is accomplished by sending a no-op memory write of zero length
6618    to the target at the specified address. It does not suffice to send
6619    the whole packet, since many stubs strip the eighth bit and
6620    subsequently compute a wrong checksum, which causes real havoc with
6621    remote_write_bytes.
6622
6623    NOTE: This can still lose if the serial line is not eight-bit
6624    clean.  In cases like this, the user should clear "remote
6625    X-packet".  */
6626
6627 static void
6628 check_binary_download (CORE_ADDR addr)
6629 {
6630   struct remote_state *rs = get_remote_state ();
6631
6632   switch (packet_support (PACKET_X))
6633     {
6634     case PACKET_DISABLE:
6635       break;
6636     case PACKET_ENABLE:
6637       break;
6638     case PACKET_SUPPORT_UNKNOWN:
6639       {
6640         char *p;
6641
6642         p = rs->buf;
6643         *p++ = 'X';
6644         p += hexnumstr (p, (ULONGEST) addr);
6645         *p++ = ',';
6646         p += hexnumstr (p, (ULONGEST) 0);
6647         *p++ = ':';
6648         *p = '\0';
6649
6650         putpkt_binary (rs->buf, (int) (p - rs->buf));
6651         getpkt (&rs->buf, &rs->buf_size, 0);
6652
6653         if (rs->buf[0] == '\0')
6654           {
6655             if (remote_debug)
6656               fprintf_unfiltered (gdb_stdlog,
6657                                   "binary downloading NOT "
6658                                   "supported by target\n");
6659             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
6660           }
6661         else
6662           {
6663             if (remote_debug)
6664               fprintf_unfiltered (gdb_stdlog,
6665                                   "binary downloading supported by target\n");
6666             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
6667           }
6668         break;
6669       }
6670     }
6671 }
6672
6673 /* Write memory data directly to the remote machine.
6674    This does not inform the data cache; the data cache uses this.
6675    HEADER is the starting part of the packet.
6676    MEMADDR is the address in the remote memory space.
6677    MYADDR is the address of the buffer in our space.
6678    LEN is the number of bytes.
6679    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6680    should send data as binary ('X'), or hex-encoded ('M').
6681
6682    The function creates packet of the form
6683        <HEADER><ADDRESS>,<LENGTH>:<DATA>
6684
6685    where encoding of <DATA> is termined by PACKET_FORMAT.
6686
6687    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6688    are omitted.
6689
6690    Return the transferred status, error or OK (an
6691    'enum target_xfer_status' value).  Save the number of bytes
6692    transferred in *XFERED_LEN.  Only transfer a single packet.  */
6693
6694 static enum target_xfer_status
6695 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
6696                         const gdb_byte *myaddr, ULONGEST len,
6697                         ULONGEST *xfered_len, char packet_format,
6698                         int use_length)
6699 {
6700   struct remote_state *rs = get_remote_state ();
6701   char *p;
6702   char *plen = NULL;
6703   int plenlen = 0;
6704   int todo;
6705   int nr_bytes;
6706   int payload_size;
6707   int payload_length;
6708   int header_length;
6709
6710   if (packet_format != 'X' && packet_format != 'M')
6711     internal_error (__FILE__, __LINE__,
6712                     _("remote_write_bytes_aux: bad packet format"));
6713
6714   if (len == 0)
6715     return TARGET_XFER_EOF;
6716
6717   payload_size = get_memory_write_packet_size ();
6718
6719   /* The packet buffer will be large enough for the payload;
6720      get_memory_packet_size ensures this.  */
6721   rs->buf[0] = '\0';
6722
6723   /* Compute the size of the actual payload by subtracting out the
6724      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
6725
6726   payload_size -= strlen ("$,:#NN");
6727   if (!use_length)
6728     /* The comma won't be used.  */
6729     payload_size += 1;
6730   header_length = strlen (header);
6731   payload_size -= header_length;
6732   payload_size -= hexnumlen (memaddr);
6733
6734   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
6735
6736   strcat (rs->buf, header);
6737   p = rs->buf + strlen (header);
6738
6739   /* Compute a best guess of the number of bytes actually transfered.  */
6740   if (packet_format == 'X')
6741     {
6742       /* Best guess at number of bytes that will fit.  */
6743       todo = min (len, payload_size);
6744       if (use_length)
6745         payload_size -= hexnumlen (todo);
6746       todo = min (todo, payload_size);
6747     }
6748   else
6749     {
6750       /* Num bytes that will fit.  */
6751       todo = min (len, payload_size / 2);
6752       if (use_length)
6753         payload_size -= hexnumlen (todo);
6754       todo = min (todo, payload_size / 2);
6755     }
6756
6757   if (todo <= 0)
6758     internal_error (__FILE__, __LINE__,
6759                     _("minimum packet size too small to write data"));
6760
6761   /* If we already need another packet, then try to align the end
6762      of this packet to a useful boundary.  */
6763   if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6764     todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6765
6766   /* Append "<memaddr>".  */
6767   memaddr = remote_address_masked (memaddr);
6768   p += hexnumstr (p, (ULONGEST) memaddr);
6769
6770   if (use_length)
6771     {
6772       /* Append ",".  */
6773       *p++ = ',';
6774
6775       /* Append <len>.  Retain the location/size of <len>.  It may need to
6776          be adjusted once the packet body has been created.  */
6777       plen = p;
6778       plenlen = hexnumstr (p, (ULONGEST) todo);
6779       p += plenlen;
6780     }
6781
6782   /* Append ":".  */
6783   *p++ = ':';
6784   *p = '\0';
6785
6786   /* Append the packet body.  */
6787   if (packet_format == 'X')
6788     {
6789       /* Binary mode.  Send target system values byte by byte, in
6790          increasing byte addresses.  Only escape certain critical
6791          characters.  */
6792       payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
6793                                              &nr_bytes, payload_size);
6794
6795       /* If not all TODO bytes fit, then we'll need another packet.  Make
6796          a second try to keep the end of the packet aligned.  Don't do
6797          this if the packet is tiny.  */
6798       if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6799         {
6800           int new_nr_bytes;
6801
6802           new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6803                           - memaddr);
6804           if (new_nr_bytes != nr_bytes)
6805             payload_length = remote_escape_output (myaddr, new_nr_bytes,
6806                                                    (gdb_byte *) p, &nr_bytes,
6807                                                    payload_size);
6808         }
6809
6810       p += payload_length;
6811       if (use_length && nr_bytes < todo)
6812         {
6813           /* Escape chars have filled up the buffer prematurely,
6814              and we have actually sent fewer bytes than planned.
6815              Fix-up the length field of the packet.  Use the same
6816              number of characters as before.  */
6817           plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6818           *plen = ':';  /* overwrite \0 from hexnumnstr() */
6819         }
6820     }
6821   else
6822     {
6823       /* Normal mode: Send target system values byte by byte, in
6824          increasing byte addresses.  Each byte is encoded as a two hex
6825          value.  */
6826       nr_bytes = bin2hex (myaddr, p, todo);
6827       p += 2 * nr_bytes;
6828     }
6829
6830   putpkt_binary (rs->buf, (int) (p - rs->buf));
6831   getpkt (&rs->buf, &rs->buf_size, 0);
6832
6833   if (rs->buf[0] == 'E')
6834     return TARGET_XFER_E_IO;
6835
6836   /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6837      fewer bytes than we'd planned.  */
6838   *xfered_len = (ULONGEST) nr_bytes;
6839   return TARGET_XFER_OK;
6840 }
6841
6842 /* Write memory data directly to the remote machine.
6843    This does not inform the data cache; the data cache uses this.
6844    MEMADDR is the address in the remote memory space.
6845    MYADDR is the address of the buffer in our space.
6846    LEN is the number of bytes.
6847
6848    Return the transferred status, error or OK (an
6849    'enum target_xfer_status' value).  Save the number of bytes
6850    transferred in *XFERED_LEN.  Only transfer a single packet.  */
6851
6852 static enum target_xfer_status
6853 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
6854                     ULONGEST *xfered_len)
6855 {
6856   char *packet_format = 0;
6857
6858   /* Check whether the target supports binary download.  */
6859   check_binary_download (memaddr);
6860
6861   switch (packet_support (PACKET_X))
6862     {
6863     case PACKET_ENABLE:
6864       packet_format = "X";
6865       break;
6866     case PACKET_DISABLE:
6867       packet_format = "M";
6868       break;
6869     case PACKET_SUPPORT_UNKNOWN:
6870       internal_error (__FILE__, __LINE__,
6871                       _("remote_write_bytes: bad internal state"));
6872     default:
6873       internal_error (__FILE__, __LINE__, _("bad switch"));
6874     }
6875
6876   return remote_write_bytes_aux (packet_format,
6877                                  memaddr, myaddr, len, xfered_len,
6878                                  packet_format[0], 1);
6879 }
6880
6881 /* Read memory data directly from the remote machine.
6882    This does not use the data cache; the data cache uses this.
6883    MEMADDR is the address in the remote memory space.
6884    MYADDR is the address of the buffer in our space.
6885    LEN is the number of bytes.
6886
6887    Return the transferred status, error or OK (an
6888    'enum target_xfer_status' value).  Save the number of bytes
6889    transferred in *XFERED_LEN.  */
6890
6891 static enum target_xfer_status
6892 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len,
6893                      ULONGEST *xfered_len)
6894 {
6895   struct remote_state *rs = get_remote_state ();
6896   int max_buf_size;             /* Max size of packet output buffer.  */
6897   char *p;
6898   int todo;
6899   int i;
6900
6901   max_buf_size = get_memory_read_packet_size ();
6902   /* The packet buffer will be large enough for the payload;
6903      get_memory_packet_size ensures this.  */
6904
6905   /* Number if bytes that will fit.  */
6906   todo = min (len, max_buf_size / 2);
6907
6908   /* Construct "m"<memaddr>","<len>".  */
6909   memaddr = remote_address_masked (memaddr);
6910   p = rs->buf;
6911   *p++ = 'm';
6912   p += hexnumstr (p, (ULONGEST) memaddr);
6913   *p++ = ',';
6914   p += hexnumstr (p, (ULONGEST) todo);
6915   *p = '\0';
6916   putpkt (rs->buf);
6917   getpkt (&rs->buf, &rs->buf_size, 0);
6918   if (rs->buf[0] == 'E'
6919       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6920       && rs->buf[3] == '\0')
6921     return TARGET_XFER_E_IO;
6922   /* Reply describes memory byte by byte, each byte encoded as two hex
6923      characters.  */
6924   p = rs->buf;
6925   i = hex2bin (p, myaddr, todo);
6926   /* Return what we have.  Let higher layers handle partial reads.  */
6927   *xfered_len = (ULONGEST) i;
6928   return TARGET_XFER_OK;
6929 }
6930
6931 /* Using the set of read-only target sections of remote, read live
6932    read-only memory.
6933
6934    For interface/parameters/return description see target.h,
6935    to_xfer_partial.  */
6936
6937 static enum target_xfer_status
6938 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
6939                                    ULONGEST memaddr, ULONGEST len,
6940                                    ULONGEST *xfered_len)
6941 {
6942   struct target_section *secp;
6943   struct target_section_table *table;
6944
6945   secp = target_section_by_addr (ops, memaddr);
6946   if (secp != NULL
6947       && (bfd_get_section_flags (secp->the_bfd_section->owner,
6948                                  secp->the_bfd_section)
6949           & SEC_READONLY))
6950     {
6951       struct target_section *p;
6952       ULONGEST memend = memaddr + len;
6953
6954       table = target_get_section_table (ops);
6955
6956       for (p = table->sections; p < table->sections_end; p++)
6957         {
6958           if (memaddr >= p->addr)
6959             {
6960               if (memend <= p->endaddr)
6961                 {
6962                   /* Entire transfer is within this section.  */
6963                   return remote_read_bytes_1 (memaddr, readbuf, len,
6964                                               xfered_len);
6965                 }
6966               else if (memaddr >= p->endaddr)
6967                 {
6968                   /* This section ends before the transfer starts.  */
6969                   continue;
6970                 }
6971               else
6972                 {
6973                   /* This section overlaps the transfer.  Just do half.  */
6974                   len = p->endaddr - memaddr;
6975                   return remote_read_bytes_1 (memaddr, readbuf, len,
6976                                               xfered_len);
6977                 }
6978             }
6979         }
6980     }
6981
6982   return TARGET_XFER_EOF;
6983 }
6984
6985 /* Similar to remote_read_bytes_1, but it reads from the remote stub
6986    first if the requested memory is unavailable in traceframe.
6987    Otherwise, fall back to remote_read_bytes_1.  */
6988
6989 static enum target_xfer_status
6990 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
6991                    gdb_byte *myaddr, ULONGEST len, ULONGEST *xfered_len)
6992 {
6993   if (len == 0)
6994     return TARGET_XFER_EOF;
6995
6996   if (get_traceframe_number () != -1)
6997     {
6998       VEC(mem_range_s) *available;
6999
7000       /* If we fail to get the set of available memory, then the
7001          target does not support querying traceframe info, and so we
7002          attempt reading from the traceframe anyway (assuming the
7003          target implements the old QTro packet then).  */
7004       if (traceframe_available_memory (&available, memaddr, len))
7005         {
7006           struct cleanup *old_chain;
7007
7008           old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7009
7010           if (VEC_empty (mem_range_s, available)
7011               || VEC_index (mem_range_s, available, 0)->start != memaddr)
7012             {
7013               enum target_xfer_status res;
7014
7015               /* Don't read into the traceframe's available
7016                  memory.  */
7017               if (!VEC_empty (mem_range_s, available))
7018                 {
7019                   LONGEST oldlen = len;
7020
7021                   len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7022                   gdb_assert (len <= oldlen);
7023                 }
7024
7025               do_cleanups (old_chain);
7026
7027               /* This goes through the topmost target again.  */
7028               res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7029                                                        len, xfered_len);
7030               if (res == TARGET_XFER_OK)
7031                 return TARGET_XFER_OK;
7032               else
7033                 {
7034                   /* No use trying further, we know some memory starting
7035                      at MEMADDR isn't available.  */
7036                   *xfered_len = len;
7037                   return TARGET_XFER_UNAVAILABLE;
7038                 }
7039             }
7040
7041           /* Don't try to read more than how much is available, in
7042              case the target implements the deprecated QTro packet to
7043              cater for older GDBs (the target's knowledge of read-only
7044              sections may be outdated by now).  */
7045           len = VEC_index (mem_range_s, available, 0)->length;
7046
7047           do_cleanups (old_chain);
7048         }
7049     }
7050
7051   return remote_read_bytes_1 (memaddr, myaddr, len, xfered_len);
7052 }
7053
7054 \f
7055
7056 /* Sends a packet with content determined by the printf format string
7057    FORMAT and the remaining arguments, then gets the reply.  Returns
7058    whether the packet was a success, a failure, or unknown.  */
7059
7060 static enum packet_result remote_send_printf (const char *format, ...)
7061   ATTRIBUTE_PRINTF (1, 2);
7062
7063 static enum packet_result
7064 remote_send_printf (const char *format, ...)
7065 {
7066   struct remote_state *rs = get_remote_state ();
7067   int max_size = get_remote_packet_size ();
7068   va_list ap;
7069
7070   va_start (ap, format);
7071
7072   rs->buf[0] = '\0';
7073   if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7074     internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7075
7076   if (putpkt (rs->buf) < 0)
7077     error (_("Communication problem with target."));
7078
7079   rs->buf[0] = '\0';
7080   getpkt (&rs->buf, &rs->buf_size, 0);
7081
7082   return packet_check_result (rs->buf);
7083 }
7084
7085 static void
7086 restore_remote_timeout (void *p)
7087 {
7088   int value = *(int *)p;
7089
7090   remote_timeout = value;
7091 }
7092
7093 /* Flash writing can take quite some time.  We'll set
7094    effectively infinite timeout for flash operations.
7095    In future, we'll need to decide on a better approach.  */
7096 static const int remote_flash_timeout = 1000;
7097
7098 static void
7099 remote_flash_erase (struct target_ops *ops,
7100                     ULONGEST address, LONGEST length)
7101 {
7102   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7103   int saved_remote_timeout = remote_timeout;
7104   enum packet_result ret;
7105   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7106                                           &saved_remote_timeout);
7107
7108   remote_timeout = remote_flash_timeout;
7109
7110   ret = remote_send_printf ("vFlashErase:%s,%s",
7111                             phex (address, addr_size),
7112                             phex (length, 4));
7113   switch (ret)
7114     {
7115     case PACKET_UNKNOWN:
7116       error (_("Remote target does not support flash erase"));
7117     case PACKET_ERROR:
7118       error (_("Error erasing flash with vFlashErase packet"));
7119     default:
7120       break;
7121     }
7122
7123   do_cleanups (back_to);
7124 }
7125
7126 static enum target_xfer_status
7127 remote_flash_write (struct target_ops *ops, ULONGEST address,
7128                     ULONGEST length, ULONGEST *xfered_len,
7129                     const gdb_byte *data)
7130 {
7131   int saved_remote_timeout = remote_timeout;
7132   enum target_xfer_status ret;
7133   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7134                                           &saved_remote_timeout);
7135
7136   remote_timeout = remote_flash_timeout;
7137   ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length,
7138                                 xfered_len,'X', 0);
7139   do_cleanups (back_to);
7140
7141   return ret;
7142 }
7143
7144 static void
7145 remote_flash_done (struct target_ops *ops)
7146 {
7147   int saved_remote_timeout = remote_timeout;
7148   int ret;
7149   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7150                                           &saved_remote_timeout);
7151
7152   remote_timeout = remote_flash_timeout;
7153   ret = remote_send_printf ("vFlashDone");
7154   do_cleanups (back_to);
7155
7156   switch (ret)
7157     {
7158     case PACKET_UNKNOWN:
7159       error (_("Remote target does not support vFlashDone"));
7160     case PACKET_ERROR:
7161       error (_("Error finishing flash operation"));
7162     default:
7163       break;
7164     }
7165 }
7166
7167 static void
7168 remote_files_info (struct target_ops *ignore)
7169 {
7170   puts_filtered ("Debugging a target over a serial line.\n");
7171 }
7172 \f
7173 /* Stuff for dealing with the packets which are part of this protocol.
7174    See comment at top of file for details.  */
7175
7176 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7177    error to higher layers.  Called when a serial error is detected.
7178    The exception message is STRING, followed by a colon and a blank,
7179    the system error message for errno at function entry and final dot
7180    for output compatibility with throw_perror_with_name.  */
7181
7182 static void
7183 unpush_and_perror (const char *string)
7184 {
7185   int saved_errno = errno;
7186
7187   remote_unpush_target ();
7188   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7189                safe_strerror (saved_errno));
7190 }
7191
7192 /* Read a single character from the remote end.  */
7193
7194 static int
7195 readchar (int timeout)
7196 {
7197   int ch;
7198   struct remote_state *rs = get_remote_state ();
7199
7200   ch = serial_readchar (rs->remote_desc, timeout);
7201
7202   if (ch >= 0)
7203     return ch;
7204
7205   switch ((enum serial_rc) ch)
7206     {
7207     case SERIAL_EOF:
7208       remote_unpush_target ();
7209       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
7210       /* no return */
7211     case SERIAL_ERROR:
7212       unpush_and_perror (_("Remote communication error.  "
7213                            "Target disconnected."));
7214       /* no return */
7215     case SERIAL_TIMEOUT:
7216       break;
7217     }
7218   return ch;
7219 }
7220
7221 /* Wrapper for serial_write that closes the target and throws if
7222    writing fails.  */
7223
7224 static void
7225 remote_serial_write (const char *str, int len)
7226 {
7227   struct remote_state *rs = get_remote_state ();
7228
7229   if (serial_write (rs->remote_desc, str, len))
7230     {
7231       unpush_and_perror (_("Remote communication error.  "
7232                            "Target disconnected."));
7233     }
7234 }
7235
7236 /* Send the command in *BUF to the remote machine, and read the reply
7237    into *BUF.  Report an error if we get an error reply.  Resize
7238    *BUF using xrealloc if necessary to hold the result, and update
7239    *SIZEOF_BUF.  */
7240
7241 static void
7242 remote_send (char **buf,
7243              long *sizeof_buf)
7244 {
7245   putpkt (*buf);
7246   getpkt (buf, sizeof_buf, 0);
7247
7248   if ((*buf)[0] == 'E')
7249     error (_("Remote failure reply: %s"), *buf);
7250 }
7251
7252 /* Return a pointer to an xmalloc'ed string representing an escaped
7253    version of BUF, of len N.  E.g. \n is converted to \\n, \t to \\t,
7254    etc.  The caller is responsible for releasing the returned
7255    memory.  */
7256
7257 static char *
7258 escape_buffer (const char *buf, int n)
7259 {
7260   struct cleanup *old_chain;
7261   struct ui_file *stb;
7262   char *str;
7263
7264   stb = mem_fileopen ();
7265   old_chain = make_cleanup_ui_file_delete (stb);
7266
7267   fputstrn_unfiltered (buf, n, '\\', stb);
7268   str = ui_file_xstrdup (stb, NULL);
7269   do_cleanups (old_chain);
7270   return str;
7271 }
7272
7273 /* Display a null-terminated packet on stdout, for debugging, using C
7274    string notation.  */
7275
7276 static void
7277 print_packet (const char *buf)
7278 {
7279   puts_filtered ("\"");
7280   fputstr_filtered (buf, '"', gdb_stdout);
7281   puts_filtered ("\"");
7282 }
7283
7284 int
7285 putpkt (const char *buf)
7286 {
7287   return putpkt_binary (buf, strlen (buf));
7288 }
7289
7290 /* Send a packet to the remote machine, with error checking.  The data
7291    of the packet is in BUF.  The string in BUF can be at most
7292    get_remote_packet_size () - 5 to account for the $, # and checksum,
7293    and for a possible /0 if we are debugging (remote_debug) and want
7294    to print the sent packet as a string.  */
7295
7296 static int
7297 putpkt_binary (const char *buf, int cnt)
7298 {
7299   struct remote_state *rs = get_remote_state ();
7300   int i;
7301   unsigned char csum = 0;
7302   char *buf2 = alloca (cnt + 6);
7303
7304   int ch;
7305   int tcount = 0;
7306   char *p;
7307   char *message;
7308
7309   /* Catch cases like trying to read memory or listing threads while
7310      we're waiting for a stop reply.  The remote server wouldn't be
7311      ready to handle this request, so we'd hang and timeout.  We don't
7312      have to worry about this in synchronous mode, because in that
7313      case it's not possible to issue a command while the target is
7314      running.  This is not a problem in non-stop mode, because in that
7315      case, the stub is always ready to process serial input.  */
7316   if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
7317     {
7318       error (_("Cannot execute this command while the target is running.\n"
7319                "Use the \"interrupt\" command to stop the target\n"
7320                "and then try again."));
7321     }
7322
7323   /* We're sending out a new packet.  Make sure we don't look at a
7324      stale cached response.  */
7325   rs->cached_wait_status = 0;
7326
7327   /* Copy the packet into buffer BUF2, encapsulating it
7328      and giving it a checksum.  */
7329
7330   p = buf2;
7331   *p++ = '$';
7332
7333   for (i = 0; i < cnt; i++)
7334     {
7335       csum += buf[i];
7336       *p++ = buf[i];
7337     }
7338   *p++ = '#';
7339   *p++ = tohex ((csum >> 4) & 0xf);
7340   *p++ = tohex (csum & 0xf);
7341
7342   /* Send it over and over until we get a positive ack.  */
7343
7344   while (1)
7345     {
7346       int started_error_output = 0;
7347
7348       if (remote_debug)
7349         {
7350           struct cleanup *old_chain;
7351           char *str;
7352
7353           *p = '\0';
7354           str = escape_buffer (buf2, p - buf2);
7355           old_chain = make_cleanup (xfree, str);
7356           fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
7357           gdb_flush (gdb_stdlog);
7358           do_cleanups (old_chain);
7359         }
7360       remote_serial_write (buf2, p - buf2);
7361
7362       /* If this is a no acks version of the remote protocol, send the
7363          packet and move on.  */
7364       if (rs->noack_mode)
7365         break;
7366
7367       /* Read until either a timeout occurs (-2) or '+' is read.
7368          Handle any notification that arrives in the mean time.  */
7369       while (1)
7370         {
7371           ch = readchar (remote_timeout);
7372
7373           if (remote_debug)
7374             {
7375               switch (ch)
7376                 {
7377                 case '+':
7378                 case '-':
7379                 case SERIAL_TIMEOUT:
7380                 case '$':
7381                 case '%':
7382                   if (started_error_output)
7383                     {
7384                       putchar_unfiltered ('\n');
7385                       started_error_output = 0;
7386                     }
7387                 }
7388             }
7389
7390           switch (ch)
7391             {
7392             case '+':
7393               if (remote_debug)
7394                 fprintf_unfiltered (gdb_stdlog, "Ack\n");
7395               return 1;
7396             case '-':
7397               if (remote_debug)
7398                 fprintf_unfiltered (gdb_stdlog, "Nak\n");
7399               /* FALLTHROUGH */
7400             case SERIAL_TIMEOUT:
7401               tcount++;
7402               if (tcount > 3)
7403                 return 0;
7404               break;            /* Retransmit buffer.  */
7405             case '$':
7406               {
7407                 if (remote_debug)
7408                   fprintf_unfiltered (gdb_stdlog,
7409                                       "Packet instead of Ack, ignoring it\n");
7410                 /* It's probably an old response sent because an ACK
7411                    was lost.  Gobble up the packet and ack it so it
7412                    doesn't get retransmitted when we resend this
7413                    packet.  */
7414                 skip_frame ();
7415                 remote_serial_write ("+", 1);
7416                 continue;       /* Now, go look for +.  */
7417               }
7418
7419             case '%':
7420               {
7421                 int val;
7422
7423                 /* If we got a notification, handle it, and go back to looking
7424                    for an ack.  */
7425                 /* We've found the start of a notification.  Now
7426                    collect the data.  */
7427                 val = read_frame (&rs->buf, &rs->buf_size);
7428                 if (val >= 0)
7429                   {
7430                     if (remote_debug)
7431                       {
7432                         struct cleanup *old_chain;
7433                         char *str;
7434
7435                         str = escape_buffer (rs->buf, val);
7436                         old_chain = make_cleanup (xfree, str);
7437                         fprintf_unfiltered (gdb_stdlog,
7438                                             "  Notification received: %s\n",
7439                                             str);
7440                         do_cleanups (old_chain);
7441                       }
7442                     handle_notification (rs->notif_state, rs->buf);
7443                     /* We're in sync now, rewait for the ack.  */
7444                     tcount = 0;
7445                   }
7446                 else
7447                   {
7448                     if (remote_debug)
7449                       {
7450                         if (!started_error_output)
7451                           {
7452                             started_error_output = 1;
7453                             fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7454                           }
7455                         fputc_unfiltered (ch & 0177, gdb_stdlog);
7456                         fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7457                       }
7458                   }
7459                 continue;
7460               }
7461               /* fall-through */
7462             default:
7463               if (remote_debug)
7464                 {
7465                   if (!started_error_output)
7466                     {
7467                       started_error_output = 1;
7468                       fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7469                     }
7470                   fputc_unfiltered (ch & 0177, gdb_stdlog);
7471                 }
7472               continue;
7473             }
7474           break;                /* Here to retransmit.  */
7475         }
7476
7477 #if 0
7478       /* This is wrong.  If doing a long backtrace, the user should be
7479          able to get out next time we call QUIT, without anything as
7480          violent as interrupt_query.  If we want to provide a way out of
7481          here without getting to the next QUIT, it should be based on
7482          hitting ^C twice as in remote_wait.  */
7483       if (quit_flag)
7484         {
7485           quit_flag = 0;
7486           interrupt_query ();
7487         }
7488 #endif
7489     }
7490   return 0;
7491 }
7492
7493 /* Come here after finding the start of a frame when we expected an
7494    ack.  Do our best to discard the rest of this packet.  */
7495
7496 static void
7497 skip_frame (void)
7498 {
7499   int c;
7500
7501   while (1)
7502     {
7503       c = readchar (remote_timeout);
7504       switch (c)
7505         {
7506         case SERIAL_TIMEOUT:
7507           /* Nothing we can do.  */
7508           return;
7509         case '#':
7510           /* Discard the two bytes of checksum and stop.  */
7511           c = readchar (remote_timeout);
7512           if (c >= 0)
7513             c = readchar (remote_timeout);
7514
7515           return;
7516         case '*':               /* Run length encoding.  */
7517           /* Discard the repeat count.  */
7518           c = readchar (remote_timeout);
7519           if (c < 0)
7520             return;
7521           break;
7522         default:
7523           /* A regular character.  */
7524           break;
7525         }
7526     }
7527 }
7528
7529 /* Come here after finding the start of the frame.  Collect the rest
7530    into *BUF, verifying the checksum, length, and handling run-length
7531    compression.  NUL terminate the buffer.  If there is not enough room,
7532    expand *BUF using xrealloc.
7533
7534    Returns -1 on error, number of characters in buffer (ignoring the
7535    trailing NULL) on success. (could be extended to return one of the
7536    SERIAL status indications).  */
7537
7538 static long
7539 read_frame (char **buf_p,
7540             long *sizeof_buf)
7541 {
7542   unsigned char csum;
7543   long bc;
7544   int c;
7545   char *buf = *buf_p;
7546   struct remote_state *rs = get_remote_state ();
7547
7548   csum = 0;
7549   bc = 0;
7550
7551   while (1)
7552     {
7553       c = readchar (remote_timeout);
7554       switch (c)
7555         {
7556         case SERIAL_TIMEOUT:
7557           if (remote_debug)
7558             fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
7559           return -1;
7560         case '$':
7561           if (remote_debug)
7562             fputs_filtered ("Saw new packet start in middle of old one\n",
7563                             gdb_stdlog);
7564           return -1;            /* Start a new packet, count retries.  */
7565         case '#':
7566           {
7567             unsigned char pktcsum;
7568             int check_0 = 0;
7569             int check_1 = 0;
7570
7571             buf[bc] = '\0';
7572
7573             check_0 = readchar (remote_timeout);
7574             if (check_0 >= 0)
7575               check_1 = readchar (remote_timeout);
7576
7577             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7578               {
7579                 if (remote_debug)
7580                   fputs_filtered ("Timeout in checksum, retrying\n",
7581                                   gdb_stdlog);
7582                 return -1;
7583               }
7584             else if (check_0 < 0 || check_1 < 0)
7585               {
7586                 if (remote_debug)
7587                   fputs_filtered ("Communication error in checksum\n",
7588                                   gdb_stdlog);
7589                 return -1;
7590               }
7591
7592             /* Don't recompute the checksum; with no ack packets we
7593                don't have any way to indicate a packet retransmission
7594                is necessary.  */
7595             if (rs->noack_mode)
7596               return bc;
7597
7598             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
7599             if (csum == pktcsum)
7600               return bc;
7601
7602             if (remote_debug)
7603               {
7604                 struct cleanup *old_chain;
7605                 char *str;
7606
7607                 str = escape_buffer (buf, bc);
7608                 old_chain = make_cleanup (xfree, str);
7609                 fprintf_unfiltered (gdb_stdlog,
7610                                     "Bad checksum, sentsum=0x%x, "
7611                                     "csum=0x%x, buf=%s\n",
7612                                     pktcsum, csum, str);
7613                 do_cleanups (old_chain);
7614               }
7615             /* Number of characters in buffer ignoring trailing
7616                NULL.  */
7617             return -1;
7618           }
7619         case '*':               /* Run length encoding.  */
7620           {
7621             int repeat;
7622
7623             csum += c;
7624             c = readchar (remote_timeout);
7625             csum += c;
7626             repeat = c - ' ' + 3;       /* Compute repeat count.  */
7627
7628             /* The character before ``*'' is repeated.  */
7629
7630             if (repeat > 0 && repeat <= 255 && bc > 0)
7631               {
7632                 if (bc + repeat - 1 >= *sizeof_buf - 1)
7633                   {
7634                     /* Make some more room in the buffer.  */
7635                     *sizeof_buf += repeat;
7636                     *buf_p = xrealloc (*buf_p, *sizeof_buf);
7637                     buf = *buf_p;
7638                   }
7639
7640                 memset (&buf[bc], buf[bc - 1], repeat);
7641                 bc += repeat;
7642                 continue;
7643               }
7644
7645             buf[bc] = '\0';
7646             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
7647             return -1;
7648           }
7649         default:
7650           if (bc >= *sizeof_buf - 1)
7651             {
7652               /* Make some more room in the buffer.  */
7653               *sizeof_buf *= 2;
7654               *buf_p = xrealloc (*buf_p, *sizeof_buf);
7655               buf = *buf_p;
7656             }
7657
7658           buf[bc++] = c;
7659           csum += c;
7660           continue;
7661         }
7662     }
7663 }
7664
7665 /* Read a packet from the remote machine, with error checking, and
7666    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
7667    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
7668    rather than timing out; this is used (in synchronous mode) to wait
7669    for a target that is is executing user code to stop.  */
7670 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7671    don't have to change all the calls to getpkt to deal with the
7672    return value, because at the moment I don't know what the right
7673    thing to do it for those.  */
7674 void
7675 getpkt (char **buf,
7676         long *sizeof_buf,
7677         int forever)
7678 {
7679   int timed_out;
7680
7681   timed_out = getpkt_sane (buf, sizeof_buf, forever);
7682 }
7683
7684
7685 /* Read a packet from the remote machine, with error checking, and
7686    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
7687    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
7688    rather than timing out; this is used (in synchronous mode) to wait
7689    for a target that is is executing user code to stop.  If FOREVER ==
7690    0, this function is allowed to time out gracefully and return an
7691    indication of this to the caller.  Otherwise return the number of
7692    bytes read.  If EXPECTING_NOTIF, consider receiving a notification
7693    enough reason to return to the caller.  *IS_NOTIF is an output
7694    boolean that indicates whether *BUF holds a notification or not
7695    (a regular packet).  */
7696
7697 static int
7698 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
7699                         int expecting_notif, int *is_notif)
7700 {
7701   struct remote_state *rs = get_remote_state ();
7702   int c;
7703   int tries;
7704   int timeout;
7705   int val = -1;
7706
7707   /* We're reading a new response.  Make sure we don't look at a
7708      previously cached response.  */
7709   rs->cached_wait_status = 0;
7710
7711   strcpy (*buf, "timeout");
7712
7713   if (forever)
7714     timeout = watchdog > 0 ? watchdog : -1;
7715   else if (expecting_notif)
7716     timeout = 0; /* There should already be a char in the buffer.  If
7717                     not, bail out.  */
7718   else
7719     timeout = remote_timeout;
7720
7721 #define MAX_TRIES 3
7722
7723   /* Process any number of notifications, and then return when
7724      we get a packet.  */
7725   for (;;)
7726     {
7727       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
7728          times.  */
7729       for (tries = 1; tries <= MAX_TRIES; tries++)
7730         {
7731           /* This can loop forever if the remote side sends us
7732              characters continuously, but if it pauses, we'll get
7733              SERIAL_TIMEOUT from readchar because of timeout.  Then
7734              we'll count that as a retry.
7735
7736              Note that even when forever is set, we will only wait
7737              forever prior to the start of a packet.  After that, we
7738              expect characters to arrive at a brisk pace.  They should
7739              show up within remote_timeout intervals.  */
7740           do
7741             c = readchar (timeout);
7742           while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
7743
7744           if (c == SERIAL_TIMEOUT)
7745             {
7746               if (expecting_notif)
7747                 return -1; /* Don't complain, it's normal to not get
7748                               anything in this case.  */
7749
7750               if (forever)      /* Watchdog went off?  Kill the target.  */
7751                 {
7752                   QUIT;
7753                   remote_unpush_target ();
7754                   throw_error (TARGET_CLOSE_ERROR,
7755                                _("Watchdog timeout has expired.  "
7756                                  "Target detached."));
7757                 }
7758               if (remote_debug)
7759                 fputs_filtered ("Timed out.\n", gdb_stdlog);
7760             }
7761           else
7762             {
7763               /* We've found the start of a packet or notification.
7764                  Now collect the data.  */
7765               val = read_frame (buf, sizeof_buf);
7766               if (val >= 0)
7767                 break;
7768             }
7769
7770           remote_serial_write ("-", 1);
7771         }
7772
7773       if (tries > MAX_TRIES)
7774         {
7775           /* We have tried hard enough, and just can't receive the
7776              packet/notification.  Give up.  */
7777           printf_unfiltered (_("Ignoring packet error, continuing...\n"));
7778
7779           /* Skip the ack char if we're in no-ack mode.  */
7780           if (!rs->noack_mode)
7781             remote_serial_write ("+", 1);
7782           return -1;
7783         }
7784
7785       /* If we got an ordinary packet, return that to our caller.  */
7786       if (c == '$')
7787         {
7788           if (remote_debug)
7789             {
7790              struct cleanup *old_chain;
7791              char *str;
7792
7793              str = escape_buffer (*buf, val);
7794              old_chain = make_cleanup (xfree, str);
7795              fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7796              do_cleanups (old_chain);
7797             }
7798
7799           /* Skip the ack char if we're in no-ack mode.  */
7800           if (!rs->noack_mode)
7801             remote_serial_write ("+", 1);
7802           if (is_notif != NULL)
7803             *is_notif = 0;
7804           return val;
7805         }
7806
7807        /* If we got a notification, handle it, and go back to looking
7808          for a packet.  */
7809       else
7810         {
7811           gdb_assert (c == '%');
7812
7813           if (remote_debug)
7814             {
7815               struct cleanup *old_chain;
7816               char *str;
7817
7818               str = escape_buffer (*buf, val);
7819               old_chain = make_cleanup (xfree, str);
7820               fprintf_unfiltered (gdb_stdlog,
7821                                   "  Notification received: %s\n",
7822                                   str);
7823               do_cleanups (old_chain);
7824             }
7825           if (is_notif != NULL)
7826             *is_notif = 1;
7827
7828           handle_notification (rs->notif_state, *buf);
7829
7830           /* Notifications require no acknowledgement.  */
7831
7832           if (expecting_notif)
7833             return val;
7834         }
7835     }
7836 }
7837
7838 static int
7839 getpkt_sane (char **buf, long *sizeof_buf, int forever)
7840 {
7841   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
7842 }
7843
7844 static int
7845 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
7846                       int *is_notif)
7847 {
7848   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
7849                                  is_notif);
7850 }
7851
7852 \f
7853 static void
7854 remote_kill (struct target_ops *ops)
7855 {
7856
7857   /* Catch errors so the user can quit from gdb even when we
7858      aren't on speaking terms with the remote system.  */
7859   TRY
7860     {
7861       putpkt ("k");
7862     }
7863   CATCH (ex, RETURN_MASK_ERROR)
7864     {
7865       if (ex.error == TARGET_CLOSE_ERROR)
7866         {
7867           /* If we got an (EOF) error that caused the target
7868              to go away, then we're done, that's what we wanted.
7869              "k" is susceptible to cause a premature EOF, given
7870              that the remote server isn't actually required to
7871              reply to "k", and it can happen that it doesn't
7872              even get to reply ACK to the "k".  */
7873           return;
7874         }
7875
7876         /* Otherwise, something went wrong.  We didn't actually kill
7877            the target.  Just propagate the exception, and let the
7878            user or higher layers decide what to do.  */
7879         throw_exception (ex);
7880     }
7881   END_CATCH
7882
7883   /* We've killed the remote end, we get to mourn it.  Since this is
7884      target remote, single-process, mourning the inferior also
7885      unpushes remote_ops.  */
7886   target_mourn_inferior ();
7887 }
7888
7889 static int
7890 remote_vkill (int pid, struct remote_state *rs)
7891 {
7892   if (packet_support (PACKET_vKill) == PACKET_DISABLE)
7893     return -1;
7894
7895   /* Tell the remote target to detach.  */
7896   xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
7897   putpkt (rs->buf);
7898   getpkt (&rs->buf, &rs->buf_size, 0);
7899
7900   switch (packet_ok (rs->buf,
7901                      &remote_protocol_packets[PACKET_vKill]))
7902     {
7903     case PACKET_OK:
7904       return 0;
7905     case PACKET_ERROR:
7906       return 1;
7907     case PACKET_UNKNOWN:
7908       return -1;
7909     default:
7910       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7911     }
7912 }
7913
7914 static void
7915 extended_remote_kill (struct target_ops *ops)
7916 {
7917   int res;
7918   int pid = ptid_get_pid (inferior_ptid);
7919   struct remote_state *rs = get_remote_state ();
7920
7921   res = remote_vkill (pid, rs);
7922   if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
7923     {
7924       /* Don't try 'k' on a multi-process aware stub -- it has no way
7925          to specify the pid.  */
7926
7927       putpkt ("k");
7928 #if 0
7929       getpkt (&rs->buf, &rs->buf_size, 0);
7930       if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7931         res = 1;
7932 #else
7933       /* Don't wait for it to die.  I'm not really sure it matters whether
7934          we do or not.  For the existing stubs, kill is a noop.  */
7935       res = 0;
7936 #endif
7937     }
7938
7939   if (res != 0)
7940     error (_("Can't kill process"));
7941
7942   target_mourn_inferior ();
7943 }
7944
7945 static void
7946 remote_mourn (struct target_ops *target)
7947 {
7948   unpush_target (target);
7949
7950   /* remote_close takes care of doing most of the clean up.  */
7951   generic_mourn_inferior ();
7952 }
7953
7954 static void
7955 extended_remote_mourn (struct target_ops *target)
7956 {
7957   struct remote_state *rs = get_remote_state ();
7958
7959   /* In case we got here due to an error, but we're going to stay
7960      connected.  */
7961   rs->waiting_for_stop_reply = 0;
7962
7963   /* If the current general thread belonged to the process we just
7964      detached from or has exited, the remote side current general
7965      thread becomes undefined.  Considering a case like this:
7966
7967      - We just got here due to a detach.
7968      - The process that we're detaching from happens to immediately
7969        report a global breakpoint being hit in non-stop mode, in the
7970        same thread we had selected before.
7971      - GDB attaches to this process again.
7972      - This event happens to be the next event we handle.
7973
7974      GDB would consider that the current general thread didn't need to
7975      be set on the stub side (with Hg), since for all it knew,
7976      GENERAL_THREAD hadn't changed.
7977
7978      Notice that although in all-stop mode, the remote server always
7979      sets the current thread to the thread reporting the stop event,
7980      that doesn't happen in non-stop mode; in non-stop, the stub *must
7981      not* change the current thread when reporting a breakpoint hit,
7982      due to the decoupling of event reporting and event handling.
7983
7984      To keep things simple, we always invalidate our notion of the
7985      current thread.  */
7986   record_currthread (rs, minus_one_ptid);
7987
7988   /* Unlike "target remote", we do not want to unpush the target; then
7989      the next time the user says "run", we won't be connected.  */
7990
7991   /* Call common code to mark the inferior as not running.      */
7992   generic_mourn_inferior ();
7993
7994   if (!have_inferiors ())
7995     {
7996       if (!remote_multi_process_p (rs))
7997         {
7998           /* Check whether the target is running now - some remote stubs
7999              automatically restart after kill.  */
8000           putpkt ("?");
8001           getpkt (&rs->buf, &rs->buf_size, 0);
8002
8003           if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8004             {
8005               /* Assume that the target has been restarted.  Set
8006                  inferior_ptid so that bits of core GDB realizes
8007                  there's something here, e.g., so that the user can
8008                  say "kill" again.  */
8009               inferior_ptid = magic_null_ptid;
8010             }
8011         }
8012     }
8013 }
8014
8015 static int
8016 extended_remote_supports_disable_randomization (struct target_ops *self)
8017 {
8018   return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
8019 }
8020
8021 static void
8022 extended_remote_disable_randomization (int val)
8023 {
8024   struct remote_state *rs = get_remote_state ();
8025   char *reply;
8026
8027   xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8028              val);
8029   putpkt (rs->buf);
8030   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8031   if (*reply == '\0')
8032     error (_("Target does not support QDisableRandomization."));
8033   if (strcmp (reply, "OK") != 0)
8034     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8035 }
8036
8037 static int
8038 extended_remote_run (char *args)
8039 {
8040   struct remote_state *rs = get_remote_state ();
8041   int len;
8042
8043   /* If the user has disabled vRun support, or we have detected that
8044      support is not available, do not try it.  */
8045   if (packet_support (PACKET_vRun) == PACKET_DISABLE)
8046     return -1;
8047
8048   strcpy (rs->buf, "vRun;");
8049   len = strlen (rs->buf);
8050
8051   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8052     error (_("Remote file name too long for run packet"));
8053   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8054                       strlen (remote_exec_file));
8055
8056   gdb_assert (args != NULL);
8057   if (*args)
8058     {
8059       struct cleanup *back_to;
8060       int i;
8061       char **argv;
8062
8063       argv = gdb_buildargv (args);
8064       back_to = make_cleanup_freeargv (argv);
8065       for (i = 0; argv[i] != NULL; i++)
8066         {
8067           if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8068             error (_("Argument list too long for run packet"));
8069           rs->buf[len++] = ';';
8070           len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8071                               strlen (argv[i]));
8072         }
8073       do_cleanups (back_to);
8074     }
8075
8076   rs->buf[len++] = '\0';
8077
8078   putpkt (rs->buf);
8079   getpkt (&rs->buf, &rs->buf_size, 0);
8080
8081   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
8082     {
8083     case PACKET_OK:
8084       /* We have a wait response.  All is well.  */
8085       return 0;
8086     case PACKET_UNKNOWN:
8087       return -1;
8088     case PACKET_ERROR:
8089       if (remote_exec_file[0] == '\0')
8090         error (_("Running the default executable on the remote target failed; "
8091                  "try \"set remote exec-file\"?"));
8092       else
8093         error (_("Running \"%s\" on the remote target failed"),
8094                remote_exec_file);
8095     default:
8096       gdb_assert_not_reached (_("bad switch"));
8097     }
8098 }
8099
8100 /* In the extended protocol we want to be able to do things like
8101    "run" and have them basically work as expected.  So we need
8102    a special create_inferior function.  We support changing the
8103    executable file and the command line arguments, but not the
8104    environment.  */
8105
8106 static void
8107 extended_remote_create_inferior (struct target_ops *ops,
8108                                  char *exec_file, char *args,
8109                                  char **env, int from_tty)
8110 {
8111   int run_worked;
8112   char *stop_reply;
8113   struct remote_state *rs = get_remote_state ();
8114
8115   /* If running asynchronously, register the target file descriptor
8116      with the event loop.  */
8117   if (target_can_async_p ())
8118     target_async (1);
8119
8120   /* Disable address space randomization if requested (and supported).  */
8121   if (extended_remote_supports_disable_randomization (ops))
8122     extended_remote_disable_randomization (disable_randomization);
8123
8124   /* Now restart the remote server.  */
8125   run_worked = extended_remote_run (args) != -1;
8126   if (!run_worked)
8127     {
8128       /* vRun was not supported.  Fail if we need it to do what the
8129          user requested.  */
8130       if (remote_exec_file[0])
8131         error (_("Remote target does not support \"set remote exec-file\""));
8132       if (args[0])
8133         error (_("Remote target does not support \"set args\" or run <ARGS>"));
8134
8135       /* Fall back to "R".  */
8136       extended_remote_restart ();
8137     }
8138
8139   if (!have_inferiors ())
8140     {
8141       /* Clean up from the last time we ran, before we mark the target
8142          running again.  This will mark breakpoints uninserted, and
8143          get_offsets may insert breakpoints.  */
8144       init_thread_list ();
8145       init_wait_for_inferior ();
8146     }
8147
8148   /* vRun's success return is a stop reply.  */
8149   stop_reply = run_worked ? rs->buf : NULL;
8150   add_current_inferior_and_thread (stop_reply);
8151
8152   /* Get updated offsets, if the stub uses qOffsets.  */
8153   get_offsets ();
8154 }
8155 \f
8156
8157 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
8158    the list of conditions (in agent expression bytecode format), if any, the
8159    target needs to evaluate.  The output is placed into the packet buffer
8160    started from BUF and ended at BUF_END.  */
8161
8162 static int
8163 remote_add_target_side_condition (struct gdbarch *gdbarch,
8164                                   struct bp_target_info *bp_tgt, char *buf,
8165                                   char *buf_end)
8166 {
8167   struct agent_expr *aexpr = NULL;
8168   int i, ix;
8169   char *pkt;
8170   char *buf_start = buf;
8171
8172   if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8173     return 0;
8174
8175   buf += strlen (buf);
8176   xsnprintf (buf, buf_end - buf, "%s", ";");
8177   buf++;
8178
8179   /* Send conditions to the target and free the vector.  */
8180   for (ix = 0;
8181        VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8182        ix++)
8183     {
8184       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
8185       buf += strlen (buf);
8186       for (i = 0; i < aexpr->len; ++i)
8187         buf = pack_hex_byte (buf, aexpr->buf[i]);
8188       *buf = '\0';
8189     }
8190   return 0;
8191 }
8192
8193 static void
8194 remote_add_target_side_commands (struct gdbarch *gdbarch,
8195                                  struct bp_target_info *bp_tgt, char *buf)
8196 {
8197   struct agent_expr *aexpr = NULL;
8198   int i, ix;
8199
8200   if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8201     return;
8202
8203   buf += strlen (buf);
8204
8205   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8206   buf += strlen (buf);
8207
8208   /* Concatenate all the agent expressions that are commands into the
8209      cmds parameter.  */
8210   for (ix = 0;
8211        VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8212        ix++)
8213     {
8214       sprintf (buf, "X%x,", aexpr->len);
8215       buf += strlen (buf);
8216       for (i = 0; i < aexpr->len; ++i)
8217         buf = pack_hex_byte (buf, aexpr->buf[i]);
8218       *buf = '\0';
8219     }
8220 }
8221
8222 /* Insert a breakpoint.  On targets that have software breakpoint
8223    support, we ask the remote target to do the work; on targets
8224    which don't, we insert a traditional memory breakpoint.  */
8225
8226 static int
8227 remote_insert_breakpoint (struct target_ops *ops,
8228                           struct gdbarch *gdbarch,
8229                           struct bp_target_info *bp_tgt)
8230 {
8231   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8232      If it succeeds, then set the support to PACKET_ENABLE.  If it
8233      fails, and the user has explicitly requested the Z support then
8234      report an error, otherwise, mark it disabled and go on.  */
8235
8236   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8237     {
8238       CORE_ADDR addr = bp_tgt->reqstd_address;
8239       struct remote_state *rs;
8240       char *p, *endbuf;
8241       int bpsize;
8242       struct condition_list *cond = NULL;
8243
8244       /* Make sure the remote is pointing at the right process, if
8245          necessary.  */
8246       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8247         set_general_process ();
8248
8249       gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8250
8251       rs = get_remote_state ();
8252       p = rs->buf;
8253       endbuf = rs->buf + get_remote_packet_size ();
8254
8255       *(p++) = 'Z';
8256       *(p++) = '0';
8257       *(p++) = ',';
8258       addr = (ULONGEST) remote_address_masked (addr);
8259       p += hexnumstr (p, addr);
8260       xsnprintf (p, endbuf - p, ",%d", bpsize);
8261
8262       if (remote_supports_cond_breakpoints (ops))
8263         remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8264
8265       if (remote_can_run_breakpoint_commands (ops))
8266         remote_add_target_side_commands (gdbarch, bp_tgt, p);
8267
8268       putpkt (rs->buf);
8269       getpkt (&rs->buf, &rs->buf_size, 0);
8270
8271       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
8272         {
8273         case PACKET_ERROR:
8274           return -1;
8275         case PACKET_OK:
8276           bp_tgt->placed_address = addr;
8277           bp_tgt->placed_size = bpsize;
8278           return 0;
8279         case PACKET_UNKNOWN:
8280           break;
8281         }
8282     }
8283
8284   /* If this breakpoint has target-side commands but this stub doesn't
8285      support Z0 packets, throw error.  */
8286   if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8287     throw_error (NOT_SUPPORTED_ERROR, _("\
8288 Target doesn't support breakpoints that have target side commands."));
8289
8290   return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
8291 }
8292
8293 static int
8294 remote_remove_breakpoint (struct target_ops *ops,
8295                           struct gdbarch *gdbarch,
8296                           struct bp_target_info *bp_tgt)
8297 {
8298   CORE_ADDR addr = bp_tgt->placed_address;
8299   struct remote_state *rs = get_remote_state ();
8300
8301   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8302     {
8303       char *p = rs->buf;
8304       char *endbuf = rs->buf + get_remote_packet_size ();
8305
8306       /* Make sure the remote is pointing at the right process, if
8307          necessary.  */
8308       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8309         set_general_process ();
8310
8311       *(p++) = 'z';
8312       *(p++) = '0';
8313       *(p++) = ',';
8314
8315       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8316       p += hexnumstr (p, addr);
8317       xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
8318
8319       putpkt (rs->buf);
8320       getpkt (&rs->buf, &rs->buf_size, 0);
8321
8322       return (rs->buf[0] == 'E');
8323     }
8324
8325   return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
8326 }
8327
8328 static int
8329 watchpoint_to_Z_packet (int type)
8330 {
8331   switch (type)
8332     {
8333     case hw_write:
8334       return Z_PACKET_WRITE_WP;
8335       break;
8336     case hw_read:
8337       return Z_PACKET_READ_WP;
8338       break;
8339     case hw_access:
8340       return Z_PACKET_ACCESS_WP;
8341       break;
8342     default:
8343       internal_error (__FILE__, __LINE__,
8344                       _("hw_bp_to_z: bad watchpoint type %d"), type);
8345     }
8346 }
8347
8348 static int
8349 remote_insert_watchpoint (struct target_ops *self,
8350                           CORE_ADDR addr, int len, int type,
8351                           struct expression *cond)
8352 {
8353   struct remote_state *rs = get_remote_state ();
8354   char *endbuf = rs->buf + get_remote_packet_size ();
8355   char *p;
8356   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8357
8358   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8359     return 1;
8360
8361   /* Make sure the remote is pointing at the right process, if
8362      necessary.  */
8363   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8364     set_general_process ();
8365
8366   xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
8367   p = strchr (rs->buf, '\0');
8368   addr = remote_address_masked (addr);
8369   p += hexnumstr (p, (ULONGEST) addr);
8370   xsnprintf (p, endbuf - p, ",%x", len);
8371
8372   putpkt (rs->buf);
8373   getpkt (&rs->buf, &rs->buf_size, 0);
8374
8375   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8376     {
8377     case PACKET_ERROR:
8378       return -1;
8379     case PACKET_UNKNOWN:
8380       return 1;
8381     case PACKET_OK:
8382       return 0;
8383     }
8384   internal_error (__FILE__, __LINE__,
8385                   _("remote_insert_watchpoint: reached end of function"));
8386 }
8387
8388 static int
8389 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8390                                      CORE_ADDR start, int length)
8391 {
8392   CORE_ADDR diff = remote_address_masked (addr - start);
8393
8394   return diff < length;
8395 }
8396
8397
8398 static int
8399 remote_remove_watchpoint (struct target_ops *self,
8400                           CORE_ADDR addr, int len, int type,
8401                           struct expression *cond)
8402 {
8403   struct remote_state *rs = get_remote_state ();
8404   char *endbuf = rs->buf + get_remote_packet_size ();
8405   char *p;
8406   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8407
8408   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8409     return -1;
8410
8411   /* Make sure the remote is pointing at the right process, if
8412      necessary.  */
8413   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8414     set_general_process ();
8415
8416   xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
8417   p = strchr (rs->buf, '\0');
8418   addr = remote_address_masked (addr);
8419   p += hexnumstr (p, (ULONGEST) addr);
8420   xsnprintf (p, endbuf - p, ",%x", len);
8421   putpkt (rs->buf);
8422   getpkt (&rs->buf, &rs->buf_size, 0);
8423
8424   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8425     {
8426     case PACKET_ERROR:
8427     case PACKET_UNKNOWN:
8428       return -1;
8429     case PACKET_OK:
8430       return 0;
8431     }
8432   internal_error (__FILE__, __LINE__,
8433                   _("remote_remove_watchpoint: reached end of function"));
8434 }
8435
8436
8437 int remote_hw_watchpoint_limit = -1;
8438 int remote_hw_watchpoint_length_limit = -1;
8439 int remote_hw_breakpoint_limit = -1;
8440
8441 static int
8442 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8443                                     CORE_ADDR addr, int len)
8444 {
8445   if (remote_hw_watchpoint_length_limit == 0)
8446     return 0;
8447   else if (remote_hw_watchpoint_length_limit < 0)
8448     return 1;
8449   else if (len <= remote_hw_watchpoint_length_limit)
8450     return 1;
8451   else
8452     return 0;
8453 }
8454
8455 static int
8456 remote_check_watch_resources (struct target_ops *self,
8457                               int type, int cnt, int ot)
8458 {
8459   if (type == bp_hardware_breakpoint)
8460     {
8461       if (remote_hw_breakpoint_limit == 0)
8462         return 0;
8463       else if (remote_hw_breakpoint_limit < 0)
8464         return 1;
8465       else if (cnt <= remote_hw_breakpoint_limit)
8466         return 1;
8467     }
8468   else
8469     {
8470       if (remote_hw_watchpoint_limit == 0)
8471         return 0;
8472       else if (remote_hw_watchpoint_limit < 0)
8473         return 1;
8474       else if (ot)
8475         return -1;
8476       else if (cnt <= remote_hw_watchpoint_limit)
8477         return 1;
8478     }
8479   return -1;
8480 }
8481
8482 /* The to_stopped_by_sw_breakpoint method of target remote.  */
8483
8484 static int
8485 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
8486 {
8487   struct remote_state *rs = get_remote_state ();
8488
8489   return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
8490 }
8491
8492 /* The to_supports_stopped_by_sw_breakpoint method of target
8493    remote.  */
8494
8495 static int
8496 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
8497 {
8498   struct remote_state *rs = get_remote_state ();
8499
8500   return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
8501 }
8502
8503 /* The to_stopped_by_hw_breakpoint method of target remote.  */
8504
8505 static int
8506 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
8507 {
8508   struct remote_state *rs = get_remote_state ();
8509
8510   return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
8511 }
8512
8513 /* The to_supports_stopped_by_hw_breakpoint method of target
8514    remote.  */
8515
8516 static int
8517 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
8518 {
8519   struct remote_state *rs = get_remote_state ();
8520
8521   return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
8522 }
8523
8524 static int
8525 remote_stopped_by_watchpoint (struct target_ops *ops)
8526 {
8527   struct remote_state *rs = get_remote_state ();
8528
8529   return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
8530 }
8531
8532 static int
8533 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
8534 {
8535   struct remote_state *rs = get_remote_state ();
8536   int rc = 0;
8537
8538   if (remote_stopped_by_watchpoint (target))
8539     {
8540       *addr_p = rs->remote_watch_data_address;
8541       rc = 1;
8542     }
8543
8544   return rc;
8545 }
8546
8547
8548 static int
8549 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
8550                              struct bp_target_info *bp_tgt)
8551 {
8552   CORE_ADDR addr = bp_tgt->reqstd_address;
8553   struct remote_state *rs;
8554   char *p, *endbuf;
8555   char *message;
8556   int bpsize;
8557
8558   /* The length field should be set to the size of a breakpoint
8559      instruction, even though we aren't inserting one ourselves.  */
8560
8561   gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8562
8563   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
8564     return -1;
8565
8566   /* Make sure the remote is pointing at the right process, if
8567      necessary.  */
8568   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8569     set_general_process ();
8570
8571   rs = get_remote_state ();
8572   p = rs->buf;
8573   endbuf = rs->buf + get_remote_packet_size ();
8574
8575   *(p++) = 'Z';
8576   *(p++) = '1';
8577   *(p++) = ',';
8578
8579   addr = remote_address_masked (addr);
8580   p += hexnumstr (p, (ULONGEST) addr);
8581   xsnprintf (p, endbuf - p, ",%x", bpsize);
8582
8583   if (remote_supports_cond_breakpoints (self))
8584     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8585
8586   if (remote_can_run_breakpoint_commands (self))
8587     remote_add_target_side_commands (gdbarch, bp_tgt, p);
8588
8589   putpkt (rs->buf);
8590   getpkt (&rs->buf, &rs->buf_size, 0);
8591
8592   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8593     {
8594     case PACKET_ERROR:
8595       if (rs->buf[1] == '.')
8596         {
8597           message = strchr (rs->buf + 2, '.');
8598           if (message)
8599             error (_("Remote failure reply: %s"), message + 1);
8600         }
8601       return -1;
8602     case PACKET_UNKNOWN:
8603       return -1;
8604     case PACKET_OK:
8605       bp_tgt->placed_address = addr;
8606       bp_tgt->placed_size = bpsize;
8607       return 0;
8608     }
8609   internal_error (__FILE__, __LINE__,
8610                   _("remote_insert_hw_breakpoint: reached end of function"));
8611 }
8612
8613
8614 static int
8615 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
8616                              struct bp_target_info *bp_tgt)
8617 {
8618   CORE_ADDR addr;
8619   struct remote_state *rs = get_remote_state ();
8620   char *p = rs->buf;
8621   char *endbuf = rs->buf + get_remote_packet_size ();
8622
8623   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
8624     return -1;
8625
8626   /* Make sure the remote is pointing at the right process, if
8627      necessary.  */
8628   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8629     set_general_process ();
8630
8631   *(p++) = 'z';
8632   *(p++) = '1';
8633   *(p++) = ',';
8634
8635   addr = remote_address_masked (bp_tgt->placed_address);
8636   p += hexnumstr (p, (ULONGEST) addr);
8637   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->placed_size);
8638
8639   putpkt (rs->buf);
8640   getpkt (&rs->buf, &rs->buf_size, 0);
8641
8642   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8643     {
8644     case PACKET_ERROR:
8645     case PACKET_UNKNOWN:
8646       return -1;
8647     case PACKET_OK:
8648       return 0;
8649     }
8650   internal_error (__FILE__, __LINE__,
8651                   _("remote_remove_hw_breakpoint: reached end of function"));
8652 }
8653
8654 /* Verify memory using the "qCRC:" request.  */
8655
8656 static int
8657 remote_verify_memory (struct target_ops *ops,
8658                       const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8659 {
8660   struct remote_state *rs = get_remote_state ();
8661   unsigned long host_crc, target_crc;
8662   char *tmp;
8663
8664   /* It doesn't make sense to use qCRC if the remote target is
8665      connected but not running.  */
8666   if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
8667     {
8668       enum packet_result result;
8669
8670       /* Make sure the remote is pointing at the right process.  */
8671       set_general_process ();
8672
8673       /* FIXME: assumes lma can fit into long.  */
8674       xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8675                  (long) lma, (long) size);
8676       putpkt (rs->buf);
8677
8678       /* Be clever; compute the host_crc before waiting for target
8679          reply.  */
8680       host_crc = xcrc32 (data, size, 0xffffffff);
8681
8682       getpkt (&rs->buf, &rs->buf_size, 0);
8683
8684       result = packet_ok (rs->buf,
8685                           &remote_protocol_packets[PACKET_qCRC]);
8686       if (result == PACKET_ERROR)
8687         return -1;
8688       else if (result == PACKET_OK)
8689         {
8690           for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8691             target_crc = target_crc * 16 + fromhex (*tmp);
8692
8693           return (host_crc == target_crc);
8694         }
8695     }
8696
8697   return simple_verify_memory (ops, data, lma, size);
8698 }
8699
8700 /* compare-sections command
8701
8702    With no arguments, compares each loadable section in the exec bfd
8703    with the same memory range on the target, and reports mismatches.
8704    Useful for verifying the image on the target against the exec file.  */
8705
8706 static void
8707 compare_sections_command (char *args, int from_tty)
8708 {
8709   asection *s;
8710   struct cleanup *old_chain;
8711   gdb_byte *sectdata;
8712   const char *sectname;
8713   bfd_size_type size;
8714   bfd_vma lma;
8715   int matched = 0;
8716   int mismatched = 0;
8717   int res;
8718   int read_only = 0;
8719
8720   if (!exec_bfd)
8721     error (_("command cannot be used without an exec file"));
8722
8723   /* Make sure the remote is pointing at the right process.  */
8724   set_general_process ();
8725
8726   if (args != NULL && strcmp (args, "-r") == 0)
8727     {
8728       read_only = 1;
8729       args = NULL;
8730     }
8731
8732   for (s = exec_bfd->sections; s; s = s->next)
8733     {
8734       if (!(s->flags & SEC_LOAD))
8735         continue;               /* Skip non-loadable section.  */
8736
8737       if (read_only && (s->flags & SEC_READONLY) == 0)
8738         continue;               /* Skip writeable sections */
8739
8740       size = bfd_get_section_size (s);
8741       if (size == 0)
8742         continue;               /* Skip zero-length section.  */
8743
8744       sectname = bfd_get_section_name (exec_bfd, s);
8745       if (args && strcmp (args, sectname) != 0)
8746         continue;               /* Not the section selected by user.  */
8747
8748       matched = 1;              /* Do this section.  */
8749       lma = s->lma;
8750
8751       sectdata = xmalloc (size);
8752       old_chain = make_cleanup (xfree, sectdata);
8753       bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
8754
8755       res = target_verify_memory (sectdata, lma, size);
8756
8757       if (res == -1)
8758         error (_("target memory fault, section %s, range %s -- %s"), sectname,
8759                paddress (target_gdbarch (), lma),
8760                paddress (target_gdbarch (), lma + size));
8761
8762       printf_filtered ("Section %s, range %s -- %s: ", sectname,
8763                        paddress (target_gdbarch (), lma),
8764                        paddress (target_gdbarch (), lma + size));
8765       if (res)
8766         printf_filtered ("matched.\n");
8767       else
8768         {
8769           printf_filtered ("MIS-MATCHED!\n");
8770           mismatched++;
8771         }
8772
8773       do_cleanups (old_chain);
8774     }
8775   if (mismatched > 0)
8776     warning (_("One or more sections of the target image does not match\n\
8777 the loaded file\n"));
8778   if (args && !matched)
8779     printf_filtered (_("No loaded section named '%s'.\n"), args);
8780 }
8781
8782 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8783    into remote target.  The number of bytes written to the remote
8784    target is returned, or -1 for error.  */
8785
8786 static enum target_xfer_status
8787 remote_write_qxfer (struct target_ops *ops, const char *object_name,
8788                     const char *annex, const gdb_byte *writebuf, 
8789                     ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
8790                     struct packet_config *packet)
8791 {
8792   int i, buf_len;
8793   ULONGEST n;
8794   struct remote_state *rs = get_remote_state ();
8795   int max_size = get_memory_write_packet_size (); 
8796
8797   if (packet->support == PACKET_DISABLE)
8798     return TARGET_XFER_E_IO;
8799
8800   /* Insert header.  */
8801   i = snprintf (rs->buf, max_size, 
8802                 "qXfer:%s:write:%s:%s:",
8803                 object_name, annex ? annex : "",
8804                 phex_nz (offset, sizeof offset));
8805   max_size -= (i + 1);
8806
8807   /* Escape as much data as fits into rs->buf.  */
8808   buf_len = remote_escape_output 
8809     (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
8810
8811   if (putpkt_binary (rs->buf, i + buf_len) < 0
8812       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8813       || packet_ok (rs->buf, packet) != PACKET_OK)
8814     return TARGET_XFER_E_IO;
8815
8816   unpack_varlen_hex (rs->buf, &n);
8817
8818   *xfered_len = n;
8819   return TARGET_XFER_OK;
8820 }
8821
8822 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8823    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8824    number of bytes read is returned, or 0 for EOF, or -1 for error.
8825    The number of bytes read may be less than LEN without indicating an
8826    EOF.  PACKET is checked and updated to indicate whether the remote
8827    target supports this object.  */
8828
8829 static enum target_xfer_status
8830 remote_read_qxfer (struct target_ops *ops, const char *object_name,
8831                    const char *annex,
8832                    gdb_byte *readbuf, ULONGEST offset, LONGEST len,
8833                    ULONGEST *xfered_len,
8834                    struct packet_config *packet)
8835 {
8836   struct remote_state *rs = get_remote_state ();
8837   LONGEST i, n, packet_len;
8838
8839   if (packet->support == PACKET_DISABLE)
8840     return TARGET_XFER_E_IO;
8841
8842   /* Check whether we've cached an end-of-object packet that matches
8843      this request.  */
8844   if (rs->finished_object)
8845     {
8846       if (strcmp (object_name, rs->finished_object) == 0
8847           && strcmp (annex ? annex : "", rs->finished_annex) == 0
8848           && offset == rs->finished_offset)
8849         return TARGET_XFER_EOF;
8850
8851
8852       /* Otherwise, we're now reading something different.  Discard
8853          the cache.  */
8854       xfree (rs->finished_object);
8855       xfree (rs->finished_annex);
8856       rs->finished_object = NULL;
8857       rs->finished_annex = NULL;
8858     }
8859
8860   /* Request only enough to fit in a single packet.  The actual data
8861      may not, since we don't know how much of it will need to be escaped;
8862      the target is free to respond with slightly less data.  We subtract
8863      five to account for the response type and the protocol frame.  */
8864   n = min (get_remote_packet_size () - 5, len);
8865   snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8866             object_name, annex ? annex : "",
8867             phex_nz (offset, sizeof offset),
8868             phex_nz (n, sizeof n));
8869   i = putpkt (rs->buf);
8870   if (i < 0)
8871     return TARGET_XFER_E_IO;
8872
8873   rs->buf[0] = '\0';
8874   packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8875   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
8876     return TARGET_XFER_E_IO;
8877
8878   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8879     error (_("Unknown remote qXfer reply: %s"), rs->buf);
8880
8881   /* 'm' means there is (or at least might be) more data after this
8882      batch.  That does not make sense unless there's at least one byte
8883      of data in this reply.  */
8884   if (rs->buf[0] == 'm' && packet_len == 1)
8885     error (_("Remote qXfer reply contained no data."));
8886
8887   /* Got some data.  */
8888   i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
8889                              packet_len - 1, readbuf, n);
8890
8891   /* 'l' is an EOF marker, possibly including a final block of data,
8892      or possibly empty.  If we have the final block of a non-empty
8893      object, record this fact to bypass a subsequent partial read.  */
8894   if (rs->buf[0] == 'l' && offset + i > 0)
8895     {
8896       rs->finished_object = xstrdup (object_name);
8897       rs->finished_annex = xstrdup (annex ? annex : "");
8898       rs->finished_offset = offset + i;
8899     }
8900
8901   if (i == 0)
8902     return TARGET_XFER_EOF;
8903   else
8904     {
8905       *xfered_len = i;
8906       return TARGET_XFER_OK;
8907     }
8908 }
8909
8910 static enum target_xfer_status
8911 remote_xfer_partial (struct target_ops *ops, enum target_object object,
8912                      const char *annex, gdb_byte *readbuf,
8913                      const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
8914                      ULONGEST *xfered_len)
8915 {
8916   struct remote_state *rs;
8917   int i;
8918   char *p2;
8919   char query_type;
8920
8921   set_remote_traceframe ();
8922   set_general_thread (inferior_ptid);
8923
8924   rs = get_remote_state ();
8925
8926   /* Handle memory using the standard memory routines.  */
8927   if (object == TARGET_OBJECT_MEMORY)
8928     {
8929       /* If the remote target is connected but not running, we should
8930          pass this request down to a lower stratum (e.g. the executable
8931          file).  */
8932       if (!target_has_execution)
8933         return TARGET_XFER_EOF;
8934
8935       if (writebuf != NULL)
8936         return remote_write_bytes (offset, writebuf, len, xfered_len);
8937       else
8938         return remote_read_bytes (ops, offset, readbuf, len, xfered_len);
8939     }
8940
8941   /* Handle SPU memory using qxfer packets.  */
8942   if (object == TARGET_OBJECT_SPU)
8943     {
8944       if (readbuf)
8945         return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
8946                                   xfered_len, &remote_protocol_packets
8947                                   [PACKET_qXfer_spu_read]);
8948       else
8949         return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
8950                                    xfered_len, &remote_protocol_packets
8951                                    [PACKET_qXfer_spu_write]);
8952     }
8953
8954   /* Handle extra signal info using qxfer packets.  */
8955   if (object == TARGET_OBJECT_SIGNAL_INFO)
8956     {
8957       if (readbuf)
8958         return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
8959                                   xfered_len, &remote_protocol_packets
8960                                   [PACKET_qXfer_siginfo_read]);
8961       else
8962         return remote_write_qxfer (ops, "siginfo", annex,
8963                                    writebuf, offset, len, xfered_len,
8964                                    &remote_protocol_packets
8965                                    [PACKET_qXfer_siginfo_write]);
8966     }
8967
8968   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8969     {
8970       if (readbuf)
8971         return remote_read_qxfer (ops, "statictrace", annex,
8972                                   readbuf, offset, len, xfered_len,
8973                                   &remote_protocol_packets
8974                                   [PACKET_qXfer_statictrace_read]);
8975       else
8976         return TARGET_XFER_E_IO;
8977     }
8978
8979   /* Only handle flash writes.  */
8980   if (writebuf != NULL)
8981     {
8982       LONGEST xfered;
8983
8984       switch (object)
8985         {
8986         case TARGET_OBJECT_FLASH:
8987           return remote_flash_write (ops, offset, len, xfered_len,
8988                                      writebuf);
8989
8990         default:
8991           return TARGET_XFER_E_IO;
8992         }
8993     }
8994
8995   /* Map pre-existing objects onto letters.  DO NOT do this for new
8996      objects!!!  Instead specify new query packets.  */
8997   switch (object)
8998     {
8999     case TARGET_OBJECT_AVR:
9000       query_type = 'R';
9001       break;
9002
9003     case TARGET_OBJECT_AUXV:
9004       gdb_assert (annex == NULL);
9005       return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9006                                 xfered_len,
9007                                 &remote_protocol_packets[PACKET_qXfer_auxv]);
9008
9009     case TARGET_OBJECT_AVAILABLE_FEATURES:
9010       return remote_read_qxfer
9011         (ops, "features", annex, readbuf, offset, len, xfered_len,
9012          &remote_protocol_packets[PACKET_qXfer_features]);
9013
9014     case TARGET_OBJECT_LIBRARIES:
9015       return remote_read_qxfer
9016         (ops, "libraries", annex, readbuf, offset, len, xfered_len,
9017          &remote_protocol_packets[PACKET_qXfer_libraries]);
9018
9019     case TARGET_OBJECT_LIBRARIES_SVR4:
9020       return remote_read_qxfer
9021         (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
9022          &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9023
9024     case TARGET_OBJECT_MEMORY_MAP:
9025       gdb_assert (annex == NULL);
9026       return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9027                                  xfered_len,
9028                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9029
9030     case TARGET_OBJECT_OSDATA:
9031       /* Should only get here if we're connected.  */
9032       gdb_assert (rs->remote_desc);
9033       return remote_read_qxfer
9034         (ops, "osdata", annex, readbuf, offset, len, xfered_len,
9035         &remote_protocol_packets[PACKET_qXfer_osdata]);
9036
9037     case TARGET_OBJECT_THREADS:
9038       gdb_assert (annex == NULL);
9039       return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9040                                 xfered_len,
9041                                 &remote_protocol_packets[PACKET_qXfer_threads]);
9042
9043     case TARGET_OBJECT_TRACEFRAME_INFO:
9044       gdb_assert (annex == NULL);
9045       return remote_read_qxfer
9046         (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
9047          &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
9048
9049     case TARGET_OBJECT_FDPIC:
9050       return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9051                                 xfered_len,
9052                                 &remote_protocol_packets[PACKET_qXfer_fdpic]);
9053
9054     case TARGET_OBJECT_OPENVMS_UIB:
9055       return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9056                                 xfered_len,
9057                                 &remote_protocol_packets[PACKET_qXfer_uib]);
9058
9059     case TARGET_OBJECT_BTRACE:
9060       return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9061                                 xfered_len,
9062         &remote_protocol_packets[PACKET_qXfer_btrace]);
9063
9064     case TARGET_OBJECT_BTRACE_CONF:
9065       return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9066                                 len, xfered_len,
9067         &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9068
9069     case TARGET_OBJECT_EXEC_FILE:
9070       return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
9071                                 len, xfered_len,
9072         &remote_protocol_packets[PACKET_qXfer_exec_file]);
9073
9074     default:
9075       return TARGET_XFER_E_IO;
9076     }
9077
9078   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
9079      large enough let the caller deal with it.  */
9080   if (len < get_remote_packet_size ())
9081     return TARGET_XFER_E_IO;
9082   len = get_remote_packet_size ();
9083
9084   /* Except for querying the minimum buffer size, target must be open.  */
9085   if (!rs->remote_desc)
9086     error (_("remote query is only available after target open"));
9087
9088   gdb_assert (annex != NULL);
9089   gdb_assert (readbuf != NULL);
9090
9091   p2 = rs->buf;
9092   *p2++ = 'q';
9093   *p2++ = query_type;
9094
9095   /* We used one buffer char for the remote protocol q command and
9096      another for the query type.  As the remote protocol encapsulation
9097      uses 4 chars plus one extra in case we are debugging
9098      (remote_debug), we have PBUFZIZ - 7 left to pack the query
9099      string.  */
9100   i = 0;
9101   while (annex[i] && (i < (get_remote_packet_size () - 8)))
9102     {
9103       /* Bad caller may have sent forbidden characters.  */
9104       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9105       *p2++ = annex[i];
9106       i++;
9107     }
9108   *p2 = '\0';
9109   gdb_assert (annex[i] == '\0');
9110
9111   i = putpkt (rs->buf);
9112   if (i < 0)
9113     return TARGET_XFER_E_IO;
9114
9115   getpkt (&rs->buf, &rs->buf_size, 0);
9116   strcpy ((char *) readbuf, rs->buf);
9117
9118   *xfered_len = strlen ((char *) readbuf);
9119   return TARGET_XFER_OK;
9120 }
9121
9122 static int
9123 remote_search_memory (struct target_ops* ops,
9124                       CORE_ADDR start_addr, ULONGEST search_space_len,
9125                       const gdb_byte *pattern, ULONGEST pattern_len,
9126                       CORE_ADDR *found_addrp)
9127 {
9128   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9129   struct remote_state *rs = get_remote_state ();
9130   int max_size = get_memory_write_packet_size ();
9131   struct packet_config *packet =
9132     &remote_protocol_packets[PACKET_qSearch_memory];
9133   /* Number of packet bytes used to encode the pattern;
9134      this could be more than PATTERN_LEN due to escape characters.  */
9135   int escaped_pattern_len;
9136   /* Amount of pattern that was encodable in the packet.  */
9137   int used_pattern_len;
9138   int i;
9139   int found;
9140   ULONGEST found_addr;
9141
9142   /* Don't go to the target if we don't have to.
9143      This is done before checking packet->support to avoid the possibility that
9144      a success for this edge case means the facility works in general.  */
9145   if (pattern_len > search_space_len)
9146     return 0;
9147   if (pattern_len == 0)
9148     {
9149       *found_addrp = start_addr;
9150       return 1;
9151     }
9152
9153   /* If we already know the packet isn't supported, fall back to the simple
9154      way of searching memory.  */
9155
9156   if (packet_config_support (packet) == PACKET_DISABLE)
9157     {
9158       /* Target doesn't provided special support, fall back and use the
9159          standard support (copy memory and do the search here).  */
9160       return simple_search_memory (ops, start_addr, search_space_len,
9161                                    pattern, pattern_len, found_addrp);
9162     }
9163
9164   /* Make sure the remote is pointing at the right process.  */
9165   set_general_process ();
9166
9167   /* Insert header.  */
9168   i = snprintf (rs->buf, max_size, 
9169                 "qSearch:memory:%s;%s;",
9170                 phex_nz (start_addr, addr_size),
9171                 phex_nz (search_space_len, sizeof (search_space_len)));
9172   max_size -= (i + 1);
9173
9174   /* Escape as much data as fits into rs->buf.  */
9175   escaped_pattern_len =
9176     remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
9177                           &used_pattern_len, max_size);
9178
9179   /* Bail if the pattern is too large.  */
9180   if (used_pattern_len != pattern_len)
9181     error (_("Pattern is too large to transmit to remote target."));
9182
9183   if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9184       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9185       || packet_ok (rs->buf, packet) != PACKET_OK)
9186     {
9187       /* The request may not have worked because the command is not
9188          supported.  If so, fall back to the simple way.  */
9189       if (packet->support == PACKET_DISABLE)
9190         {
9191           return simple_search_memory (ops, start_addr, search_space_len,
9192                                        pattern, pattern_len, found_addrp);
9193         }
9194       return -1;
9195     }
9196
9197   if (rs->buf[0] == '0')
9198     found = 0;
9199   else if (rs->buf[0] == '1')
9200     {
9201       found = 1;
9202       if (rs->buf[1] != ',')
9203         error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9204       unpack_varlen_hex (rs->buf + 2, &found_addr);
9205       *found_addrp = found_addr;
9206     }
9207   else
9208     error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9209
9210   return found;
9211 }
9212
9213 static void
9214 remote_rcmd (struct target_ops *self, const char *command,
9215              struct ui_file *outbuf)
9216 {
9217   struct remote_state *rs = get_remote_state ();
9218   char *p = rs->buf;
9219
9220   if (!rs->remote_desc)
9221     error (_("remote rcmd is only available after target open"));
9222
9223   /* Send a NULL command across as an empty command.  */
9224   if (command == NULL)
9225     command = "";
9226
9227   /* The query prefix.  */
9228   strcpy (rs->buf, "qRcmd,");
9229   p = strchr (rs->buf, '\0');
9230
9231   if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9232       > get_remote_packet_size ())
9233     error (_("\"monitor\" command ``%s'' is too long."), command);
9234
9235   /* Encode the actual command.  */
9236   bin2hex ((const gdb_byte *) command, p, strlen (command));
9237
9238   if (putpkt (rs->buf) < 0)
9239     error (_("Communication problem with target."));
9240
9241   /* get/display the response */
9242   while (1)
9243     {
9244       char *buf;
9245
9246       /* XXX - see also remote_get_noisy_reply().  */
9247       QUIT;                     /* Allow user to bail out with ^C.  */
9248       rs->buf[0] = '\0';
9249       if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9250         { 
9251           /* Timeout.  Continue to (try to) read responses.
9252              This is better than stopping with an error, assuming the stub
9253              is still executing the (long) monitor command.
9254              If needed, the user can interrupt gdb using C-c, obtaining
9255              an effect similar to stop on timeout.  */
9256           continue;
9257         }
9258       buf = rs->buf;
9259       if (buf[0] == '\0')
9260         error (_("Target does not support this command."));
9261       if (buf[0] == 'O' && buf[1] != 'K')
9262         {
9263           remote_console_output (buf + 1); /* 'O' message from stub.  */
9264           continue;
9265         }
9266       if (strcmp (buf, "OK") == 0)
9267         break;
9268       if (strlen (buf) == 3 && buf[0] == 'E'
9269           && isdigit (buf[1]) && isdigit (buf[2]))
9270         {
9271           error (_("Protocol error with Rcmd"));
9272         }
9273       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9274         {
9275           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
9276
9277           fputc_unfiltered (c, outbuf);
9278         }
9279       break;
9280     }
9281 }
9282
9283 static VEC(mem_region_s) *
9284 remote_memory_map (struct target_ops *ops)
9285 {
9286   VEC(mem_region_s) *result = NULL;
9287   char *text = target_read_stralloc (&current_target,
9288                                      TARGET_OBJECT_MEMORY_MAP, NULL);
9289
9290   if (text)
9291     {
9292       struct cleanup *back_to = make_cleanup (xfree, text);
9293
9294       result = parse_memory_map (text);
9295       do_cleanups (back_to);
9296     }
9297
9298   return result;
9299 }
9300
9301 static void
9302 packet_command (char *args, int from_tty)
9303 {
9304   struct remote_state *rs = get_remote_state ();
9305
9306   if (!rs->remote_desc)
9307     error (_("command can only be used with remote target"));
9308
9309   if (!args)
9310     error (_("remote-packet command requires packet text as argument"));
9311
9312   puts_filtered ("sending: ");
9313   print_packet (args);
9314   puts_filtered ("\n");
9315   putpkt (args);
9316
9317   getpkt (&rs->buf, &rs->buf_size, 0);
9318   puts_filtered ("received: ");
9319   print_packet (rs->buf);
9320   puts_filtered ("\n");
9321 }
9322
9323 #if 0
9324 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
9325
9326 static void display_thread_info (struct gdb_ext_thread_info *info);
9327
9328 static void threadset_test_cmd (char *cmd, int tty);
9329
9330 static void threadalive_test (char *cmd, int tty);
9331
9332 static void threadlist_test_cmd (char *cmd, int tty);
9333
9334 int get_and_display_threadinfo (threadref *ref);
9335
9336 static void threadinfo_test_cmd (char *cmd, int tty);
9337
9338 static int thread_display_step (threadref *ref, void *context);
9339
9340 static void threadlist_update_test_cmd (char *cmd, int tty);
9341
9342 static void init_remote_threadtests (void);
9343
9344 #define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid.  */
9345
9346 static void
9347 threadset_test_cmd (char *cmd, int tty)
9348 {
9349   int sample_thread = SAMPLE_THREAD;
9350
9351   printf_filtered (_("Remote threadset test\n"));
9352   set_general_thread (sample_thread);
9353 }
9354
9355
9356 static void
9357 threadalive_test (char *cmd, int tty)
9358 {
9359   int sample_thread = SAMPLE_THREAD;
9360   int pid = ptid_get_pid (inferior_ptid);
9361   ptid_t ptid = ptid_build (pid, sample_thread, 0);
9362
9363   if (remote_thread_alive (ptid))
9364     printf_filtered ("PASS: Thread alive test\n");
9365   else
9366     printf_filtered ("FAIL: Thread alive test\n");
9367 }
9368
9369 void output_threadid (char *title, threadref *ref);
9370
9371 void
9372 output_threadid (char *title, threadref *ref)
9373 {
9374   char hexid[20];
9375
9376   pack_threadid (&hexid[0], ref);       /* Convert threead id into hex.  */
9377   hexid[16] = 0;
9378   printf_filtered ("%s  %s\n", title, (&hexid[0]));
9379 }
9380
9381 static void
9382 threadlist_test_cmd (char *cmd, int tty)
9383 {
9384   int startflag = 1;
9385   threadref nextthread;
9386   int done, result_count;
9387   threadref threadlist[3];
9388
9389   printf_filtered ("Remote Threadlist test\n");
9390   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9391                               &result_count, &threadlist[0]))
9392     printf_filtered ("FAIL: threadlist test\n");
9393   else
9394     {
9395       threadref *scan = threadlist;
9396       threadref *limit = scan + result_count;
9397
9398       while (scan < limit)
9399         output_threadid (" thread ", scan++);
9400     }
9401 }
9402
9403 void
9404 display_thread_info (struct gdb_ext_thread_info *info)
9405 {
9406   output_threadid ("Threadid: ", &info->threadid);
9407   printf_filtered ("Name: %s\n ", info->shortname);
9408   printf_filtered ("State: %s\n", info->display);
9409   printf_filtered ("other: %s\n\n", info->more_display);
9410 }
9411
9412 int
9413 get_and_display_threadinfo (threadref *ref)
9414 {
9415   int result;
9416   int set;
9417   struct gdb_ext_thread_info threadinfo;
9418
9419   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9420     | TAG_MOREDISPLAY | TAG_DISPLAY;
9421   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9422     display_thread_info (&threadinfo);
9423   return result;
9424 }
9425
9426 static void
9427 threadinfo_test_cmd (char *cmd, int tty)
9428 {
9429   int athread = SAMPLE_THREAD;
9430   threadref thread;
9431   int set;
9432
9433   int_to_threadref (&thread, athread);
9434   printf_filtered ("Remote Threadinfo test\n");
9435   if (!get_and_display_threadinfo (&thread))
9436     printf_filtered ("FAIL cannot get thread info\n");
9437 }
9438
9439 static int
9440 thread_display_step (threadref *ref, void *context)
9441 {
9442   /* output_threadid(" threadstep ",ref); *//* simple test */
9443   return get_and_display_threadinfo (ref);
9444 }
9445
9446 static void
9447 threadlist_update_test_cmd (char *cmd, int tty)
9448 {
9449   printf_filtered ("Remote Threadlist update test\n");
9450   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9451 }
9452
9453 static void
9454 init_remote_threadtests (void)
9455 {
9456   add_com ("tlist", class_obscure, threadlist_test_cmd,
9457            _("Fetch and print the remote list of "
9458              "thread identifiers, one pkt only"));
9459   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
9460            _("Fetch and display info about one thread"));
9461   add_com ("tset", class_obscure, threadset_test_cmd,
9462            _("Test setting to a different thread"));
9463   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
9464            _("Iterate through updating all remote thread info"));
9465   add_com ("talive", class_obscure, threadalive_test,
9466            _(" Remote thread alive test "));
9467 }
9468
9469 #endif /* 0 */
9470
9471 /* Convert a thread ID to a string.  Returns the string in a static
9472    buffer.  */
9473
9474 static char *
9475 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
9476 {
9477   static char buf[64];
9478   struct remote_state *rs = get_remote_state ();
9479
9480   if (ptid_equal (ptid, null_ptid))
9481     return normal_pid_to_str (ptid);
9482   else if (ptid_is_pid (ptid))
9483     {
9484       /* Printing an inferior target id.  */
9485
9486       /* When multi-process extensions are off, there's no way in the
9487          remote protocol to know the remote process id, if there's any
9488          at all.  There's one exception --- when we're connected with
9489          target extended-remote, and we manually attached to a process
9490          with "attach PID".  We don't record anywhere a flag that
9491          allows us to distinguish that case from the case of
9492          connecting with extended-remote and the stub already being
9493          attached to a process, and reporting yes to qAttached, hence
9494          no smart special casing here.  */
9495       if (!remote_multi_process_p (rs))
9496         {
9497           xsnprintf (buf, sizeof buf, "Remote target");
9498           return buf;
9499         }
9500
9501       return normal_pid_to_str (ptid);
9502     }
9503   else
9504     {
9505       if (ptid_equal (magic_null_ptid, ptid))
9506         xsnprintf (buf, sizeof buf, "Thread <main>");
9507       else if (rs->extended && remote_multi_process_p (rs))
9508         xsnprintf (buf, sizeof buf, "Thread %d.%ld",
9509                    ptid_get_pid (ptid), ptid_get_lwp (ptid));
9510       else
9511         xsnprintf (buf, sizeof buf, "Thread %ld",
9512                    ptid_get_lwp (ptid));
9513       return buf;
9514     }
9515 }
9516
9517 /* Get the address of the thread local variable in OBJFILE which is
9518    stored at OFFSET within the thread local storage for thread PTID.  */
9519
9520 static CORE_ADDR
9521 remote_get_thread_local_address (struct target_ops *ops,
9522                                  ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
9523 {
9524   if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
9525     {
9526       struct remote_state *rs = get_remote_state ();
9527       char *p = rs->buf;
9528       char *endp = rs->buf + get_remote_packet_size ();
9529       enum packet_result result;
9530
9531       strcpy (p, "qGetTLSAddr:");
9532       p += strlen (p);
9533       p = write_ptid (p, endp, ptid);
9534       *p++ = ',';
9535       p += hexnumstr (p, offset);
9536       *p++ = ',';
9537       p += hexnumstr (p, lm);
9538       *p++ = '\0';
9539
9540       putpkt (rs->buf);
9541       getpkt (&rs->buf, &rs->buf_size, 0);
9542       result = packet_ok (rs->buf,
9543                           &remote_protocol_packets[PACKET_qGetTLSAddr]);
9544       if (result == PACKET_OK)
9545         {
9546           ULONGEST result;
9547
9548           unpack_varlen_hex (rs->buf, &result);
9549           return result;
9550         }
9551       else if (result == PACKET_UNKNOWN)
9552         throw_error (TLS_GENERIC_ERROR,
9553                      _("Remote target doesn't support qGetTLSAddr packet"));
9554       else
9555         throw_error (TLS_GENERIC_ERROR,
9556                      _("Remote target failed to process qGetTLSAddr request"));
9557     }
9558   else
9559     throw_error (TLS_GENERIC_ERROR,
9560                  _("TLS not supported or disabled on this target"));
9561   /* Not reached.  */
9562   return 0;
9563 }
9564
9565 /* Provide thread local base, i.e. Thread Information Block address.
9566    Returns 1 if ptid is found and thread_local_base is non zero.  */
9567
9568 static int
9569 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
9570 {
9571   if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
9572     {
9573       struct remote_state *rs = get_remote_state ();
9574       char *p = rs->buf;
9575       char *endp = rs->buf + get_remote_packet_size ();
9576       enum packet_result result;
9577
9578       strcpy (p, "qGetTIBAddr:");
9579       p += strlen (p);
9580       p = write_ptid (p, endp, ptid);
9581       *p++ = '\0';
9582
9583       putpkt (rs->buf);
9584       getpkt (&rs->buf, &rs->buf_size, 0);
9585       result = packet_ok (rs->buf,
9586                           &remote_protocol_packets[PACKET_qGetTIBAddr]);
9587       if (result == PACKET_OK)
9588         {
9589           ULONGEST result;
9590
9591           unpack_varlen_hex (rs->buf, &result);
9592           if (addr)
9593             *addr = (CORE_ADDR) result;
9594           return 1;
9595         }
9596       else if (result == PACKET_UNKNOWN)
9597         error (_("Remote target doesn't support qGetTIBAddr packet"));
9598       else
9599         error (_("Remote target failed to process qGetTIBAddr request"));
9600     }
9601   else
9602     error (_("qGetTIBAddr not supported or disabled on this target"));
9603   /* Not reached.  */
9604   return 0;
9605 }
9606
9607 /* Support for inferring a target description based on the current
9608    architecture and the size of a 'g' packet.  While the 'g' packet
9609    can have any size (since optional registers can be left off the
9610    end), some sizes are easily recognizable given knowledge of the
9611    approximate architecture.  */
9612
9613 struct remote_g_packet_guess
9614 {
9615   int bytes;
9616   const struct target_desc *tdesc;
9617 };
9618 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9619 DEF_VEC_O(remote_g_packet_guess_s);
9620
9621 struct remote_g_packet_data
9622 {
9623   VEC(remote_g_packet_guess_s) *guesses;
9624 };
9625
9626 static struct gdbarch_data *remote_g_packet_data_handle;
9627
9628 static void *
9629 remote_g_packet_data_init (struct obstack *obstack)
9630 {
9631   return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9632 }
9633
9634 void
9635 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9636                                 const struct target_desc *tdesc)
9637 {
9638   struct remote_g_packet_data *data
9639     = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9640   struct remote_g_packet_guess new_guess, *guess;
9641   int ix;
9642
9643   gdb_assert (tdesc != NULL);
9644
9645   for (ix = 0;
9646        VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9647        ix++)
9648     if (guess->bytes == bytes)
9649       internal_error (__FILE__, __LINE__,
9650                       _("Duplicate g packet description added for size %d"),
9651                       bytes);
9652
9653   new_guess.bytes = bytes;
9654   new_guess.tdesc = tdesc;
9655   VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9656 }
9657
9658 /* Return 1 if remote_read_description would do anything on this target
9659    and architecture, 0 otherwise.  */
9660
9661 static int
9662 remote_read_description_p (struct target_ops *target)
9663 {
9664   struct remote_g_packet_data *data
9665     = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9666
9667   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9668     return 1;
9669
9670   return 0;
9671 }
9672
9673 static const struct target_desc *
9674 remote_read_description (struct target_ops *target)
9675 {
9676   struct remote_g_packet_data *data
9677     = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9678
9679   /* Do not try this during initial connection, when we do not know
9680      whether there is a running but stopped thread.  */
9681   if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
9682     return target->beneath->to_read_description (target->beneath);
9683
9684   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9685     {
9686       struct remote_g_packet_guess *guess;
9687       int ix;
9688       int bytes = send_g_packet ();
9689
9690       for (ix = 0;
9691            VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9692            ix++)
9693         if (guess->bytes == bytes)
9694           return guess->tdesc;
9695
9696       /* We discard the g packet.  A minor optimization would be to
9697          hold on to it, and fill the register cache once we have selected
9698          an architecture, but it's too tricky to do safely.  */
9699     }
9700
9701   return target->beneath->to_read_description (target->beneath);
9702 }
9703
9704 /* Remote file transfer support.  This is host-initiated I/O, not
9705    target-initiated; for target-initiated, see remote-fileio.c.  */
9706
9707 /* If *LEFT is at least the length of STRING, copy STRING to
9708    *BUFFER, update *BUFFER to point to the new end of the buffer, and
9709    decrease *LEFT.  Otherwise raise an error.  */
9710
9711 static void
9712 remote_buffer_add_string (char **buffer, int *left, char *string)
9713 {
9714   int len = strlen (string);
9715
9716   if (len > *left)
9717     error (_("Packet too long for target."));
9718
9719   memcpy (*buffer, string, len);
9720   *buffer += len;
9721   *left -= len;
9722
9723   /* NUL-terminate the buffer as a convenience, if there is
9724      room.  */
9725   if (*left)
9726     **buffer = '\0';
9727 }
9728
9729 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9730    *BUFFER, update *BUFFER to point to the new end of the buffer, and
9731    decrease *LEFT.  Otherwise raise an error.  */
9732
9733 static void
9734 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9735                          int len)
9736 {
9737   if (2 * len > *left)
9738     error (_("Packet too long for target."));
9739
9740   bin2hex (bytes, *buffer, len);
9741   *buffer += 2 * len;
9742   *left -= 2 * len;
9743
9744   /* NUL-terminate the buffer as a convenience, if there is
9745      room.  */
9746   if (*left)
9747     **buffer = '\0';
9748 }
9749
9750 /* If *LEFT is large enough, convert VALUE to hex and add it to
9751    *BUFFER, update *BUFFER to point to the new end of the buffer, and
9752    decrease *LEFT.  Otherwise raise an error.  */
9753
9754 static void
9755 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9756 {
9757   int len = hexnumlen (value);
9758
9759   if (len > *left)
9760     error (_("Packet too long for target."));
9761
9762   hexnumstr (*buffer, value);
9763   *buffer += len;
9764   *left -= len;
9765
9766   /* NUL-terminate the buffer as a convenience, if there is
9767      room.  */
9768   if (*left)
9769     **buffer = '\0';
9770 }
9771
9772 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
9773    value, *REMOTE_ERRNO to the remote error number or zero if none
9774    was included, and *ATTACHMENT to point to the start of the annex
9775    if any.  The length of the packet isn't needed here; there may
9776    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9777
9778    Return 0 if the packet could be parsed, -1 if it could not.  If
9779    -1 is returned, the other variables may not be initialized.  */
9780
9781 static int
9782 remote_hostio_parse_result (char *buffer, int *retcode,
9783                             int *remote_errno, char **attachment)
9784 {
9785   char *p, *p2;
9786
9787   *remote_errno = 0;
9788   *attachment = NULL;
9789
9790   if (buffer[0] != 'F')
9791     return -1;
9792
9793   errno = 0;
9794   *retcode = strtol (&buffer[1], &p, 16);
9795   if (errno != 0 || p == &buffer[1])
9796     return -1;
9797
9798   /* Check for ",errno".  */
9799   if (*p == ',')
9800     {
9801       errno = 0;
9802       *remote_errno = strtol (p + 1, &p2, 16);
9803       if (errno != 0 || p + 1 == p2)
9804         return -1;
9805       p = p2;
9806     }
9807
9808   /* Check for ";attachment".  If there is no attachment, the
9809      packet should end here.  */
9810   if (*p == ';')
9811     {
9812       *attachment = p + 1;
9813       return 0;
9814     }
9815   else if (*p == '\0')
9816     return 0;
9817   else
9818     return -1;
9819 }
9820
9821 /* Send a prepared I/O packet to the target and read its response.
9822    The prepared packet is in the global RS->BUF before this function
9823    is called, and the answer is there when we return.
9824
9825    COMMAND_BYTES is the length of the request to send, which may include
9826    binary data.  WHICH_PACKET is the packet configuration to check
9827    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
9828    is set to the error number and -1 is returned.  Otherwise the value
9829    returned by the function is returned.
9830
9831    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9832    attachment is expected; an error will be reported if there's a
9833    mismatch.  If one is found, *ATTACHMENT will be set to point into
9834    the packet buffer and *ATTACHMENT_LEN will be set to the
9835    attachment's length.  */
9836
9837 static int
9838 remote_hostio_send_command (int command_bytes, int which_packet,
9839                             int *remote_errno, char **attachment,
9840                             int *attachment_len)
9841 {
9842   struct remote_state *rs = get_remote_state ();
9843   int ret, bytes_read;
9844   char *attachment_tmp;
9845
9846   if (!rs->remote_desc
9847       || packet_support (which_packet) == PACKET_DISABLE)
9848     {
9849       *remote_errno = FILEIO_ENOSYS;
9850       return -1;
9851     }
9852
9853   putpkt_binary (rs->buf, command_bytes);
9854   bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9855
9856   /* If it timed out, something is wrong.  Don't try to parse the
9857      buffer.  */
9858   if (bytes_read < 0)
9859     {
9860       *remote_errno = FILEIO_EINVAL;
9861       return -1;
9862     }
9863
9864   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9865     {
9866     case PACKET_ERROR:
9867       *remote_errno = FILEIO_EINVAL;
9868       return -1;
9869     case PACKET_UNKNOWN:
9870       *remote_errno = FILEIO_ENOSYS;
9871       return -1;
9872     case PACKET_OK:
9873       break;
9874     }
9875
9876   if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9877                                   &attachment_tmp))
9878     {
9879       *remote_errno = FILEIO_EINVAL;
9880       return -1;
9881     }
9882
9883   /* Make sure we saw an attachment if and only if we expected one.  */
9884   if ((attachment_tmp == NULL && attachment != NULL)
9885       || (attachment_tmp != NULL && attachment == NULL))
9886     {
9887       *remote_errno = FILEIO_EINVAL;
9888       return -1;
9889     }
9890
9891   /* If an attachment was found, it must point into the packet buffer;
9892      work out how many bytes there were.  */
9893   if (attachment_tmp != NULL)
9894     {
9895       *attachment = attachment_tmp;
9896       *attachment_len = bytes_read - (*attachment - rs->buf);
9897     }
9898
9899   return ret;
9900 }
9901
9902 /* Return nonzero if the filesystem accessed by the target_fileio_*
9903    methods is the local filesystem, zero otherwise.  */
9904
9905 static int
9906 remote_filesystem_is_local (struct target_ops *self)
9907 {
9908   return 0;
9909 }
9910
9911 /* Open FILENAME on the remote target, using FLAGS and MODE.  Return a
9912    remote file descriptor, or -1 if an error occurs (and set
9913    *REMOTE_ERRNO).  */
9914
9915 static int
9916 remote_hostio_open (struct target_ops *self,
9917                     const char *filename, int flags, int mode,
9918                     int *remote_errno)
9919 {
9920   struct remote_state *rs = get_remote_state ();
9921   char *p = rs->buf;
9922   int left = get_remote_packet_size () - 1;
9923
9924   remote_buffer_add_string (&p, &left, "vFile:open:");
9925
9926   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9927                            strlen (filename));
9928   remote_buffer_add_string (&p, &left, ",");
9929
9930   remote_buffer_add_int (&p, &left, flags);
9931   remote_buffer_add_string (&p, &left, ",");
9932
9933   remote_buffer_add_int (&p, &left, mode);
9934
9935   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9936                                      remote_errno, NULL, NULL);
9937 }
9938
9939 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9940    Return the number of bytes written, or -1 if an error occurs (and
9941    set *REMOTE_ERRNO).  */
9942
9943 static int
9944 remote_hostio_pwrite (struct target_ops *self,
9945                       int fd, const gdb_byte *write_buf, int len,
9946                       ULONGEST offset, int *remote_errno)
9947 {
9948   struct remote_state *rs = get_remote_state ();
9949   char *p = rs->buf;
9950   int left = get_remote_packet_size ();
9951   int out_len;
9952
9953   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9954
9955   remote_buffer_add_int (&p, &left, fd);
9956   remote_buffer_add_string (&p, &left, ",");
9957
9958   remote_buffer_add_int (&p, &left, offset);
9959   remote_buffer_add_string (&p, &left, ",");
9960
9961   p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
9962                              get_remote_packet_size () - (p - rs->buf));
9963
9964   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9965                                      remote_errno, NULL, NULL);
9966 }
9967
9968 /* Read up to LEN bytes FD on the remote target into READ_BUF
9969    Return the number of bytes read, or -1 if an error occurs (and
9970    set *REMOTE_ERRNO).  */
9971
9972 static int
9973 remote_hostio_pread (struct target_ops *self,
9974                      int fd, gdb_byte *read_buf, int len,
9975                      ULONGEST offset, int *remote_errno)
9976 {
9977   struct remote_state *rs = get_remote_state ();
9978   char *p = rs->buf;
9979   char *attachment;
9980   int left = get_remote_packet_size ();
9981   int ret, attachment_len;
9982   int read_len;
9983
9984   remote_buffer_add_string (&p, &left, "vFile:pread:");
9985
9986   remote_buffer_add_int (&p, &left, fd);
9987   remote_buffer_add_string (&p, &left, ",");
9988
9989   remote_buffer_add_int (&p, &left, len);
9990   remote_buffer_add_string (&p, &left, ",");
9991
9992   remote_buffer_add_int (&p, &left, offset);
9993
9994   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9995                                     remote_errno, &attachment,
9996                                     &attachment_len);
9997
9998   if (ret < 0)
9999     return ret;
10000
10001   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10002                                     read_buf, len);
10003   if (read_len != ret)
10004     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
10005
10006   return ret;
10007 }
10008
10009 /* Close FD on the remote target.  Return 0, or -1 if an error occurs
10010    (and set *REMOTE_ERRNO).  */
10011
10012 static int
10013 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
10014 {
10015   struct remote_state *rs = get_remote_state ();
10016   char *p = rs->buf;
10017   int left = get_remote_packet_size () - 1;
10018
10019   remote_buffer_add_string (&p, &left, "vFile:close:");
10020
10021   remote_buffer_add_int (&p, &left, fd);
10022
10023   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
10024                                      remote_errno, NULL, NULL);
10025 }
10026
10027 /* Unlink FILENAME on the remote target.  Return 0, or -1 if an error
10028    occurs (and set *REMOTE_ERRNO).  */
10029
10030 static int
10031 remote_hostio_unlink (struct target_ops *self,
10032                       const char *filename, int *remote_errno)
10033 {
10034   struct remote_state *rs = get_remote_state ();
10035   char *p = rs->buf;
10036   int left = get_remote_packet_size () - 1;
10037
10038   remote_buffer_add_string (&p, &left, "vFile:unlink:");
10039
10040   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10041                            strlen (filename));
10042
10043   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10044                                      remote_errno, NULL, NULL);
10045 }
10046
10047 /* Read value of symbolic link FILENAME on the remote target.  Return
10048    a null-terminated string allocated via xmalloc, or NULL if an error
10049    occurs (and set *REMOTE_ERRNO).  */
10050
10051 static char *
10052 remote_hostio_readlink (struct target_ops *self,
10053                         const char *filename, int *remote_errno)
10054 {
10055   struct remote_state *rs = get_remote_state ();
10056   char *p = rs->buf;
10057   char *attachment;
10058   int left = get_remote_packet_size ();
10059   int len, attachment_len;
10060   int read_len;
10061   char *ret;
10062
10063   remote_buffer_add_string (&p, &left, "vFile:readlink:");
10064
10065   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10066                            strlen (filename));
10067
10068   len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10069                                     remote_errno, &attachment,
10070                                     &attachment_len);
10071
10072   if (len < 0)
10073     return NULL;
10074
10075   ret = xmalloc (len + 1);
10076
10077   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10078                                     (gdb_byte *) ret, len);
10079   if (read_len != len)
10080     error (_("Readlink returned %d, but %d bytes."), len, read_len);
10081
10082   ret[len] = '\0';
10083   return ret;
10084 }
10085
10086 /* Read information about the open file FD on the remote target
10087    into ST.  Return 0 on success, or -1 if an error occurs (and
10088    set *REMOTE_ERRNO).  */
10089
10090 static int
10091 remote_hostio_fstat (struct target_ops *self,
10092                      int fd, struct stat *st,
10093                      int *remote_errno)
10094 {
10095   struct remote_state *rs = get_remote_state ();
10096   char *p = rs->buf;
10097   int left = get_remote_packet_size ();
10098   int attachment_len, ret;
10099   char *attachment;
10100   struct fio_stat fst;
10101   int read_len;
10102
10103   remote_buffer_add_string (&p, &left, "vFile:fstat:");
10104
10105   remote_buffer_add_int (&p, &left, fd);
10106
10107   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
10108                                     remote_errno, &attachment,
10109                                     &attachment_len);
10110   if (ret < 0)
10111     {
10112       if (*remote_errno != FILEIO_ENOSYS)
10113         return ret;
10114
10115       /* Strictly we should return -1, ENOSYS here, but when
10116          "set sysroot remote:" was implemented in August 2008
10117          BFD's need for a stat function was sidestepped with
10118          this hack.  This was not remedied until March 2015
10119          so we retain the previous behavior to avoid breaking
10120          compatibility.
10121
10122          Note that the memset is a March 2015 addition; older
10123          GDBs set st_size *and nothing else* so the structure
10124          would have garbage in all other fields.  This might
10125          break something but retaining the previous behavior
10126          here would be just too wrong.  */
10127
10128       memset (st, 0, sizeof (struct stat));
10129       st->st_size = INT_MAX;
10130       return 0;
10131     }
10132
10133   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10134                                     (gdb_byte *) &fst, sizeof (fst));
10135
10136   if (read_len != ret)
10137     error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
10138
10139   if (read_len != sizeof (fst))
10140     error (_("vFile:fstat returned %d bytes, but expecting %d."),
10141            read_len, (int) sizeof (fst));
10142
10143   remote_fileio_to_host_stat (&fst, st);
10144
10145   return 0;
10146 }
10147
10148 static int
10149 remote_fileio_errno_to_host (int errnum)
10150 {
10151   switch (errnum)
10152     {
10153       case FILEIO_EPERM:
10154         return EPERM;
10155       case FILEIO_ENOENT:
10156         return ENOENT;
10157       case FILEIO_EINTR:
10158         return EINTR;
10159       case FILEIO_EIO:
10160         return EIO;
10161       case FILEIO_EBADF:
10162         return EBADF;
10163       case FILEIO_EACCES:
10164         return EACCES;
10165       case FILEIO_EFAULT:
10166         return EFAULT;
10167       case FILEIO_EBUSY:
10168         return EBUSY;
10169       case FILEIO_EEXIST:
10170         return EEXIST;
10171       case FILEIO_ENODEV:
10172         return ENODEV;
10173       case FILEIO_ENOTDIR:
10174         return ENOTDIR;
10175       case FILEIO_EISDIR:
10176         return EISDIR;
10177       case FILEIO_EINVAL:
10178         return EINVAL;
10179       case FILEIO_ENFILE:
10180         return ENFILE;
10181       case FILEIO_EMFILE:
10182         return EMFILE;
10183       case FILEIO_EFBIG:
10184         return EFBIG;
10185       case FILEIO_ENOSPC:
10186         return ENOSPC;
10187       case FILEIO_ESPIPE:
10188         return ESPIPE;
10189       case FILEIO_EROFS:
10190         return EROFS;
10191       case FILEIO_ENOSYS:
10192         return ENOSYS;
10193       case FILEIO_ENAMETOOLONG:
10194         return ENAMETOOLONG;
10195     }
10196   return -1;
10197 }
10198
10199 static char *
10200 remote_hostio_error (int errnum)
10201 {
10202   int host_error = remote_fileio_errno_to_host (errnum);
10203
10204   if (host_error == -1)
10205     error (_("Unknown remote I/O error %d"), errnum);
10206   else
10207     error (_("Remote I/O error: %s"), safe_strerror (host_error));
10208 }
10209
10210 static void
10211 remote_hostio_close_cleanup (void *opaque)
10212 {
10213   int fd = *(int *) opaque;
10214   int remote_errno;
10215
10216   remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
10217 }
10218
10219 void
10220 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10221 {
10222   struct cleanup *back_to, *close_cleanup;
10223   int retcode, fd, remote_errno, bytes, io_size;
10224   FILE *file;
10225   gdb_byte *buffer;
10226   int bytes_in_buffer;
10227   int saw_eof;
10228   ULONGEST offset;
10229   struct remote_state *rs = get_remote_state ();
10230
10231   if (!rs->remote_desc)
10232     error (_("command can only be used with remote target"));
10233
10234   file = gdb_fopen_cloexec (local_file, "rb");
10235   if (file == NULL)
10236     perror_with_name (local_file);
10237   back_to = make_cleanup_fclose (file);
10238
10239   fd = remote_hostio_open (find_target_at (process_stratum),
10240                            remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
10241                                          | FILEIO_O_TRUNC),
10242                            0700, &remote_errno);
10243   if (fd == -1)
10244     remote_hostio_error (remote_errno);
10245
10246   /* Send up to this many bytes at once.  They won't all fit in the
10247      remote packet limit, so we'll transfer slightly fewer.  */
10248   io_size = get_remote_packet_size ();
10249   buffer = xmalloc (io_size);
10250   make_cleanup (xfree, buffer);
10251
10252   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10253
10254   bytes_in_buffer = 0;
10255   saw_eof = 0;
10256   offset = 0;
10257   while (bytes_in_buffer || !saw_eof)
10258     {
10259       if (!saw_eof)
10260         {
10261           bytes = fread (buffer + bytes_in_buffer, 1,
10262                          io_size - bytes_in_buffer,
10263                          file);
10264           if (bytes == 0)
10265             {
10266               if (ferror (file))
10267                 error (_("Error reading %s."), local_file);
10268               else
10269                 {
10270                   /* EOF.  Unless there is something still in the
10271                      buffer from the last iteration, we are done.  */
10272                   saw_eof = 1;
10273                   if (bytes_in_buffer == 0)
10274                     break;
10275                 }
10276             }
10277         }
10278       else
10279         bytes = 0;
10280
10281       bytes += bytes_in_buffer;
10282       bytes_in_buffer = 0;
10283
10284       retcode = remote_hostio_pwrite (find_target_at (process_stratum),
10285                                       fd, buffer, bytes,
10286                                       offset, &remote_errno);
10287
10288       if (retcode < 0)
10289         remote_hostio_error (remote_errno);
10290       else if (retcode == 0)
10291         error (_("Remote write of %d bytes returned 0!"), bytes);
10292       else if (retcode < bytes)
10293         {
10294           /* Short write.  Save the rest of the read data for the next
10295              write.  */
10296           bytes_in_buffer = bytes - retcode;
10297           memmove (buffer, buffer + retcode, bytes_in_buffer);
10298         }
10299
10300       offset += retcode;
10301     }
10302
10303   discard_cleanups (close_cleanup);
10304   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
10305     remote_hostio_error (remote_errno);
10306
10307   if (from_tty)
10308     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10309   do_cleanups (back_to);
10310 }
10311
10312 void
10313 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10314 {
10315   struct cleanup *back_to, *close_cleanup;
10316   int fd, remote_errno, bytes, io_size;
10317   FILE *file;
10318   gdb_byte *buffer;
10319   ULONGEST offset;
10320   struct remote_state *rs = get_remote_state ();
10321
10322   if (!rs->remote_desc)
10323     error (_("command can only be used with remote target"));
10324
10325   fd = remote_hostio_open (find_target_at (process_stratum),
10326                            remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
10327   if (fd == -1)
10328     remote_hostio_error (remote_errno);
10329
10330   file = gdb_fopen_cloexec (local_file, "wb");
10331   if (file == NULL)
10332     perror_with_name (local_file);
10333   back_to = make_cleanup_fclose (file);
10334
10335   /* Send up to this many bytes at once.  They won't all fit in the
10336      remote packet limit, so we'll transfer slightly fewer.  */
10337   io_size = get_remote_packet_size ();
10338   buffer = xmalloc (io_size);
10339   make_cleanup (xfree, buffer);
10340
10341   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10342
10343   offset = 0;
10344   while (1)
10345     {
10346       bytes = remote_hostio_pread (find_target_at (process_stratum),
10347                                    fd, buffer, io_size, offset, &remote_errno);
10348       if (bytes == 0)
10349         /* Success, but no bytes, means end-of-file.  */
10350         break;
10351       if (bytes == -1)
10352         remote_hostio_error (remote_errno);
10353
10354       offset += bytes;
10355
10356       bytes = fwrite (buffer, 1, bytes, file);
10357       if (bytes == 0)
10358         perror_with_name (local_file);
10359     }
10360
10361   discard_cleanups (close_cleanup);
10362   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
10363     remote_hostio_error (remote_errno);
10364
10365   if (from_tty)
10366     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10367   do_cleanups (back_to);
10368 }
10369
10370 void
10371 remote_file_delete (const char *remote_file, int from_tty)
10372 {
10373   int retcode, remote_errno;
10374   struct remote_state *rs = get_remote_state ();
10375
10376   if (!rs->remote_desc)
10377     error (_("command can only be used with remote target"));
10378
10379   retcode = remote_hostio_unlink (find_target_at (process_stratum),
10380                                   remote_file, &remote_errno);
10381   if (retcode == -1)
10382     remote_hostio_error (remote_errno);
10383
10384   if (from_tty)
10385     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10386 }
10387
10388 static void
10389 remote_put_command (char *args, int from_tty)
10390 {
10391   struct cleanup *back_to;
10392   char **argv;
10393
10394   if (args == NULL)
10395     error_no_arg (_("file to put"));
10396
10397   argv = gdb_buildargv (args);
10398   back_to = make_cleanup_freeargv (argv);
10399   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10400     error (_("Invalid parameters to remote put"));
10401
10402   remote_file_put (argv[0], argv[1], from_tty);
10403
10404   do_cleanups (back_to);
10405 }
10406
10407 static void
10408 remote_get_command (char *args, int from_tty)
10409 {
10410   struct cleanup *back_to;
10411   char **argv;
10412
10413   if (args == NULL)
10414     error_no_arg (_("file to get"));
10415
10416   argv = gdb_buildargv (args);
10417   back_to = make_cleanup_freeargv (argv);
10418   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10419     error (_("Invalid parameters to remote get"));
10420
10421   remote_file_get (argv[0], argv[1], from_tty);
10422
10423   do_cleanups (back_to);
10424 }
10425
10426 static void
10427 remote_delete_command (char *args, int from_tty)
10428 {
10429   struct cleanup *back_to;
10430   char **argv;
10431
10432   if (args == NULL)
10433     error_no_arg (_("file to delete"));
10434
10435   argv = gdb_buildargv (args);
10436   back_to = make_cleanup_freeargv (argv);
10437   if (argv[0] == NULL || argv[1] != NULL)
10438     error (_("Invalid parameters to remote delete"));
10439
10440   remote_file_delete (argv[0], from_tty);
10441
10442   do_cleanups (back_to);
10443 }
10444
10445 static void
10446 remote_command (char *args, int from_tty)
10447 {
10448   help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
10449 }
10450
10451 static int
10452 remote_can_execute_reverse (struct target_ops *self)
10453 {
10454   if (packet_support (PACKET_bs) == PACKET_ENABLE
10455       || packet_support (PACKET_bc) == PACKET_ENABLE)
10456     return 1;
10457   else
10458     return 0;
10459 }
10460
10461 static int
10462 remote_supports_non_stop (struct target_ops *self)
10463 {
10464   return 1;
10465 }
10466
10467 static int
10468 remote_supports_disable_randomization (struct target_ops *self)
10469 {
10470   /* Only supported in extended mode.  */
10471   return 0;
10472 }
10473
10474 static int
10475 remote_supports_multi_process (struct target_ops *self)
10476 {
10477   struct remote_state *rs = get_remote_state ();
10478
10479   /* Only extended-remote handles being attached to multiple
10480      processes, even though plain remote can use the multi-process
10481      thread id extensions, so that GDB knows the target process's
10482      PID.  */
10483   return rs->extended && remote_multi_process_p (rs);
10484 }
10485
10486 static int
10487 remote_supports_cond_tracepoints (void)
10488 {
10489   return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
10490 }
10491
10492 static int
10493 remote_supports_cond_breakpoints (struct target_ops *self)
10494 {
10495   return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
10496 }
10497
10498 static int
10499 remote_supports_fast_tracepoints (void)
10500 {
10501   return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
10502 }
10503
10504 static int
10505 remote_supports_static_tracepoints (void)
10506 {
10507   return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
10508 }
10509
10510 static int
10511 remote_supports_install_in_trace (void)
10512 {
10513   return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
10514 }
10515
10516 static int
10517 remote_supports_enable_disable_tracepoint (struct target_ops *self)
10518 {
10519   return (packet_support (PACKET_EnableDisableTracepoints_feature)
10520           == PACKET_ENABLE);
10521 }
10522
10523 static int
10524 remote_supports_string_tracing (struct target_ops *self)
10525 {
10526   return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
10527 }
10528
10529 static int
10530 remote_can_run_breakpoint_commands (struct target_ops *self)
10531 {
10532   return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
10533 }
10534
10535 static void
10536 remote_trace_init (struct target_ops *self)
10537 {
10538   putpkt ("QTinit");
10539   remote_get_noisy_reply (&target_buf, &target_buf_size);
10540   if (strcmp (target_buf, "OK") != 0)
10541     error (_("Target does not support this command."));
10542 }
10543
10544 static void free_actions_list (char **actions_list);
10545 static void free_actions_list_cleanup_wrapper (void *);
10546 static void
10547 free_actions_list_cleanup_wrapper (void *al)
10548 {
10549   free_actions_list (al);
10550 }
10551
10552 static void
10553 free_actions_list (char **actions_list)
10554 {
10555   int ndx;
10556
10557   if (actions_list == 0)
10558     return;
10559
10560   for (ndx = 0; actions_list[ndx]; ndx++)
10561     xfree (actions_list[ndx]);
10562
10563   xfree (actions_list);
10564 }
10565
10566 /* Recursive routine to walk through command list including loops, and
10567    download packets for each command.  */
10568
10569 static void
10570 remote_download_command_source (int num, ULONGEST addr,
10571                                 struct command_line *cmds)
10572 {
10573   struct remote_state *rs = get_remote_state ();
10574   struct command_line *cmd;
10575
10576   for (cmd = cmds; cmd; cmd = cmd->next)
10577     {
10578       QUIT;     /* Allow user to bail out with ^C.  */
10579       strcpy (rs->buf, "QTDPsrc:");
10580       encode_source_string (num, addr, "cmd", cmd->line,
10581                             rs->buf + strlen (rs->buf),
10582                             rs->buf_size - strlen (rs->buf));
10583       putpkt (rs->buf);
10584       remote_get_noisy_reply (&target_buf, &target_buf_size);
10585       if (strcmp (target_buf, "OK"))
10586         warning (_("Target does not support source download."));
10587
10588       if (cmd->control_type == while_control
10589           || cmd->control_type == while_stepping_control)
10590         {
10591           remote_download_command_source (num, addr, *cmd->body_list);
10592
10593           QUIT; /* Allow user to bail out with ^C.  */
10594           strcpy (rs->buf, "QTDPsrc:");
10595           encode_source_string (num, addr, "cmd", "end",
10596                                 rs->buf + strlen (rs->buf),
10597                                 rs->buf_size - strlen (rs->buf));
10598           putpkt (rs->buf);
10599           remote_get_noisy_reply (&target_buf, &target_buf_size);
10600           if (strcmp (target_buf, "OK"))
10601             warning (_("Target does not support source download."));
10602         }
10603     }
10604 }
10605
10606 static void
10607 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
10608 {
10609 #define BUF_SIZE 2048
10610
10611   CORE_ADDR tpaddr;
10612   char addrbuf[40];
10613   char buf[BUF_SIZE];
10614   char **tdp_actions;
10615   char **stepping_actions;
10616   int ndx;
10617   struct cleanup *old_chain = NULL;
10618   struct agent_expr *aexpr;
10619   struct cleanup *aexpr_chain = NULL;
10620   char *pkt;
10621   struct breakpoint *b = loc->owner;
10622   struct tracepoint *t = (struct tracepoint *) b;
10623
10624   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
10625   old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10626                             tdp_actions);
10627   (void) make_cleanup (free_actions_list_cleanup_wrapper,
10628                        stepping_actions);
10629
10630   tpaddr = loc->address;
10631   sprintf_vma (addrbuf, tpaddr);
10632   xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10633              addrbuf, /* address */
10634              (b->enable_state == bp_enabled ? 'E' : 'D'),
10635              t->step_count, t->pass_count);
10636   /* Fast tracepoints are mostly handled by the target, but we can
10637      tell the target how big of an instruction block should be moved
10638      around.  */
10639   if (b->type == bp_fast_tracepoint)
10640     {
10641       /* Only test for support at download time; we may not know
10642          target capabilities at definition time.  */
10643       if (remote_supports_fast_tracepoints ())
10644         {
10645           int isize;
10646
10647           if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
10648                                                 tpaddr, &isize, NULL))
10649             xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10650                        isize);
10651           else
10652             /* If it passed validation at definition but fails now,
10653                something is very wrong.  */
10654             internal_error (__FILE__, __LINE__,
10655                             _("Fast tracepoint not "
10656                               "valid during download"));
10657         }
10658       else
10659         /* Fast tracepoints are functionally identical to regular
10660            tracepoints, so don't take lack of support as a reason to
10661            give up on the trace run.  */
10662         warning (_("Target does not support fast tracepoints, "
10663                    "downloading %d as regular tracepoint"), b->number);
10664     }
10665   else if (b->type == bp_static_tracepoint)
10666     {
10667       /* Only test for support at download time; we may not know
10668          target capabilities at definition time.  */
10669       if (remote_supports_static_tracepoints ())
10670         {
10671           struct static_tracepoint_marker marker;
10672
10673           if (target_static_tracepoint_marker_at (tpaddr, &marker))
10674             strcat (buf, ":S");
10675           else
10676             error (_("Static tracepoint not valid during download"));
10677         }
10678       else
10679         /* Fast tracepoints are functionally identical to regular
10680            tracepoints, so don't take lack of support as a reason
10681            to give up on the trace run.  */
10682         error (_("Target does not support static tracepoints"));
10683     }
10684   /* If the tracepoint has a conditional, make it into an agent
10685      expression and append to the definition.  */
10686   if (loc->cond)
10687     {
10688       /* Only test support at download time, we may not know target
10689          capabilities at definition time.  */
10690       if (remote_supports_cond_tracepoints ())
10691         {
10692           aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10693           aexpr_chain = make_cleanup_free_agent_expr (aexpr);
10694           xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10695                      aexpr->len);
10696           pkt = buf + strlen (buf);
10697           for (ndx = 0; ndx < aexpr->len; ++ndx)
10698             pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10699           *pkt = '\0';
10700           do_cleanups (aexpr_chain);
10701         }
10702       else
10703         warning (_("Target does not support conditional tracepoints, "
10704                    "ignoring tp %d cond"), b->number);
10705     }
10706
10707   if (b->commands || *default_collect)
10708     strcat (buf, "-");
10709   putpkt (buf);
10710   remote_get_noisy_reply (&target_buf, &target_buf_size);
10711   if (strcmp (target_buf, "OK"))
10712     error (_("Target does not support tracepoints."));
10713
10714   /* do_single_steps (t); */
10715   if (tdp_actions)
10716     {
10717       for (ndx = 0; tdp_actions[ndx]; ndx++)
10718         {
10719           QUIT; /* Allow user to bail out with ^C.  */
10720           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10721                      b->number, addrbuf, /* address */
10722                      tdp_actions[ndx],
10723                      ((tdp_actions[ndx + 1] || stepping_actions)
10724                       ? '-' : 0));
10725           putpkt (buf);
10726           remote_get_noisy_reply (&target_buf,
10727                                   &target_buf_size);
10728           if (strcmp (target_buf, "OK"))
10729             error (_("Error on target while setting tracepoints."));
10730         }
10731     }
10732   if (stepping_actions)
10733     {
10734       for (ndx = 0; stepping_actions[ndx]; ndx++)
10735         {
10736           QUIT; /* Allow user to bail out with ^C.  */
10737           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10738                      b->number, addrbuf, /* address */
10739                      ((ndx == 0) ? "S" : ""),
10740                      stepping_actions[ndx],
10741                      (stepping_actions[ndx + 1] ? "-" : ""));
10742           putpkt (buf);
10743           remote_get_noisy_reply (&target_buf,
10744                                   &target_buf_size);
10745           if (strcmp (target_buf, "OK"))
10746             error (_("Error on target while setting tracepoints."));
10747         }
10748     }
10749
10750   if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
10751     {
10752       if (b->addr_string)
10753         {
10754           strcpy (buf, "QTDPsrc:");
10755           encode_source_string (b->number, loc->address,
10756                                 "at", b->addr_string, buf + strlen (buf),
10757                                 2048 - strlen (buf));
10758
10759           putpkt (buf);
10760           remote_get_noisy_reply (&target_buf, &target_buf_size);
10761           if (strcmp (target_buf, "OK"))
10762             warning (_("Target does not support source download."));
10763         }
10764       if (b->cond_string)
10765         {
10766           strcpy (buf, "QTDPsrc:");
10767           encode_source_string (b->number, loc->address,
10768                                 "cond", b->cond_string, buf + strlen (buf),
10769                                 2048 - strlen (buf));
10770           putpkt (buf);
10771           remote_get_noisy_reply (&target_buf, &target_buf_size);
10772           if (strcmp (target_buf, "OK"))
10773             warning (_("Target does not support source download."));
10774         }
10775       remote_download_command_source (b->number, loc->address,
10776                                       breakpoint_commands (b));
10777     }
10778
10779   do_cleanups (old_chain);
10780 }
10781
10782 static int
10783 remote_can_download_tracepoint (struct target_ops *self)
10784 {
10785   struct remote_state *rs = get_remote_state ();
10786   struct trace_status *ts;
10787   int status;
10788
10789   /* Don't try to install tracepoints until we've relocated our
10790      symbols, and fetched and merged the target's tracepoint list with
10791      ours.  */
10792   if (rs->starting_up)
10793     return 0;
10794
10795   ts = current_trace_status ();
10796   status = remote_get_trace_status (self, ts);
10797
10798   if (status == -1 || !ts->running_known || !ts->running)
10799     return 0;
10800
10801   /* If we are in a tracing experiment, but remote stub doesn't support
10802      installing tracepoint in trace, we have to return.  */
10803   if (!remote_supports_install_in_trace ())
10804     return 0;
10805
10806   return 1;
10807 }
10808
10809
10810 static void
10811 remote_download_trace_state_variable (struct target_ops *self,
10812                                       struct trace_state_variable *tsv)
10813 {
10814   struct remote_state *rs = get_remote_state ();
10815   char *p;
10816
10817   xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10818              tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10819              tsv->builtin);
10820   p = rs->buf + strlen (rs->buf);
10821   if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10822     error (_("Trace state variable name too long for tsv definition packet"));
10823   p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
10824   *p++ = '\0';
10825   putpkt (rs->buf);
10826   remote_get_noisy_reply (&target_buf, &target_buf_size);
10827   if (*target_buf == '\0')
10828     error (_("Target does not support this command."));
10829   if (strcmp (target_buf, "OK") != 0)
10830     error (_("Error on target while downloading trace state variable."));
10831 }
10832
10833 static void
10834 remote_enable_tracepoint (struct target_ops *self,
10835                           struct bp_location *location)
10836 {
10837   struct remote_state *rs = get_remote_state ();
10838   char addr_buf[40];
10839
10840   sprintf_vma (addr_buf, location->address);
10841   xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
10842              location->owner->number, addr_buf);
10843   putpkt (rs->buf);
10844   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10845   if (*rs->buf == '\0')
10846     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10847   if (strcmp (rs->buf, "OK") != 0)
10848     error (_("Error on target while enabling tracepoint."));
10849 }
10850
10851 static void
10852 remote_disable_tracepoint (struct target_ops *self,
10853                            struct bp_location *location)
10854 {
10855   struct remote_state *rs = get_remote_state ();
10856   char addr_buf[40];
10857
10858   sprintf_vma (addr_buf, location->address);
10859   xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10860              location->owner->number, addr_buf);
10861   putpkt (rs->buf);
10862   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10863   if (*rs->buf == '\0')
10864     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10865   if (strcmp (rs->buf, "OK") != 0)
10866     error (_("Error on target while disabling tracepoint."));
10867 }
10868
10869 static void
10870 remote_trace_set_readonly_regions (struct target_ops *self)
10871 {
10872   asection *s;
10873   bfd *abfd = NULL;
10874   bfd_size_type size;
10875   bfd_vma vma;
10876   int anysecs = 0;
10877   int offset = 0;
10878
10879   if (!exec_bfd)
10880     return;                     /* No information to give.  */
10881
10882   strcpy (target_buf, "QTro");
10883   offset = strlen (target_buf);
10884   for (s = exec_bfd->sections; s; s = s->next)
10885     {
10886       char tmp1[40], tmp2[40];
10887       int sec_length;
10888
10889       if ((s->flags & SEC_LOAD) == 0 ||
10890       /*  (s->flags & SEC_CODE) == 0 || */
10891           (s->flags & SEC_READONLY) == 0)
10892         continue;
10893
10894       anysecs = 1;
10895       vma = bfd_get_section_vma (abfd, s);
10896       size = bfd_get_section_size (s);
10897       sprintf_vma (tmp1, vma);
10898       sprintf_vma (tmp2, vma + size);
10899       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10900       if (offset + sec_length + 1 > target_buf_size)
10901         {
10902           if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
10903             warning (_("\
10904 Too many sections for read-only sections definition packet."));
10905           break;
10906         }
10907       xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
10908                  tmp1, tmp2);
10909       offset += sec_length;
10910     }
10911   if (anysecs)
10912     {
10913       putpkt (target_buf);
10914       getpkt (&target_buf, &target_buf_size, 0);
10915     }
10916 }
10917
10918 static void
10919 remote_trace_start (struct target_ops *self)
10920 {
10921   putpkt ("QTStart");
10922   remote_get_noisy_reply (&target_buf, &target_buf_size);
10923   if (*target_buf == '\0')
10924     error (_("Target does not support this command."));
10925   if (strcmp (target_buf, "OK") != 0)
10926     error (_("Bogus reply from target: %s"), target_buf);
10927 }
10928
10929 static int
10930 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
10931 {
10932   /* Initialize it just to avoid a GCC false warning.  */
10933   char *p = NULL;
10934   /* FIXME we need to get register block size some other way.  */
10935   extern int trace_regblock_size;
10936   enum packet_result result;
10937
10938   if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
10939     return -1;
10940
10941   trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10942
10943   putpkt ("qTStatus");
10944
10945   TRY
10946     {
10947       p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10948     }
10949   CATCH (ex, RETURN_MASK_ERROR)
10950     {
10951       if (ex.error != TARGET_CLOSE_ERROR)
10952         {
10953           exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10954           return -1;
10955         }
10956       throw_exception (ex);
10957     }
10958   END_CATCH
10959
10960   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
10961
10962   /* If the remote target doesn't do tracing, flag it.  */
10963   if (result == PACKET_UNKNOWN)
10964     return -1;
10965
10966   /* We're working with a live target.  */
10967   ts->filename = NULL;
10968
10969   if (*p++ != 'T')
10970     error (_("Bogus trace status reply from target: %s"), target_buf);
10971
10972   /* Function 'parse_trace_status' sets default value of each field of
10973      'ts' at first, so we don't have to do it here.  */
10974   parse_trace_status (p, ts);
10975
10976   return ts->running;
10977 }
10978
10979 static void
10980 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
10981                               struct uploaded_tp *utp)
10982 {
10983   struct remote_state *rs = get_remote_state ();
10984   char *reply;
10985   struct bp_location *loc;
10986   struct tracepoint *tp = (struct tracepoint *) bp;
10987   size_t size = get_remote_packet_size ();
10988
10989   if (tp)
10990     {
10991       tp->base.hit_count = 0;
10992       tp->traceframe_usage = 0;
10993       for (loc = tp->base.loc; loc; loc = loc->next)
10994         {
10995           /* If the tracepoint was never downloaded, don't go asking for
10996              any status.  */
10997           if (tp->number_on_target == 0)
10998             continue;
10999           xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
11000                      phex_nz (loc->address, 0));
11001           putpkt (rs->buf);
11002           reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11003           if (reply && *reply)
11004             {
11005               if (*reply == 'V')
11006                 parse_tracepoint_status (reply + 1, bp, utp);
11007             }
11008         }
11009     }
11010   else if (utp)
11011     {
11012       utp->hit_count = 0;
11013       utp->traceframe_usage = 0;
11014       xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
11015                  phex_nz (utp->addr, 0));
11016       putpkt (rs->buf);
11017       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11018       if (reply && *reply)
11019         {
11020           if (*reply == 'V')
11021             parse_tracepoint_status (reply + 1, bp, utp);
11022         }
11023     }
11024 }
11025
11026 static void
11027 remote_trace_stop (struct target_ops *self)
11028 {
11029   putpkt ("QTStop");
11030   remote_get_noisy_reply (&target_buf, &target_buf_size);
11031   if (*target_buf == '\0')
11032     error (_("Target does not support this command."));
11033   if (strcmp (target_buf, "OK") != 0)
11034     error (_("Bogus reply from target: %s"), target_buf);
11035 }
11036
11037 static int
11038 remote_trace_find (struct target_ops *self,
11039                    enum trace_find_type type, int num,
11040                    CORE_ADDR addr1, CORE_ADDR addr2,
11041                    int *tpp)
11042 {
11043   struct remote_state *rs = get_remote_state ();
11044   char *endbuf = rs->buf + get_remote_packet_size ();
11045   char *p, *reply;
11046   int target_frameno = -1, target_tracept = -1;
11047
11048   /* Lookups other than by absolute frame number depend on the current
11049      trace selected, so make sure it is correct on the remote end
11050      first.  */
11051   if (type != tfind_number)
11052     set_remote_traceframe ();
11053
11054   p = rs->buf;
11055   strcpy (p, "QTFrame:");
11056   p = strchr (p, '\0');
11057   switch (type)
11058     {
11059     case tfind_number:
11060       xsnprintf (p, endbuf - p, "%x", num);
11061       break;
11062     case tfind_pc:
11063       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
11064       break;
11065     case tfind_tp:
11066       xsnprintf (p, endbuf - p, "tdp:%x", num);
11067       break;
11068     case tfind_range:
11069       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11070                  phex_nz (addr2, 0));
11071       break;
11072     case tfind_outside:
11073       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11074                  phex_nz (addr2, 0));
11075       break;
11076     default:
11077       error (_("Unknown trace find type %d"), type);
11078     }
11079
11080   putpkt (rs->buf);
11081   reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
11082   if (*reply == '\0')
11083     error (_("Target does not support this command."));
11084
11085   while (reply && *reply)
11086     switch (*reply)
11087       {
11088       case 'F':
11089         p = ++reply;
11090         target_frameno = (int) strtol (p, &reply, 16);
11091         if (reply == p)
11092           error (_("Unable to parse trace frame number"));
11093         /* Don't update our remote traceframe number cache on failure
11094            to select a remote traceframe.  */
11095         if (target_frameno == -1)
11096           return -1;
11097         break;
11098       case 'T':
11099         p = ++reply;
11100         target_tracept = (int) strtol (p, &reply, 16);
11101         if (reply == p)
11102           error (_("Unable to parse tracepoint number"));
11103         break;
11104       case 'O':         /* "OK"? */
11105         if (reply[1] == 'K' && reply[2] == '\0')
11106           reply += 2;
11107         else
11108           error (_("Bogus reply from target: %s"), reply);
11109         break;
11110       default:
11111         error (_("Bogus reply from target: %s"), reply);
11112       }
11113   if (tpp)
11114     *tpp = target_tracept;
11115
11116   rs->remote_traceframe_number = target_frameno;
11117   return target_frameno;
11118 }
11119
11120 static int
11121 remote_get_trace_state_variable_value (struct target_ops *self,
11122                                        int tsvnum, LONGEST *val)
11123 {
11124   struct remote_state *rs = get_remote_state ();
11125   char *reply;
11126   ULONGEST uval;
11127
11128   set_remote_traceframe ();
11129
11130   xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
11131   putpkt (rs->buf);
11132   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11133   if (reply && *reply)
11134     {
11135       if (*reply == 'V')
11136         {
11137           unpack_varlen_hex (reply + 1, &uval);
11138           *val = (LONGEST) uval;
11139           return 1;
11140         }
11141     }
11142   return 0;
11143 }
11144
11145 static int
11146 remote_save_trace_data (struct target_ops *self, const char *filename)
11147 {
11148   struct remote_state *rs = get_remote_state ();
11149   char *p, *reply;
11150
11151   p = rs->buf;
11152   strcpy (p, "QTSave:");
11153   p += strlen (p);
11154   if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11155     error (_("Remote file name too long for trace save packet"));
11156   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
11157   *p++ = '\0';
11158   putpkt (rs->buf);
11159   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11160   if (*reply == '\0')
11161     error (_("Target does not support this command."));
11162   if (strcmp (reply, "OK") != 0)
11163     error (_("Bogus reply from target: %s"), reply);
11164   return 0;
11165 }
11166
11167 /* This is basically a memory transfer, but needs to be its own packet
11168    because we don't know how the target actually organizes its trace
11169    memory, plus we want to be able to ask for as much as possible, but
11170    not be unhappy if we don't get as much as we ask for.  */
11171
11172 static LONGEST
11173 remote_get_raw_trace_data (struct target_ops *self,
11174                            gdb_byte *buf, ULONGEST offset, LONGEST len)
11175 {
11176   struct remote_state *rs = get_remote_state ();
11177   char *reply;
11178   char *p;
11179   int rslt;
11180
11181   p = rs->buf;
11182   strcpy (p, "qTBuffer:");
11183   p += strlen (p);
11184   p += hexnumstr (p, offset);
11185   *p++ = ',';
11186   p += hexnumstr (p, len);
11187   *p++ = '\0';
11188
11189   putpkt (rs->buf);
11190   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11191   if (reply && *reply)
11192     {
11193       /* 'l' by itself means we're at the end of the buffer and
11194          there is nothing more to get.  */
11195       if (*reply == 'l')
11196         return 0;
11197
11198       /* Convert the reply into binary.  Limit the number of bytes to
11199          convert according to our passed-in buffer size, rather than
11200          what was returned in the packet; if the target is
11201          unexpectedly generous and gives us a bigger reply than we
11202          asked for, we don't want to crash.  */
11203       rslt = hex2bin (target_buf, buf, len);
11204       return rslt;
11205     }
11206
11207   /* Something went wrong, flag as an error.  */
11208   return -1;
11209 }
11210
11211 static void
11212 remote_set_disconnected_tracing (struct target_ops *self, int val)
11213 {
11214   struct remote_state *rs = get_remote_state ();
11215
11216   if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
11217     {
11218       char *reply;
11219
11220       xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
11221       putpkt (rs->buf);
11222       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11223       if (*reply == '\0')
11224         error (_("Target does not support this command."));
11225       if (strcmp (reply, "OK") != 0)
11226         error (_("Bogus reply from target: %s"), reply);
11227     }
11228   else if (val)
11229     warning (_("Target does not support disconnected tracing."));
11230 }
11231
11232 static int
11233 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11234 {
11235   struct thread_info *info = find_thread_ptid (ptid);
11236
11237   if (info && info->priv)
11238     return info->priv->core;
11239   return -1;
11240 }
11241
11242 static void
11243 remote_set_circular_trace_buffer (struct target_ops *self, int val)
11244 {
11245   struct remote_state *rs = get_remote_state ();
11246   char *reply;
11247
11248   xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
11249   putpkt (rs->buf);
11250   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11251   if (*reply == '\0')
11252     error (_("Target does not support this command."));
11253   if (strcmp (reply, "OK") != 0)
11254     error (_("Bogus reply from target: %s"), reply);
11255 }
11256
11257 static struct traceframe_info *
11258 remote_traceframe_info (struct target_ops *self)
11259 {
11260   char *text;
11261
11262   text = target_read_stralloc (&current_target,
11263                                TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11264   if (text != NULL)
11265     {
11266       struct traceframe_info *info;
11267       struct cleanup *back_to = make_cleanup (xfree, text);
11268
11269       info = parse_traceframe_info (text);
11270       do_cleanups (back_to);
11271       return info;
11272     }
11273
11274   return NULL;
11275 }
11276
11277 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
11278    instruction on which a fast tracepoint may be placed.  Returns -1
11279    if the packet is not supported, and 0 if the minimum instruction
11280    length is unknown.  */
11281
11282 static int
11283 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
11284 {
11285   struct remote_state *rs = get_remote_state ();
11286   char *reply;
11287
11288   /* If we're not debugging a process yet, the IPA can't be
11289      loaded.  */
11290   if (!target_has_execution)
11291     return 0;
11292
11293   /* Make sure the remote is pointing at the right process.  */
11294   set_general_process ();
11295
11296   xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
11297   putpkt (rs->buf);
11298   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11299   if (*reply == '\0')
11300     return -1;
11301   else
11302     {
11303       ULONGEST min_insn_len;
11304
11305       unpack_varlen_hex (reply, &min_insn_len);
11306
11307       return (int) min_insn_len;
11308     }
11309 }
11310
11311 static void
11312 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
11313 {
11314   if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
11315     {
11316       struct remote_state *rs = get_remote_state ();
11317       char *buf = rs->buf;
11318       char *endbuf = rs->buf + get_remote_packet_size ();
11319       enum packet_result result;
11320
11321       gdb_assert (val >= 0 || val == -1);
11322       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11323       /* Send -1 as literal "-1" to avoid host size dependency.  */
11324       if (val < 0)
11325         {
11326           *buf++ = '-';
11327           buf += hexnumstr (buf, (ULONGEST) -val);
11328         }
11329       else
11330         buf += hexnumstr (buf, (ULONGEST) val);
11331
11332       putpkt (rs->buf);
11333       remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11334       result = packet_ok (rs->buf,
11335                   &remote_protocol_packets[PACKET_QTBuffer_size]);
11336
11337       if (result != PACKET_OK)
11338         warning (_("Bogus reply from target: %s"), rs->buf);
11339     }
11340 }
11341
11342 static int
11343 remote_set_trace_notes (struct target_ops *self,
11344                         const char *user, const char *notes,
11345                         const char *stop_notes)
11346 {
11347   struct remote_state *rs = get_remote_state ();
11348   char *reply;
11349   char *buf = rs->buf;
11350   char *endbuf = rs->buf + get_remote_packet_size ();
11351   int nbytes;
11352
11353   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11354   if (user)
11355     {
11356       buf += xsnprintf (buf, endbuf - buf, "user:");
11357       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
11358       buf += 2 * nbytes;
11359       *buf++ = ';';
11360     }
11361   if (notes)
11362     {
11363       buf += xsnprintf (buf, endbuf - buf, "notes:");
11364       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
11365       buf += 2 * nbytes;
11366       *buf++ = ';';
11367     }
11368   if (stop_notes)
11369     {
11370       buf += xsnprintf (buf, endbuf - buf, "tstop:");
11371       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
11372       buf += 2 * nbytes;
11373       *buf++ = ';';
11374     }
11375   /* Ensure the buffer is terminated.  */
11376   *buf = '\0';
11377
11378   putpkt (rs->buf);
11379   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11380   if (*reply == '\0')
11381     return 0;
11382
11383   if (strcmp (reply, "OK") != 0)
11384     error (_("Bogus reply from target: %s"), reply);
11385
11386   return 1;
11387 }
11388
11389 static int
11390 remote_use_agent (struct target_ops *self, int use)
11391 {
11392   if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
11393     {
11394       struct remote_state *rs = get_remote_state ();
11395
11396       /* If the stub supports QAgent.  */
11397       xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
11398       putpkt (rs->buf);
11399       getpkt (&rs->buf, &rs->buf_size, 0);
11400
11401       if (strcmp (rs->buf, "OK") == 0)
11402         {
11403           use_agent = use;
11404           return 1;
11405         }
11406     }
11407
11408   return 0;
11409 }
11410
11411 static int
11412 remote_can_use_agent (struct target_ops *self)
11413 {
11414   return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
11415 }
11416
11417 struct btrace_target_info
11418 {
11419   /* The ptid of the traced thread.  */
11420   ptid_t ptid;
11421
11422   /* The obtained branch trace configuration.  */
11423   struct btrace_config conf;
11424 };
11425
11426 /* Reset our idea of our target's btrace configuration.  */
11427
11428 static void
11429 remote_btrace_reset (void)
11430 {
11431   struct remote_state *rs = get_remote_state ();
11432
11433   memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
11434 }
11435
11436 /* Check whether the target supports branch tracing.  */
11437
11438 static int
11439 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
11440 {
11441   if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
11442     return 0;
11443   if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
11444     return 0;
11445
11446   switch (format)
11447     {
11448       case BTRACE_FORMAT_NONE:
11449         return 0;
11450
11451       case BTRACE_FORMAT_BTS:
11452         return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
11453     }
11454
11455   internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
11456 }
11457
11458 /* Synchronize the configuration with the target.  */
11459
11460 static void
11461 btrace_sync_conf (const struct btrace_config *conf)
11462 {
11463   struct packet_config *packet;
11464   struct remote_state *rs;
11465   char *buf, *pos, *endbuf;
11466
11467   rs = get_remote_state ();
11468   buf = rs->buf;
11469   endbuf = buf + get_remote_packet_size ();
11470
11471   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
11472   if (packet_config_support (packet) == PACKET_ENABLE
11473       && conf->bts.size != rs->btrace_config.bts.size)
11474     {
11475       pos = buf;
11476       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
11477                         conf->bts.size);
11478
11479       putpkt (buf);
11480       getpkt (&buf, &rs->buf_size, 0);
11481
11482       if (packet_ok (buf, packet) == PACKET_ERROR)
11483         {
11484           if (buf[0] == 'E' && buf[1] == '.')
11485             error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
11486           else
11487             error (_("Failed to configure the BTS buffer size."));
11488         }
11489
11490       rs->btrace_config.bts.size = conf->bts.size;
11491     }
11492 }
11493
11494 /* Read the current thread's btrace configuration from the target and
11495    store it into CONF.  */
11496
11497 static void
11498 btrace_read_config (struct btrace_config *conf)
11499 {
11500   char *xml;
11501
11502   xml = target_read_stralloc (&current_target,
11503                               TARGET_OBJECT_BTRACE_CONF, "");
11504   if (xml != NULL)
11505     {
11506       struct cleanup *cleanup;
11507
11508       cleanup = make_cleanup (xfree, xml);
11509       parse_xml_btrace_conf (conf, xml);
11510       do_cleanups (cleanup);
11511     }
11512 }
11513
11514 /* Enable branch tracing.  */
11515
11516 static struct btrace_target_info *
11517 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
11518                       const struct btrace_config *conf)
11519 {
11520   struct btrace_target_info *tinfo = NULL;
11521   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11522   struct remote_state *rs = get_remote_state ();
11523   char *buf = rs->buf;
11524   char *endbuf = rs->buf + get_remote_packet_size ();
11525
11526   if (packet_config_support (packet) != PACKET_ENABLE)
11527     error (_("Target does not support branch tracing."));
11528
11529   btrace_sync_conf (conf);
11530
11531   set_general_thread (ptid);
11532
11533   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11534   putpkt (rs->buf);
11535   getpkt (&rs->buf, &rs->buf_size, 0);
11536
11537   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11538     {
11539       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11540         error (_("Could not enable branch tracing for %s: %s"),
11541                target_pid_to_str (ptid), rs->buf + 2);
11542       else
11543         error (_("Could not enable branch tracing for %s."),
11544                target_pid_to_str (ptid));
11545     }
11546
11547   tinfo = xzalloc (sizeof (*tinfo));
11548   tinfo->ptid = ptid;
11549
11550   /* If we fail to read the configuration, we lose some information, but the
11551      tracing itself is not impacted.  */
11552   TRY
11553     {
11554       btrace_read_config (&tinfo->conf);
11555     }
11556   CATCH (err, RETURN_MASK_ERROR)
11557     {
11558       if (err.message != NULL)
11559         warning ("%s", err.message);
11560     }
11561   END_CATCH
11562
11563   return tinfo;
11564 }
11565
11566 /* Disable branch tracing.  */
11567
11568 static void
11569 remote_disable_btrace (struct target_ops *self,
11570                        struct btrace_target_info *tinfo)
11571 {
11572   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
11573   struct remote_state *rs = get_remote_state ();
11574   char *buf = rs->buf;
11575   char *endbuf = rs->buf + get_remote_packet_size ();
11576
11577   if (packet_config_support (packet) != PACKET_ENABLE)
11578     error (_("Target does not support branch tracing."));
11579
11580   set_general_thread (tinfo->ptid);
11581
11582   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11583   putpkt (rs->buf);
11584   getpkt (&rs->buf, &rs->buf_size, 0);
11585
11586   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11587     {
11588       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11589         error (_("Could not disable branch tracing for %s: %s"),
11590                target_pid_to_str (tinfo->ptid), rs->buf + 2);
11591       else
11592         error (_("Could not disable branch tracing for %s."),
11593                target_pid_to_str (tinfo->ptid));
11594     }
11595
11596   xfree (tinfo);
11597 }
11598
11599 /* Teardown branch tracing.  */
11600
11601 static void
11602 remote_teardown_btrace (struct target_ops *self,
11603                         struct btrace_target_info *tinfo)
11604 {
11605   /* We must not talk to the target during teardown.  */
11606   xfree (tinfo);
11607 }
11608
11609 /* Read the branch trace.  */
11610
11611 static enum btrace_error
11612 remote_read_btrace (struct target_ops *self,
11613                     struct btrace_data *btrace,
11614                     struct btrace_target_info *tinfo,
11615                     enum btrace_read_type type)
11616 {
11617   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11618   struct remote_state *rs = get_remote_state ();
11619   struct cleanup *cleanup;
11620   const char *annex;
11621   char *xml;
11622
11623   if (packet_config_support (packet) != PACKET_ENABLE)
11624     error (_("Target does not support branch tracing."));
11625
11626 #if !defined(HAVE_LIBEXPAT)
11627   error (_("Cannot process branch tracing result. XML parsing not supported."));
11628 #endif
11629
11630   switch (type)
11631     {
11632     case BTRACE_READ_ALL:
11633       annex = "all";
11634       break;
11635     case BTRACE_READ_NEW:
11636       annex = "new";
11637       break;
11638     case BTRACE_READ_DELTA:
11639       annex = "delta";
11640       break;
11641     default:
11642       internal_error (__FILE__, __LINE__,
11643                       _("Bad branch tracing read type: %u."),
11644                       (unsigned int) type);
11645     }
11646
11647   xml = target_read_stralloc (&current_target,
11648                               TARGET_OBJECT_BTRACE, annex);
11649   if (xml == NULL)
11650     return BTRACE_ERR_UNKNOWN;
11651
11652   cleanup = make_cleanup (xfree, xml);
11653   parse_xml_btrace (btrace, xml);
11654   do_cleanups (cleanup);
11655
11656   return BTRACE_ERR_NONE;
11657 }
11658
11659 static const struct btrace_config *
11660 remote_btrace_conf (struct target_ops *self,
11661                     const struct btrace_target_info *tinfo)
11662 {
11663   return &tinfo->conf;
11664 }
11665
11666 static int
11667 remote_augmented_libraries_svr4_read (struct target_ops *self)
11668 {
11669   return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
11670           == PACKET_ENABLE);
11671 }
11672
11673 /* Implementation of to_load.  */
11674
11675 static void
11676 remote_load (struct target_ops *self, const char *name, int from_tty)
11677 {
11678   generic_load (name, from_tty);
11679 }
11680
11681 /* Accepts an integer PID; returns a string representing a file that
11682    can be opened on the remote side to get the symbols for the child
11683    process.  Returns NULL if the operation is not supported.  */
11684
11685 static char *
11686 remote_pid_to_exec_file (struct target_ops *self, int pid)
11687 {
11688   static char *filename = NULL;
11689   struct inferior *inf;
11690   char *annex = NULL;
11691
11692   if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
11693     return NULL;
11694
11695   if (filename != NULL)
11696     xfree (filename);
11697
11698   inf = find_inferior_pid (pid);
11699   if (inf == NULL)
11700     internal_error (__FILE__, __LINE__,
11701                     _("not currently attached to process %d"), pid);
11702
11703   if (!inf->fake_pid_p)
11704     {
11705       const int annex_size = 9;
11706
11707       annex = alloca (annex_size);
11708       xsnprintf (annex, annex_size, "%x", pid);
11709     }
11710
11711   filename = target_read_stralloc (&current_target,
11712                                    TARGET_OBJECT_EXEC_FILE, annex);
11713
11714   return filename;
11715 }
11716
11717 static void
11718 init_remote_ops (void)
11719 {
11720   remote_ops.to_shortname = "remote";
11721   remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
11722   remote_ops.to_doc =
11723     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11724 Specify the serial device it is connected to\n\
11725 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
11726   remote_ops.to_open = remote_open;
11727   remote_ops.to_close = remote_close;
11728   remote_ops.to_detach = remote_detach;
11729   remote_ops.to_disconnect = remote_disconnect;
11730   remote_ops.to_resume = remote_resume;
11731   remote_ops.to_wait = remote_wait;
11732   remote_ops.to_fetch_registers = remote_fetch_registers;
11733   remote_ops.to_store_registers = remote_store_registers;
11734   remote_ops.to_prepare_to_store = remote_prepare_to_store;
11735   remote_ops.to_files_info = remote_files_info;
11736   remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11737   remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
11738   remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
11739   remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
11740   remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
11741   remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
11742   remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11743   remote_ops.to_stopped_data_address = remote_stopped_data_address;
11744   remote_ops.to_watchpoint_addr_within_range =
11745     remote_watchpoint_addr_within_range;
11746   remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11747   remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11748   remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
11749   remote_ops.to_region_ok_for_hw_watchpoint
11750      = remote_region_ok_for_hw_watchpoint;
11751   remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11752   remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
11753   remote_ops.to_kill = remote_kill;
11754   remote_ops.to_load = remote_load;
11755   remote_ops.to_mourn_inferior = remote_mourn;
11756   remote_ops.to_pass_signals = remote_pass_signals;
11757   remote_ops.to_program_signals = remote_program_signals;
11758   remote_ops.to_thread_alive = remote_thread_alive;
11759   remote_ops.to_update_thread_list = remote_update_thread_list;
11760   remote_ops.to_pid_to_str = remote_pid_to_str;
11761   remote_ops.to_extra_thread_info = remote_threads_extra_info;
11762   remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
11763   remote_ops.to_stop = remote_stop;
11764   remote_ops.to_xfer_partial = remote_xfer_partial;
11765   remote_ops.to_rcmd = remote_rcmd;
11766   remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
11767   remote_ops.to_log_command = serial_log_command;
11768   remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
11769   remote_ops.to_stratum = process_stratum;
11770   remote_ops.to_has_all_memory = default_child_has_all_memory;
11771   remote_ops.to_has_memory = default_child_has_memory;
11772   remote_ops.to_has_stack = default_child_has_stack;
11773   remote_ops.to_has_registers = default_child_has_registers;
11774   remote_ops.to_has_execution = default_child_has_execution;
11775   remote_ops.to_has_thread_control = tc_schedlock;    /* can lock scheduler */
11776   remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
11777   remote_ops.to_magic = OPS_MAGIC;
11778   remote_ops.to_memory_map = remote_memory_map;
11779   remote_ops.to_flash_erase = remote_flash_erase;
11780   remote_ops.to_flash_done = remote_flash_done;
11781   remote_ops.to_read_description = remote_read_description;
11782   remote_ops.to_search_memory = remote_search_memory;
11783   remote_ops.to_can_async_p = remote_can_async_p;
11784   remote_ops.to_is_async_p = remote_is_async_p;
11785   remote_ops.to_async = remote_async;
11786   remote_ops.to_terminal_inferior = remote_terminal_inferior;
11787   remote_ops.to_terminal_ours = remote_terminal_ours;
11788   remote_ops.to_supports_non_stop = remote_supports_non_stop;
11789   remote_ops.to_supports_multi_process = remote_supports_multi_process;
11790   remote_ops.to_supports_disable_randomization
11791     = remote_supports_disable_randomization;
11792   remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
11793   remote_ops.to_fileio_open = remote_hostio_open;
11794   remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11795   remote_ops.to_fileio_pread = remote_hostio_pread;
11796   remote_ops.to_fileio_fstat = remote_hostio_fstat;
11797   remote_ops.to_fileio_close = remote_hostio_close;
11798   remote_ops.to_fileio_unlink = remote_hostio_unlink;
11799   remote_ops.to_fileio_readlink = remote_hostio_readlink;
11800   remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
11801   remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
11802   remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
11803   remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
11804   remote_ops.to_trace_init = remote_trace_init;
11805   remote_ops.to_download_tracepoint = remote_download_tracepoint;
11806   remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
11807   remote_ops.to_download_trace_state_variable
11808     = remote_download_trace_state_variable;
11809   remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11810   remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
11811   remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11812   remote_ops.to_trace_start = remote_trace_start;
11813   remote_ops.to_get_trace_status = remote_get_trace_status;
11814   remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
11815   remote_ops.to_trace_stop = remote_trace_stop;
11816   remote_ops.to_trace_find = remote_trace_find;
11817   remote_ops.to_get_trace_state_variable_value
11818     = remote_get_trace_state_variable_value;
11819   remote_ops.to_save_trace_data = remote_save_trace_data;
11820   remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
11821   remote_ops.to_upload_trace_state_variables
11822     = remote_upload_trace_state_variables;
11823   remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
11824   remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
11825   remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
11826   remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
11827   remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
11828   remote_ops.to_set_trace_notes = remote_set_trace_notes;
11829   remote_ops.to_core_of_thread = remote_core_of_thread;
11830   remote_ops.to_verify_memory = remote_verify_memory;
11831   remote_ops.to_get_tib_address = remote_get_tib_address;
11832   remote_ops.to_set_permissions = remote_set_permissions;
11833   remote_ops.to_static_tracepoint_marker_at
11834     = remote_static_tracepoint_marker_at;
11835   remote_ops.to_static_tracepoint_markers_by_strid
11836     = remote_static_tracepoint_markers_by_strid;
11837   remote_ops.to_traceframe_info = remote_traceframe_info;
11838   remote_ops.to_use_agent = remote_use_agent;
11839   remote_ops.to_can_use_agent = remote_can_use_agent;
11840   remote_ops.to_supports_btrace = remote_supports_btrace;
11841   remote_ops.to_enable_btrace = remote_enable_btrace;
11842   remote_ops.to_disable_btrace = remote_disable_btrace;
11843   remote_ops.to_teardown_btrace = remote_teardown_btrace;
11844   remote_ops.to_read_btrace = remote_read_btrace;
11845   remote_ops.to_btrace_conf = remote_btrace_conf;
11846   remote_ops.to_augmented_libraries_svr4_read =
11847     remote_augmented_libraries_svr4_read;
11848 }
11849
11850 /* Set up the extended remote vector by making a copy of the standard
11851    remote vector and adding to it.  */
11852
11853 static void
11854 init_extended_remote_ops (void)
11855 {
11856   extended_remote_ops = remote_ops;
11857
11858   extended_remote_ops.to_shortname = "extended-remote";
11859   extended_remote_ops.to_longname =
11860     "Extended remote serial target in gdb-specific protocol";
11861   extended_remote_ops.to_doc =
11862     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11863 Specify the serial device it is connected to (e.g. /dev/ttya).";
11864   extended_remote_ops.to_open = extended_remote_open;
11865   extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11866   extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
11867   extended_remote_ops.to_detach = extended_remote_detach;
11868   extended_remote_ops.to_attach = extended_remote_attach;
11869   extended_remote_ops.to_post_attach = extended_remote_post_attach;
11870   extended_remote_ops.to_kill = extended_remote_kill;
11871   extended_remote_ops.to_supports_disable_randomization
11872     = extended_remote_supports_disable_randomization;
11873 }
11874
11875 static int
11876 remote_can_async_p (struct target_ops *ops)
11877 {
11878   struct remote_state *rs = get_remote_state ();
11879
11880   if (!target_async_permitted)
11881     /* We only enable async when the user specifically asks for it.  */
11882     return 0;
11883
11884   /* We're async whenever the serial device is.  */
11885   return serial_can_async_p (rs->remote_desc);
11886 }
11887
11888 static int
11889 remote_is_async_p (struct target_ops *ops)
11890 {
11891   struct remote_state *rs = get_remote_state ();
11892
11893   if (!target_async_permitted)
11894     /* We only enable async when the user specifically asks for it.  */
11895     return 0;
11896
11897   /* We're async whenever the serial device is.  */
11898   return serial_is_async_p (rs->remote_desc);
11899 }
11900
11901 /* Pass the SERIAL event on and up to the client.  One day this code
11902    will be able to delay notifying the client of an event until the
11903    point where an entire packet has been received.  */
11904
11905 static serial_event_ftype remote_async_serial_handler;
11906
11907 static void
11908 remote_async_serial_handler (struct serial *scb, void *context)
11909 {
11910   struct remote_state *rs = context;
11911
11912   /* Don't propogate error information up to the client.  Instead let
11913      the client find out about the error by querying the target.  */
11914   inferior_event_handler (INF_REG_EVENT, NULL);
11915 }
11916
11917 static void
11918 remote_async_inferior_event_handler (gdb_client_data data)
11919 {
11920   inferior_event_handler (INF_REG_EVENT, NULL);
11921 }
11922
11923 static void
11924 remote_async (struct target_ops *ops, int enable)
11925 {
11926   struct remote_state *rs = get_remote_state ();
11927
11928   if (enable)
11929     {
11930       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
11931
11932       /* If there are pending events in the stop reply queue tell the
11933          event loop to process them.  */
11934       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
11935         mark_async_event_handler (remote_async_inferior_event_token);
11936     }
11937   else
11938     {
11939       serial_async (rs->remote_desc, NULL, NULL);
11940       clear_async_event_handler (remote_async_inferior_event_token);
11941     }
11942 }
11943
11944 static void
11945 set_remote_cmd (char *args, int from_tty)
11946 {
11947   help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
11948 }
11949
11950 static void
11951 show_remote_cmd (char *args, int from_tty)
11952 {
11953   /* We can't just use cmd_show_list here, because we want to skip
11954      the redundant "show remote Z-packet" and the legacy aliases.  */
11955   struct cleanup *showlist_chain;
11956   struct cmd_list_element *list = remote_show_cmdlist;
11957   struct ui_out *uiout = current_uiout;
11958
11959   showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
11960   for (; list != NULL; list = list->next)
11961     if (strcmp (list->name, "Z-packet") == 0)
11962       continue;
11963     else if (list->type == not_set_cmd)
11964       /* Alias commands are exactly like the original, except they
11965          don't have the normal type.  */
11966       continue;
11967     else
11968       {
11969         struct cleanup *option_chain
11970           = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
11971
11972         ui_out_field_string (uiout, "name", list->name);
11973         ui_out_text (uiout, ":  ");
11974         if (list->type == show_cmd)
11975           do_show_command ((char *) NULL, from_tty, list);
11976         else
11977           cmd_func (list, NULL, from_tty);
11978         /* Close the tuple.  */
11979         do_cleanups (option_chain);
11980       }
11981
11982   /* Close the tuple.  */
11983   do_cleanups (showlist_chain);
11984 }
11985
11986
11987 /* Function to be called whenever a new objfile (shlib) is detected.  */
11988 static void
11989 remote_new_objfile (struct objfile *objfile)
11990 {
11991   struct remote_state *rs = get_remote_state ();
11992
11993   if (rs->remote_desc != 0)             /* Have a remote connection.  */
11994     remote_check_symbols ();
11995 }
11996
11997 /* Pull all the tracepoints defined on the target and create local
11998    data structures representing them.  We don't want to create real
11999    tracepoints yet, we don't want to mess up the user's existing
12000    collection.  */
12001   
12002 static int
12003 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
12004 {
12005   struct remote_state *rs = get_remote_state ();
12006   char *p;
12007
12008   /* Ask for a first packet of tracepoint definition.  */
12009   putpkt ("qTfP");
12010   getpkt (&rs->buf, &rs->buf_size, 0);
12011   p = rs->buf;
12012   while (*p && *p != 'l')
12013     {
12014       parse_tracepoint_definition (p, utpp);
12015       /* Ask for another packet of tracepoint definition.  */
12016       putpkt ("qTsP");
12017       getpkt (&rs->buf, &rs->buf_size, 0);
12018       p = rs->buf;
12019     }
12020   return 0;
12021 }
12022
12023 static int
12024 remote_upload_trace_state_variables (struct target_ops *self,
12025                                      struct uploaded_tsv **utsvp)
12026 {
12027   struct remote_state *rs = get_remote_state ();
12028   char *p;
12029
12030   /* Ask for a first packet of variable definition.  */
12031   putpkt ("qTfV");
12032   getpkt (&rs->buf, &rs->buf_size, 0);
12033   p = rs->buf;
12034   while (*p && *p != 'l')
12035     {
12036       parse_tsv_definition (p, utsvp);
12037       /* Ask for another packet of variable definition.  */
12038       putpkt ("qTsV");
12039       getpkt (&rs->buf, &rs->buf_size, 0);
12040       p = rs->buf;
12041     }
12042   return 0;
12043 }
12044
12045 /* The "set/show range-stepping" show hook.  */
12046
12047 static void
12048 show_range_stepping (struct ui_file *file, int from_tty,
12049                      struct cmd_list_element *c,
12050                      const char *value)
12051 {
12052   fprintf_filtered (file,
12053                     _("Debugger's willingness to use range stepping "
12054                       "is %s.\n"), value);
12055 }
12056
12057 /* The "set/show range-stepping" set hook.  */
12058
12059 static void
12060 set_range_stepping (char *ignore_args, int from_tty,
12061                     struct cmd_list_element *c)
12062 {
12063   struct remote_state *rs = get_remote_state ();
12064
12065   /* Whene enabling, check whether range stepping is actually
12066      supported by the target, and warn if not.  */
12067   if (use_range_stepping)
12068     {
12069       if (rs->remote_desc != NULL)
12070         {
12071           if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12072             remote_vcont_probe (rs);
12073
12074           if (packet_support (PACKET_vCont) == PACKET_ENABLE
12075               && rs->supports_vCont.r)
12076             return;
12077         }
12078
12079       warning (_("Range stepping is not supported by the current target"));
12080     }
12081 }
12082
12083 void
12084 _initialize_remote (void)
12085 {
12086   struct remote_state *rs;
12087   struct cmd_list_element *cmd;
12088   const char *cmd_name;
12089
12090   /* architecture specific data */
12091   remote_gdbarch_data_handle =
12092     gdbarch_data_register_post_init (init_remote_state);
12093   remote_g_packet_data_handle =
12094     gdbarch_data_register_pre_init (remote_g_packet_data_init);
12095
12096   /* Initialize the per-target state.  At the moment there is only one
12097      of these, not one per target.  Only one target is active at a
12098      time.  */
12099   remote_state = new_remote_state ();
12100
12101   init_remote_ops ();
12102   add_target (&remote_ops);
12103
12104   init_extended_remote_ops ();
12105   add_target (&extended_remote_ops);
12106
12107   /* Hook into new objfile notification.  */
12108   observer_attach_new_objfile (remote_new_objfile);
12109   /* We're no longer interested in notification events of an inferior
12110      when it exits.  */
12111   observer_attach_inferior_exit (discard_pending_stop_replies);
12112
12113   /* Set up signal handlers.  */
12114   async_sigint_remote_token =
12115     create_async_signal_handler (async_remote_interrupt, NULL);
12116   async_sigint_remote_twice_token =
12117     create_async_signal_handler (async_remote_interrupt_twice, NULL);
12118
12119 #if 0
12120   init_remote_threadtests ();
12121 #endif
12122
12123   stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
12124   /* set/show remote ...  */
12125
12126   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
12127 Remote protocol specific variables\n\
12128 Configure various remote-protocol specific variables such as\n\
12129 the packets being used"),
12130                   &remote_set_cmdlist, "set remote ",
12131                   0 /* allow-unknown */, &setlist);
12132   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
12133 Remote protocol specific variables\n\
12134 Configure various remote-protocol specific variables such as\n\
12135 the packets being used"),
12136                   &remote_show_cmdlist, "show remote ",
12137                   0 /* allow-unknown */, &showlist);
12138
12139   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
12140 Compare section data on target to the exec file.\n\
12141 Argument is a single section name (default: all loaded sections).\n\
12142 To compare only read-only loaded sections, specify the -r option."),
12143            &cmdlist);
12144
12145   add_cmd ("packet", class_maintenance, packet_command, _("\
12146 Send an arbitrary packet to a remote target.\n\
12147    maintenance packet TEXT\n\
12148 If GDB is talking to an inferior via the GDB serial protocol, then\n\
12149 this command sends the string TEXT to the inferior, and displays the\n\
12150 response packet.  GDB supplies the initial `$' character, and the\n\
12151 terminating `#' character and checksum."),
12152            &maintenancelist);
12153
12154   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
12155 Set whether to send break if interrupted."), _("\
12156 Show whether to send break if interrupted."), _("\
12157 If set, a break, instead of a cntrl-c, is sent to the remote target."),
12158                            set_remotebreak, show_remotebreak,
12159                            &setlist, &showlist);
12160   cmd_name = "remotebreak";
12161   cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
12162   deprecate_cmd (cmd, "set remote interrupt-sequence");
12163   cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
12164   cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
12165   deprecate_cmd (cmd, "show remote interrupt-sequence");
12166
12167   add_setshow_enum_cmd ("interrupt-sequence", class_support,
12168                         interrupt_sequence_modes, &interrupt_sequence_mode,
12169                         _("\
12170 Set interrupt sequence to remote target."), _("\
12171 Show interrupt sequence to remote target."), _("\
12172 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
12173                         NULL, show_interrupt_sequence,
12174                         &remote_set_cmdlist,
12175                         &remote_show_cmdlist);
12176
12177   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
12178                            &interrupt_on_connect, _("\
12179 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("            \
12180 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("           \
12181 If set, interrupt sequence is sent to remote target."),
12182                            NULL, NULL,
12183                            &remote_set_cmdlist, &remote_show_cmdlist);
12184
12185   /* Install commands for configuring memory read/write packets.  */
12186
12187   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
12188 Set the maximum number of bytes per memory write packet (deprecated)."),
12189            &setlist);
12190   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
12191 Show the maximum number of bytes per memory write packet (deprecated)."),
12192            &showlist);
12193   add_cmd ("memory-write-packet-size", no_class,
12194            set_memory_write_packet_size, _("\
12195 Set the maximum number of bytes per memory-write packet.\n\
12196 Specify the number of bytes in a packet or 0 (zero) for the\n\
12197 default packet size.  The actual limit is further reduced\n\
12198 dependent on the target.  Specify ``fixed'' to disable the\n\
12199 further restriction and ``limit'' to enable that restriction."),
12200            &remote_set_cmdlist);
12201   add_cmd ("memory-read-packet-size", no_class,
12202            set_memory_read_packet_size, _("\
12203 Set the maximum number of bytes per memory-read packet.\n\
12204 Specify the number of bytes in a packet or 0 (zero) for the\n\
12205 default packet size.  The actual limit is further reduced\n\
12206 dependent on the target.  Specify ``fixed'' to disable the\n\
12207 further restriction and ``limit'' to enable that restriction."),
12208            &remote_set_cmdlist);
12209   add_cmd ("memory-write-packet-size", no_class,
12210            show_memory_write_packet_size,
12211            _("Show the maximum number of bytes per memory-write packet."),
12212            &remote_show_cmdlist);
12213   add_cmd ("memory-read-packet-size", no_class,
12214            show_memory_read_packet_size,
12215            _("Show the maximum number of bytes per memory-read packet."),
12216            &remote_show_cmdlist);
12217
12218   add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
12219                             &remote_hw_watchpoint_limit, _("\
12220 Set the maximum number of target hardware watchpoints."), _("\
12221 Show the maximum number of target hardware watchpoints."), _("\
12222 Specify a negative limit for unlimited."),
12223                             NULL, NULL, /* FIXME: i18n: The maximum
12224                                            number of target hardware
12225                                            watchpoints is %s.  */
12226                             &remote_set_cmdlist, &remote_show_cmdlist);
12227   add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
12228                             &remote_hw_watchpoint_length_limit, _("\
12229 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
12230 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
12231 Specify a negative limit for unlimited."),
12232                             NULL, NULL, /* FIXME: i18n: The maximum
12233                                            length (in bytes) of a target
12234                                            hardware watchpoint is %s.  */
12235                             &remote_set_cmdlist, &remote_show_cmdlist);
12236   add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
12237                             &remote_hw_breakpoint_limit, _("\
12238 Set the maximum number of target hardware breakpoints."), _("\
12239 Show the maximum number of target hardware breakpoints."), _("\
12240 Specify a negative limit for unlimited."),
12241                             NULL, NULL, /* FIXME: i18n: The maximum
12242                                            number of target hardware
12243                                            breakpoints is %s.  */
12244                             &remote_set_cmdlist, &remote_show_cmdlist);
12245
12246   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
12247                              &remote_address_size, _("\
12248 Set the maximum size of the address (in bits) in a memory packet."), _("\
12249 Show the maximum size of the address (in bits) in a memory packet."), NULL,
12250                              NULL,
12251                              NULL, /* FIXME: i18n: */
12252                              &setlist, &showlist);
12253
12254   init_all_packet_configs ();
12255
12256   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
12257                          "X", "binary-download", 1);
12258
12259   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
12260                          "vCont", "verbose-resume", 0);
12261
12262   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
12263                          "QPassSignals", "pass-signals", 0);
12264
12265   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
12266                          "QProgramSignals", "program-signals", 0);
12267
12268   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
12269                          "qSymbol", "symbol-lookup", 0);
12270
12271   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
12272                          "P", "set-register", 1);
12273
12274   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
12275                          "p", "fetch-register", 1);
12276
12277   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
12278                          "Z0", "software-breakpoint", 0);
12279
12280   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
12281                          "Z1", "hardware-breakpoint", 0);
12282
12283   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
12284                          "Z2", "write-watchpoint", 0);
12285
12286   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
12287                          "Z3", "read-watchpoint", 0);
12288
12289   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
12290                          "Z4", "access-watchpoint", 0);
12291
12292   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
12293                          "qXfer:auxv:read", "read-aux-vector", 0);
12294
12295   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
12296                          "qXfer:exec-file:read", "pid-to-exec-file", 0);
12297
12298   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
12299                          "qXfer:features:read", "target-features", 0);
12300
12301   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
12302                          "qXfer:libraries:read", "library-info", 0);
12303
12304   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
12305                          "qXfer:libraries-svr4:read", "library-info-svr4", 0);
12306
12307   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
12308                          "qXfer:memory-map:read", "memory-map", 0);
12309
12310   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
12311                          "qXfer:spu:read", "read-spu-object", 0);
12312
12313   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
12314                          "qXfer:spu:write", "write-spu-object", 0);
12315
12316   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
12317                         "qXfer:osdata:read", "osdata", 0);
12318
12319   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
12320                          "qXfer:threads:read", "threads", 0);
12321
12322   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12323                          "qXfer:siginfo:read", "read-siginfo-object", 0);
12324
12325   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12326                          "qXfer:siginfo:write", "write-siginfo-object", 0);
12327
12328   add_packet_config_cmd
12329     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
12330      "qXfer:traceframe-info:read", "traceframe-info", 0);
12331
12332   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12333                          "qXfer:uib:read", "unwind-info-block", 0);
12334
12335   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
12336                          "qGetTLSAddr", "get-thread-local-storage-address",
12337                          0);
12338
12339   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12340                          "qGetTIBAddr", "get-thread-information-block-address",
12341                          0);
12342
12343   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12344                          "bc", "reverse-continue", 0);
12345
12346   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12347                          "bs", "reverse-step", 0);
12348
12349   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12350                          "qSupported", "supported-packets", 0);
12351
12352   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12353                          "qSearch:memory", "search-memory", 0);
12354
12355   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12356                          "qTStatus", "trace-status", 0);
12357
12358   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12359                          "vFile:open", "hostio-open", 0);
12360
12361   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12362                          "vFile:pread", "hostio-pread", 0);
12363
12364   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12365                          "vFile:pwrite", "hostio-pwrite", 0);
12366
12367   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12368                          "vFile:close", "hostio-close", 0);
12369
12370   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12371                          "vFile:unlink", "hostio-unlink", 0);
12372
12373   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12374                          "vFile:readlink", "hostio-readlink", 0);
12375
12376   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
12377                          "vFile:fstat", "hostio-fstat", 0);
12378
12379   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12380                          "vAttach", "attach", 0);
12381
12382   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12383                          "vRun", "run", 0);
12384
12385   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12386                          "QStartNoAckMode", "noack", 0);
12387
12388   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12389                          "vKill", "kill", 0);
12390
12391   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12392                          "qAttached", "query-attached", 0);
12393
12394   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
12395                          "ConditionalTracepoints",
12396                          "conditional-tracepoints", 0);
12397
12398   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12399                          "ConditionalBreakpoints",
12400                          "conditional-breakpoints", 0);
12401
12402   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12403                          "BreakpointCommands",
12404                          "breakpoint-commands", 0);
12405
12406   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12407                          "FastTracepoints", "fast-tracepoints", 0);
12408
12409   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12410                          "TracepointSource", "TracepointSource", 0);
12411
12412   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12413                          "QAllow", "allow", 0);
12414
12415   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12416                          "StaticTracepoints", "static-tracepoints", 0);
12417
12418   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12419                          "InstallInTrace", "install-in-trace", 0);
12420
12421   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12422                          "qXfer:statictrace:read", "read-sdata-object", 0);
12423
12424   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12425                          "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12426
12427   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12428                          "QDisableRandomization", "disable-randomization", 0);
12429
12430   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12431                          "QAgent", "agent", 0);
12432
12433   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12434                          "QTBuffer:size", "trace-buffer-size", 0);
12435
12436   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12437        "Qbtrace:off", "disable-btrace", 0);
12438
12439   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12440        "Qbtrace:bts", "enable-btrace", 0);
12441
12442   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12443        "qXfer:btrace", "read-btrace", 0);
12444
12445   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
12446        "qXfer:btrace-conf", "read-btrace-conf", 0);
12447
12448   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
12449        "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
12450
12451   add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
12452                          "swbreak-feature", "swbreak-feature", 0);
12453
12454   add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
12455                          "hwbreak-feature", "hwbreak-feature", 0);
12456
12457   add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
12458                          "fork-event-feature", "fork-event-feature", 0);
12459
12460   add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
12461                          "vfork-event-feature", "vfork-event-feature", 0);
12462
12463   /* Assert that we've registered "set remote foo-packet" commands
12464      for all packet configs.  */
12465   {
12466     int i;
12467
12468     for (i = 0; i < PACKET_MAX; i++)
12469       {
12470         /* Ideally all configs would have a command associated.  Some
12471            still don't though.  */
12472         int excepted;
12473
12474         switch (i)
12475           {
12476           case PACKET_QNonStop:
12477           case PACKET_multiprocess_feature:
12478           case PACKET_EnableDisableTracepoints_feature:
12479           case PACKET_tracenz_feature:
12480           case PACKET_DisconnectedTracing_feature:
12481           case PACKET_augmented_libraries_svr4_read_feature:
12482           case PACKET_qCRC:
12483             /* Additions to this list need to be well justified:
12484                pre-existing packets are OK; new packets are not.  */
12485             excepted = 1;
12486             break;
12487           default:
12488             excepted = 0;
12489             break;
12490           }
12491
12492         /* This catches both forgetting to add a config command, and
12493            forgetting to remove a packet from the exception list.  */
12494         gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
12495       }
12496   }
12497
12498   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
12499      Z sub-packet has its own set and show commands, but users may
12500      have sets to this variable in their .gdbinit files (or in their
12501      documentation).  */
12502   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
12503                                 &remote_Z_packet_detect, _("\
12504 Set use of remote protocol `Z' packets"), _("\
12505 Show use of remote protocol `Z' packets "), _("\
12506 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
12507 packets."),
12508                                 set_remote_protocol_Z_packet_cmd,
12509                                 show_remote_protocol_Z_packet_cmd,
12510                                 /* FIXME: i18n: Use of remote protocol
12511                                    `Z' packets is %s.  */
12512                                 &remote_set_cmdlist, &remote_show_cmdlist);
12513
12514   add_prefix_cmd ("remote", class_files, remote_command, _("\
12515 Manipulate files on the remote system\n\
12516 Transfer files to and from the remote target system."),
12517                   &remote_cmdlist, "remote ",
12518                   0 /* allow-unknown */, &cmdlist);
12519
12520   add_cmd ("put", class_files, remote_put_command,
12521            _("Copy a local file to the remote system."),
12522            &remote_cmdlist);
12523
12524   add_cmd ("get", class_files, remote_get_command,
12525            _("Copy a remote file to the local system."),
12526            &remote_cmdlist);
12527
12528   add_cmd ("delete", class_files, remote_delete_command,
12529            _("Delete a remote file."),
12530            &remote_cmdlist);
12531
12532   remote_exec_file = xstrdup ("");
12533   add_setshow_string_noescape_cmd ("exec-file", class_files,
12534                                    &remote_exec_file, _("\
12535 Set the remote pathname for \"run\""), _("\
12536 Show the remote pathname for \"run\""), NULL, NULL, NULL,
12537                                    &remote_set_cmdlist, &remote_show_cmdlist);
12538
12539   add_setshow_boolean_cmd ("range-stepping", class_run,
12540                            &use_range_stepping, _("\
12541 Enable or disable range stepping."), _("\
12542 Show whether target-assisted range stepping is enabled."), _("\
12543 If on, and the target supports it, when stepping a source line, GDB\n\
12544 tells the target to step the corresponding range of addresses itself instead\n\
12545 of issuing multiple single-steps.  This speeds up source level\n\
12546 stepping.  If off, GDB always issues single-steps, even if range\n\
12547 stepping is supported by the target.  The default is on."),
12548                            set_range_stepping,
12549                            show_range_stepping,
12550                            &setlist,
12551                            &showlist);
12552
12553   /* Eventually initialize fileio.  See fileio.c */
12554   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
12555
12556   /* Take advantage of the fact that the TID field is not used, to tag
12557      special ptids with it set to != 0.  */
12558   magic_null_ptid = ptid_build (42000, -1, 1);
12559   not_sent_ptid = ptid_build (42000, -2, 1);
12560   any_thread_ptid = ptid_build (42000, 0, 1);
12561
12562   target_buf_size = 2048;
12563   target_buf = xmalloc (target_buf_size);
12564 }
12565