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