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