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