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