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