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