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