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