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