* remote.c (struct remote_arch_state): Doc fix.
[external/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,
4    1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006
5    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 2 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, write to the Free Software
21    Foundation, Inc., 51 Franklin Street, Fifth Floor,
22    Boston, MA 02110-1301, USA.  */
23
24 /* See the GDB User Guide for details of the GDB remote protocol.  */
25
26 #include "defs.h"
27 #include "gdb_string.h"
28 #include <ctype.h>
29 #include <fcntl.h>
30 #include "inferior.h"
31 #include "bfd.h"
32 #include "symfile.h"
33 #include "exceptions.h"
34 #include "target.h"
35 /*#include "terminal.h" */
36 #include "gdbcmd.h"
37 #include "objfiles.h"
38 #include "gdb-stabs.h"
39 #include "gdbthread.h"
40 #include "remote.h"
41 #include "regcache.h"
42 #include "value.h"
43 #include "gdb_assert.h"
44 #include "observer.h"
45 #include "solib.h"
46 #include "cli/cli-decode.h"
47 #include "cli/cli-setshow.h"
48
49 #include <ctype.h>
50 #include <sys/time.h>
51
52 #include "event-loop.h"
53 #include "event-top.h"
54 #include "inf-loop.h"
55
56 #include <signal.h>
57 #include "serial.h"
58
59 #include "gdbcore.h" /* for exec_bfd */
60
61 #include "remote-fileio.h"
62
63 #include "memory-map.h"
64
65 /* The size to align memory write packets, when practical.  The protocol
66    does not guarantee any alignment, and gdb will generate short
67    writes and unaligned writes, but even as a best-effort attempt this
68    can improve bulk transfers.  For instance, if a write is misaligned
69    relative to the target's data bus, the stub may need to make an extra
70    round trip fetching data from the target.  This doesn't make a
71    huge difference, but it's easy to do, so we try to be helpful.
72
73    The alignment chosen is arbitrary; usually data bus width is
74    important here, not the possibly larger cache line size.  */
75 enum { REMOTE_ALIGN_WRITES = 16 };
76
77 /* Prototypes for local functions.  */
78 static void cleanup_sigint_signal_handler (void *dummy);
79 static void initialize_sigint_signal_handler (void);
80 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
81
82 static void handle_remote_sigint (int);
83 static void handle_remote_sigint_twice (int);
84 static void async_remote_interrupt (gdb_client_data);
85 void async_remote_interrupt_twice (gdb_client_data);
86
87 static void build_remote_gdbarch_data (void);
88
89 static void remote_files_info (struct target_ops *ignore);
90
91 static void remote_prepare_to_store (void);
92
93 static void remote_fetch_registers (int regno);
94
95 static void remote_resume (ptid_t ptid, int step,
96                            enum target_signal siggnal);
97 static void remote_async_resume (ptid_t ptid, int step,
98                                  enum target_signal siggnal);
99 static void remote_open (char *name, int from_tty);
100 static void remote_async_open (char *name, int from_tty);
101
102 static void extended_remote_open (char *name, int from_tty);
103 static void extended_remote_async_open (char *name, int from_tty);
104
105 static void remote_open_1 (char *, int, struct target_ops *, int extended_p,
106                            int async_p);
107
108 static void remote_close (int quitting);
109
110 static void remote_store_registers (int regno);
111
112 static void remote_mourn (void);
113 static void remote_async_mourn (void);
114
115 static void extended_remote_restart (void);
116
117 static void extended_remote_mourn (void);
118
119 static void remote_mourn_1 (struct target_ops *);
120
121 static void remote_send (char **buf, long *sizeof_buf_p);
122
123 static int readchar (int timeout);
124
125 static ptid_t remote_wait (ptid_t ptid,
126                                  struct target_waitstatus *status);
127 static ptid_t remote_async_wait (ptid_t ptid,
128                                        struct target_waitstatus *status);
129
130 static void remote_kill (void);
131 static void remote_async_kill (void);
132
133 static int tohex (int nib);
134
135 static void remote_detach (char *args, int from_tty);
136
137 static void remote_interrupt (int signo);
138
139 static void remote_interrupt_twice (int signo);
140
141 static void interrupt_query (void);
142
143 static void set_thread (int, int);
144
145 static int remote_thread_alive (ptid_t);
146
147 static void get_offsets (void);
148
149 static void skip_frame (void);
150
151 static long read_frame (char **buf_p, long *sizeof_buf);
152
153 static int hexnumlen (ULONGEST num);
154
155 static void init_remote_ops (void);
156
157 static void init_extended_remote_ops (void);
158
159 static void remote_stop (void);
160
161 static int ishex (int ch, int *val);
162
163 static int stubhex (int ch);
164
165 static int hexnumstr (char *, ULONGEST);
166
167 static int hexnumnstr (char *, ULONGEST, int);
168
169 static CORE_ADDR remote_address_masked (CORE_ADDR);
170
171 static void print_packet (char *);
172
173 static unsigned long crc32 (unsigned char *, int, unsigned int);
174
175 static void compare_sections_command (char *, int);
176
177 static void packet_command (char *, int);
178
179 static int stub_unpack_int (char *buff, int fieldlength);
180
181 static ptid_t remote_current_thread (ptid_t oldptid);
182
183 static void remote_find_new_threads (void);
184
185 static void record_currthread (int currthread);
186
187 static int fromhex (int a);
188
189 static int hex2bin (const char *hex, gdb_byte *bin, int count);
190
191 static int bin2hex (const gdb_byte *bin, char *hex, int count);
192
193 static int putpkt_binary (char *buf, int cnt);
194
195 static void check_binary_download (CORE_ADDR addr);
196
197 struct packet_config;
198
199 static void show_packet_config_cmd (struct packet_config *config);
200
201 static void update_packet_config (struct packet_config *config);
202
203 static void set_remote_protocol_packet_cmd (char *args, int from_tty,
204                                             struct cmd_list_element *c);
205
206 static void show_remote_protocol_packet_cmd (struct ui_file *file,
207                                              int from_tty,
208                                              struct cmd_list_element *c,
209                                              const char *value);
210
211 void _initialize_remote (void);
212
213 /* For "set remote" and "show remote".  */
214
215 static struct cmd_list_element *remote_set_cmdlist;
216 static struct cmd_list_element *remote_show_cmdlist;
217
218 /* Description of the remote protocol state for the currently
219    connected target.  This is per-target state, and independent of the
220    selected architecture.  */
221
222 struct remote_state
223 {
224   /* A buffer to use for incoming packets, and its current size.  The
225      buffer is grown dynamically for larger incoming packets.
226      Outgoing packets may also be constructed in this buffer.
227      BUF_SIZE is always at least REMOTE_PACKET_SIZE;
228      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
229      packets.  */
230   char *buf;
231   long buf_size;
232
233   /* If we negotiated packet size explicitly (and thus can bypass
234      heuristics for the largest packet size that will not overflow
235      a buffer in the stub), this will be set to that packet size.
236      Otherwise zero, meaning to use the guessed size.  */
237   long explicit_packet_size;
238 };
239
240 /* This data could be associated with a target, but we do not always
241    have access to the current target when we need it, so for now it is
242    static.  This will be fine for as long as only one target is in use
243    at a time.  */
244 static struct remote_state remote_state;
245
246 static struct remote_state *
247 get_remote_state_raw (void)
248 {
249   return &remote_state;
250 }
251
252 /* Description of the remote protocol for a given architecture.  */
253
254 struct packet_reg
255 {
256   long offset; /* Offset into G packet.  */
257   long regnum; /* GDB's internal register number.  */
258   LONGEST pnum; /* Remote protocol register number.  */
259   int in_g_packet; /* Always part of G packet.  */
260   /* long size in bytes;  == register_size (current_gdbarch, regnum);
261      at present.  */
262   /* char *name; == REGISTER_NAME (regnum); at present.  */
263 };
264
265 struct remote_arch_state
266 {
267   /* Description of the remote protocol registers.  */
268   long sizeof_g_packet;
269
270   /* Description of the remote protocol registers indexed by REGNUM
271      (making an array NUM_REGS in size).  */
272   struct packet_reg *regs;
273
274   /* This is the size (in chars) of the first response to the ``g''
275      packet.  It is used as a heuristic when determining the maximum
276      size of memory-read and memory-write packets.  A target will
277      typically only reserve a buffer large enough to hold the ``g''
278      packet.  The size does not include packet overhead (headers and
279      trailers).  */
280   long actual_register_packet_size;
281
282   /* This is the maximum size (in chars) of a non read/write packet.
283      It is also used as a cap on the size of read/write packets.  */
284   long remote_packet_size;
285 };
286
287
288 /* Handle for retreving the remote protocol data from gdbarch.  */
289 static struct gdbarch_data *remote_gdbarch_data_handle;
290
291 static struct remote_arch_state *
292 get_remote_arch_state (void)
293 {
294   return gdbarch_data (current_gdbarch, remote_gdbarch_data_handle);
295 }
296
297 /* Fetch the global remote target state.  */
298
299 static struct remote_state *
300 get_remote_state (void)
301 {
302   /* Make sure that the remote architecture state has been
303      initialized, because doing so might reallocate rs->buf.  Any
304      function which calls getpkt also needs to be mindful of changes
305      to rs->buf, but this call limits the number of places which run
306      into trouble.  */
307   get_remote_arch_state ();
308
309   return get_remote_state_raw ();
310 }
311
312 static int
313 compare_pnums (const void *lhs_, const void *rhs_)
314 {
315   const struct packet_reg * const *lhs = lhs_;
316   const struct packet_reg * const *rhs = rhs_;
317
318   if ((*lhs)->pnum < (*rhs)->pnum)
319     return -1;
320   else if ((*lhs)->pnum == (*rhs)->pnum)
321     return 0;
322   else
323     return 1;
324 }
325
326 static void *
327 init_remote_state (struct gdbarch *gdbarch)
328 {
329   int regnum, num_remote_regs, offset;
330   struct remote_state *rs = get_remote_state_raw ();
331   struct remote_arch_state *rsa;
332   struct packet_reg **remote_regs;
333
334   rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
335
336   /* Assume a 1:1 regnum<->pnum table.  */
337   rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch, NUM_REGS, struct packet_reg);
338   for (regnum = 0; regnum < NUM_REGS; regnum++)
339     {
340       struct packet_reg *r = &rsa->regs[regnum];
341       r->pnum = regnum;
342       r->regnum = regnum;
343     }
344
345   /* Define the g/G packet format as the contents of each register
346      with a remote protocol number, in order of ascending protocol
347      number.  */
348
349   remote_regs = alloca (NUM_REGS * sizeof (struct packet_reg *));
350   for (num_remote_regs = 0, regnum = 0; regnum < NUM_REGS; regnum++)
351     if (rsa->regs[regnum].pnum != -1)
352       remote_regs[num_remote_regs++] = &rsa->regs[regnum];
353
354   qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
355          compare_pnums);
356
357   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
358     {
359       remote_regs[regnum]->in_g_packet = 1;
360       remote_regs[regnum]->offset = offset;
361       offset += register_size (current_gdbarch, remote_regs[regnum]->regnum);
362     }
363
364   /* Record the maximum possible size of the g packet - it may turn out
365      to be smaller.  */
366   rsa->sizeof_g_packet = offset;
367
368   /* Default maximum number of characters in a packet body. Many
369      remote stubs have a hardwired buffer size of 400 bytes
370      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
371      as the maximum packet-size to ensure that the packet and an extra
372      NUL character can always fit in the buffer.  This stops GDB
373      trashing stubs that try to squeeze an extra NUL into what is
374      already a full buffer (As of 1999-12-04 that was most stubs).  */
375   rsa->remote_packet_size = 400 - 1;
376
377   /* This one is filled in when a ``g'' packet is received.  */
378   rsa->actual_register_packet_size = 0;
379
380   /* Should rsa->sizeof_g_packet needs more space than the
381      default, adjust the size accordingly. Remember that each byte is
382      encoded as two characters. 32 is the overhead for the packet
383      header / footer. NOTE: cagney/1999-10-26: I suspect that 8
384      (``$NN:G...#NN'') is a better guess, the below has been padded a
385      little.  */
386   if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
387     rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
388
389   /* Make sure that the packet buffer is plenty big enough for
390      this architecture.  */
391   if (rs->buf_size < rsa->remote_packet_size)
392     {
393       rs->buf_size = 2 * rsa->remote_packet_size;
394       rs->buf = xrealloc (rs->buf, rs->buf_size);
395     }
396
397   return rsa;
398 }
399
400 /* Return the current allowed size of a remote packet.  This is
401    inferred from the current architecture, and should be used to
402    limit the length of outgoing packets.  */
403 static long
404 get_remote_packet_size (void)
405 {
406   struct remote_state *rs = get_remote_state ();
407   struct remote_arch_state *rsa = get_remote_arch_state ();
408
409   if (rs->explicit_packet_size)
410     return rs->explicit_packet_size;
411
412   return rsa->remote_packet_size;
413 }
414
415 static struct packet_reg *
416 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
417 {
418   if (regnum < 0 && regnum >= NUM_REGS)
419     return NULL;
420   else
421     {
422       struct packet_reg *r = &rsa->regs[regnum];
423       gdb_assert (r->regnum == regnum);
424       return r;
425     }
426 }
427
428 static struct packet_reg *
429 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
430 {
431   int i;
432   for (i = 0; i < NUM_REGS; i++)
433     {
434       struct packet_reg *r = &rsa->regs[i];
435       if (r->pnum == pnum)
436         return r;
437     }
438   return NULL;
439 }
440
441 /* FIXME: graces/2002-08-08: These variables should eventually be
442    bound to an instance of the target object (as in gdbarch-tdep()),
443    when such a thing exists.  */
444
445 /* This is set to the data address of the access causing the target
446    to stop for a watchpoint.  */
447 static CORE_ADDR remote_watch_data_address;
448
449 /* This is non-zero if target stopped for a watchpoint.  */
450 static int remote_stopped_by_watchpoint_p;
451
452 static struct target_ops remote_ops;
453
454 static struct target_ops extended_remote_ops;
455
456 /* Temporary target ops. Just like the remote_ops and
457    extended_remote_ops, but with asynchronous support.  */
458 static struct target_ops remote_async_ops;
459
460 static struct target_ops extended_async_remote_ops;
461
462 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
463    ``forever'' still use the normal timeout mechanism.  This is
464    currently used by the ASYNC code to guarentee that target reads
465    during the initial connect always time-out.  Once getpkt has been
466    modified to return a timeout indication and, in turn
467    remote_wait()/wait_for_inferior() have gained a timeout parameter
468    this can go away.  */
469 static int wait_forever_enabled_p = 1;
470
471
472 /* This variable chooses whether to send a ^C or a break when the user
473    requests program interruption.  Although ^C is usually what remote
474    systems expect, and that is the default here, sometimes a break is
475    preferable instead.  */
476
477 static int remote_break;
478
479 /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
480    remote_open knows that we don't have a file open when the program
481    starts.  */
482 static struct serial *remote_desc = NULL;
483
484 /* This variable sets the number of bits in an address that are to be
485    sent in a memory ("M" or "m") packet.  Normally, after stripping
486    leading zeros, the entire address would be sent. This variable
487    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
488    initial implementation of remote.c restricted the address sent in
489    memory packets to ``host::sizeof long'' bytes - (typically 32
490    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
491    address was never sent.  Since fixing this bug may cause a break in
492    some remote targets this variable is principly provided to
493    facilitate backward compatibility.  */
494
495 static int remote_address_size;
496
497 /* Tempoary to track who currently owns the terminal.  See
498    target_async_terminal_* for more details.  */
499
500 static int remote_async_terminal_ours_p;
501
502 \f
503 /* User configurable variables for the number of characters in a
504    memory read/write packet.  MIN (rsa->remote_packet_size,
505    rsa->sizeof_g_packet) is the default.  Some targets need smaller
506    values (fifo overruns, et.al.) and some users need larger values
507    (speed up transfers).  The variables ``preferred_*'' (the user
508    request), ``current_*'' (what was actually set) and ``forced_*''
509    (Positive - a soft limit, negative - a hard limit).  */
510
511 struct memory_packet_config
512 {
513   char *name;
514   long size;
515   int fixed_p;
516 };
517
518 /* Compute the current size of a read/write packet.  Since this makes
519    use of ``actual_register_packet_size'' the computation is dynamic.  */
520
521 static long
522 get_memory_packet_size (struct memory_packet_config *config)
523 {
524   struct remote_state *rs = get_remote_state ();
525   struct remote_arch_state *rsa = get_remote_arch_state ();
526
527   /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
528      law?) that some hosts don't cope very well with large alloca()
529      calls.  Eventually the alloca() code will be replaced by calls to
530      xmalloc() and make_cleanups() allowing this restriction to either
531      be lifted or removed.  */
532 #ifndef MAX_REMOTE_PACKET_SIZE
533 #define MAX_REMOTE_PACKET_SIZE 16384
534 #endif
535   /* NOTE: 20 ensures we can write at least one byte.  */
536 #ifndef MIN_REMOTE_PACKET_SIZE
537 #define MIN_REMOTE_PACKET_SIZE 20
538 #endif
539   long what_they_get;
540   if (config->fixed_p)
541     {
542       if (config->size <= 0)
543         what_they_get = MAX_REMOTE_PACKET_SIZE;
544       else
545         what_they_get = config->size;
546     }
547   else
548     {
549       what_they_get = get_remote_packet_size ();
550       /* Limit the packet to the size specified by the user.  */
551       if (config->size > 0
552           && what_they_get > config->size)
553         what_they_get = config->size;
554
555       /* Limit it to the size of the targets ``g'' response unless we have
556          permission from the stub to use a larger packet size.  */
557       if (rs->explicit_packet_size == 0
558           && rsa->actual_register_packet_size > 0
559           && what_they_get > rsa->actual_register_packet_size)
560         what_they_get = rsa->actual_register_packet_size;
561     }
562   if (what_they_get > MAX_REMOTE_PACKET_SIZE)
563     what_they_get = MAX_REMOTE_PACKET_SIZE;
564   if (what_they_get < MIN_REMOTE_PACKET_SIZE)
565     what_they_get = MIN_REMOTE_PACKET_SIZE;
566
567   /* Make sure there is room in the global buffer for this packet
568      (including its trailing NUL byte).  */
569   if (rs->buf_size < what_they_get + 1)
570     {
571       rs->buf_size = 2 * what_they_get;
572       rs->buf = xrealloc (rs->buf, 2 * what_they_get);
573     }
574
575   return what_they_get;
576 }
577
578 /* Update the size of a read/write packet. If they user wants
579    something really big then do a sanity check.  */
580
581 static void
582 set_memory_packet_size (char *args, struct memory_packet_config *config)
583 {
584   int fixed_p = config->fixed_p;
585   long size = config->size;
586   if (args == NULL)
587     error (_("Argument required (integer, `fixed' or `limited')."));
588   else if (strcmp (args, "hard") == 0
589       || strcmp (args, "fixed") == 0)
590     fixed_p = 1;
591   else if (strcmp (args, "soft") == 0
592            || strcmp (args, "limit") == 0)
593     fixed_p = 0;
594   else
595     {
596       char *end;
597       size = strtoul (args, &end, 0);
598       if (args == end)
599         error (_("Invalid %s (bad syntax)."), config->name);
600 #if 0
601       /* Instead of explicitly capping the size of a packet to
602          MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
603          instead allowed to set the size to something arbitrarily
604          large.  */
605       if (size > MAX_REMOTE_PACKET_SIZE)
606         error (_("Invalid %s (too large)."), config->name);
607 #endif
608     }
609   /* Extra checks?  */
610   if (fixed_p && !config->fixed_p)
611     {
612       if (! query (_("The target may not be able to correctly handle a %s\n"
613                    "of %ld bytes. Change the packet size? "),
614                    config->name, size))
615         error (_("Packet size not changed."));
616     }
617   /* Update the config.  */
618   config->fixed_p = fixed_p;
619   config->size = size;
620 }
621
622 static void
623 show_memory_packet_size (struct memory_packet_config *config)
624 {
625   printf_filtered (_("The %s is %ld. "), config->name, config->size);
626   if (config->fixed_p)
627     printf_filtered (_("Packets are fixed at %ld bytes.\n"),
628                      get_memory_packet_size (config));
629   else
630     printf_filtered (_("Packets are limited to %ld bytes.\n"),
631                      get_memory_packet_size (config));
632 }
633
634 static struct memory_packet_config memory_write_packet_config =
635 {
636   "memory-write-packet-size",
637 };
638
639 static void
640 set_memory_write_packet_size (char *args, int from_tty)
641 {
642   set_memory_packet_size (args, &memory_write_packet_config);
643 }
644
645 static void
646 show_memory_write_packet_size (char *args, int from_tty)
647 {
648   show_memory_packet_size (&memory_write_packet_config);
649 }
650
651 static long
652 get_memory_write_packet_size (void)
653 {
654   return get_memory_packet_size (&memory_write_packet_config);
655 }
656
657 static struct memory_packet_config memory_read_packet_config =
658 {
659   "memory-read-packet-size",
660 };
661
662 static void
663 set_memory_read_packet_size (char *args, int from_tty)
664 {
665   set_memory_packet_size (args, &memory_read_packet_config);
666 }
667
668 static void
669 show_memory_read_packet_size (char *args, int from_tty)
670 {
671   show_memory_packet_size (&memory_read_packet_config);
672 }
673
674 static long
675 get_memory_read_packet_size (void)
676 {
677   long size = get_memory_packet_size (&memory_read_packet_config);
678   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
679      extra buffer size argument before the memory read size can be
680      increased beyond this.  */
681   if (size > get_remote_packet_size ())
682     size = get_remote_packet_size ();
683   return size;
684 }
685
686 \f
687 /* Generic configuration support for packets the stub optionally
688    supports. Allows the user to specify the use of the packet as well
689    as allowing GDB to auto-detect support in the remote stub.  */
690
691 enum packet_support
692   {
693     PACKET_SUPPORT_UNKNOWN = 0,
694     PACKET_ENABLE,
695     PACKET_DISABLE
696   };
697
698 struct packet_config
699   {
700     const char *name;
701     const char *title;
702     enum auto_boolean detect;
703     enum packet_support support;
704   };
705
706 /* Analyze a packet's return value and update the packet config
707    accordingly.  */
708
709 enum packet_result
710 {
711   PACKET_ERROR,
712   PACKET_OK,
713   PACKET_UNKNOWN
714 };
715
716 static void
717 update_packet_config (struct packet_config *config)
718 {
719   switch (config->detect)
720     {
721     case AUTO_BOOLEAN_TRUE:
722       config->support = PACKET_ENABLE;
723       break;
724     case AUTO_BOOLEAN_FALSE:
725       config->support = PACKET_DISABLE;
726       break;
727     case AUTO_BOOLEAN_AUTO:
728       config->support = PACKET_SUPPORT_UNKNOWN;
729       break;
730     }
731 }
732
733 static void
734 show_packet_config_cmd (struct packet_config *config)
735 {
736   char *support = "internal-error";
737   switch (config->support)
738     {
739     case PACKET_ENABLE:
740       support = "enabled";
741       break;
742     case PACKET_DISABLE:
743       support = "disabled";
744       break;
745     case PACKET_SUPPORT_UNKNOWN:
746       support = "unknown";
747       break;
748     }
749   switch (config->detect)
750     {
751     case AUTO_BOOLEAN_AUTO:
752       printf_filtered (_("Support for the `%s' packet is auto-detected, currently %s.\n"),
753                        config->name, support);
754       break;
755     case AUTO_BOOLEAN_TRUE:
756     case AUTO_BOOLEAN_FALSE:
757       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
758                        config->name, support);
759       break;
760     }
761 }
762
763 static void
764 add_packet_config_cmd (struct packet_config *config, const char *name,
765                        const char *title, int legacy)
766 {
767   char *set_doc;
768   char *show_doc;
769   char *cmd_name;
770
771   config->name = name;
772   config->title = title;
773   config->detect = AUTO_BOOLEAN_AUTO;
774   config->support = PACKET_SUPPORT_UNKNOWN;
775   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
776                         name, title);
777   show_doc = xstrprintf ("Show current use of remote protocol `%s' (%s) packet",
778                          name, title);
779   /* set/show TITLE-packet {auto,on,off} */
780   cmd_name = xstrprintf ("%s-packet", title);
781   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
782                                 &config->detect, set_doc, show_doc, NULL, /* help_doc */
783                                 set_remote_protocol_packet_cmd,
784                                 show_remote_protocol_packet_cmd,
785                                 &remote_set_cmdlist, &remote_show_cmdlist);
786   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
787   if (legacy)
788     {
789       char *legacy_name;
790       legacy_name = xstrprintf ("%s-packet", name);
791       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
792                      &remote_set_cmdlist);
793       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
794                      &remote_show_cmdlist);
795     }
796 }
797
798 static enum packet_result
799 packet_check_result (const char *buf)
800 {
801   if (buf[0] != '\0')
802     {
803       /* The stub recognized the packet request.  Check that the
804          operation succeeded.  */
805       if (buf[0] == 'E'
806           && isxdigit (buf[1]) && isxdigit (buf[2])
807           && buf[3] == '\0')
808         /* "Enn"  - definitly an error.  */
809         return PACKET_ERROR;
810
811       /* Always treat "E." as an error.  This will be used for
812          more verbose error messages, such as E.memtypes.  */
813       if (buf[0] == 'E' && buf[1] == '.')
814         return PACKET_ERROR;
815
816       /* The packet may or may not be OK.  Just assume it is.  */
817       return PACKET_OK;
818     }
819   else
820     /* The stub does not support the packet.  */
821     return PACKET_UNKNOWN;
822 }
823
824 static enum packet_result
825 packet_ok (const char *buf, struct packet_config *config)
826 {
827   enum packet_result result;
828
829   result = packet_check_result (buf);
830   switch (result)
831     {
832     case PACKET_OK:
833     case PACKET_ERROR:
834       /* The stub recognized the packet request.  */
835       switch (config->support)
836         {
837         case PACKET_SUPPORT_UNKNOWN:
838           if (remote_debug)
839             fprintf_unfiltered (gdb_stdlog,
840                                     "Packet %s (%s) is supported\n",
841                                     config->name, config->title);
842           config->support = PACKET_ENABLE;
843           break;
844         case PACKET_DISABLE:
845           internal_error (__FILE__, __LINE__,
846                           _("packet_ok: attempt to use a disabled packet"));
847           break;
848         case PACKET_ENABLE:
849           break;
850         }
851       break;
852     case PACKET_UNKNOWN:
853       /* The stub does not support the packet.  */
854       switch (config->support)
855         {
856         case PACKET_ENABLE:
857           if (config->detect == AUTO_BOOLEAN_AUTO)
858             /* If the stub previously indicated that the packet was
859                supported then there is a protocol error..  */
860             error (_("Protocol error: %s (%s) conflicting enabled responses."),
861                    config->name, config->title);
862           else
863             /* The user set it wrong.  */
864             error (_("Enabled packet %s (%s) not recognized by stub"),
865                    config->name, config->title);
866           break;
867         case PACKET_SUPPORT_UNKNOWN:
868           if (remote_debug)
869             fprintf_unfiltered (gdb_stdlog,
870                                 "Packet %s (%s) is NOT supported\n",
871                                 config->name, config->title);
872           config->support = PACKET_DISABLE;
873           break;
874         case PACKET_DISABLE:
875           break;
876         }
877       break;
878     }
879
880   return result;
881 }
882
883 enum {
884   PACKET_vCont = 0,
885   PACKET_X,
886   PACKET_qSymbol,
887   PACKET_P,
888   PACKET_p,
889   PACKET_Z0,
890   PACKET_Z1,
891   PACKET_Z2,
892   PACKET_Z3,
893   PACKET_Z4,
894   PACKET_qXfer_auxv,
895   PACKET_qXfer_memory_map,
896   PACKET_qGetTLSAddr,
897   PACKET_qSupported,
898   PACKET_QPassSignals,
899   PACKET_MAX
900 };
901
902 static struct packet_config remote_protocol_packets[PACKET_MAX];
903
904 static void
905 set_remote_protocol_packet_cmd (char *args, int from_tty,
906                                 struct cmd_list_element *c)
907 {
908   struct packet_config *packet;
909
910   for (packet = remote_protocol_packets;
911        packet < &remote_protocol_packets[PACKET_MAX];
912        packet++)
913     {
914       if (&packet->detect == c->var)
915         {
916           update_packet_config (packet);
917           return;
918         }
919     }
920   internal_error (__FILE__, __LINE__, "Could not find config for %s",
921                   c->name);
922 }
923
924 static void
925 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
926                                  struct cmd_list_element *c,
927                                  const char *value)
928 {
929   struct packet_config *packet;
930
931   for (packet = remote_protocol_packets;
932        packet < &remote_protocol_packets[PACKET_MAX];
933        packet++)
934     {
935       if (&packet->detect == c->var)
936         {
937           show_packet_config_cmd (packet);
938           return;
939         }
940     }
941   internal_error (__FILE__, __LINE__, "Could not find config for %s",
942                   c->name);
943 }
944
945 /* Should we try one of the 'Z' requests?  */
946
947 enum Z_packet_type
948 {
949   Z_PACKET_SOFTWARE_BP,
950   Z_PACKET_HARDWARE_BP,
951   Z_PACKET_WRITE_WP,
952   Z_PACKET_READ_WP,
953   Z_PACKET_ACCESS_WP,
954   NR_Z_PACKET_TYPES
955 };
956
957 /* For compatibility with older distributions.  Provide a ``set remote
958    Z-packet ...'' command that updates all the Z packet types.  */
959
960 static enum auto_boolean remote_Z_packet_detect;
961
962 static void
963 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
964                                   struct cmd_list_element *c)
965 {
966   int i;
967   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
968     {
969       remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
970       update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
971     }
972 }
973
974 static void
975 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
976                                    struct cmd_list_element *c,
977                                    const char *value)
978 {
979   int i;
980   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
981     {
982       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
983     }
984 }
985
986 /* Should we try the 'ThreadInfo' query packet?
987
988    This variable (NOT available to the user: auto-detect only!)
989    determines whether GDB will use the new, simpler "ThreadInfo"
990    query or the older, more complex syntax for thread queries.
991    This is an auto-detect variable (set to true at each connect,
992    and set to false when the target fails to recognize it).  */
993
994 static int use_threadinfo_query;
995 static int use_threadextra_query;
996
997 /* Tokens for use by the asynchronous signal handlers for SIGINT.  */
998 static void *sigint_remote_twice_token;
999 static void *sigint_remote_token;
1000
1001 /* These are pointers to hook functions that may be set in order to
1002    modify resume/wait behavior for a particular architecture.  */
1003
1004 void (*deprecated_target_resume_hook) (void);
1005 void (*deprecated_target_wait_loop_hook) (void);
1006 \f
1007
1008
1009 /* These are the threads which we last sent to the remote system.
1010    -1 for all or -2 for not sent yet.  */
1011 static int general_thread;
1012 static int continue_thread;
1013
1014 /* Call this function as a result of
1015    1) A halt indication (T packet) containing a thread id
1016    2) A direct query of currthread
1017    3) Successful execution of set thread
1018  */
1019
1020 static void
1021 record_currthread (int currthread)
1022 {
1023   general_thread = currthread;
1024
1025   /* If this is a new thread, add it to GDB's thread list.
1026      If we leave it up to WFI to do this, bad things will happen.  */
1027   if (!in_thread_list (pid_to_ptid (currthread)))
1028     {
1029       add_thread (pid_to_ptid (currthread));
1030       ui_out_text (uiout, "[New ");
1031       ui_out_text (uiout, target_pid_to_str (pid_to_ptid (currthread)));
1032       ui_out_text (uiout, "]\n");
1033     }
1034 }
1035
1036 static char *last_pass_packet;
1037
1038 /* If 'QPassSignals' is supported, tell the remote stub what signals
1039    it can simply pass through to the inferior without reporting.  */
1040
1041 static void
1042 remote_pass_signals (void)
1043 {
1044   if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1045     {
1046       char *pass_packet, *p;
1047       int numsigs = (int) TARGET_SIGNAL_LAST;
1048       int count = 0, i;
1049
1050       gdb_assert (numsigs < 256);
1051       for (i = 0; i < numsigs; i++)
1052         {
1053           if (signal_stop_state (i) == 0
1054               && signal_print_state (i) == 0
1055               && signal_pass_state (i) == 1)
1056             count++;
1057         }
1058       pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1059       strcpy (pass_packet, "QPassSignals:");
1060       p = pass_packet + strlen (pass_packet);
1061       for (i = 0; i < numsigs; i++)
1062         {
1063           if (signal_stop_state (i) == 0
1064               && signal_print_state (i) == 0
1065               && signal_pass_state (i) == 1)
1066             {
1067               if (i >= 16)
1068                 *p++ = tohex (i >> 4);
1069               *p++ = tohex (i & 15);
1070               if (count)
1071                 *p++ = ';';
1072               else
1073                 break;
1074               count--;
1075             }
1076         }
1077       *p = 0;
1078       if (!last_pass_packet || strcmp (last_pass_packet, pass_packet))
1079         {
1080           struct remote_state *rs = get_remote_state ();
1081           char *buf = rs->buf;
1082
1083           putpkt (pass_packet);
1084           getpkt (&rs->buf, &rs->buf_size, 0);
1085           packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
1086           if (last_pass_packet)
1087             xfree (last_pass_packet);
1088           last_pass_packet = pass_packet;
1089         }
1090       else
1091         xfree (pass_packet);
1092     }
1093 }
1094
1095 #define MAGIC_NULL_PID 42000
1096
1097 static void
1098 set_thread (int th, int gen)
1099 {
1100   struct remote_state *rs = get_remote_state ();
1101   char *buf = rs->buf;
1102   int state = gen ? general_thread : continue_thread;
1103
1104   if (state == th)
1105     return;
1106
1107   buf[0] = 'H';
1108   buf[1] = gen ? 'g' : 'c';
1109   if (th == MAGIC_NULL_PID)
1110     {
1111       buf[2] = '0';
1112       buf[3] = '\0';
1113     }
1114   else if (th < 0)
1115     xsnprintf (&buf[2], get_remote_packet_size () - 2, "-%x", -th);
1116   else
1117     xsnprintf (&buf[2], get_remote_packet_size () - 2, "%x", th);
1118   putpkt (buf);
1119   getpkt (&rs->buf, &rs->buf_size, 0);
1120   if (gen)
1121     general_thread = th;
1122   else
1123     continue_thread = th;
1124 }
1125 \f
1126 /*  Return nonzero if the thread TH is still alive on the remote system.  */
1127
1128 static int
1129 remote_thread_alive (ptid_t ptid)
1130 {
1131   struct remote_state *rs = get_remote_state ();
1132   int tid = PIDGET (ptid);
1133
1134   if (tid < 0)
1135     xsnprintf (rs->buf, get_remote_packet_size (), "T-%08x", -tid);
1136   else
1137     xsnprintf (rs->buf, get_remote_packet_size (), "T%08x", tid);
1138   putpkt (rs->buf);
1139   getpkt (&rs->buf, &rs->buf_size, 0);
1140   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1141 }
1142
1143 /* About these extended threadlist and threadinfo packets.  They are
1144    variable length packets but, the fields within them are often fixed
1145    length.  They are redundent enough to send over UDP as is the
1146    remote protocol in general.  There is a matching unit test module
1147    in libstub.  */
1148
1149 #define OPAQUETHREADBYTES 8
1150
1151 /* a 64 bit opaque identifier */
1152 typedef unsigned char threadref[OPAQUETHREADBYTES];
1153
1154 /* WARNING: This threadref data structure comes from the remote O.S.,
1155    libstub protocol encoding, and remote.c. it is not particularly
1156    changable.  */
1157
1158 /* Right now, the internal structure is int. We want it to be bigger.
1159    Plan to fix this.
1160  */
1161
1162 typedef int gdb_threadref;      /* Internal GDB thread reference.  */
1163
1164 /* gdb_ext_thread_info is an internal GDB data structure which is
1165    equivalent to the reply of the remote threadinfo packet.  */
1166
1167 struct gdb_ext_thread_info
1168   {
1169     threadref threadid;         /* External form of thread reference.  */
1170     int active;                 /* Has state interesting to GDB?
1171                                    regs, stack.  */
1172     char display[256];          /* Brief state display, name,
1173                                    blocked/suspended.  */
1174     char shortname[32];         /* To be used to name threads.  */
1175     char more_display[256];     /* Long info, statistics, queue depth,
1176                                    whatever.  */
1177   };
1178
1179 /* The volume of remote transfers can be limited by submitting
1180    a mask containing bits specifying the desired information.
1181    Use a union of these values as the 'selection' parameter to
1182    get_thread_info. FIXME: Make these TAG names more thread specific.
1183  */
1184
1185 #define TAG_THREADID 1
1186 #define TAG_EXISTS 2
1187 #define TAG_DISPLAY 4
1188 #define TAG_THREADNAME 8
1189 #define TAG_MOREDISPLAY 16
1190
1191 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1192
1193 char *unpack_varlen_hex (char *buff, ULONGEST *result);
1194
1195 static char *unpack_nibble (char *buf, int *val);
1196
1197 static char *pack_nibble (char *buf, int nibble);
1198
1199 static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
1200
1201 static char *unpack_byte (char *buf, int *value);
1202
1203 static char *pack_int (char *buf, int value);
1204
1205 static char *unpack_int (char *buf, int *value);
1206
1207 static char *unpack_string (char *src, char *dest, int length);
1208
1209 static char *pack_threadid (char *pkt, threadref *id);
1210
1211 static char *unpack_threadid (char *inbuf, threadref *id);
1212
1213 void int_to_threadref (threadref *id, int value);
1214
1215 static int threadref_to_int (threadref *ref);
1216
1217 static void copy_threadref (threadref *dest, threadref *src);
1218
1219 static int threadmatch (threadref *dest, threadref *src);
1220
1221 static char *pack_threadinfo_request (char *pkt, int mode,
1222                                       threadref *id);
1223
1224 static int remote_unpack_thread_info_response (char *pkt,
1225                                                threadref *expectedref,
1226                                                struct gdb_ext_thread_info
1227                                                *info);
1228
1229
1230 static int remote_get_threadinfo (threadref *threadid,
1231                                   int fieldset, /*TAG mask */
1232                                   struct gdb_ext_thread_info *info);
1233
1234 static char *pack_threadlist_request (char *pkt, int startflag,
1235                                       int threadcount,
1236                                       threadref *nextthread);
1237
1238 static int parse_threadlist_response (char *pkt,
1239                                       int result_limit,
1240                                       threadref *original_echo,
1241                                       threadref *resultlist,
1242                                       int *doneflag);
1243
1244 static int remote_get_threadlist (int startflag,
1245                                   threadref *nextthread,
1246                                   int result_limit,
1247                                   int *done,
1248                                   int *result_count,
1249                                   threadref *threadlist);
1250
1251 typedef int (*rmt_thread_action) (threadref *ref, void *context);
1252
1253 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1254                                        void *context, int looplimit);
1255
1256 static int remote_newthread_step (threadref *ref, void *context);
1257
1258 /* Encode 64 bits in 16 chars of hex.  */
1259
1260 static const char hexchars[] = "0123456789abcdef";
1261
1262 static int
1263 ishex (int ch, int *val)
1264 {
1265   if ((ch >= 'a') && (ch <= 'f'))
1266     {
1267       *val = ch - 'a' + 10;
1268       return 1;
1269     }
1270   if ((ch >= 'A') && (ch <= 'F'))
1271     {
1272       *val = ch - 'A' + 10;
1273       return 1;
1274     }
1275   if ((ch >= '0') && (ch <= '9'))
1276     {
1277       *val = ch - '0';
1278       return 1;
1279     }
1280   return 0;
1281 }
1282
1283 static int
1284 stubhex (int ch)
1285 {
1286   if (ch >= 'a' && ch <= 'f')
1287     return ch - 'a' + 10;
1288   if (ch >= '0' && ch <= '9')
1289     return ch - '0';
1290   if (ch >= 'A' && ch <= 'F')
1291     return ch - 'A' + 10;
1292   return -1;
1293 }
1294
1295 static int
1296 stub_unpack_int (char *buff, int fieldlength)
1297 {
1298   int nibble;
1299   int retval = 0;
1300
1301   while (fieldlength)
1302     {
1303       nibble = stubhex (*buff++);
1304       retval |= nibble;
1305       fieldlength--;
1306       if (fieldlength)
1307         retval = retval << 4;
1308     }
1309   return retval;
1310 }
1311
1312 char *
1313 unpack_varlen_hex (char *buff,  /* packet to parse */
1314                    ULONGEST *result)
1315 {
1316   int nibble;
1317   ULONGEST retval = 0;
1318
1319   while (ishex (*buff, &nibble))
1320     {
1321       buff++;
1322       retval = retval << 4;
1323       retval |= nibble & 0x0f;
1324     }
1325   *result = retval;
1326   return buff;
1327 }
1328
1329 static char *
1330 unpack_nibble (char *buf, int *val)
1331 {
1332   ishex (*buf++, val);
1333   return buf;
1334 }
1335
1336 static char *
1337 pack_nibble (char *buf, int nibble)
1338 {
1339   *buf++ = hexchars[(nibble & 0x0f)];
1340   return buf;
1341 }
1342
1343 static char *
1344 pack_hex_byte (char *pkt, int byte)
1345 {
1346   *pkt++ = hexchars[(byte >> 4) & 0xf];
1347   *pkt++ = hexchars[(byte & 0xf)];
1348   return pkt;
1349 }
1350
1351 static char *
1352 unpack_byte (char *buf, int *value)
1353 {
1354   *value = stub_unpack_int (buf, 2);
1355   return buf + 2;
1356 }
1357
1358 static char *
1359 pack_int (char *buf, int value)
1360 {
1361   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
1362   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
1363   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
1364   buf = pack_hex_byte (buf, (value & 0xff));
1365   return buf;
1366 }
1367
1368 static char *
1369 unpack_int (char *buf, int *value)
1370 {
1371   *value = stub_unpack_int (buf, 8);
1372   return buf + 8;
1373 }
1374
1375 #if 0                   /* Currently unused, uncomment when needed.  */
1376 static char *pack_string (char *pkt, char *string);
1377
1378 static char *
1379 pack_string (char *pkt, char *string)
1380 {
1381   char ch;
1382   int len;
1383
1384   len = strlen (string);
1385   if (len > 200)
1386     len = 200;          /* Bigger than most GDB packets, junk???  */
1387   pkt = pack_hex_byte (pkt, len);
1388   while (len-- > 0)
1389     {
1390       ch = *string++;
1391       if ((ch == '\0') || (ch == '#'))
1392         ch = '*';               /* Protect encapsulation.  */
1393       *pkt++ = ch;
1394     }
1395   return pkt;
1396 }
1397 #endif /* 0 (unused) */
1398
1399 static char *
1400 unpack_string (char *src, char *dest, int length)
1401 {
1402   while (length--)
1403     *dest++ = *src++;
1404   *dest = '\0';
1405   return src;
1406 }
1407
1408 static char *
1409 pack_threadid (char *pkt, threadref *id)
1410 {
1411   char *limit;
1412   unsigned char *altid;
1413
1414   altid = (unsigned char *) id;
1415   limit = pkt + BUF_THREAD_ID_SIZE;
1416   while (pkt < limit)
1417     pkt = pack_hex_byte (pkt, *altid++);
1418   return pkt;
1419 }
1420
1421
1422 static char *
1423 unpack_threadid (char *inbuf, threadref *id)
1424 {
1425   char *altref;
1426   char *limit = inbuf + BUF_THREAD_ID_SIZE;
1427   int x, y;
1428
1429   altref = (char *) id;
1430
1431   while (inbuf < limit)
1432     {
1433       x = stubhex (*inbuf++);
1434       y = stubhex (*inbuf++);
1435       *altref++ = (x << 4) | y;
1436     }
1437   return inbuf;
1438 }
1439
1440 /* Externally, threadrefs are 64 bits but internally, they are still
1441    ints. This is due to a mismatch of specifications.  We would like
1442    to use 64bit thread references internally.  This is an adapter
1443    function.  */
1444
1445 void
1446 int_to_threadref (threadref *id, int value)
1447 {
1448   unsigned char *scan;
1449
1450   scan = (unsigned char *) id;
1451   {
1452     int i = 4;
1453     while (i--)
1454       *scan++ = 0;
1455   }
1456   *scan++ = (value >> 24) & 0xff;
1457   *scan++ = (value >> 16) & 0xff;
1458   *scan++ = (value >> 8) & 0xff;
1459   *scan++ = (value & 0xff);
1460 }
1461
1462 static int
1463 threadref_to_int (threadref *ref)
1464 {
1465   int i, value = 0;
1466   unsigned char *scan;
1467
1468   scan = *ref;
1469   scan += 4;
1470   i = 4;
1471   while (i-- > 0)
1472     value = (value << 8) | ((*scan++) & 0xff);
1473   return value;
1474 }
1475
1476 static void
1477 copy_threadref (threadref *dest, threadref *src)
1478 {
1479   int i;
1480   unsigned char *csrc, *cdest;
1481
1482   csrc = (unsigned char *) src;
1483   cdest = (unsigned char *) dest;
1484   i = 8;
1485   while (i--)
1486     *cdest++ = *csrc++;
1487 }
1488
1489 static int
1490 threadmatch (threadref *dest, threadref *src)
1491 {
1492   /* Things are broken right now, so just assume we got a match.  */
1493 #if 0
1494   unsigned char *srcp, *destp;
1495   int i, result;
1496   srcp = (char *) src;
1497   destp = (char *) dest;
1498
1499   result = 1;
1500   while (i-- > 0)
1501     result &= (*srcp++ == *destp++) ? 1 : 0;
1502   return result;
1503 #endif
1504   return 1;
1505 }
1506
1507 /*
1508    threadid:1,        # always request threadid
1509    context_exists:2,
1510    display:4,
1511    unique_name:8,
1512    more_display:16
1513  */
1514
1515 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
1516
1517 static char *
1518 pack_threadinfo_request (char *pkt, int mode, threadref *id)
1519 {
1520   *pkt++ = 'q';                         /* Info Query */
1521   *pkt++ = 'P';                         /* process or thread info */
1522   pkt = pack_int (pkt, mode);           /* mode */
1523   pkt = pack_threadid (pkt, id);        /* threadid */
1524   *pkt = '\0';                          /* terminate */
1525   return pkt;
1526 }
1527
1528 /* These values tag the fields in a thread info response packet.  */
1529 /* Tagging the fields allows us to request specific fields and to
1530    add more fields as time goes by.  */
1531
1532 #define TAG_THREADID 1          /* Echo the thread identifier.  */
1533 #define TAG_EXISTS 2            /* Is this process defined enough to
1534                                    fetch registers and its stack?  */
1535 #define TAG_DISPLAY 4           /* A short thing maybe to put on a window */
1536 #define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is.  */
1537 #define TAG_MOREDISPLAY 16      /* Whatever the kernel wants to say about
1538                                    the process.  */
1539
1540 static int
1541 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
1542                                     struct gdb_ext_thread_info *info)
1543 {
1544   struct remote_state *rs = get_remote_state ();
1545   int mask, length;
1546   int tag;
1547   threadref ref;
1548   char *limit = pkt + rs->buf_size; /* Plausible parsing limit.  */
1549   int retval = 1;
1550
1551   /* info->threadid = 0; FIXME: implement zero_threadref.  */
1552   info->active = 0;
1553   info->display[0] = '\0';
1554   info->shortname[0] = '\0';
1555   info->more_display[0] = '\0';
1556
1557   /* Assume the characters indicating the packet type have been
1558      stripped.  */
1559   pkt = unpack_int (pkt, &mask);        /* arg mask */
1560   pkt = unpack_threadid (pkt, &ref);
1561
1562   if (mask == 0)
1563     warning (_("Incomplete response to threadinfo request."));
1564   if (!threadmatch (&ref, expectedref))
1565     {                   /* This is an answer to a different request.  */
1566       warning (_("ERROR RMT Thread info mismatch."));
1567       return 0;
1568     }
1569   copy_threadref (&info->threadid, &ref);
1570
1571   /* Loop on tagged fields , try to bail if somthing goes wrong.  */
1572
1573   /* Packets are terminated with nulls.  */
1574   while ((pkt < limit) && mask && *pkt)
1575     {
1576       pkt = unpack_int (pkt, &tag);     /* tag */
1577       pkt = unpack_byte (pkt, &length); /* length */
1578       if (!(tag & mask))                /* Tags out of synch with mask.  */
1579         {
1580           warning (_("ERROR RMT: threadinfo tag mismatch."));
1581           retval = 0;
1582           break;
1583         }
1584       if (tag == TAG_THREADID)
1585         {
1586           if (length != 16)
1587             {
1588               warning (_("ERROR RMT: length of threadid is not 16."));
1589               retval = 0;
1590               break;
1591             }
1592           pkt = unpack_threadid (pkt, &ref);
1593           mask = mask & ~TAG_THREADID;
1594           continue;
1595         }
1596       if (tag == TAG_EXISTS)
1597         {
1598           info->active = stub_unpack_int (pkt, length);
1599           pkt += length;
1600           mask = mask & ~(TAG_EXISTS);
1601           if (length > 8)
1602             {
1603               warning (_("ERROR RMT: 'exists' length too long."));
1604               retval = 0;
1605               break;
1606             }
1607           continue;
1608         }
1609       if (tag == TAG_THREADNAME)
1610         {
1611           pkt = unpack_string (pkt, &info->shortname[0], length);
1612           mask = mask & ~TAG_THREADNAME;
1613           continue;
1614         }
1615       if (tag == TAG_DISPLAY)
1616         {
1617           pkt = unpack_string (pkt, &info->display[0], length);
1618           mask = mask & ~TAG_DISPLAY;
1619           continue;
1620         }
1621       if (tag == TAG_MOREDISPLAY)
1622         {
1623           pkt = unpack_string (pkt, &info->more_display[0], length);
1624           mask = mask & ~TAG_MOREDISPLAY;
1625           continue;
1626         }
1627       warning (_("ERROR RMT: unknown thread info tag."));
1628       break;                    /* Not a tag we know about.  */
1629     }
1630   return retval;
1631 }
1632
1633 static int
1634 remote_get_threadinfo (threadref *threadid, int fieldset,       /* TAG mask */
1635                        struct gdb_ext_thread_info *info)
1636 {
1637   struct remote_state *rs = get_remote_state ();
1638   int result;
1639
1640   pack_threadinfo_request (rs->buf, fieldset, threadid);
1641   putpkt (rs->buf);
1642   getpkt (&rs->buf, &rs->buf_size, 0);
1643   result = remote_unpack_thread_info_response (rs->buf + 2,
1644                                                threadid, info);
1645   return result;
1646 }
1647
1648 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
1649
1650 static char *
1651 pack_threadlist_request (char *pkt, int startflag, int threadcount,
1652                          threadref *nextthread)
1653 {
1654   *pkt++ = 'q';                 /* info query packet */
1655   *pkt++ = 'L';                 /* Process LIST or threadLIST request */
1656   pkt = pack_nibble (pkt, startflag);           /* initflag 1 bytes */
1657   pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
1658   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
1659   *pkt = '\0';
1660   return pkt;
1661 }
1662
1663 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
1664
1665 static int
1666 parse_threadlist_response (char *pkt, int result_limit,
1667                            threadref *original_echo, threadref *resultlist,
1668                            int *doneflag)
1669 {
1670   struct remote_state *rs = get_remote_state ();
1671   char *limit;
1672   int count, resultcount, done;
1673
1674   resultcount = 0;
1675   /* Assume the 'q' and 'M chars have been stripped.  */
1676   limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
1677   /* done parse past here */
1678   pkt = unpack_byte (pkt, &count);      /* count field */
1679   pkt = unpack_nibble (pkt, &done);
1680   /* The first threadid is the argument threadid.  */
1681   pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
1682   while ((count-- > 0) && (pkt < limit))
1683     {
1684       pkt = unpack_threadid (pkt, resultlist++);
1685       if (resultcount++ >= result_limit)
1686         break;
1687     }
1688   if (doneflag)
1689     *doneflag = done;
1690   return resultcount;
1691 }
1692
1693 static int
1694 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
1695                        int *done, int *result_count, threadref *threadlist)
1696 {
1697   struct remote_state *rs = get_remote_state ();
1698   static threadref echo_nextthread;
1699   int result = 1;
1700
1701   /* Trancate result limit to be smaller than the packet size.  */
1702   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10) >= get_remote_packet_size ())
1703     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
1704
1705   pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
1706   putpkt (rs->buf);
1707   getpkt (&rs->buf, &rs->buf_size, 0);
1708
1709   *result_count =
1710     parse_threadlist_response (rs->buf + 2, result_limit, &echo_nextthread,
1711                                threadlist, done);
1712
1713   if (!threadmatch (&echo_nextthread, nextthread))
1714     {
1715       /* FIXME: This is a good reason to drop the packet.  */
1716       /* Possably, there is a duplicate response.  */
1717       /* Possabilities :
1718          retransmit immediatly - race conditions
1719          retransmit after timeout - yes
1720          exit
1721          wait for packet, then exit
1722        */
1723       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
1724       return 0;                 /* I choose simply exiting.  */
1725     }
1726   if (*result_count <= 0)
1727     {
1728       if (*done != 1)
1729         {
1730           warning (_("RMT ERROR : failed to get remote thread list."));
1731           result = 0;
1732         }
1733       return result;            /* break; */
1734     }
1735   if (*result_count > result_limit)
1736     {
1737       *result_count = 0;
1738       warning (_("RMT ERROR: threadlist response longer than requested."));
1739       return 0;
1740     }
1741   return result;
1742 }
1743
1744 /* This is the interface between remote and threads, remotes upper
1745    interface.  */
1746
1747 /* remote_find_new_threads retrieves the thread list and for each
1748    thread in the list, looks up the thread in GDB's internal list,
1749    ading the thread if it does not already exist.  This involves
1750    getting partial thread lists from the remote target so, polling the
1751    quit_flag is required.  */
1752
1753
1754 /* About this many threadisds fit in a packet.  */
1755
1756 #define MAXTHREADLISTRESULTS 32
1757
1758 static int
1759 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
1760                             int looplimit)
1761 {
1762   int done, i, result_count;
1763   int startflag = 1;
1764   int result = 1;
1765   int loopcount = 0;
1766   static threadref nextthread;
1767   static threadref resultthreadlist[MAXTHREADLISTRESULTS];
1768
1769   done = 0;
1770   while (!done)
1771     {
1772       if (loopcount++ > looplimit)
1773         {
1774           result = 0;
1775           warning (_("Remote fetch threadlist -infinite loop-."));
1776           break;
1777         }
1778       if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
1779                                   &done, &result_count, resultthreadlist))
1780         {
1781           result = 0;
1782           break;
1783         }
1784       /* Clear for later iterations.  */
1785       startflag = 0;
1786       /* Setup to resume next batch of thread references, set nextthread.  */
1787       if (result_count >= 1)
1788         copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
1789       i = 0;
1790       while (result_count--)
1791         if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
1792           break;
1793     }
1794   return result;
1795 }
1796
1797 static int
1798 remote_newthread_step (threadref *ref, void *context)
1799 {
1800   ptid_t ptid;
1801
1802   ptid = pid_to_ptid (threadref_to_int (ref));
1803
1804   if (!in_thread_list (ptid))
1805     add_thread (ptid);
1806   return 1;                     /* continue iterator */
1807 }
1808
1809 #define CRAZY_MAX_THREADS 1000
1810
1811 static ptid_t
1812 remote_current_thread (ptid_t oldpid)
1813 {
1814   struct remote_state *rs = get_remote_state ();
1815
1816   putpkt ("qC");
1817   getpkt (&rs->buf, &rs->buf_size, 0);
1818   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
1819     /* Use strtoul here, so we'll correctly parse values whose highest
1820        bit is set.  The protocol carries them as a simple series of
1821        hex digits; in the absence of a sign, strtol will see such
1822        values as positive numbers out of range for signed 'long', and
1823        return LONG_MAX to indicate an overflow.  */
1824     return pid_to_ptid (strtoul (&rs->buf[2], NULL, 16));
1825   else
1826     return oldpid;
1827 }
1828
1829 /* Find new threads for info threads command.
1830  * Original version, using John Metzler's thread protocol.
1831  */
1832
1833 static void
1834 remote_find_new_threads (void)
1835 {
1836   remote_threadlist_iterator (remote_newthread_step, 0,
1837                               CRAZY_MAX_THREADS);
1838   if (PIDGET (inferior_ptid) == MAGIC_NULL_PID) /* ack ack ack */
1839     inferior_ptid = remote_current_thread (inferior_ptid);
1840 }
1841
1842 /*
1843  * Find all threads for info threads command.
1844  * Uses new thread protocol contributed by Cisco.
1845  * Falls back and attempts to use the older method (above)
1846  * if the target doesn't respond to the new method.
1847  */
1848
1849 static void
1850 remote_threads_info (void)
1851 {
1852   struct remote_state *rs = get_remote_state ();
1853   char *bufp;
1854   int tid;
1855
1856   if (remote_desc == 0)         /* paranoia */
1857     error (_("Command can only be used when connected to the remote target."));
1858
1859   if (use_threadinfo_query)
1860     {
1861       putpkt ("qfThreadInfo");
1862       getpkt (&rs->buf, &rs->buf_size, 0);
1863       bufp = rs->buf;
1864       if (bufp[0] != '\0')              /* q packet recognized */
1865         {
1866           while (*bufp++ == 'm')        /* reply contains one or more TID */
1867             {
1868               do
1869                 {
1870                   /* Use strtoul here, so we'll correctly parse values
1871                      whose highest bit is set.  The protocol carries
1872                      them as a simple series of hex digits; in the
1873                      absence of a sign, strtol will see such values as
1874                      positive numbers out of range for signed 'long',
1875                      and return LONG_MAX to indicate an overflow.  */
1876                   tid = strtoul (bufp, &bufp, 16);
1877                   if (tid != 0 && !in_thread_list (pid_to_ptid (tid)))
1878                     add_thread (pid_to_ptid (tid));
1879                 }
1880               while (*bufp++ == ',');   /* comma-separated list */
1881               putpkt ("qsThreadInfo");
1882               getpkt (&rs->buf, &rs->buf_size, 0);
1883               bufp = rs->buf;
1884             }
1885           return;       /* done */
1886         }
1887     }
1888
1889   /* Else fall back to old method based on jmetzler protocol.  */
1890   use_threadinfo_query = 0;
1891   remote_find_new_threads ();
1892   return;
1893 }
1894
1895 /*
1896  * Collect a descriptive string about the given thread.
1897  * The target may say anything it wants to about the thread
1898  * (typically info about its blocked / runnable state, name, etc.).
1899  * This string will appear in the info threads display.
1900  *
1901  * Optional: targets are not required to implement this function.
1902  */
1903
1904 static char *
1905 remote_threads_extra_info (struct thread_info *tp)
1906 {
1907   struct remote_state *rs = get_remote_state ();
1908   int result;
1909   int set;
1910   threadref id;
1911   struct gdb_ext_thread_info threadinfo;
1912   static char display_buf[100]; /* arbitrary...  */
1913   int n = 0;                    /* position in display_buf */
1914
1915   if (remote_desc == 0)         /* paranoia */
1916     internal_error (__FILE__, __LINE__,
1917                     _("remote_threads_extra_info"));
1918
1919   if (use_threadextra_query)
1920     {
1921       xsnprintf (rs->buf, get_remote_packet_size (), "qThreadExtraInfo,%x",
1922                  PIDGET (tp->ptid));
1923       putpkt (rs->buf);
1924       getpkt (&rs->buf, &rs->buf_size, 0);
1925       if (rs->buf[0] != 0)
1926         {
1927           n = min (strlen (rs->buf) / 2, sizeof (display_buf));
1928           result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
1929           display_buf [result] = '\0';
1930           return display_buf;
1931         }
1932     }
1933
1934   /* If the above query fails, fall back to the old method.  */
1935   use_threadextra_query = 0;
1936   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
1937     | TAG_MOREDISPLAY | TAG_DISPLAY;
1938   int_to_threadref (&id, PIDGET (tp->ptid));
1939   if (remote_get_threadinfo (&id, set, &threadinfo))
1940     if (threadinfo.active)
1941       {
1942         if (*threadinfo.shortname)
1943           n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
1944                           " Name: %s,", threadinfo.shortname);
1945         if (*threadinfo.display)
1946           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
1947                           " State: %s,", threadinfo.display);
1948         if (*threadinfo.more_display)
1949           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
1950                           " Priority: %s", threadinfo.more_display);
1951
1952         if (n > 0)
1953           {
1954             /* For purely cosmetic reasons, clear up trailing commas.  */
1955             if (',' == display_buf[n-1])
1956               display_buf[n-1] = ' ';
1957             return display_buf;
1958           }
1959       }
1960   return NULL;
1961 }
1962 \f
1963
1964 /* Restart the remote side; this is an extended protocol operation.  */
1965
1966 static void
1967 extended_remote_restart (void)
1968 {
1969   struct remote_state *rs = get_remote_state ();
1970
1971   /* Send the restart command; for reasons I don't understand the
1972      remote side really expects a number after the "R".  */
1973   xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
1974   putpkt (rs->buf);
1975
1976   remote_fileio_reset ();
1977
1978   /* Now query for status so this looks just like we restarted
1979      gdbserver from scratch.  */
1980   putpkt ("?");
1981   getpkt (&rs->buf, &rs->buf_size, 0);
1982 }
1983 \f
1984 /* Clean up connection to a remote debugger.  */
1985
1986 static void
1987 remote_close (int quitting)
1988 {
1989   if (remote_desc)
1990     serial_close (remote_desc);
1991   remote_desc = NULL;
1992 }
1993
1994 /* Query the remote side for the text, data and bss offsets.  */
1995
1996 static void
1997 get_offsets (void)
1998 {
1999   struct remote_state *rs = get_remote_state ();
2000   char *buf;
2001   char *ptr;
2002   int lose;
2003   CORE_ADDR text_addr, data_addr, bss_addr;
2004   struct section_offsets *offs;
2005
2006   putpkt ("qOffsets");
2007   getpkt (&rs->buf, &rs->buf_size, 0);
2008   buf = rs->buf;
2009
2010   if (buf[0] == '\000')
2011     return;                     /* Return silently.  Stub doesn't support
2012                                    this command.  */
2013   if (buf[0] == 'E')
2014     {
2015       warning (_("Remote failure reply: %s"), buf);
2016       return;
2017     }
2018
2019   /* Pick up each field in turn.  This used to be done with scanf, but
2020      scanf will make trouble if CORE_ADDR size doesn't match
2021      conversion directives correctly.  The following code will work
2022      with any size of CORE_ADDR.  */
2023   text_addr = data_addr = bss_addr = 0;
2024   ptr = buf;
2025   lose = 0;
2026
2027   if (strncmp (ptr, "Text=", 5) == 0)
2028     {
2029       ptr += 5;
2030       /* Don't use strtol, could lose on big values.  */
2031       while (*ptr && *ptr != ';')
2032         text_addr = (text_addr << 4) + fromhex (*ptr++);
2033     }
2034   else
2035     lose = 1;
2036
2037   if (!lose && strncmp (ptr, ";Data=", 6) == 0)
2038     {
2039       ptr += 6;
2040       while (*ptr && *ptr != ';')
2041         data_addr = (data_addr << 4) + fromhex (*ptr++);
2042     }
2043   else
2044     lose = 1;
2045
2046   if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
2047     {
2048       ptr += 5;
2049       while (*ptr && *ptr != ';')
2050         bss_addr = (bss_addr << 4) + fromhex (*ptr++);
2051     }
2052   else
2053     lose = 1;
2054
2055   if (lose)
2056     error (_("Malformed response to offset query, %s"), buf);
2057
2058   if (symfile_objfile == NULL)
2059     return;
2060
2061   offs = ((struct section_offsets *)
2062           alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
2063   memcpy (offs, symfile_objfile->section_offsets,
2064           SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
2065
2066   offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
2067
2068   /* This is a temporary kludge to force data and bss to use the same offsets
2069      because that's what nlmconv does now.  The real solution requires changes
2070      to the stub and remote.c that I don't have time to do right now.  */
2071
2072   offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
2073   offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
2074
2075   objfile_relocate (symfile_objfile, offs);
2076 }
2077
2078 /* Stub for catch_exception.  */
2079
2080 static void
2081 remote_start_remote (struct ui_out *uiout, void *from_tty_p)
2082 {
2083   int from_tty = * (int *) from_tty_p;
2084
2085   immediate_quit++;             /* Allow user to interrupt it.  */
2086
2087   /* Ack any packet which the remote side has already sent.  */
2088   serial_write (remote_desc, "+", 1);
2089
2090   /* Let the stub know that we want it to return the thread.  */
2091   set_thread (-1, 0);
2092
2093   inferior_ptid = remote_current_thread (inferior_ptid);
2094
2095   get_offsets ();               /* Get text, data & bss offsets.  */
2096
2097   putpkt ("?");                 /* Initiate a query from remote machine.  */
2098   immediate_quit--;
2099
2100   start_remote (from_tty);      /* Initialize gdb process mechanisms.  */
2101 }
2102
2103 /* Open a connection to a remote debugger.
2104    NAME is the filename used for communication.  */
2105
2106 static void
2107 remote_open (char *name, int from_tty)
2108 {
2109   remote_open_1 (name, from_tty, &remote_ops, 0, 0);
2110 }
2111
2112 /* Just like remote_open, but with asynchronous support.  */
2113 static void
2114 remote_async_open (char *name, int from_tty)
2115 {
2116   remote_open_1 (name, from_tty, &remote_async_ops, 0, 1);
2117 }
2118
2119 /* Open a connection to a remote debugger using the extended
2120    remote gdb protocol.  NAME is the filename used for communication.  */
2121
2122 static void
2123 extended_remote_open (char *name, int from_tty)
2124 {
2125   remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */,
2126                  0 /* async_p */);
2127 }
2128
2129 /* Just like extended_remote_open, but with asynchronous support.  */
2130 static void
2131 extended_remote_async_open (char *name, int from_tty)
2132 {
2133   remote_open_1 (name, from_tty, &extended_async_remote_ops,
2134                  1 /*extended_p */, 1 /* async_p */);
2135 }
2136
2137 /* Generic code for opening a connection to a remote target.  */
2138
2139 static void
2140 init_all_packet_configs (void)
2141 {
2142   int i;
2143   for (i = 0; i < PACKET_MAX; i++)
2144     update_packet_config (&remote_protocol_packets[i]);
2145 }
2146
2147 /* Symbol look-up.  */
2148
2149 static void
2150 remote_check_symbols (struct objfile *objfile)
2151 {
2152   struct remote_state *rs = get_remote_state ();
2153   char *msg, *reply, *tmp;
2154   struct minimal_symbol *sym;
2155   int end;
2156
2157   if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
2158     return;
2159
2160   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
2161      because we need both at the same time.  */
2162   msg = alloca (get_remote_packet_size ());
2163
2164   /* Invite target to request symbol lookups.  */
2165
2166   putpkt ("qSymbol::");
2167   getpkt (&rs->buf, &rs->buf_size, 0);
2168   packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2169   reply = rs->buf;
2170
2171   while (strncmp (reply, "qSymbol:", 8) == 0)
2172     {
2173       tmp = &reply[8];
2174       end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
2175       msg[end] = '\0';
2176       sym = lookup_minimal_symbol (msg, NULL, NULL);
2177       if (sym == NULL)
2178         xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
2179       else
2180         xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
2181                    paddr_nz (SYMBOL_VALUE_ADDRESS (sym)),
2182                    &reply[8]);
2183       putpkt (msg);
2184       getpkt (&rs->buf, &rs->buf_size, 0);
2185       reply = rs->buf;
2186     }
2187 }
2188
2189 static struct serial *
2190 remote_serial_open (char *name)
2191 {
2192   static int udp_warning = 0;
2193
2194   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
2195      of in ser-tcp.c, because it is the remote protocol assuming that the
2196      serial connection is reliable and not the serial connection promising
2197      to be.  */
2198   if (!udp_warning && strncmp (name, "udp:", 4) == 0)
2199     {
2200       warning (_("\
2201 The remote protocol may be unreliable over UDP.\n\
2202 Some events may be lost, rendering further debugging impossible."));
2203       udp_warning = 1;
2204     }
2205
2206   return serial_open (name);
2207 }
2208
2209 /* This type describes each known response to the qSupported
2210    packet.  */
2211 struct protocol_feature
2212 {
2213   /* The name of this protocol feature.  */
2214   const char *name;
2215
2216   /* The default for this protocol feature.  */
2217   enum packet_support default_support;
2218
2219   /* The function to call when this feature is reported, or after
2220      qSupported processing if the feature is not supported.
2221      The first argument points to this structure.  The second
2222      argument indicates whether the packet requested support be
2223      enabled, disabled, or probed (or the default, if this function
2224      is being called at the end of processing and this feature was
2225      not reported).  The third argument may be NULL; if not NULL, it
2226      is a NUL-terminated string taken from the packet following
2227      this feature's name and an equals sign.  */
2228   void (*func) (const struct protocol_feature *, enum packet_support,
2229                 const char *);
2230
2231   /* The corresponding packet for this feature.  Only used if
2232      FUNC is remote_supported_packet.  */
2233   int packet;
2234 };
2235
2236 static void
2237 remote_supported_packet (const struct protocol_feature *feature,
2238                          enum packet_support support,
2239                          const char *argument)
2240 {
2241   if (argument)
2242     {
2243       warning (_("Remote qSupported response supplied an unexpected value for"
2244                  " \"%s\"."), feature->name);
2245       return;
2246     }
2247
2248   if (remote_protocol_packets[feature->packet].support
2249       == PACKET_SUPPORT_UNKNOWN)
2250     remote_protocol_packets[feature->packet].support = support;
2251 }
2252
2253 static void
2254 remote_packet_size (const struct protocol_feature *feature,
2255                     enum packet_support support, const char *value)
2256 {
2257   struct remote_state *rs = get_remote_state ();
2258
2259   int packet_size;
2260   char *value_end;
2261
2262   if (support != PACKET_ENABLE)
2263     return;
2264
2265   if (value == NULL || *value == '\0')
2266     {
2267       warning (_("Remote target reported \"%s\" without a size."),
2268                feature->name);
2269       return;
2270     }
2271
2272   errno = 0;
2273   packet_size = strtol (value, &value_end, 16);
2274   if (errno != 0 || *value_end != '\0' || packet_size < 0)
2275     {
2276       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
2277                feature->name, value);
2278       return;
2279     }
2280
2281   if (packet_size > MAX_REMOTE_PACKET_SIZE)
2282     {
2283       warning (_("limiting remote suggested packet size (%d bytes) to %d"),
2284                packet_size, MAX_REMOTE_PACKET_SIZE);
2285       packet_size = MAX_REMOTE_PACKET_SIZE;
2286     }
2287
2288   /* Record the new maximum packet size.  */
2289   rs->explicit_packet_size = packet_size;
2290 }
2291
2292 static struct protocol_feature remote_protocol_features[] = {
2293   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
2294   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
2295     PACKET_qXfer_auxv },
2296   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
2297     PACKET_qXfer_memory_map },
2298   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
2299     PACKET_QPassSignals },
2300 };
2301
2302 static void
2303 remote_query_supported (void)
2304 {
2305   struct remote_state *rs = get_remote_state ();
2306   char *next;
2307   int i;
2308   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
2309
2310   /* The packet support flags are handled differently for this packet
2311      than for most others.  We treat an error, a disabled packet, and
2312      an empty response identically: any features which must be reported
2313      to be used will be automatically disabled.  An empty buffer
2314      accomplishes this, since that is also the representation for a list
2315      containing no features.  */
2316
2317   rs->buf[0] = 0;
2318   if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
2319     {
2320       putpkt ("qSupported");
2321       getpkt (&rs->buf, &rs->buf_size, 0);
2322
2323       /* If an error occured, warn, but do not return - just reset the
2324          buffer to empty and go on to disable features.  */
2325       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
2326           == PACKET_ERROR)
2327         {
2328           warning (_("Remote failure reply: %s"), rs->buf);
2329           rs->buf[0] = 0;
2330         }
2331     }
2332
2333   memset (seen, 0, sizeof (seen));
2334
2335   next = rs->buf;
2336   while (*next)
2337     {
2338       enum packet_support is_supported;
2339       char *p, *end, *name_end, *value;
2340
2341       /* First separate out this item from the rest of the packet.  If
2342          there's another item after this, we overwrite the separator
2343          (terminated strings are much easier to work with).  */
2344       p = next;
2345       end = strchr (p, ';');
2346       if (end == NULL)
2347         {
2348           end = p + strlen (p);
2349           next = end;
2350         }
2351       else
2352         {
2353           *end = '\0';
2354           next = end + 1;
2355
2356           if (end == p)
2357             {
2358               warning (_("empty item in \"qSupported\" response"));
2359               continue;
2360             }
2361         }
2362
2363       name_end = strchr (p, '=');
2364       if (name_end)
2365         {
2366           /* This is a name=value entry.  */
2367           is_supported = PACKET_ENABLE;
2368           value = name_end + 1;
2369           *name_end = '\0';
2370         }
2371       else
2372         {
2373           value = NULL;
2374           switch (end[-1])
2375             {
2376             case '+':
2377               is_supported = PACKET_ENABLE;
2378               break;
2379
2380             case '-':
2381               is_supported = PACKET_DISABLE;
2382               break;
2383
2384             case '?':
2385               is_supported = PACKET_SUPPORT_UNKNOWN;
2386               break;
2387
2388             default:
2389               warning (_("unrecognized item \"%s\" in \"qSupported\" response"), p);
2390               continue;
2391             }
2392           end[-1] = '\0';
2393         }
2394
2395       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
2396         if (strcmp (remote_protocol_features[i].name, p) == 0)
2397           {
2398             const struct protocol_feature *feature;
2399
2400             seen[i] = 1;
2401             feature = &remote_protocol_features[i];
2402             feature->func (feature, is_supported, value);
2403             break;
2404           }
2405     }
2406
2407   /* If we increased the packet size, make sure to increase the global
2408      buffer size also.  We delay this until after parsing the entire
2409      qSupported packet, because this is the same buffer we were
2410      parsing.  */
2411   if (rs->buf_size < rs->explicit_packet_size)
2412     {
2413       rs->buf_size = rs->explicit_packet_size;
2414       rs->buf = xrealloc (rs->buf, rs->buf_size);
2415     }
2416
2417   /* Handle the defaults for unmentioned features.  */
2418   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
2419     if (!seen[i])
2420       {
2421         const struct protocol_feature *feature;
2422
2423         feature = &remote_protocol_features[i];
2424         feature->func (feature, feature->default_support, NULL);
2425       }
2426 }
2427
2428
2429 static void
2430 remote_open_1 (char *name, int from_tty, struct target_ops *target,
2431                int extended_p, int async_p)
2432 {
2433   struct remote_state *rs = get_remote_state ();
2434   if (name == 0)
2435     error (_("To open a remote debug connection, you need to specify what\n"
2436            "serial device is attached to the remote system\n"
2437            "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
2438
2439   /* See FIXME above.  */
2440   if (!async_p)
2441     wait_forever_enabled_p = 1;
2442
2443   target_preopen (from_tty);
2444
2445   unpush_target (target);
2446
2447   /* Make sure we send the passed signals list the next time we resume.  */
2448   xfree (last_pass_packet);
2449   last_pass_packet = NULL;
2450
2451   remote_fileio_reset ();
2452   reopen_exec_file ();
2453   reread_symbols ();
2454
2455   remote_desc = remote_serial_open (name);
2456   if (!remote_desc)
2457     perror_with_name (name);
2458
2459   if (baud_rate != -1)
2460     {
2461       if (serial_setbaudrate (remote_desc, baud_rate))
2462         {
2463           /* The requested speed could not be set.  Error out to
2464              top level after closing remote_desc.  Take care to
2465              set remote_desc to NULL to avoid closing remote_desc
2466              more than once.  */
2467           serial_close (remote_desc);
2468           remote_desc = NULL;
2469           perror_with_name (name);
2470         }
2471     }
2472
2473   serial_raw (remote_desc);
2474
2475   /* If there is something sitting in the buffer we might take it as a
2476      response to a command, which would be bad.  */
2477   serial_flush_input (remote_desc);
2478
2479   if (from_tty)
2480     {
2481       puts_filtered ("Remote debugging using ");
2482       puts_filtered (name);
2483       puts_filtered ("\n");
2484     }
2485   push_target (target);         /* Switch to using remote target now.  */
2486
2487   /* Reset the target state; these things will be queried either by
2488      remote_query_supported or as they are needed.  */
2489   init_all_packet_configs ();
2490   rs->explicit_packet_size = 0;
2491
2492   general_thread = -2;
2493   continue_thread = -2;
2494
2495   /* Probe for ability to use "ThreadInfo" query, as required.  */
2496   use_threadinfo_query = 1;
2497   use_threadextra_query = 1;
2498
2499   /* The first packet we send to the target is the optional "supported
2500      packets" request.  If the target can answer this, it will tell us
2501      which later probes to skip.  */
2502   remote_query_supported ();
2503
2504   /* Without this, some commands which require an active target (such
2505      as kill) won't work.  This variable serves (at least) double duty
2506      as both the pid of the target process (if it has such), and as a
2507      flag indicating that a target is active.  These functions should
2508      be split out into seperate variables, especially since GDB will
2509      someday have a notion of debugging several processes.  */
2510
2511   inferior_ptid = pid_to_ptid (MAGIC_NULL_PID);
2512
2513   if (async_p)
2514     {
2515       /* With this target we start out by owning the terminal.  */
2516       remote_async_terminal_ours_p = 1;
2517
2518       /* FIXME: cagney/1999-09-23: During the initial connection it is
2519          assumed that the target is already ready and able to respond to
2520          requests. Unfortunately remote_start_remote() eventually calls
2521          wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
2522          around this. Eventually a mechanism that allows
2523          wait_for_inferior() to expect/get timeouts will be
2524          implemented.  */
2525       wait_forever_enabled_p = 0;
2526     }
2527
2528   /* First delete any symbols previously loaded from shared libraries.  */
2529   no_shared_libraries (NULL, 0);
2530
2531   /* Start the remote connection.  If error() or QUIT, discard this
2532      target (we'd otherwise be in an inconsistent state) and then
2533      propogate the error on up the exception chain.  This ensures that
2534      the caller doesn't stumble along blindly assuming that the
2535      function succeeded.  The CLI doesn't have this problem but other
2536      UI's, such as MI do.
2537
2538      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
2539      this function should return an error indication letting the
2540      caller restore the previous state.  Unfortunately the command
2541      ``target remote'' is directly wired to this function making that
2542      impossible.  On a positive note, the CLI side of this problem has
2543      been fixed - the function set_cmd_context() makes it possible for
2544      all the ``target ....'' commands to share a common callback
2545      function.  See cli-dump.c.  */
2546   {
2547     struct gdb_exception ex
2548       = catch_exception (uiout, remote_start_remote, &from_tty,
2549                          RETURN_MASK_ALL);
2550     if (ex.reason < 0)
2551       {
2552         pop_target ();
2553         if (async_p)
2554           wait_forever_enabled_p = 1;
2555         throw_exception (ex);
2556       }
2557   }
2558
2559   if (async_p)
2560     wait_forever_enabled_p = 1;
2561
2562   if (extended_p)
2563     {
2564       /* Tell the remote that we are using the extended protocol.  */
2565       putpkt ("!");
2566       getpkt (&rs->buf, &rs->buf_size, 0);
2567     }
2568
2569   if (exec_bfd)         /* No use without an exec file.  */
2570     remote_check_symbols (symfile_objfile);
2571 }
2572
2573 /* This takes a program previously attached to and detaches it.  After
2574    this is done, GDB can be used to debug some other program.  We
2575    better not have left any breakpoints in the target program or it'll
2576    die when it hits one.  */
2577
2578 static void
2579 remote_detach (char *args, int from_tty)
2580 {
2581   struct remote_state *rs = get_remote_state ();
2582
2583   if (args)
2584     error (_("Argument given to \"detach\" when remotely debugging."));
2585
2586   /* Tell the remote target to detach.  */
2587   strcpy (rs->buf, "D");
2588   remote_send (&rs->buf, &rs->buf_size);
2589
2590   /* Unregister the file descriptor from the event loop.  */
2591   if (target_is_async_p ())
2592     serial_async (remote_desc, NULL, 0);
2593
2594   target_mourn_inferior ();
2595   if (from_tty)
2596     puts_filtered ("Ending remote debugging.\n");
2597 }
2598
2599 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
2600
2601 static void
2602 remote_disconnect (struct target_ops *target, char *args, int from_tty)
2603 {
2604   if (args)
2605     error (_("Argument given to \"detach\" when remotely debugging."));
2606
2607   /* Unregister the file descriptor from the event loop.  */
2608   if (target_is_async_p ())
2609     serial_async (remote_desc, NULL, 0);
2610
2611   target_mourn_inferior ();
2612   if (from_tty)
2613     puts_filtered ("Ending remote debugging.\n");
2614 }
2615
2616 /* Convert hex digit A to a number.  */
2617
2618 static int
2619 fromhex (int a)
2620 {
2621   if (a >= '0' && a <= '9')
2622     return a - '0';
2623   else if (a >= 'a' && a <= 'f')
2624     return a - 'a' + 10;
2625   else if (a >= 'A' && a <= 'F')
2626     return a - 'A' + 10;
2627   else
2628     error (_("Reply contains invalid hex digit %d"), a);
2629 }
2630
2631 static int
2632 hex2bin (const char *hex, gdb_byte *bin, int count)
2633 {
2634   int i;
2635
2636   for (i = 0; i < count; i++)
2637     {
2638       if (hex[0] == 0 || hex[1] == 0)
2639         {
2640           /* Hex string is short, or of uneven length.
2641              Return the count that has been converted so far.  */
2642           return i;
2643         }
2644       *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
2645       hex += 2;
2646     }
2647   return i;
2648 }
2649
2650 /* Convert number NIB to a hex digit.  */
2651
2652 static int
2653 tohex (int nib)
2654 {
2655   if (nib < 10)
2656     return '0' + nib;
2657   else
2658     return 'a' + nib - 10;
2659 }
2660
2661 static int
2662 bin2hex (const gdb_byte *bin, char *hex, int count)
2663 {
2664   int i;
2665   /* May use a length, or a nul-terminated string as input.  */
2666   if (count == 0)
2667     count = strlen ((char *) bin);
2668
2669   for (i = 0; i < count; i++)
2670     {
2671       *hex++ = tohex ((*bin >> 4) & 0xf);
2672       *hex++ = tohex (*bin++ & 0xf);
2673     }
2674   *hex = 0;
2675   return i;
2676 }
2677 \f
2678 /* Check for the availability of vCont.  This function should also check
2679    the response.  */
2680
2681 static void
2682 remote_vcont_probe (struct remote_state *rs)
2683 {
2684   char *buf;
2685
2686   strcpy (rs->buf, "vCont?");
2687   putpkt (rs->buf);
2688   getpkt (&rs->buf, &rs->buf_size, 0);
2689   buf = rs->buf;
2690
2691   /* Make sure that the features we assume are supported.  */
2692   if (strncmp (buf, "vCont", 5) == 0)
2693     {
2694       char *p = &buf[5];
2695       int support_s, support_S, support_c, support_C;
2696
2697       support_s = 0;
2698       support_S = 0;
2699       support_c = 0;
2700       support_C = 0;
2701       while (p && *p == ';')
2702         {
2703           p++;
2704           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
2705             support_s = 1;
2706           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
2707             support_S = 1;
2708           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
2709             support_c = 1;
2710           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
2711             support_C = 1;
2712
2713           p = strchr (p, ';');
2714         }
2715
2716       /* If s, S, c, and C are not all supported, we can't use vCont.  Clearing
2717          BUF will make packet_ok disable the packet.  */
2718       if (!support_s || !support_S || !support_c || !support_C)
2719         buf[0] = 0;
2720     }
2721
2722   packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
2723 }
2724
2725 /* Resume the remote inferior by using a "vCont" packet.  The thread
2726    to be resumed is PTID; STEP and SIGGNAL indicate whether the
2727    resumed thread should be single-stepped and/or signalled.  If PTID's
2728    PID is -1, then all threads are resumed; the thread to be stepped and/or
2729    signalled is given in the global INFERIOR_PTID.  This function returns
2730    non-zero iff it resumes the inferior.
2731
2732    This function issues a strict subset of all possible vCont commands at the
2733    moment.  */
2734
2735 static int
2736 remote_vcont_resume (ptid_t ptid, int step, enum target_signal siggnal)
2737 {
2738   struct remote_state *rs = get_remote_state ();
2739   int pid = PIDGET (ptid);
2740   char *buf = NULL, *outbuf;
2741   struct cleanup *old_cleanup;
2742
2743   if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
2744     remote_vcont_probe (rs);
2745
2746   if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
2747     return 0;
2748
2749   /* If we could generate a wider range of packets, we'd have to worry
2750      about overflowing BUF.  Should there be a generic
2751      "multi-part-packet" packet?  */
2752
2753   if (PIDGET (inferior_ptid) == MAGIC_NULL_PID)
2754     {
2755       /* MAGIC_NULL_PTID means that we don't have any active threads, so we
2756          don't have any PID numbers the inferior will understand.  Make sure
2757          to only send forms that do not specify a PID.  */
2758       if (step && siggnal != TARGET_SIGNAL_0)
2759         outbuf = xstrprintf ("vCont;S%02x", siggnal);
2760       else if (step)
2761         outbuf = xstrprintf ("vCont;s");
2762       else if (siggnal != TARGET_SIGNAL_0)
2763         outbuf = xstrprintf ("vCont;C%02x", siggnal);
2764       else
2765         outbuf = xstrprintf ("vCont;c");
2766     }
2767   else if (pid == -1)
2768     {
2769       /* Resume all threads, with preference for INFERIOR_PTID.  */
2770       if (step && siggnal != TARGET_SIGNAL_0)
2771         outbuf = xstrprintf ("vCont;S%02x:%x;c", siggnal,
2772                              PIDGET (inferior_ptid));
2773       else if (step)
2774         outbuf = xstrprintf ("vCont;s:%x;c", PIDGET (inferior_ptid));
2775       else if (siggnal != TARGET_SIGNAL_0)
2776         outbuf = xstrprintf ("vCont;C%02x:%x;c", siggnal,
2777                              PIDGET (inferior_ptid));
2778       else
2779         outbuf = xstrprintf ("vCont;c");
2780     }
2781   else
2782     {
2783       /* Scheduler locking; resume only PTID.  */
2784       if (step && siggnal != TARGET_SIGNAL_0)
2785         outbuf = xstrprintf ("vCont;S%02x:%x", siggnal, pid);
2786       else if (step)
2787         outbuf = xstrprintf ("vCont;s:%x", pid);
2788       else if (siggnal != TARGET_SIGNAL_0)
2789         outbuf = xstrprintf ("vCont;C%02x:%x", siggnal, pid);
2790       else
2791         outbuf = xstrprintf ("vCont;c:%x", pid);
2792     }
2793
2794   gdb_assert (outbuf && strlen (outbuf) < get_remote_packet_size ());
2795   old_cleanup = make_cleanup (xfree, outbuf);
2796
2797   putpkt (outbuf);
2798
2799   do_cleanups (old_cleanup);
2800
2801   return 1;
2802 }
2803
2804 /* Tell the remote machine to resume.  */
2805
2806 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
2807
2808 static int last_sent_step;
2809
2810 static void
2811 remote_resume (ptid_t ptid, int step, enum target_signal siggnal)
2812 {
2813   struct remote_state *rs = get_remote_state ();
2814   char *buf;
2815   int pid = PIDGET (ptid);
2816
2817   last_sent_signal = siggnal;
2818   last_sent_step = step;
2819
2820   /* A hook for when we need to do something at the last moment before
2821      resumption.  */
2822   if (deprecated_target_resume_hook)
2823     (*deprecated_target_resume_hook) ();
2824
2825   /* Update the inferior on signals to silently pass, if they've changed.  */
2826   remote_pass_signals ();
2827
2828   /* The vCont packet doesn't need to specify threads via Hc.  */
2829   if (remote_vcont_resume (ptid, step, siggnal))
2830     return;
2831
2832   /* All other supported resume packets do use Hc, so call set_thread.  */
2833   if (pid == -1)
2834     set_thread (0, 0);          /* Run any thread.  */
2835   else
2836     set_thread (pid, 0);        /* Run this thread.  */
2837
2838   buf = rs->buf;
2839   if (siggnal != TARGET_SIGNAL_0)
2840     {
2841       buf[0] = step ? 'S' : 'C';
2842       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
2843       buf[2] = tohex (((int) siggnal) & 0xf);
2844       buf[3] = '\0';
2845     }
2846   else
2847     strcpy (buf, step ? "s" : "c");
2848
2849   putpkt (buf);
2850 }
2851
2852 /* Same as remote_resume, but with async support.  */
2853 static void
2854 remote_async_resume (ptid_t ptid, int step, enum target_signal siggnal)
2855 {
2856   remote_resume (ptid, step, siggnal);
2857
2858   /* We are about to start executing the inferior, let's register it
2859      with the event loop. NOTE: this is the one place where all the
2860      execution commands end up. We could alternatively do this in each
2861      of the execution commands in infcmd.c.  */
2862   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
2863      into infcmd.c in order to allow inferior function calls to work
2864      NOT asynchronously.  */
2865   if (target_can_async_p ())
2866     target_async (inferior_event_handler, 0);
2867   /* Tell the world that the target is now executing.  */
2868   /* FIXME: cagney/1999-09-23: Is it the targets responsibility to set
2869      this?  Instead, should the client of target just assume (for
2870      async targets) that the target is going to start executing?  Is
2871      this information already found in the continuation block?  */
2872   if (target_is_async_p ())
2873     target_executing = 1;
2874 }
2875 \f
2876
2877 /* Set up the signal handler for SIGINT, while the target is
2878    executing, ovewriting the 'regular' SIGINT signal handler.  */
2879 static void
2880 initialize_sigint_signal_handler (void)
2881 {
2882   sigint_remote_token =
2883     create_async_signal_handler (async_remote_interrupt, NULL);
2884   signal (SIGINT, handle_remote_sigint);
2885 }
2886
2887 /* Signal handler for SIGINT, while the target is executing.  */
2888 static void
2889 handle_remote_sigint (int sig)
2890 {
2891   signal (sig, handle_remote_sigint_twice);
2892   sigint_remote_twice_token =
2893     create_async_signal_handler (async_remote_interrupt_twice, NULL);
2894   mark_async_signal_handler_wrapper (sigint_remote_token);
2895 }
2896
2897 /* Signal handler for SIGINT, installed after SIGINT has already been
2898    sent once.  It will take effect the second time that the user sends
2899    a ^C.  */
2900 static void
2901 handle_remote_sigint_twice (int sig)
2902 {
2903   signal (sig, handle_sigint);
2904   sigint_remote_twice_token =
2905     create_async_signal_handler (inferior_event_handler_wrapper, NULL);
2906   mark_async_signal_handler_wrapper (sigint_remote_twice_token);
2907 }
2908
2909 /* Perform the real interruption of the target execution, in response
2910    to a ^C.  */
2911 static void
2912 async_remote_interrupt (gdb_client_data arg)
2913 {
2914   if (remote_debug)
2915     fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
2916
2917   target_stop ();
2918 }
2919
2920 /* Perform interrupt, if the first attempt did not succeed. Just give
2921    up on the target alltogether.  */
2922 void
2923 async_remote_interrupt_twice (gdb_client_data arg)
2924 {
2925   if (remote_debug)
2926     fprintf_unfiltered (gdb_stdlog, "remote_interrupt_twice called\n");
2927   /* Do something only if the target was not killed by the previous
2928      cntl-C.  */
2929   if (target_executing)
2930     {
2931       interrupt_query ();
2932       signal (SIGINT, handle_remote_sigint);
2933     }
2934 }
2935
2936 /* Reinstall the usual SIGINT handlers, after the target has
2937    stopped.  */
2938 static void
2939 cleanup_sigint_signal_handler (void *dummy)
2940 {
2941   signal (SIGINT, handle_sigint);
2942   if (sigint_remote_twice_token)
2943     delete_async_signal_handler ((struct async_signal_handler **)
2944                                  &sigint_remote_twice_token);
2945   if (sigint_remote_token)
2946     delete_async_signal_handler ((struct async_signal_handler **)
2947                                  &sigint_remote_token);
2948 }
2949
2950 /* Send ^C to target to halt it.  Target will respond, and send us a
2951    packet.  */
2952 static void (*ofunc) (int);
2953
2954 /* The command line interface's stop routine. This function is installed
2955    as a signal handler for SIGINT. The first time a user requests a
2956    stop, we call remote_stop to send a break or ^C. If there is no
2957    response from the target (it didn't stop when the user requested it),
2958    we ask the user if he'd like to detach from the target.  */
2959 static void
2960 remote_interrupt (int signo)
2961 {
2962   /* If this doesn't work, try more severe steps.  */
2963   signal (signo, remote_interrupt_twice);
2964
2965   if (remote_debug)
2966     fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
2967
2968   target_stop ();
2969 }
2970
2971 /* The user typed ^C twice.  */
2972
2973 static void
2974 remote_interrupt_twice (int signo)
2975 {
2976   signal (signo, ofunc);
2977   interrupt_query ();
2978   signal (signo, remote_interrupt);
2979 }
2980
2981 /* This is the generic stop called via the target vector. When a target
2982    interrupt is requested, either by the command line or the GUI, we
2983    will eventually end up here.  */
2984 static void
2985 remote_stop (void)
2986 {
2987   /* Send a break or a ^C, depending on user preference.  */
2988   if (remote_debug)
2989     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
2990
2991   if (remote_break)
2992     serial_send_break (remote_desc);
2993   else
2994     serial_write (remote_desc, "\003", 1);
2995 }
2996
2997 /* Ask the user what to do when an interrupt is received.  */
2998
2999 static void
3000 interrupt_query (void)
3001 {
3002   target_terminal_ours ();
3003
3004   if (query ("Interrupted while waiting for the program.\n\
3005 Give up (and stop debugging it)? "))
3006     {
3007       target_mourn_inferior ();
3008       deprecated_throw_reason (RETURN_QUIT);
3009     }
3010
3011   target_terminal_inferior ();
3012 }
3013
3014 /* Enable/disable target terminal ownership.  Most targets can use
3015    terminal groups to control terminal ownership.  Remote targets are
3016    different in that explicit transfer of ownership to/from GDB/target
3017    is required.  */
3018
3019 static void
3020 remote_async_terminal_inferior (void)
3021 {
3022   /* FIXME: cagney/1999-09-27: Shouldn't need to test for
3023      sync_execution here.  This function should only be called when
3024      GDB is resuming the inferior in the forground.  A background
3025      resume (``run&'') should leave GDB in control of the terminal and
3026      consequently should not call this code.  */
3027   if (!sync_execution)
3028     return;
3029   /* FIXME: cagney/1999-09-27: Closely related to the above.  Make
3030      calls target_terminal_*() idenpotent. The event-loop GDB talking
3031      to an asynchronous target with a synchronous command calls this
3032      function from both event-top.c and infrun.c/infcmd.c.  Once GDB
3033      stops trying to transfer the terminal to the target when it
3034      shouldn't this guard can go away.  */
3035   if (!remote_async_terminal_ours_p)
3036     return;
3037   delete_file_handler (input_fd);
3038   remote_async_terminal_ours_p = 0;
3039   initialize_sigint_signal_handler ();
3040   /* NOTE: At this point we could also register our selves as the
3041      recipient of all input.  Any characters typed could then be
3042      passed on down to the target.  */
3043 }
3044
3045 static void
3046 remote_async_terminal_ours (void)
3047 {
3048   /* See FIXME in remote_async_terminal_inferior.  */
3049   if (!sync_execution)
3050     return;
3051   /* See FIXME in remote_async_terminal_inferior.  */
3052   if (remote_async_terminal_ours_p)
3053     return;
3054   cleanup_sigint_signal_handler (NULL);
3055   add_file_handler (input_fd, stdin_event_handler, 0);
3056   remote_async_terminal_ours_p = 1;
3057 }
3058
3059 /* If nonzero, ignore the next kill.  */
3060
3061 int kill_kludge;
3062
3063 void
3064 remote_console_output (char *msg)
3065 {
3066   char *p;
3067
3068   for (p = msg; p[0] && p[1]; p += 2)
3069     {
3070       char tb[2];
3071       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
3072       tb[0] = c;
3073       tb[1] = 0;
3074       fputs_unfiltered (tb, gdb_stdtarg);
3075     }
3076   gdb_flush (gdb_stdtarg);
3077 }
3078
3079 /* Wait until the remote machine stops, then return,
3080    storing status in STATUS just as `wait' would.
3081    Returns "pid", which in the case of a multi-threaded
3082    remote OS, is the thread-id.  */
3083
3084 static ptid_t
3085 remote_wait (ptid_t ptid, struct target_waitstatus *status)
3086 {
3087   struct remote_state *rs = get_remote_state ();
3088   struct remote_arch_state *rsa = get_remote_arch_state ();
3089   ULONGEST thread_num = -1;
3090   ULONGEST addr;
3091
3092   status->kind = TARGET_WAITKIND_EXITED;
3093   status->value.integer = 0;
3094
3095   while (1)
3096     {
3097       char *buf, *p;
3098
3099       ofunc = signal (SIGINT, remote_interrupt);
3100       getpkt (&rs->buf, &rs->buf_size, 1);
3101       signal (SIGINT, ofunc);
3102
3103       buf = rs->buf;
3104
3105       /* This is a hook for when we need to do something (perhaps the
3106          collection of trace data) every time the target stops.  */
3107       if (deprecated_target_wait_loop_hook)
3108         (*deprecated_target_wait_loop_hook) ();
3109
3110       remote_stopped_by_watchpoint_p = 0;
3111
3112       switch (buf[0])
3113         {
3114         case 'E':               /* Error of some sort.  */
3115           warning (_("Remote failure reply: %s"), buf);
3116           continue;
3117         case 'F':               /* File-I/O request.  */
3118           remote_fileio_request (buf);
3119           continue;
3120         case 'T':               /* Status with PC, SP, FP, ...  */
3121           {
3122             gdb_byte regs[MAX_REGISTER_SIZE];
3123
3124             /* Expedited reply, containing Signal, {regno, reg} repeat.  */
3125             /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
3126                ss = signal number
3127                n... = register number
3128                r... = register contents
3129              */
3130             p = &buf[3];        /* after Txx */
3131
3132             while (*p)
3133               {
3134                 char *p1;
3135                 char *p_temp;
3136                 int fieldsize;
3137                 LONGEST pnum = 0;
3138
3139                 /* If the packet contains a register number save it in
3140                    pnum and set p1 to point to the character following
3141                    it.  Otherwise p1 points to p.  */
3142
3143                 /* If this packet is an awatch packet, don't parse the
3144                    'a' as a register number.  */
3145
3146                 if (strncmp (p, "awatch", strlen("awatch")) != 0)
3147                   {
3148                     /* Read the ``P'' register number.  */
3149                     pnum = strtol (p, &p_temp, 16);
3150                     p1 = p_temp;
3151                   }
3152                 else
3153                   p1 = p;
3154
3155                 if (p1 == p)    /* No register number present here.  */
3156                   {
3157                     p1 = strchr (p, ':');
3158                     if (p1 == NULL)
3159                       error (_("Malformed packet(a) (missing colon): %s\n\
3160 Packet: '%s'\n"),
3161                              p, buf);
3162                     if (strncmp (p, "thread", p1 - p) == 0)
3163                       {
3164                         p_temp = unpack_varlen_hex (++p1, &thread_num);
3165                         record_currthread (thread_num);
3166                         p = p_temp;
3167                       }
3168                     else if ((strncmp (p, "watch", p1 - p) == 0)
3169                              || (strncmp (p, "rwatch", p1 - p) == 0)
3170                              || (strncmp (p, "awatch", p1 - p) == 0))
3171                       {
3172                         remote_stopped_by_watchpoint_p = 1;
3173                         p = unpack_varlen_hex (++p1, &addr);
3174                         remote_watch_data_address = (CORE_ADDR)addr;
3175                       }
3176                     else
3177                       {
3178                         /* Silently skip unknown optional info.  */
3179                         p_temp = strchr (p1 + 1, ';');
3180                         if (p_temp)
3181                           p = p_temp;
3182                       }
3183                   }
3184                 else
3185                   {
3186                     struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
3187                     p = p1;
3188
3189                     if (*p++ != ':')
3190                       error (_("Malformed packet(b) (missing colon): %s\n\
3191 Packet: '%s'\n"),
3192                              p, buf);
3193
3194                     if (reg == NULL)
3195                       error (_("Remote sent bad register number %s: %s\n\
3196 Packet: '%s'\n"),
3197                              phex_nz (pnum, 0), p, buf);
3198
3199                     fieldsize = hex2bin (p, regs,
3200                                          register_size (current_gdbarch,
3201                                                         reg->regnum));
3202                     p += 2 * fieldsize;
3203                     if (fieldsize < register_size (current_gdbarch,
3204                                                    reg->regnum))
3205                       warning (_("Remote reply is too short: %s"), buf);
3206                     regcache_raw_supply (current_regcache,
3207                                          reg->regnum, regs);
3208                   }
3209
3210                 if (*p++ != ';')
3211                   error (_("Remote register badly formatted: %s\nhere: %s"),
3212                          buf, p);
3213               }
3214           }
3215           /* fall through */
3216         case 'S':               /* Old style status, just signal only.  */
3217           status->kind = TARGET_WAITKIND_STOPPED;
3218           status->value.sig = (enum target_signal)
3219             (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3220
3221           if (buf[3] == 'p')
3222             {
3223               thread_num = strtol ((const char *) &buf[4], NULL, 16);
3224               record_currthread (thread_num);
3225             }
3226           goto got_status;
3227         case 'W':               /* Target exited.  */
3228           {
3229             /* The remote process exited.  */
3230             status->kind = TARGET_WAITKIND_EXITED;
3231             status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
3232             goto got_status;
3233           }
3234         case 'X':
3235           status->kind = TARGET_WAITKIND_SIGNALLED;
3236           status->value.sig = (enum target_signal)
3237             (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3238           kill_kludge = 1;
3239
3240           goto got_status;
3241         case 'O':               /* Console output.  */
3242           remote_console_output (buf + 1);
3243           continue;
3244         case '\0':
3245           if (last_sent_signal != TARGET_SIGNAL_0)
3246             {
3247               /* Zero length reply means that we tried 'S' or 'C' and
3248                  the remote system doesn't support it.  */
3249               target_terminal_ours_for_output ();
3250               printf_filtered
3251                 ("Can't send signals to this remote system.  %s not sent.\n",
3252                  target_signal_to_name (last_sent_signal));
3253               last_sent_signal = TARGET_SIGNAL_0;
3254               target_terminal_inferior ();
3255
3256               strcpy ((char *) buf, last_sent_step ? "s" : "c");
3257               putpkt ((char *) buf);
3258               continue;
3259             }
3260           /* else fallthrough */
3261         default:
3262           warning (_("Invalid remote reply: %s"), buf);
3263           continue;
3264         }
3265     }
3266 got_status:
3267   if (thread_num != -1)
3268     {
3269       return pid_to_ptid (thread_num);
3270     }
3271   return inferior_ptid;
3272 }
3273
3274 /* Async version of remote_wait.  */
3275 static ptid_t
3276 remote_async_wait (ptid_t ptid, struct target_waitstatus *status)
3277 {
3278   struct remote_state *rs = get_remote_state ();
3279   struct remote_arch_state *rsa = get_remote_arch_state ();
3280   ULONGEST thread_num = -1;
3281   ULONGEST addr;
3282
3283   status->kind = TARGET_WAITKIND_EXITED;
3284   status->value.integer = 0;
3285
3286   remote_stopped_by_watchpoint_p = 0;
3287
3288   while (1)
3289     {
3290       char *buf, *p;
3291
3292       if (!target_is_async_p ())
3293         ofunc = signal (SIGINT, remote_interrupt);
3294       /* FIXME: cagney/1999-09-27: If we're in async mode we should
3295          _never_ wait for ever -> test on target_is_async_p().
3296          However, before we do that we need to ensure that the caller
3297          knows how to take the target into/out of async mode.  */
3298       getpkt (&rs->buf, &rs->buf_size, wait_forever_enabled_p);
3299       if (!target_is_async_p ())
3300         signal (SIGINT, ofunc);
3301
3302       buf = rs->buf;
3303
3304       /* This is a hook for when we need to do something (perhaps the
3305          collection of trace data) every time the target stops.  */
3306       if (deprecated_target_wait_loop_hook)
3307         (*deprecated_target_wait_loop_hook) ();
3308
3309       switch (buf[0])
3310         {
3311         case 'E':               /* Error of some sort.  */
3312           warning (_("Remote failure reply: %s"), buf);
3313           continue;
3314         case 'F':               /* File-I/O request.  */
3315           remote_fileio_request (buf);
3316           continue;
3317         case 'T':               /* Status with PC, SP, FP, ...  */
3318           {
3319             gdb_byte regs[MAX_REGISTER_SIZE];
3320
3321             /* Expedited reply, containing Signal, {regno, reg} repeat.  */
3322             /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
3323                ss = signal number
3324                n... = register number
3325                r... = register contents
3326              */
3327             p = &buf[3];        /* after Txx */
3328
3329             while (*p)
3330               {
3331                 char *p1;
3332                 char *p_temp;
3333                 int fieldsize;
3334                 long pnum = 0;
3335
3336                 /* If the packet contains a register number, save it
3337                    in pnum and set p1 to point to the character
3338                    following it.  Otherwise p1 points to p.  */
3339
3340                 /* If this packet is an awatch packet, don't parse the 'a'
3341                    as a register number.  */
3342
3343                 if (!strncmp (p, "awatch", strlen ("awatch")) != 0)
3344                   {
3345                     /* Read the register number.  */
3346                     pnum = strtol (p, &p_temp, 16);
3347                     p1 = p_temp;
3348                   }
3349                 else
3350                   p1 = p;
3351
3352                 if (p1 == p)    /* No register number present here.  */
3353                   {
3354                     p1 = strchr (p, ':');
3355                     if (p1 == NULL)
3356                       error (_("Malformed packet(a) (missing colon): %s\n\
3357 Packet: '%s'\n"),
3358                              p, buf);
3359                     if (strncmp (p, "thread", p1 - p) == 0)
3360                       {
3361                         p_temp = unpack_varlen_hex (++p1, &thread_num);
3362                         record_currthread (thread_num);
3363                         p = p_temp;
3364                       }
3365                     else if ((strncmp (p, "watch", p1 - p) == 0)
3366                              || (strncmp (p, "rwatch", p1 - p) == 0)
3367                              || (strncmp (p, "awatch", p1 - p) == 0))
3368                       {
3369                         remote_stopped_by_watchpoint_p = 1;
3370                         p = unpack_varlen_hex (++p1, &addr);
3371                         remote_watch_data_address = (CORE_ADDR)addr;
3372                       }
3373                     else
3374                       {
3375                         /* Silently skip unknown optional info.  */
3376                         p_temp = strchr (p1 + 1, ';');
3377                         if (p_temp)
3378                           p = p_temp;
3379                       }
3380                   }
3381
3382                 else
3383                   {
3384                     struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
3385                     p = p1;
3386                     if (*p++ != ':')
3387                       error (_("Malformed packet(b) (missing colon): %s\n\
3388 Packet: '%s'\n"),
3389                              p, buf);
3390
3391                     if (reg == NULL)
3392                       error (_("Remote sent bad register number %ld: %s\n\
3393 Packet: '%s'\n"),
3394                              pnum, p, buf);
3395
3396                     fieldsize = hex2bin (p, regs,
3397                                          register_size (current_gdbarch,
3398                                                         reg->regnum));
3399                     p += 2 * fieldsize;
3400                     if (fieldsize < register_size (current_gdbarch,
3401                                                    reg->regnum))
3402                       warning (_("Remote reply is too short: %s"), buf);
3403                     regcache_raw_supply (current_regcache, reg->regnum, regs);
3404                   }
3405
3406                 if (*p++ != ';')
3407                   error (_("Remote register badly formatted: %s\nhere: %s"),
3408                          buf, p);
3409               }
3410           }
3411           /* fall through */
3412         case 'S':               /* Old style status, just signal only.  */
3413           status->kind = TARGET_WAITKIND_STOPPED;
3414           status->value.sig = (enum target_signal)
3415             (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3416
3417           if (buf[3] == 'p')
3418             {
3419               thread_num = strtol ((const char *) &buf[4], NULL, 16);
3420               record_currthread (thread_num);
3421             }
3422           goto got_status;
3423         case 'W':               /* Target exited.  */
3424           {
3425             /* The remote process exited.  */
3426             status->kind = TARGET_WAITKIND_EXITED;
3427             status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
3428             goto got_status;
3429           }
3430         case 'X':
3431           status->kind = TARGET_WAITKIND_SIGNALLED;
3432           status->value.sig = (enum target_signal)
3433             (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3434           kill_kludge = 1;
3435
3436           goto got_status;
3437         case 'O':               /* Console output.  */
3438           remote_console_output (buf + 1);
3439           /* Return immediately to the event loop. The event loop will
3440              still be waiting on the inferior afterwards.  */
3441           status->kind = TARGET_WAITKIND_IGNORE;
3442           goto got_status;
3443         case '\0':
3444           if (last_sent_signal != TARGET_SIGNAL_0)
3445             {
3446               /* Zero length reply means that we tried 'S' or 'C' and
3447                  the remote system doesn't support it.  */
3448               target_terminal_ours_for_output ();
3449               printf_filtered
3450                 ("Can't send signals to this remote system.  %s not sent.\n",
3451                  target_signal_to_name (last_sent_signal));
3452               last_sent_signal = TARGET_SIGNAL_0;
3453               target_terminal_inferior ();
3454
3455               strcpy ((char *) buf, last_sent_step ? "s" : "c");
3456               putpkt ((char *) buf);
3457               continue;
3458             }
3459           /* else fallthrough */
3460         default:
3461           warning (_("Invalid remote reply: %s"), buf);
3462           continue;
3463         }
3464     }
3465 got_status:
3466   if (thread_num != -1)
3467     {
3468       return pid_to_ptid (thread_num);
3469     }
3470   return inferior_ptid;
3471 }
3472
3473 /* Fetch a single register using a 'p' packet.  */
3474
3475 static int
3476 fetch_register_using_p (struct packet_reg *reg)
3477 {
3478   struct remote_state *rs = get_remote_state ();
3479   char *buf, *p;
3480   char regp[MAX_REGISTER_SIZE];
3481   int i;
3482
3483   if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
3484     return 0;
3485
3486   if (reg->pnum == -1)
3487     return 0;
3488
3489   p = rs->buf;
3490   *p++ = 'p';
3491   p += hexnumstr (p, reg->pnum);
3492   *p++ = '\0';
3493   remote_send (&rs->buf, &rs->buf_size);
3494
3495   buf = rs->buf;
3496
3497   switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
3498     {
3499     case PACKET_OK:
3500       break;
3501     case PACKET_UNKNOWN:
3502       return 0;
3503     case PACKET_ERROR:
3504       error (_("Could not fetch register \"%s\""),
3505              gdbarch_register_name (current_gdbarch, reg->regnum));
3506     }
3507
3508   /* If this register is unfetchable, tell the regcache.  */
3509   if (buf[0] == 'x')
3510     {
3511       regcache_raw_supply (current_regcache, reg->regnum, NULL);
3512       set_register_cached (reg->regnum, -1);
3513       return 1;
3514     }
3515
3516   /* Otherwise, parse and supply the value.  */
3517   p = buf;
3518   i = 0;
3519   while (p[0] != 0)
3520     {
3521       if (p[1] == 0)
3522         error (_("fetch_register_using_p: early buf termination"));
3523
3524       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
3525       p += 2;
3526     }
3527   regcache_raw_supply (current_regcache, reg->regnum, regp);
3528   return 1;
3529 }
3530
3531 /* Fetch the registers included in the target's 'g' packet.  */
3532
3533 static void
3534 fetch_registers_using_g (void)
3535 {
3536   struct remote_state *rs = get_remote_state ();
3537   struct remote_arch_state *rsa = get_remote_arch_state ();
3538   int i, buf_len;
3539   char *p;
3540   char *regs;
3541
3542   sprintf (rs->buf, "g");
3543   remote_send (&rs->buf, &rs->buf_size);
3544
3545   buf_len = strlen (rs->buf);
3546
3547   /* Sanity check the received packet.  */
3548   if (buf_len % 2 != 0)
3549     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
3550   if (REGISTER_BYTES_OK_P () && !REGISTER_BYTES_OK (buf_len / 2))
3551     error (_("Remote 'g' packet reply is wrong length: %s"), rs->buf);
3552   if (buf_len > 2 * rsa->sizeof_g_packet)
3553     error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
3554
3555   /* Save the size of the packet sent to us by the target.  It is used
3556      as a heuristic when determining the max size of packets that the
3557      target can safely receive.  */
3558   if (rsa->actual_register_packet_size == 0)
3559     rsa->actual_register_packet_size = buf_len;
3560
3561   /* If this is smaller than we guessed the 'g' packet would be,
3562      update our records.  A 'g' reply that doesn't include a register's
3563      value implies either that the register is not available, or that
3564      the 'p' packet must be used.  */
3565   if (buf_len < 2 * rsa->sizeof_g_packet)
3566     {
3567       rsa->sizeof_g_packet = buf_len / 2;
3568
3569       for (i = 0; i < NUM_REGS; i++)
3570         {
3571           if (rsa->regs[i].pnum == -1)
3572             continue;
3573
3574           if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
3575             rsa->regs[i].in_g_packet = 0;
3576           else
3577             rsa->regs[i].in_g_packet = 1;
3578         }
3579     }
3580
3581   regs = alloca (rsa->sizeof_g_packet);
3582
3583   /* Unimplemented registers read as all bits zero.  */
3584   memset (regs, 0, rsa->sizeof_g_packet);
3585
3586   /* We can get out of synch in various cases.  If the first character
3587      in the buffer is not a hex character, assume that has happened
3588      and try to fetch another packet to read.  */
3589   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
3590          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
3591          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
3592          && rs->buf[0] != 'x')  /* New: unavailable register value.  */
3593     {
3594       if (remote_debug)
3595         fprintf_unfiltered (gdb_stdlog,
3596                             "Bad register packet; fetching a new packet\n");
3597       getpkt (&rs->buf, &rs->buf_size, 0);
3598     }
3599
3600   /* Reply describes registers byte by byte, each byte encoded as two
3601      hex characters.  Suck them all up, then supply them to the
3602      register cacheing/storage mechanism.  */
3603
3604   p = rs->buf;
3605   for (i = 0; i < rsa->sizeof_g_packet; i++)
3606     {
3607       if (p[0] == 0 || p[1] == 0)
3608         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
3609         internal_error (__FILE__, __LINE__,
3610                         "unexpected end of 'g' packet reply");
3611
3612       if (p[0] == 'x' && p[1] == 'x')
3613         regs[i] = 0;            /* 'x' */
3614       else
3615         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
3616       p += 2;
3617     }
3618
3619   {
3620     int i;
3621     for (i = 0; i < NUM_REGS; i++)
3622       {
3623         struct packet_reg *r = &rsa->regs[i];
3624         if (r->in_g_packet)
3625           {
3626             if (r->offset * 2 >= strlen (rs->buf))
3627               /* This shouldn't happen - we adjusted in_g_packet above.  */
3628               internal_error (__FILE__, __LINE__,
3629                               "unexpected end of 'g' packet reply");
3630             else if (rs->buf[r->offset * 2] == 'x')
3631               {
3632                 gdb_assert (r->offset * 2 < strlen (rs->buf));
3633                 /* The register isn't available, mark it as such (at
3634                    the same time setting the value to zero).  */
3635                 regcache_raw_supply (current_regcache, r->regnum, NULL);
3636                 set_register_cached (i, -1);
3637               }
3638             else
3639               regcache_raw_supply (current_regcache, r->regnum,
3640                                    regs + r->offset);
3641           }
3642       }
3643   }
3644 }
3645
3646 static void
3647 remote_fetch_registers (int regnum)
3648 {
3649   struct remote_state *rs = get_remote_state ();
3650   struct remote_arch_state *rsa = get_remote_arch_state ();
3651   int i;
3652
3653   set_thread (PIDGET (inferior_ptid), 1);
3654
3655   if (regnum >= 0)
3656     {
3657       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
3658       gdb_assert (reg != NULL);
3659
3660       /* If this register might be in the 'g' packet, try that first -
3661          we are likely to read more than one register.  If this is the
3662          first 'g' packet, we might be overly optimistic about its
3663          contents, so fall back to 'p'.  */
3664       if (reg->in_g_packet)
3665         {
3666           fetch_registers_using_g ();
3667           if (reg->in_g_packet)
3668             return;
3669         }
3670
3671       if (fetch_register_using_p (reg))
3672         return;
3673
3674       /* This register is not available.  */
3675       regcache_raw_supply (current_regcache, reg->regnum, NULL);
3676       set_register_cached (reg->regnum, -1);
3677
3678       return;
3679     }
3680
3681   fetch_registers_using_g ();
3682
3683   for (i = 0; i < NUM_REGS; i++)
3684     if (!rsa->regs[i].in_g_packet)
3685       if (!fetch_register_using_p (&rsa->regs[i]))
3686         {
3687           /* This register is not available.  */
3688           regcache_raw_supply (current_regcache, i, NULL);
3689           set_register_cached (i, -1);
3690         }
3691 }
3692
3693 /* Prepare to store registers.  Since we may send them all (using a
3694    'G' request), we have to read out the ones we don't want to change
3695    first.  */
3696
3697 static void
3698 remote_prepare_to_store (void)
3699 {
3700   struct remote_arch_state *rsa = get_remote_arch_state ();
3701   int i;
3702   gdb_byte buf[MAX_REGISTER_SIZE];
3703
3704   /* Make sure the entire registers array is valid.  */
3705   switch (remote_protocol_packets[PACKET_P].support)
3706     {
3707     case PACKET_DISABLE:
3708     case PACKET_SUPPORT_UNKNOWN:
3709       /* Make sure all the necessary registers are cached.  */
3710       for (i = 0; i < NUM_REGS; i++)
3711         if (rsa->regs[i].in_g_packet)
3712           regcache_raw_read (current_regcache, rsa->regs[i].regnum, buf);
3713       break;
3714     case PACKET_ENABLE:
3715       break;
3716     }
3717 }
3718
3719 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
3720    packet was not recognized.  */
3721
3722 static int
3723 store_register_using_P (struct packet_reg *reg)
3724 {
3725   struct remote_state *rs = get_remote_state ();
3726   struct remote_arch_state *rsa = get_remote_arch_state ();
3727   /* Try storing a single register.  */
3728   char *buf = rs->buf;
3729   gdb_byte regp[MAX_REGISTER_SIZE];
3730   char *p;
3731
3732   if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
3733     return 0;
3734
3735   if (reg->pnum == -1)
3736     return 0;
3737
3738   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
3739   p = buf + strlen (buf);
3740   regcache_raw_collect (current_regcache, reg->regnum, regp);
3741   bin2hex (regp, p, register_size (current_gdbarch, reg->regnum));
3742   remote_send (&rs->buf, &rs->buf_size);
3743
3744   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
3745     {
3746     case PACKET_OK:
3747       return 1;
3748     case PACKET_ERROR:
3749       error (_("Could not write register \"%s\""),
3750              gdbarch_register_name (current_gdbarch, reg->regnum));
3751     case PACKET_UNKNOWN:
3752       return 0;
3753     default:
3754       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
3755     }
3756 }
3757
3758 /* Store register REGNUM, or all registers if REGNUM == -1, from the
3759    contents of the register cache buffer.  FIXME: ignores errors.  */
3760
3761 static void
3762 store_registers_using_G (void)
3763 {
3764   struct remote_state *rs = get_remote_state ();
3765   struct remote_arch_state *rsa = get_remote_arch_state ();
3766   gdb_byte *regs;
3767   char *p;
3768
3769   /* Extract all the registers in the regcache copying them into a
3770      local buffer.  */
3771   {
3772     int i;
3773     regs = alloca (rsa->sizeof_g_packet);
3774     memset (regs, 0, rsa->sizeof_g_packet);
3775     for (i = 0; i < NUM_REGS; i++)
3776       {
3777         struct packet_reg *r = &rsa->regs[i];
3778         if (r->in_g_packet)
3779           regcache_raw_collect (current_regcache, r->regnum, regs + r->offset);
3780       }
3781   }
3782
3783   /* Command describes registers byte by byte,
3784      each byte encoded as two hex characters.  */
3785   p = rs->buf;
3786   *p++ = 'G';
3787   /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
3788      updated.  */
3789   bin2hex (regs, p, rsa->sizeof_g_packet);
3790   remote_send (&rs->buf, &rs->buf_size);
3791 }
3792
3793 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
3794    of the register cache buffer.  FIXME: ignores errors.  */
3795
3796 static void
3797 remote_store_registers (int regnum)
3798 {
3799   struct remote_state *rs = get_remote_state ();
3800   struct remote_arch_state *rsa = get_remote_arch_state ();
3801   int i;
3802
3803   set_thread (PIDGET (inferior_ptid), 1);
3804
3805   if (regnum >= 0)
3806     {
3807       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
3808       gdb_assert (reg != NULL);
3809
3810       /* Always prefer to store registers using the 'P' packet if
3811          possible; we often change only a small number of registers.
3812          Sometimes we change a larger number; we'd need help from a
3813          higher layer to know to use 'G'.  */
3814       if (store_register_using_P (reg))
3815         return;
3816
3817       /* For now, don't complain if we have no way to write the
3818          register.  GDB loses track of unavailable registers too
3819          easily.  Some day, this may be an error.  We don't have
3820          any way to read the register, either... */
3821       if (!reg->in_g_packet)
3822         return;
3823
3824       store_registers_using_G ();
3825       return;
3826     }
3827
3828   store_registers_using_G ();
3829
3830   for (i = 0; i < NUM_REGS; i++)
3831     if (!rsa->regs[i].in_g_packet)
3832       if (!store_register_using_P (&rsa->regs[i]))
3833         /* See above for why we do not issue an error here.  */
3834         continue;
3835 }
3836 \f
3837
3838 /* Return the number of hex digits in num.  */
3839
3840 static int
3841 hexnumlen (ULONGEST num)
3842 {
3843   int i;
3844
3845   for (i = 0; num != 0; i++)
3846     num >>= 4;
3847
3848   return max (i, 1);
3849 }
3850
3851 /* Set BUF to the minimum number of hex digits representing NUM.  */
3852
3853 static int
3854 hexnumstr (char *buf, ULONGEST num)
3855 {
3856   int len = hexnumlen (num);
3857   return hexnumnstr (buf, num, len);
3858 }
3859
3860
3861 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
3862
3863 static int
3864 hexnumnstr (char *buf, ULONGEST num, int width)
3865 {
3866   int i;
3867
3868   buf[width] = '\0';
3869
3870   for (i = width - 1; i >= 0; i--)
3871     {
3872       buf[i] = "0123456789abcdef"[(num & 0xf)];
3873       num >>= 4;
3874     }
3875
3876   return width;
3877 }
3878
3879 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
3880
3881 static CORE_ADDR
3882 remote_address_masked (CORE_ADDR addr)
3883 {
3884   if (remote_address_size > 0
3885       && remote_address_size < (sizeof (ULONGEST) * 8))
3886     {
3887       /* Only create a mask when that mask can safely be constructed
3888          in a ULONGEST variable.  */
3889       ULONGEST mask = 1;
3890       mask = (mask << remote_address_size) - 1;
3891       addr &= mask;
3892     }
3893   return addr;
3894 }
3895
3896 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
3897    binary data in OUT_BUF.  Set *OUT_LEN to the length of the data
3898    encoded in OUT_BUF, and return the number of bytes in OUT_BUF
3899    (which may be more than *OUT_LEN due to escape characters).  The
3900    total number of bytes in the output buffer will be at most
3901    OUT_MAXLEN.  */
3902
3903 static int
3904 remote_escape_output (const gdb_byte *buffer, int len,
3905                       gdb_byte *out_buf, int *out_len,
3906                       int out_maxlen)
3907 {
3908   int input_index, output_index;
3909
3910   output_index = 0;
3911   for (input_index = 0; input_index < len; input_index++)
3912     {
3913       gdb_byte b = buffer[input_index];
3914
3915       if (b == '$' || b == '#' || b == '}')
3916         {
3917           /* These must be escaped.  */
3918           if (output_index + 2 > out_maxlen)
3919             break;
3920           out_buf[output_index++] = '}';
3921           out_buf[output_index++] = b ^ 0x20;
3922         }
3923       else
3924         {
3925           if (output_index + 1 > out_maxlen)
3926             break;
3927           out_buf[output_index++] = b;
3928         }
3929     }
3930
3931   *out_len = input_index;
3932   return output_index;
3933 }
3934
3935 /* Convert BUFFER, escaped data LEN bytes long, into binary data
3936    in OUT_BUF.  Return the number of bytes written to OUT_BUF.
3937    Raise an error if the total number of bytes exceeds OUT_MAXLEN.
3938
3939    This function reverses remote_escape_output.  It allows more
3940    escaped characters than that function does, in particular because
3941    '*' must be escaped to avoid the run-length encoding processing
3942    in reading packets.  */
3943
3944 static int
3945 remote_unescape_input (const gdb_byte *buffer, int len,
3946                        gdb_byte *out_buf, int out_maxlen)
3947 {
3948   int input_index, output_index;
3949   int escaped;
3950
3951   output_index = 0;
3952   escaped = 0;
3953   for (input_index = 0; input_index < len; input_index++)
3954     {
3955       gdb_byte b = buffer[input_index];
3956
3957       if (output_index + 1 > out_maxlen)
3958         {
3959           warning (_("Received too much data from remote target;"
3960                      " ignoring overflow."));
3961           return output_index;
3962         }
3963
3964       if (escaped)
3965         {
3966           out_buf[output_index++] = b ^ 0x20;
3967           escaped = 0;
3968         }
3969       else if (b == '}')
3970         escaped = 1;
3971       else
3972         out_buf[output_index++] = b;
3973     }
3974
3975   if (escaped)
3976     error (_("Unmatched escape character in target response."));
3977
3978   return output_index;
3979 }
3980
3981 /* Determine whether the remote target supports binary downloading.
3982    This is accomplished by sending a no-op memory write of zero length
3983    to the target at the specified address. It does not suffice to send
3984    the whole packet, since many stubs strip the eighth bit and
3985    subsequently compute a wrong checksum, which causes real havoc with
3986    remote_write_bytes.
3987
3988    NOTE: This can still lose if the serial line is not eight-bit
3989    clean. In cases like this, the user should clear "remote
3990    X-packet".  */
3991
3992 static void
3993 check_binary_download (CORE_ADDR addr)
3994 {
3995   struct remote_state *rs = get_remote_state ();
3996
3997   switch (remote_protocol_packets[PACKET_X].support)
3998     {
3999     case PACKET_DISABLE:
4000       break;
4001     case PACKET_ENABLE:
4002       break;
4003     case PACKET_SUPPORT_UNKNOWN:
4004       {
4005         char *p;
4006
4007         p = rs->buf;
4008         *p++ = 'X';
4009         p += hexnumstr (p, (ULONGEST) addr);
4010         *p++ = ',';
4011         p += hexnumstr (p, (ULONGEST) 0);
4012         *p++ = ':';
4013         *p = '\0';
4014
4015         putpkt_binary (rs->buf, (int) (p - rs->buf));
4016         getpkt (&rs->buf, &rs->buf_size, 0);
4017
4018         if (rs->buf[0] == '\0')
4019           {
4020             if (remote_debug)
4021               fprintf_unfiltered (gdb_stdlog,
4022                                   "binary downloading NOT suppported by target\n");
4023             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
4024           }
4025         else
4026           {
4027             if (remote_debug)
4028               fprintf_unfiltered (gdb_stdlog,
4029                                   "binary downloading suppported by target\n");
4030             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
4031           }
4032         break;
4033       }
4034     }
4035 }
4036
4037 /* Write memory data directly to the remote machine.
4038    This does not inform the data cache; the data cache uses this.
4039    HEADER is the starting part of the packet.
4040    MEMADDR is the address in the remote memory space.
4041    MYADDR is the address of the buffer in our space.
4042    LEN is the number of bytes.
4043    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
4044    should send data as binary ('X'), or hex-encoded ('M').
4045
4046    The function creates packet of the form
4047        <HEADER><ADDRESS>,<LENGTH>:<DATA>
4048
4049    where encoding of <DATA> is termined by PACKET_FORMAT.
4050
4051    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
4052    are omitted.
4053
4054    Returns the number of bytes transferred, or 0 (setting errno) for
4055    error.  Only transfer a single packet.  */
4056
4057 static int
4058 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
4059                         const gdb_byte *myaddr, int len,
4060                         char packet_format, int use_length)
4061 {
4062   struct remote_state *rs = get_remote_state ();
4063   char *p;
4064   char *plen = NULL;
4065   int plenlen = 0;
4066   int todo;
4067   int nr_bytes;
4068   int payload_size;
4069   int payload_length;
4070   int header_length;
4071
4072   if (packet_format != 'X' && packet_format != 'M')
4073     internal_error (__FILE__, __LINE__,
4074                     "remote_write_bytes_aux: bad packet format");
4075
4076   /* Should this be the selected frame?  */
4077   gdbarch_remote_translate_xfer_address (current_gdbarch,
4078                                          current_regcache,
4079                                          memaddr, len,
4080                                          &memaddr, &len);
4081
4082   if (len <= 0)
4083     return 0;
4084
4085   payload_size = get_memory_write_packet_size ();
4086
4087   /* The packet buffer will be large enough for the payload;
4088      get_memory_packet_size ensures this.  */
4089   rs->buf[0] = '\0';
4090
4091   /* Compute the size of the actual payload by subtracting out the
4092      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".
4093      */
4094   payload_size -= strlen ("$,:#NN");
4095   if (!use_length)
4096     /* The comma won't be used. */
4097     payload_size += 1;
4098   header_length = strlen (header);
4099   payload_size -= header_length;
4100   payload_size -= hexnumlen (memaddr);
4101
4102   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
4103
4104   strcat (rs->buf, header);
4105   p = rs->buf + strlen (header);
4106
4107   /* Compute a best guess of the number of bytes actually transfered.  */
4108   if (packet_format == 'X')
4109     {
4110       /* Best guess at number of bytes that will fit.  */
4111       todo = min (len, payload_size);
4112       if (use_length)
4113         payload_size -= hexnumlen (todo);
4114       todo = min (todo, payload_size);
4115     }
4116   else
4117     {
4118       /* Num bytes that will fit.  */
4119       todo = min (len, payload_size / 2);
4120       if (use_length)
4121         payload_size -= hexnumlen (todo);
4122       todo = min (todo, payload_size / 2);
4123     }
4124
4125   if (todo <= 0)
4126     internal_error (__FILE__, __LINE__,
4127                     _("minumum packet size too small to write data"));
4128
4129   /* If we already need another packet, then try to align the end
4130      of this packet to a useful boundary.  */
4131   if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
4132     todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
4133
4134   /* Append "<memaddr>".  */
4135   memaddr = remote_address_masked (memaddr);
4136   p += hexnumstr (p, (ULONGEST) memaddr);
4137
4138   if (use_length)
4139     {
4140       /* Append ",".  */
4141       *p++ = ',';
4142
4143       /* Append <len>.  Retain the location/size of <len>.  It may need to
4144          be adjusted once the packet body has been created.  */
4145       plen = p;
4146       plenlen = hexnumstr (p, (ULONGEST) todo);
4147       p += plenlen;
4148     }
4149
4150   /* Append ":".  */
4151   *p++ = ':';
4152   *p = '\0';
4153
4154   /* Append the packet body.  */
4155   if (packet_format == 'X')
4156     {
4157       /* Binary mode.  Send target system values byte by byte, in
4158          increasing byte addresses.  Only escape certain critical
4159          characters.  */
4160       payload_length = remote_escape_output (myaddr, todo, p, &nr_bytes,
4161                                              payload_size);
4162
4163       /* If not all TODO bytes fit, then we'll need another packet.  Make
4164          a second try to keep the end of the packet aligned.  Don't do
4165          this if the packet is tiny.  */
4166       if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
4167         {
4168           int new_nr_bytes;
4169
4170           new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
4171                           - memaddr);
4172           if (new_nr_bytes != nr_bytes)
4173             payload_length = remote_escape_output (myaddr, new_nr_bytes,
4174                                                    p, &nr_bytes,
4175                                                    payload_size);
4176         }
4177
4178       p += payload_length;
4179       if (use_length && nr_bytes < todo)
4180         {
4181           /* Escape chars have filled up the buffer prematurely,
4182              and we have actually sent fewer bytes than planned.
4183              Fix-up the length field of the packet.  Use the same
4184              number of characters as before.  */
4185           plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
4186           *plen = ':';  /* overwrite \0 from hexnumnstr() */
4187         }
4188     }
4189   else
4190     {
4191       /* Normal mode: Send target system values byte by byte, in
4192          increasing byte addresses.  Each byte is encoded as a two hex
4193          value.  */
4194       nr_bytes = bin2hex (myaddr, p, todo);
4195       p += 2 * nr_bytes;
4196     }
4197
4198   putpkt_binary (rs->buf, (int) (p - rs->buf));
4199   getpkt (&rs->buf, &rs->buf_size, 0);
4200
4201   if (rs->buf[0] == 'E')
4202     {
4203       /* There is no correspondance between what the remote protocol
4204          uses for errors and errno codes.  We would like a cleaner way
4205          of representing errors (big enough to include errno codes,
4206          bfd_error codes, and others).  But for now just return EIO.  */
4207       errno = EIO;
4208       return 0;
4209     }
4210
4211   /* Return NR_BYTES, not TODO, in case escape chars caused us to send
4212      fewer bytes than we'd planned.  */
4213   return nr_bytes;
4214 }
4215
4216 /* Write memory data directly to the remote machine.
4217    This does not inform the data cache; the data cache uses this.
4218    MEMADDR is the address in the remote memory space.
4219    MYADDR is the address of the buffer in our space.
4220    LEN is the number of bytes.
4221
4222    Returns number of bytes transferred, or 0 (setting errno) for
4223    error.  Only transfer a single packet.  */
4224
4225 int
4226 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
4227 {
4228   char *packet_format = 0;
4229
4230   /* Check whether the target supports binary download.  */
4231   check_binary_download (memaddr);
4232
4233   switch (remote_protocol_packets[PACKET_X].support)
4234     {
4235     case PACKET_ENABLE:
4236       packet_format = "X";
4237       break;
4238     case PACKET_DISABLE:
4239       packet_format = "M";
4240       break;
4241     case PACKET_SUPPORT_UNKNOWN:
4242       internal_error (__FILE__, __LINE__,
4243                       _("remote_write_bytes: bad internal state"));
4244     default:
4245       internal_error (__FILE__, __LINE__, _("bad switch"));
4246     }
4247
4248   return remote_write_bytes_aux (packet_format,
4249                                  memaddr, myaddr, len, packet_format[0], 1);
4250 }
4251
4252 /* Read memory data directly from the remote machine.
4253    This does not use the data cache; the data cache uses this.
4254    MEMADDR is the address in the remote memory space.
4255    MYADDR is the address of the buffer in our space.
4256    LEN is the number of bytes.
4257
4258    Returns number of bytes transferred, or 0 for error.  */
4259
4260 /* NOTE: cagney/1999-10-18: This function (and its siblings in other
4261    remote targets) shouldn't attempt to read the entire buffer.
4262    Instead it should read a single packet worth of data and then
4263    return the byte size of that packet to the caller.  The caller (its
4264    caller and its callers caller ;-) already contains code for
4265    handling partial reads.  */
4266
4267 int
4268 remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
4269 {
4270   struct remote_state *rs = get_remote_state ();
4271   int max_buf_size;             /* Max size of packet output buffer.  */
4272   int origlen;
4273
4274   /* Should this be the selected frame?  */
4275   gdbarch_remote_translate_xfer_address (current_gdbarch,
4276                                          current_regcache,
4277                                          memaddr, len,
4278                                          &memaddr, &len);
4279
4280   if (len <= 0)
4281     return 0;
4282
4283   max_buf_size = get_memory_read_packet_size ();
4284   /* The packet buffer will be large enough for the payload;
4285      get_memory_packet_size ensures this.  */
4286
4287   origlen = len;
4288   while (len > 0)
4289     {
4290       char *p;
4291       int todo;
4292       int i;
4293
4294       todo = min (len, max_buf_size / 2);       /* num bytes that will fit */
4295
4296       /* construct "m"<memaddr>","<len>" */
4297       /* sprintf (rs->buf, "m%lx,%x", (unsigned long) memaddr, todo); */
4298       memaddr = remote_address_masked (memaddr);
4299       p = rs->buf;
4300       *p++ = 'm';
4301       p += hexnumstr (p, (ULONGEST) memaddr);
4302       *p++ = ',';
4303       p += hexnumstr (p, (ULONGEST) todo);
4304       *p = '\0';
4305
4306       putpkt (rs->buf);
4307       getpkt (&rs->buf, &rs->buf_size, 0);
4308
4309       if (rs->buf[0] == 'E'
4310           && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
4311           && rs->buf[3] == '\0')
4312         {
4313           /* There is no correspondance between what the remote
4314              protocol uses for errors and errno codes.  We would like
4315              a cleaner way of representing errors (big enough to
4316              include errno codes, bfd_error codes, and others).  But
4317              for now just return EIO.  */
4318           errno = EIO;
4319           return 0;
4320         }
4321
4322       /* Reply describes memory byte by byte,
4323          each byte encoded as two hex characters.  */
4324
4325       p = rs->buf;
4326       if ((i = hex2bin (p, myaddr, todo)) < todo)
4327         {
4328           /* Reply is short.  This means that we were able to read
4329              only part of what we wanted to.  */
4330           return i + (origlen - len);
4331         }
4332       myaddr += todo;
4333       memaddr += todo;
4334       len -= todo;
4335     }
4336   return origlen;
4337 }
4338 \f
4339 /* Read or write LEN bytes from inferior memory at MEMADDR,
4340    transferring to or from debugger address BUFFER.  Write to inferior
4341    if SHOULD_WRITE is nonzero.  Returns length of data written or
4342    read; 0 for error.  TARGET is unused.  */
4343
4344 static int
4345 remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
4346                     int should_write, struct mem_attrib *attrib,
4347                     struct target_ops *target)
4348 {
4349   int res;
4350
4351   if (should_write)
4352     res = remote_write_bytes (mem_addr, buffer, mem_len);
4353   else
4354     res = remote_read_bytes (mem_addr, buffer, mem_len);
4355
4356   return res;
4357 }
4358
4359 /* Sends a packet with content determined by the printf format string
4360    FORMAT and the remaining arguments, then gets the reply.  Returns
4361    whether the packet was a success, a failure, or unknown.  */
4362
4363 enum packet_result
4364 remote_send_printf (const char *format, ...)
4365 {
4366   struct remote_state *rs = get_remote_state ();
4367   int max_size = get_remote_packet_size ();
4368
4369   va_list ap;
4370   va_start (ap, format);
4371
4372   rs->buf[0] = '\0';
4373   if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
4374     internal_error (__FILE__, __LINE__, "Too long remote packet.");
4375
4376   if (putpkt (rs->buf) < 0)
4377     error (_("Communication problem with target."));
4378
4379   rs->buf[0] = '\0';
4380   getpkt (&rs->buf, &rs->buf_size, 0);
4381
4382   return packet_check_result (rs->buf);
4383 }
4384
4385 static void
4386 restore_remote_timeout (void *p)
4387 {
4388   int value = *(int *)p;
4389   remote_timeout = value;
4390 }
4391
4392 /* Flash writing can take quite some time.  We'll set
4393    effectively infinite timeout for flash operations.
4394    In future, we'll need to decide on a better approach.  */
4395 static const int remote_flash_timeout = 1000;
4396
4397 static void
4398 remote_flash_erase (struct target_ops *ops,
4399                     ULONGEST address, LONGEST length)
4400 {
4401   int saved_remote_timeout = remote_timeout;
4402   enum packet_result ret;
4403
4404   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
4405                                           &saved_remote_timeout);
4406   remote_timeout = remote_flash_timeout;
4407
4408   ret = remote_send_printf ("vFlashErase:%s,%s",
4409                             paddr (address),
4410                             phex (length, 4));
4411   switch (ret)
4412     {
4413     case PACKET_UNKNOWN:
4414       error (_("Remote target does not support flash erase"));
4415     case PACKET_ERROR:
4416       error (_("Error erasing flash with vFlashErase packet"));
4417     default:
4418       break;
4419     }
4420
4421   do_cleanups (back_to);
4422 }
4423
4424 static LONGEST
4425 remote_flash_write (struct target_ops *ops,
4426                     ULONGEST address, LONGEST length,
4427                     const gdb_byte *data)
4428 {
4429   int saved_remote_timeout = remote_timeout;
4430   int ret;
4431   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
4432                                           &saved_remote_timeout);
4433
4434   remote_timeout = remote_flash_timeout;
4435   ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
4436   do_cleanups (back_to);
4437
4438   return ret;
4439 }
4440
4441 static void
4442 remote_flash_done (struct target_ops *ops)
4443 {
4444   int saved_remote_timeout = remote_timeout;
4445   int ret;
4446   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
4447                                           &saved_remote_timeout);
4448
4449   remote_timeout = remote_flash_timeout;
4450   ret = remote_send_printf ("vFlashDone");
4451   do_cleanups (back_to);
4452
4453   switch (ret)
4454     {
4455     case PACKET_UNKNOWN:
4456       error (_("Remote target does not support vFlashDone"));
4457     case PACKET_ERROR:
4458       error (_("Error finishing flash operation"));
4459     default:
4460       break;
4461     }
4462 }
4463
4464 static void
4465 remote_files_info (struct target_ops *ignore)
4466 {
4467   puts_filtered ("Debugging a target over a serial line.\n");
4468 }
4469 \f
4470 /* Stuff for dealing with the packets which are part of this protocol.
4471    See comment at top of file for details.  */
4472
4473 /* Read a single character from the remote end.  */
4474
4475 static int
4476 readchar (int timeout)
4477 {
4478   int ch;
4479
4480   ch = serial_readchar (remote_desc, timeout);
4481
4482   if (ch >= 0)
4483     return ch;
4484
4485   switch ((enum serial_rc) ch)
4486     {
4487     case SERIAL_EOF:
4488       target_mourn_inferior ();
4489       error (_("Remote connection closed"));
4490       /* no return */
4491     case SERIAL_ERROR:
4492       perror_with_name (_("Remote communication error"));
4493       /* no return */
4494     case SERIAL_TIMEOUT:
4495       break;
4496     }
4497   return ch;
4498 }
4499
4500 /* Send the command in *BUF to the remote machine, and read the reply
4501    into *BUF.  Report an error if we get an error reply.  Resize
4502    *BUF using xrealloc if necessary to hold the result, and update
4503    *SIZEOF_BUF.  */
4504
4505 static void
4506 remote_send (char **buf,
4507              long *sizeof_buf)
4508 {
4509   putpkt (*buf);
4510   getpkt (buf, sizeof_buf, 0);
4511
4512   if ((*buf)[0] == 'E')
4513     error (_("Remote failure reply: %s"), *buf);
4514 }
4515
4516 /* Display a null-terminated packet on stdout, for debugging, using C
4517    string notation.  */
4518
4519 static void
4520 print_packet (char *buf)
4521 {
4522   puts_filtered ("\"");
4523   fputstr_filtered (buf, '"', gdb_stdout);
4524   puts_filtered ("\"");
4525 }
4526
4527 int
4528 putpkt (char *buf)
4529 {
4530   return putpkt_binary (buf, strlen (buf));
4531 }
4532
4533 /* Send a packet to the remote machine, with error checking.  The data
4534    of the packet is in BUF.  The string in BUF can be at most
4535    get_remote_packet_size () - 5 to account for the $, # and checksum,
4536    and for a possible /0 if we are debugging (remote_debug) and want
4537    to print the sent packet as a string.  */
4538
4539 static int
4540 putpkt_binary (char *buf, int cnt)
4541 {
4542   int i;
4543   unsigned char csum = 0;
4544   char *buf2 = alloca (cnt + 6);
4545
4546   int ch;
4547   int tcount = 0;
4548   char *p;
4549
4550   /* Copy the packet into buffer BUF2, encapsulating it
4551      and giving it a checksum.  */
4552
4553   p = buf2;
4554   *p++ = '$';
4555
4556   for (i = 0; i < cnt; i++)
4557     {
4558       csum += buf[i];
4559       *p++ = buf[i];
4560     }
4561   *p++ = '#';
4562   *p++ = tohex ((csum >> 4) & 0xf);
4563   *p++ = tohex (csum & 0xf);
4564
4565   /* Send it over and over until we get a positive ack.  */
4566
4567   while (1)
4568     {
4569       int started_error_output = 0;
4570
4571       if (remote_debug)
4572         {
4573           *p = '\0';
4574           fprintf_unfiltered (gdb_stdlog, "Sending packet: ");
4575           fputstrn_unfiltered (buf2, p - buf2, 0, gdb_stdlog);
4576           fprintf_unfiltered (gdb_stdlog, "...");
4577           gdb_flush (gdb_stdlog);
4578         }
4579       if (serial_write (remote_desc, buf2, p - buf2))
4580         perror_with_name (_("putpkt: write failed"));
4581
4582       /* Read until either a timeout occurs (-2) or '+' is read.  */
4583       while (1)
4584         {
4585           ch = readchar (remote_timeout);
4586
4587           if (remote_debug)
4588             {
4589               switch (ch)
4590                 {
4591                 case '+':
4592                 case '-':
4593                 case SERIAL_TIMEOUT:
4594                 case '$':
4595                   if (started_error_output)
4596                     {
4597                       putchar_unfiltered ('\n');
4598                       started_error_output = 0;
4599                     }
4600                 }
4601             }
4602
4603           switch (ch)
4604             {
4605             case '+':
4606               if (remote_debug)
4607                 fprintf_unfiltered (gdb_stdlog, "Ack\n");
4608               return 1;
4609             case '-':
4610               if (remote_debug)
4611                 fprintf_unfiltered (gdb_stdlog, "Nak\n");
4612             case SERIAL_TIMEOUT:
4613               tcount++;
4614               if (tcount > 3)
4615                 return 0;
4616               break;            /* Retransmit buffer.  */
4617             case '$':
4618               {
4619                 if (remote_debug)
4620                   fprintf_unfiltered (gdb_stdlog,
4621                                       "Packet instead of Ack, ignoring it\n");
4622                 /* It's probably an old response sent because an ACK
4623                    was lost.  Gobble up the packet and ack it so it
4624                    doesn't get retransmitted when we resend this
4625                    packet.  */
4626                 skip_frame ();
4627                 serial_write (remote_desc, "+", 1);
4628                 continue;       /* Now, go look for +.  */
4629               }
4630             default:
4631               if (remote_debug)
4632                 {
4633                   if (!started_error_output)
4634                     {
4635                       started_error_output = 1;
4636                       fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
4637                     }
4638                   fputc_unfiltered (ch & 0177, gdb_stdlog);
4639                 }
4640               continue;
4641             }
4642           break;                /* Here to retransmit.  */
4643         }
4644
4645 #if 0
4646       /* This is wrong.  If doing a long backtrace, the user should be
4647          able to get out next time we call QUIT, without anything as
4648          violent as interrupt_query.  If we want to provide a way out of
4649          here without getting to the next QUIT, it should be based on
4650          hitting ^C twice as in remote_wait.  */
4651       if (quit_flag)
4652         {
4653           quit_flag = 0;
4654           interrupt_query ();
4655         }
4656 #endif
4657     }
4658 }
4659
4660 /* Come here after finding the start of a frame when we expected an
4661    ack.  Do our best to discard the rest of this packet.  */
4662
4663 static void
4664 skip_frame (void)
4665 {
4666   int c;
4667
4668   while (1)
4669     {
4670       c = readchar (remote_timeout);
4671       switch (c)
4672         {
4673         case SERIAL_TIMEOUT:
4674           /* Nothing we can do.  */
4675           return;
4676         case '#':
4677           /* Discard the two bytes of checksum and stop.  */
4678           c = readchar (remote_timeout);
4679           if (c >= 0)
4680             c = readchar (remote_timeout);
4681
4682           return;
4683         case '*':               /* Run length encoding.  */
4684           /* Discard the repeat count.  */
4685           c = readchar (remote_timeout);
4686           if (c < 0)
4687             return;
4688           break;
4689         default:
4690           /* A regular character.  */
4691           break;
4692         }
4693     }
4694 }
4695
4696 /* Come here after finding the start of the frame.  Collect the rest
4697    into *BUF, verifying the checksum, length, and handling run-length
4698    compression.  NUL terminate the buffer.  If there is not enough room,
4699    expand *BUF using xrealloc.
4700
4701    Returns -1 on error, number of characters in buffer (ignoring the
4702    trailing NULL) on success. (could be extended to return one of the
4703    SERIAL status indications).  */
4704
4705 static long
4706 read_frame (char **buf_p,
4707             long *sizeof_buf)
4708 {
4709   unsigned char csum;
4710   long bc;
4711   int c;
4712   char *buf = *buf_p;
4713
4714   csum = 0;
4715   bc = 0;
4716
4717   while (1)
4718     {
4719       c = readchar (remote_timeout);
4720       switch (c)
4721         {
4722         case SERIAL_TIMEOUT:
4723           if (remote_debug)
4724             fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
4725           return -1;
4726         case '$':
4727           if (remote_debug)
4728             fputs_filtered ("Saw new packet start in middle of old one\n",
4729                             gdb_stdlog);
4730           return -1;            /* Start a new packet, count retries.  */
4731         case '#':
4732           {
4733             unsigned char pktcsum;
4734             int check_0 = 0;
4735             int check_1 = 0;
4736
4737             buf[bc] = '\0';
4738
4739             check_0 = readchar (remote_timeout);
4740             if (check_0 >= 0)
4741               check_1 = readchar (remote_timeout);
4742
4743             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
4744               {
4745                 if (remote_debug)
4746                   fputs_filtered ("Timeout in checksum, retrying\n",
4747                                   gdb_stdlog);
4748                 return -1;
4749               }
4750             else if (check_0 < 0 || check_1 < 0)
4751               {
4752                 if (remote_debug)
4753                   fputs_filtered ("Communication error in checksum\n",
4754                                   gdb_stdlog);
4755                 return -1;
4756               }
4757
4758             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
4759             if (csum == pktcsum)
4760               return bc;
4761
4762             if (remote_debug)
4763               {
4764                 fprintf_filtered (gdb_stdlog,
4765                               "Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
4766                                   pktcsum, csum);
4767                 fputstrn_filtered (buf, bc, 0, gdb_stdlog);
4768                 fputs_filtered ("\n", gdb_stdlog);
4769               }
4770             /* Number of characters in buffer ignoring trailing
4771                NULL.  */
4772             return -1;
4773           }
4774         case '*':               /* Run length encoding.  */
4775           {
4776             int repeat;
4777             csum += c;
4778
4779             c = readchar (remote_timeout);
4780             csum += c;
4781             repeat = c - ' ' + 3;       /* Compute repeat count.  */
4782
4783             /* The character before ``*'' is repeated.  */
4784
4785             if (repeat > 0 && repeat <= 255 && bc > 0)
4786               {
4787                 if (bc + repeat - 1 >= *sizeof_buf - 1)
4788                   {
4789                     /* Make some more room in the buffer.  */
4790                     *sizeof_buf += repeat;
4791                     *buf_p = xrealloc (*buf_p, *sizeof_buf);
4792                     buf = *buf_p;
4793                   }
4794
4795                 memset (&buf[bc], buf[bc - 1], repeat);
4796                 bc += repeat;
4797                 continue;
4798               }
4799
4800             buf[bc] = '\0';
4801             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
4802             return -1;
4803           }
4804         default:
4805           if (bc >= *sizeof_buf - 1)
4806             {
4807               /* Make some more room in the buffer.  */
4808               *sizeof_buf *= 2;
4809               *buf_p = xrealloc (*buf_p, *sizeof_buf);
4810               buf = *buf_p;
4811             }
4812
4813           buf[bc++] = c;
4814           csum += c;
4815           continue;
4816         }
4817     }
4818 }
4819
4820 /* Read a packet from the remote machine, with error checking, and
4821    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
4822    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
4823    rather than timing out; this is used (in synchronous mode) to wait
4824    for a target that is is executing user code to stop.  */
4825 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
4826    don't have to change all the calls to getpkt to deal with the
4827    return value, because at the moment I don't know what the right
4828    thing to do it for those.  */
4829 void
4830 getpkt (char **buf,
4831         long *sizeof_buf,
4832         int forever)
4833 {
4834   int timed_out;
4835
4836   timed_out = getpkt_sane (buf, sizeof_buf, forever);
4837 }
4838
4839
4840 /* Read a packet from the remote machine, with error checking, and
4841    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
4842    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
4843    rather than timing out; this is used (in synchronous mode) to wait
4844    for a target that is is executing user code to stop.  If FOREVER ==
4845    0, this function is allowed to time out gracefully and return an
4846    indication of this to the caller.  Otherwise return the number
4847    of bytes read.  */
4848 static int
4849 getpkt_sane (char **buf, long *sizeof_buf, int forever)
4850 {
4851   int c;
4852   int tries;
4853   int timeout;
4854   int val;
4855
4856   strcpy (*buf, "timeout");
4857
4858   if (forever)
4859     {
4860       timeout = watchdog > 0 ? watchdog : -1;
4861     }
4862
4863   else
4864     timeout = remote_timeout;
4865
4866 #define MAX_TRIES 3
4867
4868   for (tries = 1; tries <= MAX_TRIES; tries++)
4869     {
4870       /* This can loop forever if the remote side sends us characters
4871          continuously, but if it pauses, we'll get a zero from
4872          readchar because of timeout.  Then we'll count that as a
4873          retry.  */
4874
4875       /* Note that we will only wait forever prior to the start of a
4876          packet.  After that, we expect characters to arrive at a
4877          brisk pace.  They should show up within remote_timeout
4878          intervals.  */
4879
4880       do
4881         {
4882           c = readchar (timeout);
4883
4884           if (c == SERIAL_TIMEOUT)
4885             {
4886               if (forever)      /* Watchdog went off?  Kill the target.  */
4887                 {
4888                   QUIT;
4889                   target_mourn_inferior ();
4890                   error (_("Watchdog has expired.  Target detached."));
4891                 }
4892               if (remote_debug)
4893                 fputs_filtered ("Timed out.\n", gdb_stdlog);
4894               goto retry;
4895             }
4896         }
4897       while (c != '$');
4898
4899       /* We've found the start of a packet, now collect the data.  */
4900
4901       val = read_frame (buf, sizeof_buf);
4902
4903       if (val >= 0)
4904         {
4905           if (remote_debug)
4906             {
4907               fprintf_unfiltered (gdb_stdlog, "Packet received: ");
4908               fputstrn_unfiltered (*buf, val, 0, gdb_stdlog);
4909               fprintf_unfiltered (gdb_stdlog, "\n");
4910             }
4911           serial_write (remote_desc, "+", 1);
4912           return val;
4913         }
4914
4915       /* Try the whole thing again.  */
4916     retry:
4917       serial_write (remote_desc, "-", 1);
4918     }
4919
4920   /* We have tried hard enough, and just can't receive the packet.
4921      Give up.  */
4922
4923   printf_unfiltered (_("Ignoring packet error, continuing...\n"));
4924   serial_write (remote_desc, "+", 1);
4925   return -1;
4926 }
4927 \f
4928 static void
4929 remote_kill (void)
4930 {
4931   /* For some mysterious reason, wait_for_inferior calls kill instead of
4932      mourn after it gets TARGET_WAITKIND_SIGNALLED.  Work around it.  */
4933   if (kill_kludge)
4934     {
4935       kill_kludge = 0;
4936       target_mourn_inferior ();
4937       return;
4938     }
4939
4940   /* Use catch_errors so the user can quit from gdb even when we aren't on
4941      speaking terms with the remote system.  */
4942   catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
4943
4944   /* Don't wait for it to die.  I'm not really sure it matters whether
4945      we do or not.  For the existing stubs, kill is a noop.  */
4946   target_mourn_inferior ();
4947 }
4948
4949 /* Async version of remote_kill.  */
4950 static void
4951 remote_async_kill (void)
4952 {
4953   /* Unregister the file descriptor from the event loop.  */
4954   if (target_is_async_p ())
4955     serial_async (remote_desc, NULL, 0);
4956
4957   /* For some mysterious reason, wait_for_inferior calls kill instead of
4958      mourn after it gets TARGET_WAITKIND_SIGNALLED.  Work around it.  */
4959   if (kill_kludge)
4960     {
4961       kill_kludge = 0;
4962       target_mourn_inferior ();
4963       return;
4964     }
4965
4966   /* Use catch_errors so the user can quit from gdb even when we
4967      aren't on speaking terms with the remote system.  */
4968   catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
4969
4970   /* Don't wait for it to die.  I'm not really sure it matters whether
4971      we do or not.  For the existing stubs, kill is a noop.  */
4972   target_mourn_inferior ();
4973 }
4974
4975 static void
4976 remote_mourn (void)
4977 {
4978   remote_mourn_1 (&remote_ops);
4979 }
4980
4981 static void
4982 remote_async_mourn (void)
4983 {
4984   remote_mourn_1 (&remote_async_ops);
4985 }
4986
4987 static void
4988 extended_remote_mourn (void)
4989 {
4990   /* We do _not_ want to mourn the target like this; this will
4991      remove the extended remote target  from the target stack,
4992      and the next time the user says "run" it'll fail.
4993
4994      FIXME: What is the right thing to do here?  */
4995 #if 0
4996   remote_mourn_1 (&extended_remote_ops);
4997 #endif
4998 }
4999
5000 /* Worker function for remote_mourn.  */
5001 static void
5002 remote_mourn_1 (struct target_ops *target)
5003 {
5004   unpush_target (target);
5005   generic_mourn_inferior ();
5006 }
5007
5008 /* In the extended protocol we want to be able to do things like
5009    "run" and have them basically work as expected.  So we need
5010    a special create_inferior function.
5011
5012    FIXME: One day add support for changing the exec file
5013    we're debugging, arguments and an environment.  */
5014
5015 static void
5016 extended_remote_create_inferior (char *exec_file, char *args,
5017                                  char **env, int from_tty)
5018 {
5019   /* Rip out the breakpoints; we'll reinsert them after restarting
5020      the remote server.  */
5021   remove_breakpoints ();
5022
5023   /* Now restart the remote server.  */
5024   extended_remote_restart ();
5025
5026   /* Now put the breakpoints back in.  This way we're safe if the
5027      restart function works via a unix fork on the remote side.  */
5028   insert_breakpoints ();
5029
5030   /* Clean up from the last time we were running.  */
5031   clear_proceed_status ();
5032 }
5033
5034 /* Async version of extended_remote_create_inferior.  */
5035 static void
5036 extended_remote_async_create_inferior (char *exec_file, char *args,
5037                                        char **env, int from_tty)
5038 {
5039   /* Rip out the breakpoints; we'll reinsert them after restarting
5040      the remote server.  */
5041   remove_breakpoints ();
5042
5043   /* If running asynchronously, register the target file descriptor
5044      with the event loop.  */
5045   if (target_can_async_p ())
5046     target_async (inferior_event_handler, 0);
5047
5048   /* Now restart the remote server.  */
5049   extended_remote_restart ();
5050
5051   /* Now put the breakpoints back in.  This way we're safe if the
5052      restart function works via a unix fork on the remote side.  */
5053   insert_breakpoints ();
5054
5055   /* Clean up from the last time we were running.  */
5056   clear_proceed_status ();
5057 }
5058 \f
5059
5060 /* On some machines, e.g. 68k, we may use a different breakpoint
5061    instruction than other targets; in those use
5062    DEPRECATED_REMOTE_BREAKPOINT instead of just BREAKPOINT_FROM_PC.
5063    Also, bi-endian targets may define
5064    DEPRECATED_LITTLE_REMOTE_BREAKPOINT and
5065    DEPRECATED_BIG_REMOTE_BREAKPOINT.  If none of these are defined, we
5066    just call the standard routines that are in mem-break.c.  */
5067
5068 /* NOTE: cagney/2003-06-08: This is silly.  A remote and simulator
5069    target should use an identical BREAKPOINT_FROM_PC.  As for native,
5070    the ARCH-OS-tdep.c code can override the default.  */
5071
5072 #if defined (DEPRECATED_LITTLE_REMOTE_BREAKPOINT) && defined (DEPRECATED_BIG_REMOTE_BREAKPOINT) && !defined(DEPRECATED_REMOTE_BREAKPOINT)
5073 #define DEPRECATED_REMOTE_BREAKPOINT
5074 #endif
5075
5076 #ifdef DEPRECATED_REMOTE_BREAKPOINT
5077
5078 /* If the target isn't bi-endian, just pretend it is.  */
5079 #if !defined (DEPRECATED_LITTLE_REMOTE_BREAKPOINT) && !defined (DEPRECATED_BIG_REMOTE_BREAKPOINT)
5080 #define DEPRECATED_LITTLE_REMOTE_BREAKPOINT DEPRECATED_REMOTE_BREAKPOINT
5081 #define DEPRECATED_BIG_REMOTE_BREAKPOINT DEPRECATED_REMOTE_BREAKPOINT
5082 #endif
5083
5084 static unsigned char big_break_insn[] = DEPRECATED_BIG_REMOTE_BREAKPOINT;
5085 static unsigned char little_break_insn[] = DEPRECATED_LITTLE_REMOTE_BREAKPOINT;
5086
5087 #endif /* DEPRECATED_REMOTE_BREAKPOINT */
5088
5089 /* Insert a breakpoint.  On targets that have software breakpoint
5090    support, we ask the remote target to do the work; on targets
5091    which don't, we insert a traditional memory breakpoint.  */
5092
5093 static int
5094 remote_insert_breakpoint (struct bp_target_info *bp_tgt)
5095 {
5096   CORE_ADDR addr = bp_tgt->placed_address;
5097   struct remote_state *rs = get_remote_state ();
5098 #ifdef DEPRECATED_REMOTE_BREAKPOINT
5099   int val;
5100 #endif
5101
5102   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
5103      If it succeeds, then set the support to PACKET_ENABLE.  If it
5104      fails, and the user has explicitly requested the Z support then
5105      report an error, otherwise, mark it disabled and go on.  */
5106
5107   if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
5108     {
5109       char *p = rs->buf;
5110
5111       *(p++) = 'Z';
5112       *(p++) = '0';
5113       *(p++) = ',';
5114       BREAKPOINT_FROM_PC (&bp_tgt->placed_address, &bp_tgt->placed_size);
5115       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
5116       p += hexnumstr (p, addr);
5117       sprintf (p, ",%d", bp_tgt->placed_size);
5118
5119       putpkt (rs->buf);
5120       getpkt (&rs->buf, &rs->buf_size, 0);
5121
5122       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
5123         {
5124         case PACKET_ERROR:
5125           return -1;
5126         case PACKET_OK:
5127           return 0;
5128         case PACKET_UNKNOWN:
5129           break;
5130         }
5131     }
5132
5133 #ifdef DEPRECATED_REMOTE_BREAKPOINT
5134   bp_tgt->placed_size = bp_tgt->shadow_len = sizeof big_break_insn;
5135   val = target_read_memory (addr, bp_tgt->shadow_contents, bp_tgt->shadow_len);
5136
5137   if (val == 0)
5138     {
5139       if (TARGET_BYTE_ORDER == BFD_ENDIAN_BIG)
5140         val = target_write_memory (addr, (char *) big_break_insn,
5141                                    sizeof big_break_insn);
5142       else
5143         val = target_write_memory (addr, (char *) little_break_insn,
5144                                    sizeof little_break_insn);
5145     }
5146
5147   return val;
5148 #else
5149   return memory_insert_breakpoint (bp_tgt);
5150 #endif /* DEPRECATED_REMOTE_BREAKPOINT */
5151 }
5152
5153 static int
5154 remote_remove_breakpoint (struct bp_target_info *bp_tgt)
5155 {
5156   CORE_ADDR addr = bp_tgt->placed_address;
5157   struct remote_state *rs = get_remote_state ();
5158   int bp_size;
5159
5160   if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
5161     {
5162       char *p = rs->buf;
5163
5164       *(p++) = 'z';
5165       *(p++) = '0';
5166       *(p++) = ',';
5167
5168       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
5169       p += hexnumstr (p, addr);
5170       sprintf (p, ",%d", bp_tgt->placed_size);
5171
5172       putpkt (rs->buf);
5173       getpkt (&rs->buf, &rs->buf_size, 0);
5174
5175       return (rs->buf[0] == 'E');
5176     }
5177
5178 #ifdef DEPRECATED_REMOTE_BREAKPOINT
5179   return target_write_memory (bp_tgt->placed_address, bp_tgt->shadow_contents,
5180                               bp_tgt->shadow_len);
5181 #else
5182   return memory_remove_breakpoint (bp_tgt);
5183 #endif /* DEPRECATED_REMOTE_BREAKPOINT */
5184 }
5185
5186 static int
5187 watchpoint_to_Z_packet (int type)
5188 {
5189   switch (type)
5190     {
5191     case hw_write:
5192       return Z_PACKET_WRITE_WP;
5193       break;
5194     case hw_read:
5195       return Z_PACKET_READ_WP;
5196       break;
5197     case hw_access:
5198       return Z_PACKET_ACCESS_WP;
5199       break;
5200     default:
5201       internal_error (__FILE__, __LINE__,
5202                       _("hw_bp_to_z: bad watchpoint type %d"), type);
5203     }
5204 }
5205
5206 static int
5207 remote_insert_watchpoint (CORE_ADDR addr, int len, int type)
5208 {
5209   struct remote_state *rs = get_remote_state ();
5210   char *p;
5211   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
5212
5213   if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
5214     return -1;
5215
5216   sprintf (rs->buf, "Z%x,", packet);
5217   p = strchr (rs->buf, '\0');
5218   addr = remote_address_masked (addr);
5219   p += hexnumstr (p, (ULONGEST) addr);
5220   sprintf (p, ",%x", len);
5221
5222   putpkt (rs->buf);
5223   getpkt (&rs->buf, &rs->buf_size, 0);
5224
5225   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
5226     {
5227     case PACKET_ERROR:
5228     case PACKET_UNKNOWN:
5229       return -1;
5230     case PACKET_OK:
5231       return 0;
5232     }
5233   internal_error (__FILE__, __LINE__,
5234                   _("remote_insert_watchpoint: reached end of function"));
5235 }
5236
5237
5238 static int
5239 remote_remove_watchpoint (CORE_ADDR addr, int len, int type)
5240 {
5241   struct remote_state *rs = get_remote_state ();
5242   char *p;
5243   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
5244
5245   if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
5246     return -1;
5247
5248   sprintf (rs->buf, "z%x,", packet);
5249   p = strchr (rs->buf, '\0');
5250   addr = remote_address_masked (addr);
5251   p += hexnumstr (p, (ULONGEST) addr);
5252   sprintf (p, ",%x", len);
5253   putpkt (rs->buf);
5254   getpkt (&rs->buf, &rs->buf_size, 0);
5255
5256   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
5257     {
5258     case PACKET_ERROR:
5259     case PACKET_UNKNOWN:
5260       return -1;
5261     case PACKET_OK:
5262       return 0;
5263     }
5264   internal_error (__FILE__, __LINE__,
5265                   _("remote_remove_watchpoint: reached end of function"));
5266 }
5267
5268
5269 int remote_hw_watchpoint_limit = -1;
5270 int remote_hw_breakpoint_limit = -1;
5271
5272 static int
5273 remote_check_watch_resources (int type, int cnt, int ot)
5274 {
5275   if (type == bp_hardware_breakpoint)
5276     {
5277       if (remote_hw_breakpoint_limit == 0)
5278         return 0;
5279       else if (remote_hw_breakpoint_limit < 0)
5280         return 1;
5281       else if (cnt <= remote_hw_breakpoint_limit)
5282         return 1;
5283     }
5284   else
5285     {
5286       if (remote_hw_watchpoint_limit == 0)
5287         return 0;
5288       else if (remote_hw_watchpoint_limit < 0)
5289         return 1;
5290       else if (ot)
5291         return -1;
5292       else if (cnt <= remote_hw_watchpoint_limit)
5293         return 1;
5294     }
5295   return -1;
5296 }
5297
5298 static int
5299 remote_stopped_by_watchpoint (void)
5300 {
5301     return remote_stopped_by_watchpoint_p;
5302 }
5303
5304 extern int stepped_after_stopped_by_watchpoint;
5305
5306 static int
5307 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
5308 {
5309   int rc = 0;
5310   if (remote_stopped_by_watchpoint ()
5311       || stepped_after_stopped_by_watchpoint)
5312     {
5313       *addr_p = remote_watch_data_address;
5314       rc = 1;
5315     }
5316
5317   return rc;
5318 }
5319
5320
5321 static int
5322 remote_insert_hw_breakpoint (struct bp_target_info *bp_tgt)
5323 {
5324   CORE_ADDR addr;
5325   struct remote_state *rs = get_remote_state ();
5326   char *p = rs->buf;
5327
5328   /* The length field should be set to the size of a breakpoint
5329      instruction, even though we aren't inserting one ourselves.  */
5330
5331   BREAKPOINT_FROM_PC (&bp_tgt->placed_address, &bp_tgt->placed_size);
5332
5333   if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5334     return -1;
5335
5336   *(p++) = 'Z';
5337   *(p++) = '1';
5338   *(p++) = ',';
5339
5340   addr = remote_address_masked (bp_tgt->placed_address);
5341   p += hexnumstr (p, (ULONGEST) addr);
5342   sprintf (p, ",%x", bp_tgt->placed_size);
5343
5344   putpkt (rs->buf);
5345   getpkt (&rs->buf, &rs->buf_size, 0);
5346
5347   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
5348     {
5349     case PACKET_ERROR:
5350     case PACKET_UNKNOWN:
5351       return -1;
5352     case PACKET_OK:
5353       return 0;
5354     }
5355   internal_error (__FILE__, __LINE__,
5356                   _("remote_insert_hw_breakpoint: reached end of function"));
5357 }
5358
5359
5360 static int
5361 remote_remove_hw_breakpoint (struct bp_target_info *bp_tgt)
5362 {
5363   CORE_ADDR addr;
5364   struct remote_state *rs = get_remote_state ();
5365   char *p = rs->buf;
5366
5367   if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5368     return -1;
5369
5370   *(p++) = 'z';
5371   *(p++) = '1';
5372   *(p++) = ',';
5373
5374   addr = remote_address_masked (bp_tgt->placed_address);
5375   p += hexnumstr (p, (ULONGEST) addr);
5376   sprintf (p, ",%x", bp_tgt->placed_size);
5377
5378   putpkt (rs->buf);
5379   getpkt (&rs->buf, &rs->buf_size, 0);
5380
5381   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
5382     {
5383     case PACKET_ERROR:
5384     case PACKET_UNKNOWN:
5385       return -1;
5386     case PACKET_OK:
5387       return 0;
5388     }
5389   internal_error (__FILE__, __LINE__,
5390                   _("remote_remove_hw_breakpoint: reached end of function"));
5391 }
5392
5393 /* Some targets are only capable of doing downloads, and afterwards
5394    they switch to the remote serial protocol.  This function provides
5395    a clean way to get from the download target to the remote target.
5396    It's basically just a wrapper so that we don't have to expose any
5397    of the internal workings of remote.c.
5398
5399    Prior to calling this routine, you should shutdown the current
5400    target code, else you will get the "A program is being debugged
5401    already..." message.  Usually a call to pop_target() suffices.  */
5402
5403 void
5404 push_remote_target (char *name, int from_tty)
5405 {
5406   printf_filtered (_("Switching to remote protocol\n"));
5407   remote_open (name, from_tty);
5408 }
5409
5410 /* Table used by the crc32 function to calcuate the checksum.  */
5411
5412 static unsigned long crc32_table[256] =
5413 {0, 0};
5414
5415 static unsigned long
5416 crc32 (unsigned char *buf, int len, unsigned int crc)
5417 {
5418   if (!crc32_table[1])
5419     {
5420       /* Initialize the CRC table and the decoding table.  */
5421       int i, j;
5422       unsigned int c;
5423
5424       for (i = 0; i < 256; i++)
5425         {
5426           for (c = i << 24, j = 8; j > 0; --j)
5427             c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
5428           crc32_table[i] = c;
5429         }
5430     }
5431
5432   while (len--)
5433     {
5434       crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
5435       buf++;
5436     }
5437   return crc;
5438 }
5439
5440 /* compare-sections command
5441
5442    With no arguments, compares each loadable section in the exec bfd
5443    with the same memory range on the target, and reports mismatches.
5444    Useful for verifying the image on the target against the exec file.
5445    Depends on the target understanding the new "qCRC:" request.  */
5446
5447 /* FIXME: cagney/1999-10-26: This command should be broken down into a
5448    target method (target verify memory) and generic version of the
5449    actual command.  This will allow other high-level code (especially
5450    generic_load()) to make use of this target functionality.  */
5451
5452 static void
5453 compare_sections_command (char *args, int from_tty)
5454 {
5455   struct remote_state *rs = get_remote_state ();
5456   asection *s;
5457   unsigned long host_crc, target_crc;
5458   extern bfd *exec_bfd;
5459   struct cleanup *old_chain;
5460   char *tmp;
5461   char *sectdata;
5462   const char *sectname;
5463   bfd_size_type size;
5464   bfd_vma lma;
5465   int matched = 0;
5466   int mismatched = 0;
5467
5468   if (!exec_bfd)
5469     error (_("command cannot be used without an exec file"));
5470   if (!current_target.to_shortname ||
5471       strcmp (current_target.to_shortname, "remote") != 0)
5472     error (_("command can only be used with remote target"));
5473
5474   for (s = exec_bfd->sections; s; s = s->next)
5475     {
5476       if (!(s->flags & SEC_LOAD))
5477         continue;               /* skip non-loadable section */
5478
5479       size = bfd_get_section_size (s);
5480       if (size == 0)
5481         continue;               /* skip zero-length section */
5482
5483       sectname = bfd_get_section_name (exec_bfd, s);
5484       if (args && strcmp (args, sectname) != 0)
5485         continue;               /* not the section selected by user */
5486
5487       matched = 1;              /* do this section */
5488       lma = s->lma;
5489       /* FIXME: assumes lma can fit into long.  */
5490       xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
5491                  (long) lma, (long) size);
5492       putpkt (rs->buf);
5493
5494       /* Be clever; compute the host_crc before waiting for target
5495          reply.  */
5496       sectdata = xmalloc (size);
5497       old_chain = make_cleanup (xfree, sectdata);
5498       bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
5499       host_crc = crc32 ((unsigned char *) sectdata, size, 0xffffffff);
5500
5501       getpkt (&rs->buf, &rs->buf_size, 0);
5502       if (rs->buf[0] == 'E')
5503         error (_("target memory fault, section %s, range 0x%s -- 0x%s"),
5504                sectname, paddr (lma), paddr (lma + size));
5505       if (rs->buf[0] != 'C')
5506         error (_("remote target does not support this operation"));
5507
5508       for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
5509         target_crc = target_crc * 16 + fromhex (*tmp);
5510
5511       printf_filtered ("Section %s, range 0x%s -- 0x%s: ",
5512                        sectname, paddr (lma), paddr (lma + size));
5513       if (host_crc == target_crc)
5514         printf_filtered ("matched.\n");
5515       else
5516         {
5517           printf_filtered ("MIS-MATCHED!\n");
5518           mismatched++;
5519         }
5520
5521       do_cleanups (old_chain);
5522     }
5523   if (mismatched > 0)
5524     warning (_("One or more sections of the remote executable does not match\n\
5525 the loaded file\n"));
5526   if (args && !matched)
5527     printf_filtered (_("No loaded section named '%s'.\n"), args);
5528 }
5529
5530 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
5531    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
5532    number of bytes read is returned, or 0 for EOF, or -1 for error.
5533    The number of bytes read may be less than LEN without indicating an
5534    EOF.  PACKET is checked and updated to indicate whether the remote
5535    target supports this object.  */
5536
5537 static LONGEST
5538 remote_read_qxfer (struct target_ops *ops, const char *object_name,
5539                    const char *annex,
5540                    gdb_byte *readbuf, ULONGEST offset, LONGEST len,
5541                    struct packet_config *packet)
5542 {
5543   static char *finished_object;
5544   static char *finished_annex;
5545   static ULONGEST finished_offset;
5546
5547   struct remote_state *rs = get_remote_state ();
5548   unsigned int total = 0;
5549   LONGEST i, n, packet_len;
5550
5551   if (packet->support == PACKET_DISABLE)
5552     return -1;
5553
5554   /* Check whether we've cached an end-of-object packet that matches
5555      this request.  */
5556   if (finished_object)
5557     {
5558       if (strcmp (object_name, finished_object) == 0
5559           && strcmp (annex ? annex : "", finished_annex) == 0
5560           && offset == finished_offset)
5561         return 0;
5562
5563       /* Otherwise, we're now reading something different.  Discard
5564          the cache.  */
5565       xfree (finished_object);
5566       xfree (finished_annex);
5567       finished_object = NULL;
5568       finished_annex = NULL;
5569     }
5570
5571   /* Request only enough to fit in a single packet.  The actual data
5572      may not, since we don't know how much of it will need to be escaped;
5573      the target is free to respond with slightly less data.  We subtract
5574      five to account for the response type and the protocol frame.  */
5575   n = min (get_remote_packet_size () - 5, len);
5576   snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
5577             object_name, annex ? annex : "",
5578             phex_nz (offset, sizeof offset),
5579             phex_nz (n, sizeof n));
5580   i = putpkt (rs->buf);
5581   if (i < 0)
5582     return -1;
5583
5584   rs->buf[0] = '\0';
5585   packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
5586   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
5587     return -1;
5588
5589   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
5590     error (_("Unknown remote qXfer reply: %s"), rs->buf);
5591
5592   /* 'm' means there is (or at least might be) more data after this
5593      batch.  That does not make sense unless there's at least one byte
5594      of data in this reply.  */
5595   if (rs->buf[0] == 'm' && packet_len == 1)
5596     error (_("Remote qXfer reply contained no data."));
5597
5598   /* Got some data.  */
5599   i = remote_unescape_input (rs->buf + 1, packet_len - 1, readbuf, n);
5600
5601   /* 'l' is an EOF marker, possibly including a final block of data,
5602      or possibly empty.  Record it to bypass the next read, if one is
5603      issued.  */
5604   if (rs->buf[0] == 'l')
5605     {
5606       finished_object = xstrdup (object_name);
5607       finished_annex = xstrdup (annex ? annex : "");
5608       finished_offset = offset + i;
5609     }
5610
5611   return i;
5612 }
5613
5614 static LONGEST
5615 remote_xfer_partial (struct target_ops *ops, enum target_object object,
5616                      const char *annex, gdb_byte *readbuf,
5617                      const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
5618 {
5619   struct remote_state *rs = get_remote_state ();
5620   int i;
5621   char *p2;
5622   char query_type;
5623
5624   /* Handle memory using the standard memory routines.  */
5625   if (object == TARGET_OBJECT_MEMORY)
5626     {
5627       int xfered;
5628       errno = 0;
5629
5630       if (writebuf != NULL)
5631         xfered = remote_write_bytes (offset, writebuf, len);
5632       else
5633         xfered = remote_read_bytes (offset, readbuf, len);
5634
5635       if (xfered > 0)
5636         return xfered;
5637       else if (xfered == 0 && errno == 0)
5638         return 0;
5639       else
5640         return -1;
5641     }
5642
5643   /* Only handle flash writes.  */
5644   if (writebuf != NULL)
5645     {
5646       LONGEST xfered;
5647
5648       switch (object)
5649         {
5650         case TARGET_OBJECT_FLASH:
5651           xfered = remote_flash_write (ops, offset, len, writebuf);
5652
5653           if (xfered > 0)
5654             return xfered;
5655           else if (xfered == 0 && errno == 0)
5656             return 0;
5657           else
5658             return -1;
5659
5660         default:
5661           return -1;
5662         }
5663     }
5664
5665   /* Map pre-existing objects onto letters.  DO NOT do this for new
5666      objects!!!  Instead specify new query packets.  */
5667   switch (object)
5668     {
5669     case TARGET_OBJECT_AVR:
5670       query_type = 'R';
5671       break;
5672
5673     case TARGET_OBJECT_AUXV:
5674       gdb_assert (annex == NULL);
5675       return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
5676                                 &remote_protocol_packets[PACKET_qXfer_auxv]);
5677
5678     case TARGET_OBJECT_MEMORY_MAP:
5679       gdb_assert (annex == NULL);
5680       return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
5681                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);
5682
5683     default:
5684       return -1;
5685     }
5686
5687   /* Note: a zero OFFSET and LEN can be used to query the minimum
5688      buffer size.  */
5689   if (offset == 0 && len == 0)
5690     return (get_remote_packet_size ());
5691   /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
5692      large enough let the caller deal with it.  */
5693   if (len < get_remote_packet_size ())
5694     return -1;
5695   len = get_remote_packet_size ();
5696
5697   /* Except for querying the minimum buffer size, target must be open.  */
5698   if (!remote_desc)
5699     error (_("remote query is only available after target open"));
5700
5701   gdb_assert (annex != NULL);
5702   gdb_assert (readbuf != NULL);
5703
5704   p2 = rs->buf;
5705   *p2++ = 'q';
5706   *p2++ = query_type;
5707
5708   /* We used one buffer char for the remote protocol q command and
5709      another for the query type.  As the remote protocol encapsulation
5710      uses 4 chars plus one extra in case we are debugging
5711      (remote_debug), we have PBUFZIZ - 7 left to pack the query
5712      string.  */
5713   i = 0;
5714   while (annex[i] && (i < (get_remote_packet_size () - 8)))
5715     {
5716       /* Bad caller may have sent forbidden characters.  */
5717       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
5718       *p2++ = annex[i];
5719       i++;
5720     }
5721   *p2 = '\0';
5722   gdb_assert (annex[i] == '\0');
5723
5724   i = putpkt (rs->buf);
5725   if (i < 0)
5726     return i;
5727
5728   getpkt (&rs->buf, &rs->buf_size, 0);
5729   strcpy ((char *) readbuf, rs->buf);
5730
5731   return strlen ((char *) readbuf);
5732 }
5733
5734 static void
5735 remote_rcmd (char *command,
5736              struct ui_file *outbuf)
5737 {
5738   struct remote_state *rs = get_remote_state ();
5739   char *p = rs->buf;
5740
5741   if (!remote_desc)
5742     error (_("remote rcmd is only available after target open"));
5743
5744   /* Send a NULL command across as an empty command.  */
5745   if (command == NULL)
5746     command = "";
5747
5748   /* The query prefix.  */
5749   strcpy (rs->buf, "qRcmd,");
5750   p = strchr (rs->buf, '\0');
5751
5752   if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/) > get_remote_packet_size ())
5753     error (_("\"monitor\" command ``%s'' is too long."), command);
5754
5755   /* Encode the actual command.  */
5756   bin2hex ((gdb_byte *) command, p, 0);
5757
5758   if (putpkt (rs->buf) < 0)
5759     error (_("Communication problem with target."));
5760
5761   /* get/display the response */
5762   while (1)
5763     {
5764       char *buf;
5765
5766       /* XXX - see also tracepoint.c:remote_get_noisy_reply().  */
5767       rs->buf[0] = '\0';
5768       getpkt (&rs->buf, &rs->buf_size, 0);
5769       buf = rs->buf;
5770       if (buf[0] == '\0')
5771         error (_("Target does not support this command."));
5772       if (buf[0] == 'O' && buf[1] != 'K')
5773         {
5774           remote_console_output (buf + 1); /* 'O' message from stub.  */
5775           continue;
5776         }
5777       if (strcmp (buf, "OK") == 0)
5778         break;
5779       if (strlen (buf) == 3 && buf[0] == 'E'
5780           && isdigit (buf[1]) && isdigit (buf[2]))
5781         {
5782           error (_("Protocol error with Rcmd"));
5783         }
5784       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
5785         {
5786           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
5787           fputc_unfiltered (c, outbuf);
5788         }
5789       break;
5790     }
5791 }
5792
5793 static VEC(mem_region_s) *
5794 remote_memory_map (struct target_ops *ops)
5795 {
5796   VEC(mem_region_s) *result = NULL;
5797   char *text = target_read_stralloc (&current_target,
5798                                      TARGET_OBJECT_MEMORY_MAP, NULL);
5799
5800   if (text)
5801     {
5802       struct cleanup *back_to = make_cleanup (xfree, text);
5803       result = parse_memory_map (text);
5804       do_cleanups (back_to);
5805     }
5806
5807   return result;
5808 }
5809
5810 static void
5811 packet_command (char *args, int from_tty)
5812 {
5813   struct remote_state *rs = get_remote_state ();
5814
5815   if (!remote_desc)
5816     error (_("command can only be used with remote target"));
5817
5818   if (!args)
5819     error (_("remote-packet command requires packet text as argument"));
5820
5821   puts_filtered ("sending: ");
5822   print_packet (args);
5823   puts_filtered ("\n");
5824   putpkt (args);
5825
5826   getpkt (&rs->buf, &rs->buf_size, 0);
5827   puts_filtered ("received: ");
5828   print_packet (rs->buf);
5829   puts_filtered ("\n");
5830 }
5831
5832 #if 0
5833 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
5834
5835 static void display_thread_info (struct gdb_ext_thread_info *info);
5836
5837 static void threadset_test_cmd (char *cmd, int tty);
5838
5839 static void threadalive_test (char *cmd, int tty);
5840
5841 static void threadlist_test_cmd (char *cmd, int tty);
5842
5843 int get_and_display_threadinfo (threadref *ref);
5844
5845 static void threadinfo_test_cmd (char *cmd, int tty);
5846
5847 static int thread_display_step (threadref *ref, void *context);
5848
5849 static void threadlist_update_test_cmd (char *cmd, int tty);
5850
5851 static void init_remote_threadtests (void);
5852
5853 #define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid.  */
5854
5855 static void
5856 threadset_test_cmd (char *cmd, int tty)
5857 {
5858   int sample_thread = SAMPLE_THREAD;
5859
5860   printf_filtered (_("Remote threadset test\n"));
5861   set_thread (sample_thread, 1);
5862 }
5863
5864
5865 static void
5866 threadalive_test (char *cmd, int tty)
5867 {
5868   int sample_thread = SAMPLE_THREAD;
5869
5870   if (remote_thread_alive (pid_to_ptid (sample_thread)))
5871     printf_filtered ("PASS: Thread alive test\n");
5872   else
5873     printf_filtered ("FAIL: Thread alive test\n");
5874 }
5875
5876 void output_threadid (char *title, threadref *ref);
5877
5878 void
5879 output_threadid (char *title, threadref *ref)
5880 {
5881   char hexid[20];
5882
5883   pack_threadid (&hexid[0], ref);       /* Convert threead id into hex.  */
5884   hexid[16] = 0;
5885   printf_filtered ("%s  %s\n", title, (&hexid[0]));
5886 }
5887
5888 static void
5889 threadlist_test_cmd (char *cmd, int tty)
5890 {
5891   int startflag = 1;
5892   threadref nextthread;
5893   int done, result_count;
5894   threadref threadlist[3];
5895
5896   printf_filtered ("Remote Threadlist test\n");
5897   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
5898                               &result_count, &threadlist[0]))
5899     printf_filtered ("FAIL: threadlist test\n");
5900   else
5901     {
5902       threadref *scan = threadlist;
5903       threadref *limit = scan + result_count;
5904
5905       while (scan < limit)
5906         output_threadid (" thread ", scan++);
5907     }
5908 }
5909
5910 void
5911 display_thread_info (struct gdb_ext_thread_info *info)
5912 {
5913   output_threadid ("Threadid: ", &info->threadid);
5914   printf_filtered ("Name: %s\n ", info->shortname);
5915   printf_filtered ("State: %s\n", info->display);
5916   printf_filtered ("other: %s\n\n", info->more_display);
5917 }
5918
5919 int
5920 get_and_display_threadinfo (threadref *ref)
5921 {
5922   int result;
5923   int set;
5924   struct gdb_ext_thread_info threadinfo;
5925
5926   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
5927     | TAG_MOREDISPLAY | TAG_DISPLAY;
5928   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
5929     display_thread_info (&threadinfo);
5930   return result;
5931 }
5932
5933 static void
5934 threadinfo_test_cmd (char *cmd, int tty)
5935 {
5936   int athread = SAMPLE_THREAD;
5937   threadref thread;
5938   int set;
5939
5940   int_to_threadref (&thread, athread);
5941   printf_filtered ("Remote Threadinfo test\n");
5942   if (!get_and_display_threadinfo (&thread))
5943     printf_filtered ("FAIL cannot get thread info\n");
5944 }
5945
5946 static int
5947 thread_display_step (threadref *ref, void *context)
5948 {
5949   /* output_threadid(" threadstep ",ref); *//* simple test */
5950   return get_and_display_threadinfo (ref);
5951 }
5952
5953 static void
5954 threadlist_update_test_cmd (char *cmd, int tty)
5955 {
5956   printf_filtered ("Remote Threadlist update test\n");
5957   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
5958 }
5959
5960 static void
5961 init_remote_threadtests (void)
5962 {
5963   add_com ("tlist", class_obscure, threadlist_test_cmd, _("\
5964 Fetch and print the remote list of thread identifiers, one pkt only"));
5965   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
5966            _("Fetch and display info about one thread"));
5967   add_com ("tset", class_obscure, threadset_test_cmd,
5968            _("Test setting to a different thread"));
5969   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
5970            _("Iterate through updating all remote thread info"));
5971   add_com ("talive", class_obscure, threadalive_test,
5972            _(" Remote thread alive test "));
5973 }
5974
5975 #endif /* 0 */
5976
5977 /* Convert a thread ID to a string.  Returns the string in a static
5978    buffer.  */
5979
5980 static char *
5981 remote_pid_to_str (ptid_t ptid)
5982 {
5983   static char buf[32];
5984
5985   xsnprintf (buf, sizeof buf, "Thread %d", ptid_get_pid (ptid));
5986   return buf;
5987 }
5988
5989 /* Get the address of the thread local variable in OBJFILE which is
5990    stored at OFFSET within the thread local storage for thread PTID.  */
5991
5992 static CORE_ADDR
5993 remote_get_thread_local_address (ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
5994 {
5995   if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
5996     {
5997       struct remote_state *rs = get_remote_state ();
5998       char *p = rs->buf;
5999       enum packet_result result;
6000
6001       strcpy (p, "qGetTLSAddr:");
6002       p += strlen (p);
6003       p += hexnumstr (p, PIDGET (ptid));
6004       *p++ = ',';
6005       p += hexnumstr (p, offset);
6006       *p++ = ',';
6007       p += hexnumstr (p, lm);
6008       *p++ = '\0';
6009
6010       putpkt (rs->buf);
6011       getpkt (&rs->buf, &rs->buf_size, 0);
6012       result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_qGetTLSAddr]);
6013       if (result == PACKET_OK)
6014         {
6015           ULONGEST result;
6016
6017           unpack_varlen_hex (rs->buf, &result);
6018           return result;
6019         }
6020       else if (result == PACKET_UNKNOWN)
6021         throw_error (TLS_GENERIC_ERROR,
6022                      _("Remote target doesn't support qGetTLSAddr packet"));
6023       else
6024         throw_error (TLS_GENERIC_ERROR,
6025                      _("Remote target failed to process qGetTLSAddr request"));
6026     }
6027   else
6028     throw_error (TLS_GENERIC_ERROR,
6029                  _("TLS not supported or disabled on this target"));
6030   /* Not reached.  */
6031   return 0;
6032 }
6033
6034 static void
6035 init_remote_ops (void)
6036 {
6037   remote_ops.to_shortname = "remote";
6038   remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
6039   remote_ops.to_doc =
6040     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
6041 Specify the serial device it is connected to\n\
6042 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
6043   remote_ops.to_open = remote_open;
6044   remote_ops.to_close = remote_close;
6045   remote_ops.to_detach = remote_detach;
6046   remote_ops.to_disconnect = remote_disconnect;
6047   remote_ops.to_resume = remote_resume;
6048   remote_ops.to_wait = remote_wait;
6049   remote_ops.to_fetch_registers = remote_fetch_registers;
6050   remote_ops.to_store_registers = remote_store_registers;
6051   remote_ops.to_prepare_to_store = remote_prepare_to_store;
6052   remote_ops.deprecated_xfer_memory = remote_xfer_memory;
6053   remote_ops.to_files_info = remote_files_info;
6054   remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
6055   remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
6056   remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
6057   remote_ops.to_stopped_data_address = remote_stopped_data_address;
6058   remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
6059   remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
6060   remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
6061   remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
6062   remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
6063   remote_ops.to_kill = remote_kill;
6064   remote_ops.to_load = generic_load;
6065   remote_ops.to_mourn_inferior = remote_mourn;
6066   remote_ops.to_thread_alive = remote_thread_alive;
6067   remote_ops.to_find_new_threads = remote_threads_info;
6068   remote_ops.to_pid_to_str = remote_pid_to_str;
6069   remote_ops.to_extra_thread_info = remote_threads_extra_info;
6070   remote_ops.to_stop = remote_stop;
6071   remote_ops.to_xfer_partial = remote_xfer_partial;
6072   remote_ops.to_rcmd = remote_rcmd;
6073   remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
6074   remote_ops.to_stratum = process_stratum;
6075   remote_ops.to_has_all_memory = 1;
6076   remote_ops.to_has_memory = 1;
6077   remote_ops.to_has_stack = 1;
6078   remote_ops.to_has_registers = 1;
6079   remote_ops.to_has_execution = 1;
6080   remote_ops.to_has_thread_control = tc_schedlock;      /* can lock scheduler */
6081   remote_ops.to_magic = OPS_MAGIC;
6082   remote_ops.to_memory_map = remote_memory_map;
6083   remote_ops.to_flash_erase = remote_flash_erase;
6084   remote_ops.to_flash_done = remote_flash_done;
6085 }
6086
6087 /* Set up the extended remote vector by making a copy of the standard
6088    remote vector and adding to it.  */
6089
6090 static void
6091 init_extended_remote_ops (void)
6092 {
6093   extended_remote_ops = remote_ops;
6094
6095   extended_remote_ops.to_shortname = "extended-remote";
6096   extended_remote_ops.to_longname =
6097     "Extended remote serial target in gdb-specific protocol";
6098   extended_remote_ops.to_doc =
6099     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
6100 Specify the serial device it is connected to (e.g. /dev/ttya).",
6101     extended_remote_ops.to_open = extended_remote_open;
6102   extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
6103   extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
6104 }
6105
6106 static int
6107 remote_can_async_p (void)
6108 {
6109   /* We're async whenever the serial device is.  */
6110   return (current_target.to_async_mask_value) && serial_can_async_p (remote_desc);
6111 }
6112
6113 static int
6114 remote_is_async_p (void)
6115 {
6116   /* We're async whenever the serial device is.  */
6117   return (current_target.to_async_mask_value) && serial_is_async_p (remote_desc);
6118 }
6119
6120 /* Pass the SERIAL event on and up to the client.  One day this code
6121    will be able to delay notifying the client of an event until the
6122    point where an entire packet has been received.  */
6123
6124 static void (*async_client_callback) (enum inferior_event_type event_type,
6125                                       void *context);
6126 static void *async_client_context;
6127 static serial_event_ftype remote_async_serial_handler;
6128
6129 static void
6130 remote_async_serial_handler (struct serial *scb, void *context)
6131 {
6132   /* Don't propogate error information up to the client.  Instead let
6133      the client find out about the error by querying the target.  */
6134   async_client_callback (INF_REG_EVENT, async_client_context);
6135 }
6136
6137 static void
6138 remote_async (void (*callback) (enum inferior_event_type event_type,
6139                                 void *context), void *context)
6140 {
6141   if (current_target.to_async_mask_value == 0)
6142     internal_error (__FILE__, __LINE__,
6143                     _("Calling remote_async when async is masked"));
6144
6145   if (callback != NULL)
6146     {
6147       serial_async (remote_desc, remote_async_serial_handler, NULL);
6148       async_client_callback = callback;
6149       async_client_context = context;
6150     }
6151   else
6152     serial_async (remote_desc, NULL, NULL);
6153 }
6154
6155 /* Target async and target extended-async.
6156
6157    This are temporary targets, until it is all tested.  Eventually
6158    async support will be incorporated int the usual 'remote'
6159    target.  */
6160
6161 static void
6162 init_remote_async_ops (void)
6163 {
6164   remote_async_ops.to_shortname = "async";
6165   remote_async_ops.to_longname =
6166     "Remote serial target in async version of the gdb-specific protocol";
6167   remote_async_ops.to_doc =
6168     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
6169 Specify the serial device it is connected to (e.g. /dev/ttya).";
6170   remote_async_ops.to_open = remote_async_open;
6171   remote_async_ops.to_close = remote_close;
6172   remote_async_ops.to_detach = remote_detach;
6173   remote_async_ops.to_disconnect = remote_disconnect;
6174   remote_async_ops.to_resume = remote_async_resume;
6175   remote_async_ops.to_wait = remote_async_wait;
6176   remote_async_ops.to_fetch_registers = remote_fetch_registers;
6177   remote_async_ops.to_store_registers = remote_store_registers;
6178   remote_async_ops.to_prepare_to_store = remote_prepare_to_store;
6179   remote_async_ops.deprecated_xfer_memory = remote_xfer_memory;
6180   remote_async_ops.to_files_info = remote_files_info;
6181   remote_async_ops.to_insert_breakpoint = remote_insert_breakpoint;
6182   remote_async_ops.to_remove_breakpoint = remote_remove_breakpoint;
6183   remote_async_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
6184   remote_async_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
6185   remote_async_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
6186   remote_async_ops.to_insert_watchpoint = remote_insert_watchpoint;
6187   remote_async_ops.to_remove_watchpoint = remote_remove_watchpoint;
6188   remote_async_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
6189   remote_async_ops.to_stopped_data_address = remote_stopped_data_address;
6190   remote_async_ops.to_terminal_inferior = remote_async_terminal_inferior;
6191   remote_async_ops.to_terminal_ours = remote_async_terminal_ours;
6192   remote_async_ops.to_kill = remote_async_kill;
6193   remote_async_ops.to_load = generic_load;
6194   remote_async_ops.to_mourn_inferior = remote_async_mourn;
6195   remote_async_ops.to_thread_alive = remote_thread_alive;
6196   remote_async_ops.to_find_new_threads = remote_threads_info;
6197   remote_async_ops.to_pid_to_str = remote_pid_to_str;
6198   remote_async_ops.to_extra_thread_info = remote_threads_extra_info;
6199   remote_async_ops.to_stop = remote_stop;
6200   remote_async_ops.to_xfer_partial = remote_xfer_partial;
6201   remote_async_ops.to_rcmd = remote_rcmd;
6202   remote_async_ops.to_stratum = process_stratum;
6203   remote_async_ops.to_has_all_memory = 1;
6204   remote_async_ops.to_has_memory = 1;
6205   remote_async_ops.to_has_stack = 1;
6206   remote_async_ops.to_has_registers = 1;
6207   remote_async_ops.to_has_execution = 1;
6208   remote_async_ops.to_has_thread_control = tc_schedlock;        /* can lock scheduler */
6209   remote_async_ops.to_can_async_p = remote_can_async_p;
6210   remote_async_ops.to_is_async_p = remote_is_async_p;
6211   remote_async_ops.to_async = remote_async;
6212   remote_async_ops.to_async_mask_value = 1;
6213   remote_async_ops.to_magic = OPS_MAGIC;
6214   remote_async_ops.to_memory_map = remote_memory_map;
6215   remote_async_ops.to_flash_erase = remote_flash_erase;
6216   remote_async_ops.to_flash_done = remote_flash_done;
6217 }
6218
6219 /* Set up the async extended remote vector by making a copy of the standard
6220    remote vector and adding to it.  */
6221
6222 static void
6223 init_extended_async_remote_ops (void)
6224 {
6225   extended_async_remote_ops = remote_async_ops;
6226
6227   extended_async_remote_ops.to_shortname = "extended-async";
6228   extended_async_remote_ops.to_longname =
6229     "Extended remote serial target in async gdb-specific protocol";
6230   extended_async_remote_ops.to_doc =
6231     "Use a remote computer via a serial line, using an async gdb-specific protocol.\n\
6232 Specify the serial device it is connected to (e.g. /dev/ttya).",
6233     extended_async_remote_ops.to_open = extended_remote_async_open;
6234   extended_async_remote_ops.to_create_inferior = extended_remote_async_create_inferior;
6235   extended_async_remote_ops.to_mourn_inferior = extended_remote_mourn;
6236 }
6237
6238 static void
6239 set_remote_cmd (char *args, int from_tty)
6240 {
6241   help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
6242 }
6243
6244 static void
6245 show_remote_cmd (char *args, int from_tty)
6246 {
6247   /* We can't just use cmd_show_list here, because we want to skip
6248      the redundant "show remote Z-packet" and the legacy aliases.  */
6249   struct cleanup *showlist_chain;
6250   struct cmd_list_element *list = remote_show_cmdlist;
6251
6252   showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
6253   for (; list != NULL; list = list->next)
6254     if (strcmp (list->name, "Z-packet") == 0)
6255       continue;
6256     else if (list->type == not_set_cmd)
6257       /* Alias commands are exactly like the original, except they
6258          don't have the normal type.  */
6259       continue;
6260     else
6261       {
6262         struct cleanup *option_chain
6263           = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
6264         ui_out_field_string (uiout, "name", list->name);
6265         ui_out_text (uiout, ":  ");
6266         if (list->type == show_cmd)
6267           do_setshow_command ((char *) NULL, from_tty, list);
6268         else
6269           cmd_func (list, NULL, from_tty);
6270         /* Close the tuple.  */
6271         do_cleanups (option_chain);
6272       }
6273
6274   /* Close the tuple.  */
6275   do_cleanups (showlist_chain);
6276 }
6277
6278 static void
6279 build_remote_gdbarch_data (void)
6280 {
6281   remote_address_size = TARGET_ADDR_BIT;
6282 }
6283
6284 /* Saved pointer to previous owner of the new_objfile event.  */
6285 static void (*remote_new_objfile_chain) (struct objfile *);
6286
6287 /* Function to be called whenever a new objfile (shlib) is detected.  */
6288 static void
6289 remote_new_objfile (struct objfile *objfile)
6290 {
6291   if (remote_desc != 0)         /* Have a remote connection.  */
6292     {
6293       remote_check_symbols (objfile);
6294     }
6295   /* Call predecessor on chain, if any.  */
6296   if (remote_new_objfile_chain)
6297     remote_new_objfile_chain (objfile);
6298 }
6299
6300 void
6301 _initialize_remote (void)
6302 {
6303   struct remote_state *rs;
6304
6305   /* architecture specific data */
6306   remote_gdbarch_data_handle =
6307     gdbarch_data_register_post_init (init_remote_state);
6308
6309   /* Old tacky stuff.  NOTE: This comes after the remote protocol so
6310      that the remote protocol has been initialized.  */
6311   DEPRECATED_REGISTER_GDBARCH_SWAP (remote_address_size);
6312   deprecated_register_gdbarch_swap (NULL, 0, build_remote_gdbarch_data);
6313
6314   /* Initialize the per-target state.  At the moment there is only one
6315      of these, not one per target.  Only one target is active at a
6316      time.  The default buffer size is unimportant; it will be expanded
6317      whenever a larger buffer is needed.  */
6318   rs = get_remote_state_raw ();
6319   rs->buf_size = 400;
6320   rs->buf = xmalloc (rs->buf_size);
6321
6322   init_remote_ops ();
6323   add_target (&remote_ops);
6324
6325   init_extended_remote_ops ();
6326   add_target (&extended_remote_ops);
6327
6328   init_remote_async_ops ();
6329   add_target (&remote_async_ops);
6330
6331   init_extended_async_remote_ops ();
6332   add_target (&extended_async_remote_ops);
6333
6334   /* Hook into new objfile notification.  */
6335   remote_new_objfile_chain = deprecated_target_new_objfile_hook;
6336   deprecated_target_new_objfile_hook  = remote_new_objfile;
6337
6338 #if 0
6339   init_remote_threadtests ();
6340 #endif
6341
6342   /* set/show remote ...  */
6343
6344   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
6345 Remote protocol specific variables\n\
6346 Configure various remote-protocol specific variables such as\n\
6347 the packets being used"),
6348                   &remote_set_cmdlist, "set remote ",
6349                   0 /* allow-unknown */, &setlist);
6350   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
6351 Remote protocol specific variables\n\
6352 Configure various remote-protocol specific variables such as\n\
6353 the packets being used"),
6354                   &remote_show_cmdlist, "show remote ",
6355                   0 /* allow-unknown */, &showlist);
6356
6357   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
6358 Compare section data on target to the exec file.\n\
6359 Argument is a single section name (default: all loaded sections)."),
6360            &cmdlist);
6361
6362   add_cmd ("packet", class_maintenance, packet_command, _("\
6363 Send an arbitrary packet to a remote target.\n\
6364    maintenance packet TEXT\n\
6365 If GDB is talking to an inferior via the GDB serial protocol, then\n\
6366 this command sends the string TEXT to the inferior, and displays the\n\
6367 response packet.  GDB supplies the initial `$' character, and the\n\
6368 terminating `#' character and checksum."),
6369            &maintenancelist);
6370
6371   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
6372 Set whether to send break if interrupted."), _("\
6373 Show whether to send break if interrupted."), _("\
6374 If set, a break, instead of a cntrl-c, is sent to the remote target."),
6375                            NULL, NULL, /* FIXME: i18n: Whether to send break if interrupted is %s.  */
6376                            &setlist, &showlist);
6377
6378   /* Install commands for configuring memory read/write packets.  */
6379
6380   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
6381 Set the maximum number of bytes per memory write packet (deprecated)."),
6382            &setlist);
6383   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
6384 Show the maximum number of bytes per memory write packet (deprecated)."),
6385            &showlist);
6386   add_cmd ("memory-write-packet-size", no_class,
6387            set_memory_write_packet_size, _("\
6388 Set the maximum number of bytes per memory-write packet.\n\
6389 Specify the number of bytes in a packet or 0 (zero) for the\n\
6390 default packet size.  The actual limit is further reduced\n\
6391 dependent on the target.  Specify ``fixed'' to disable the\n\
6392 further restriction and ``limit'' to enable that restriction."),
6393            &remote_set_cmdlist);
6394   add_cmd ("memory-read-packet-size", no_class,
6395            set_memory_read_packet_size, _("\
6396 Set the maximum number of bytes per memory-read packet.\n\
6397 Specify the number of bytes in a packet or 0 (zero) for the\n\
6398 default packet size.  The actual limit is further reduced\n\
6399 dependent on the target.  Specify ``fixed'' to disable the\n\
6400 further restriction and ``limit'' to enable that restriction."),
6401            &remote_set_cmdlist);
6402   add_cmd ("memory-write-packet-size", no_class,
6403            show_memory_write_packet_size,
6404            _("Show the maximum number of bytes per memory-write packet."),
6405            &remote_show_cmdlist);
6406   add_cmd ("memory-read-packet-size", no_class,
6407            show_memory_read_packet_size,
6408            _("Show the maximum number of bytes per memory-read packet."),
6409            &remote_show_cmdlist);
6410
6411   add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
6412                             &remote_hw_watchpoint_limit, _("\
6413 Set the maximum number of target hardware watchpoints."), _("\
6414 Show the maximum number of target hardware watchpoints."), _("\
6415 Specify a negative limit for unlimited."),
6416                             NULL, NULL, /* FIXME: i18n: The maximum number of target hardware watchpoints is %s.  */
6417                             &remote_set_cmdlist, &remote_show_cmdlist);
6418   add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
6419                             &remote_hw_breakpoint_limit, _("\
6420 Set the maximum number of target hardware breakpoints."), _("\
6421 Show the maximum number of target hardware breakpoints."), _("\
6422 Specify a negative limit for unlimited."),
6423                             NULL, NULL, /* FIXME: i18n: The maximum number of target hardware breakpoints is %s.  */
6424                             &remote_set_cmdlist, &remote_show_cmdlist);
6425
6426   add_setshow_integer_cmd ("remoteaddresssize", class_obscure,
6427                            &remote_address_size, _("\
6428 Set the maximum size of the address (in bits) in a memory packet."), _("\
6429 Show the maximum size of the address (in bits) in a memory packet."), NULL,
6430                            NULL,
6431                            NULL, /* FIXME: i18n: */
6432                            &setlist, &showlist);
6433
6434   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
6435                          "X", "binary-download", 1);
6436
6437   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
6438                          "vCont", "verbose-resume", 0);
6439
6440   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
6441                          "QPassSignals", "pass-signals", 0);
6442
6443   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
6444                          "qSymbol", "symbol-lookup", 0);
6445
6446   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
6447                          "P", "set-register", 1);
6448
6449   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
6450                          "p", "fetch-register", 1);
6451
6452   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
6453                          "Z0", "software-breakpoint", 0);
6454
6455   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
6456                          "Z1", "hardware-breakpoint", 0);
6457
6458   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
6459                          "Z2", "write-watchpoint", 0);
6460
6461   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
6462                          "Z3", "read-watchpoint", 0);
6463
6464   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
6465                          "Z4", "access-watchpoint", 0);
6466
6467   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
6468                          "qXfer:auxv:read", "read-aux-vector", 0);
6469
6470   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
6471                          "qXfer:memory-map:read", "memory-map", 0);
6472
6473   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
6474                          "qGetTLSAddr", "get-thread-local-storage-address",
6475                          0);
6476
6477   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
6478                          "qSupported", "supported-packets", 0);
6479
6480   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
6481      Z sub-packet has its own set and show commands, but users may
6482      have sets to this variable in their .gdbinit files (or in their
6483      documentation).  */
6484   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
6485                                 &remote_Z_packet_detect, _("\
6486 Set use of remote protocol `Z' packets"), _("\
6487 Show use of remote protocol `Z' packets "), _("\
6488 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
6489 packets."),
6490                                 set_remote_protocol_Z_packet_cmd,
6491                                 show_remote_protocol_Z_packet_cmd, /* FIXME: i18n: Use of remote protocol `Z' packets is %s.  */
6492                                 &remote_set_cmdlist, &remote_show_cmdlist);
6493
6494   /* Eventually initialize fileio.  See fileio.c */
6495   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
6496 }