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