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