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