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