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