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