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