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