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