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