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