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