b4f7ce6460da7c9f52fd5880d6d6d97fb0937d72
[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, 1998 
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, Boston, MA 02111-1307, USA.  */
20
21 /* Remote communication protocol.
22
23    A debug packet whose contents are <data>
24    is encapsulated for transmission in the form:
25
26         $ <data> # CSUM1 CSUM2
27
28         <data> must be ASCII alphanumeric and cannot include characters
29         '$' or '#'.  If <data> starts with two characters followed by
30         ':', then the existing stubs interpret this as a sequence number.
31
32         CSUM1 and CSUM2 are ascii hex representation of an 8-bit 
33         checksum of <data>, the most significant nibble is sent first.
34         the hex digits 0-9,a-f are used.
35
36    Receiver responds with:
37
38         +       - if CSUM is correct and ready for next packet
39         -       - if CSUM is incorrect
40
41    <data> is as follows:
42    Most values are encoded in ascii hex digits.  Signal numbers are according
43    to the numbering in target.h.
44
45         Request         Packet
46
47         set thread      Hct...          Set thread for subsequent operations.
48                                         c = 'c' for thread used in step and 
49                                         continue; t... can be -1 for all
50                                         threads.
51                                         c = 'g' for thread used in other
52                                         operations.  If zero, pick a thread,
53                                         any thread.
54         reply           OK              for success
55                         ENN             for an error.
56
57         read registers  g
58         reply           XX....X         Each byte of register data
59                                         is described by two hex digits.
60                                         Registers are in the internal order
61                                         for GDB, and the bytes in a register
62                                         are in the same order the machine uses.
63                         or ENN          for an error.
64
65         write regs      GXX..XX         Each byte of register data
66                                         is described by two hex digits.
67         reply           OK              for success
68                         ENN             for an error
69
70         write reg       Pn...=r...      Write register n... with value r...,
71                                         which contains two hex digits for each
72                                         byte in the register (target byte
73                                         order).
74         reply           OK              for success
75                         ENN             for an error
76         (not supported by all stubs).
77
78         read mem        mAA..AA,LLLL    AA..AA is address, LLLL is length.
79         reply           XX..XX          XX..XX is mem contents
80                                         Can be fewer bytes than requested
81                                         if able to read only part of the data.
82                         or ENN          NN is errno
83
84         write mem       MAA..AA,LLLL:XX..XX
85                                         AA..AA is address,
86                                         LLLL is number of bytes,
87                                         XX..XX is data
88         reply           OK              for success
89                         ENN             for an error (this includes the case
90                                         where only part of the data was
91                                         written).
92
93         continue        cAA..AA         AA..AA is address to resume
94                                         If AA..AA is omitted,
95                                         resume at same address.
96
97         step            sAA..AA         AA..AA is address to resume
98                                         If AA..AA is omitted,
99                                         resume at same address.
100
101         continue with   Csig;AA..AA     Continue with signal sig (hex signal
102         signal                          number).  If ;AA..AA is omitted, 
103                                         resume at same address.
104
105         step with       Ssig;AA..AA     Like 'C' but step not continue.
106         signal
107
108         last signal     ?               Reply the current reason for stopping.
109                                         This is the same reply as is generated
110                                         for step or cont : SAA where AA is the
111                                         signal number.
112
113         detach          D               Reply OK.
114
115         There is no immediate reply to step or cont.
116         The reply comes when the machine stops.
117         It is           SAA             AA is the signal number.
118
119         or...           TAAn...:r...;n...:r...;n...:r...;
120                                         AA = signal number
121                                         n... = register number (hex)
122                                           r... = register contents
123                                         n... = `thread'
124                                           r... = thread process ID.  This is
125                                                  a hex integer.
126                                         n... = other string not starting 
127                                             with valid hex digit.
128                                           gdb should ignore this n,r pair
129                                           and go on to the next.  This way
130                                           we can extend the protocol.
131         or...           WAA             The process exited, and AA is
132                                         the exit status.  This is only
133                                         applicable for certains sorts of
134                                         targets.
135         or...           XAA             The process terminated with signal
136                                         AA.
137         or...           OXX..XX XX..XX  is hex encoding of ASCII data. This
138                                         can happen at any time while the 
139                                         program is running and the debugger 
140                                         should continue to wait for 
141                                         'W', 'T', etc.
142
143         thread alive    TXX             Find out if the thread XX is alive.
144         reply           OK              thread is still alive
145                         ENN             thread is dead
146         
147         remote restart  RXX             Restart the remote server
148
149         extended ops    !               Use the extended remote protocol.
150                                         Sticky -- only needs to be set once.
151
152         kill request    k
153
154         toggle debug    d               toggle debug flag (see 386 & 68k stubs)
155         reset           r               reset -- see sparc stub.
156         reserved        <other>         On other requests, the stub should
157                                         ignore the request and send an empty
158                                         response ($#<checksum>).  This way
159                                         we can extend the protocol and GDB
160                                         can tell whether the stub it is
161                                         talking to uses the old or the new.
162         search          tAA:PP,MM       Search backwards starting at address
163                                         AA for a match with pattern PP and
164                                         mask MM.  PP and MM are 4 bytes.
165                                         Not supported by all stubs.
166
167         general query   qXXXX           Request info about XXXX.
168         general set     QXXXX=yyyy      Set value of XXXX to yyyy.
169         query sect offs qOffsets        Get section offsets.  Reply is
170                                         Text=xxx;Data=yyy;Bss=zzz
171
172         Responses can be run-length encoded to save space.  A '*' means that
173         the next character is an ASCII encoding giving a repeat count which
174         stands for that many repititions of the character preceding the '*'.
175         The encoding is n+29, yielding a printable character where n >=3 
176         (which is where rle starts to win).  Don't use an n > 126.
177
178         So 
179         "0* " means the same as "0000".  */
180
181 #include "defs.h"
182 #include "gdb_string.h"
183 #include <fcntl.h>
184 #include "frame.h"
185 #include "inferior.h"
186 #include "bfd.h"
187 #include "symfile.h"
188 #include "target.h"
189 #include "wait.h"
190 /*#include "terminal.h"*/
191 #include "gdbcmd.h"
192 #include "objfiles.h"
193 #include "gdb-stabs.h"
194 #include "gdbthread.h"
195
196 #include "dcache.h"
197
198 #ifdef USG
199 #include <sys/types.h>
200 #endif
201
202 #include <signal.h>
203 #include "serial.h"
204
205 /* Prototypes for local functions */
206
207 static int remote_write_bytes PARAMS ((CORE_ADDR memaddr,
208                                        char *myaddr, int len));
209
210 static int remote_read_bytes PARAMS ((CORE_ADDR memaddr,
211                                       char *myaddr, int len));
212
213 static void remote_files_info PARAMS ((struct target_ops *ignore));
214
215 static int remote_xfer_memory PARAMS ((CORE_ADDR memaddr, char * myaddr,
216                                        int len, int should_write,
217                                        struct target_ops * target));
218
219 static void remote_prepare_to_store PARAMS ((void));
220
221 static void remote_fetch_registers PARAMS ((int regno));
222
223 static void remote_resume PARAMS ((int pid, int step,
224                                    enum target_signal siggnal));
225
226 static int remote_start_remote PARAMS ((char *dummy));
227
228 static void remote_open PARAMS ((char *name, int from_tty));
229
230 static void extended_remote_open PARAMS ((char *name, int from_tty));
231
232 static void remote_open_1 PARAMS ((char *, int, struct target_ops *,
233                                    int extended_p));
234
235 static void remote_close PARAMS ((int quitting));
236
237 static void remote_store_registers PARAMS ((int regno));
238
239 static void remote_mourn PARAMS ((void));
240
241 static void extended_remote_restart PARAMS ((void));
242
243 static void extended_remote_mourn PARAMS ((void));
244
245 static void extended_remote_create_inferior PARAMS ((char *, char *, char **));
246
247 static void remote_mourn_1 PARAMS ((struct target_ops *));
248
249 static void remote_send PARAMS ((char *buf));
250
251 static int readchar PARAMS ((int timeout));
252
253 static int remote_wait PARAMS ((int pid, struct target_waitstatus * status));
254
255 static void remote_kill PARAMS ((void));
256
257 static int tohex PARAMS ((int nib));
258
259 static void remote_detach PARAMS ((char *args, int from_tty));
260
261 static void remote_interrupt PARAMS ((int signo));
262
263 static void interrupt_query PARAMS ((void));
264
265 static void set_thread PARAMS ((int, int));
266
267 static int remote_thread_alive PARAMS ((int));
268
269 static void get_offsets PARAMS ((void));
270
271 static int read_frame PARAMS ((char *));
272
273 static int remote_insert_breakpoint PARAMS ((CORE_ADDR, char *));
274
275 static int remote_remove_breakpoint PARAMS ((CORE_ADDR, char *));
276
277 static int hexnumlen PARAMS ((ULONGEST num));
278
279 static void init_remote_ops PARAMS ((void));
280
281 static void init_extended_remote_ops PARAMS ((void));
282
283 static void remote_stop PARAMS ((void));
284
285 static int ishex PARAMS ((int ch, int *val));
286
287 static int stubhex PARAMS ((int ch));
288
289 static int hexnumstr PARAMS ((char *, ULONGEST));
290
291 static CORE_ADDR remote_address_masked PARAMS ((CORE_ADDR));
292
293 static void print_packet PARAMS ((char *));
294
295 static unsigned long crc32 PARAMS ((unsigned char *, int, unsigned int));
296
297 static void compare_sections_command PARAMS ((char *, int));
298
299 static void packet_command PARAMS ((char *, int));
300
301 static int stub_unpack_int PARAMS ((char *buff, int fieldlength));
302
303 char *unpack_varlen_hex PARAMS ((char *buff, int *result));
304
305 static char *unpack_nibble PARAMS ((char *buf, int *val));
306
307 static char *pack_nibble PARAMS ((char *buf, int nibble));
308
309 static char *pack_hex_byte PARAMS ((char *pkt, unsigned char byte));
310
311 static char *unpack_byte PARAMS ((char *buf, int *value));
312
313 static char *pack_int PARAMS ((char *buf, int value));
314
315 static char *unpack_int PARAMS ((char *buf, int *value));
316
317 static char *unpack_string PARAMS ((char *src, char *dest, int length));
318
319 static char *pack_threadid PARAMS ((char *pkt, threadref *id));
320
321 static char *unpack_threadid PARAMS ((char *inbuf, threadref *id));
322
323 void int_to_threadref PARAMS ((threadref *id, int value));
324
325 static int threadref_to_int PARAMS ((threadref *ref));
326
327 static void copy_threadref PARAMS ((threadref *dest, threadref *src));
328
329 static int threadmatch PARAMS ((threadref *dest, threadref *src));
330
331 static char *pack_threadinfo_request PARAMS ((char *pkt, int mode,
332                                               threadref *id));
333
334 static int remote_unpack_thread_info_response PARAMS ((char *pkt,
335                                                        threadref *expectedref,
336                                                        struct gdb_ext_thread_info *info));
337
338
339 static int remote_get_threadinfo PARAMS ((threadref *threadid,
340                                           int fieldset, /*TAG mask */
341                                           struct gdb_ext_thread_info *info));
342
343 static int adapt_remote_get_threadinfo PARAMS ((gdb_threadref *ref,
344                                                 int selection,
345                                                 struct gdb_ext_thread_info *info));
346
347 static char *pack_threadlist_request PARAMS ((char *pkt, int startflag,
348                                               int threadcount,
349                                               threadref *nextthread));
350
351 static int parse_threadlist_response PARAMS ((char *pkt,
352                                               int result_limit,
353                                               threadref *original_echo,
354                                               threadref *resultlist,
355                                               int *doneflag));
356
357 static int remote_get_threadlist PARAMS ((int startflag,
358                                           threadref *nextthread,
359                                           int result_limit,
360                                           int *done,
361                                           int *result_count,
362                                           threadref *threadlist));
363
364 typedef int (*rmt_thread_action) (threadref *ref, void *context);
365
366 static int remote_threadlist_iterator PARAMS ((rmt_thread_action stepfunction,
367                                                void *context, int looplimit));
368
369 static int remote_newthread_step PARAMS ((threadref *ref, void *context));
370
371 static int remote_current_thread PARAMS ((int oldpid));
372
373 int remote_find_new_threads PARAMS ((void));
374
375 static void record_currthread PARAMS ((int currthread));
376
377 static void init_remote_threads PARAMS ((void));
378
379 /* exported functions */
380
381 extern int fromhex PARAMS ((int a));
382
383 extern void getpkt PARAMS ((char *buf, int forever));
384
385 extern int putpkt PARAMS ((char *buf));
386
387 void remote_console_output PARAMS ((char *));
388
389 /* Define the target subroutine names */
390
391 void open_remote_target PARAMS ((char *, int, struct target_ops *, int));
392
393 void _initialize_remote PARAMS ((void));
394
395 /* */
396
397 static struct target_ops remote_ops;
398
399 static struct target_ops extended_remote_ops;
400
401 static struct target_thread_vector remote_thread_vec;
402
403 /* This was 5 seconds, which is a long time to sit and wait.
404    Unless this is going though some terminal server or multiplexer or
405    other form of hairy serial connection, I would think 2 seconds would
406    be plenty.  */
407
408 /* Changed to allow option to set timeout value.
409    was static int remote_timeout = 2; */
410 extern int remote_timeout;
411
412 /* This variable chooses whether to send a ^C or a break when the user
413    requests program interruption.  Although ^C is usually what remote
414    systems expect, and that is the default here, sometimes a break is
415    preferable instead.  */
416
417 static int remote_break;
418
419 /* Has the user attempted to interrupt the target? If so, then offer
420    the user the opportunity to bail out completely if he interrupts
421    again. */
422 static int interrupted_already = 0;
423
424 /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
425    remote_open knows that we don't have a file open when the program
426    starts.  */
427 static serial_t remote_desc = NULL;
428
429 /* Having this larger than 400 causes us to be incompatible with m68k-stub.c
430    and i386-stub.c.  Normally, no one would notice because it only matters
431    for writing large chunks of memory (e.g. in downloads).  Also, this needs
432    to be more than 400 if required to hold the registers (see below, where
433    we round it up based on REGISTER_BYTES).  */
434 #define PBUFSIZ 400
435
436 /* Maximum number of bytes to read/write at once.  The value here
437    is chosen to fill up a packet (the headers account for the 32).  */
438 #define MAXBUFBYTES ((PBUFSIZ-32)/2)
439
440 /* Round up PBUFSIZ to hold all the registers, at least.  */
441 /* The blank line after the #if seems to be required to work around a
442    bug in HP's PA compiler.  */
443 #if REGISTER_BYTES > MAXBUFBYTES
444
445 #undef PBUFSIZ
446 #define PBUFSIZ (REGISTER_BYTES * 2 + 32)
447 #endif
448
449
450 /* This variable sets the number of bytes to be written to the target
451    in a single packet.  Normally PBUFSIZ is satisfactory, but some
452    targets need smaller values (perhaps because the receiving end
453    is slow).  */
454
455 static int remote_write_size = PBUFSIZ;
456
457 /* This variable sets the number of bits in an address that are to be
458    sent in a memory ("M" or "m") packet.  Normally, after stripping
459    leading zeros, the entire address would be sent. This variable
460    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
461    initial implementation of remote.c restricted the address sent in
462    memory packets to ``host::sizeof long'' bytes - (typically 32
463    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
464    address was never sent.  Since fixing this bug may cause a break in
465    some remote targets this variable is principly provided to
466    facilitate backward compatibility. */
467
468 static int remote_address_size;
469
470 /* This is the size (in chars) of the first response to the `g' command.  This
471    is used to limit the size of the memory read and write commands to prevent
472    stub buffers from overflowing.  The size does not include headers and
473    trailers, it is only the payload size. */
474
475 static int remote_register_buf_size = 0;
476
477 /* Should we try the 'P' request?  If this is set to one when the stub
478    doesn't support 'P', the only consequence is some unnecessary traffic.  */
479 static int stub_supports_P = 1;
480
481 /* These are pointers to hook functions that may be set in order to
482    modify resume/wait behavior for a particular architecture.  */
483
484 void (*target_resume_hook) PARAMS ((void));
485 void (*target_wait_loop_hook) PARAMS ((void));
486
487 \f
488
489 /* These are the threads which we last sent to the remote system.
490    -1 for all or -2 for not sent yet.  */
491 static int general_thread;
492 static int cont_thread;
493
494 /* Call this function as a result of
495    1) A halt indication (T packet) containing a thread id
496    2) A direct query of currthread
497    3) Successful execution of set thread
498  */
499
500 static void
501 record_currthread (currthread)
502      int currthread;
503 {
504 #if 0   /* target_wait must not modify inferior_pid! */
505   inferior_pid = currthread;
506 #endif
507   general_thread = currthread;
508 #if 0   /* setting cont_thread has a different meaning 
509            from having the target report its thread id.  */
510   cont_thread = currthread;
511 #endif
512   /* If this is a new thread, add it to GDB's thread list.
513      If we leave it up to WFI to do this, bad things will happen.  */
514   if (!in_thread_list (currthread))
515     add_thread (currthread);
516 }
517
518 #define MAGIC_NULL_PID 42000
519
520 static void
521 set_thread (th, gen)
522      int th;
523      int gen;
524 {
525   char buf[PBUFSIZ];
526   int state = gen ? general_thread : cont_thread;
527
528   if (state == th)
529     return;
530
531   buf[0] = 'H';
532   buf[1] = gen ? 'g' : 'c';
533   if (th == MAGIC_NULL_PID)
534     {
535       buf[2] = '0';
536       buf[3] = '\0';
537     }
538   else if (th < 0)
539     sprintf (&buf[2], "-%x", -th);
540   else
541     sprintf (&buf[2], "%x", th);
542   putpkt (buf);
543   getpkt (buf, 0);
544   if (gen)
545     general_thread = th;
546   else
547     cont_thread = th;
548 }
549 \f
550 /*  Return nonzero if the thread TH is still alive on the remote system.  */
551
552 static int
553 remote_thread_alive (th)
554      int th;
555 {
556   char buf[PBUFSIZ];
557
558   buf[0] = 'T';
559   if (th < 0)
560     sprintf (&buf[1], "-%08x", -th);
561   else
562     sprintf (&buf[1], "%08x", th);
563   putpkt (buf);
564   getpkt (buf, 0);
565   return (buf[0] == 'O' && buf[1] == 'K');
566 }
567
568 /* About these extended threadlist and threadinfo packets.  They are
569    variable length packets but, the fields within them are often fixed
570    length.  They are redundent enough to send over UDP as is the
571    remote protocol in general.  There is a matching unit test module
572    in libstub.  */
573
574 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES*2)
575
576 /* encode 64 bits in 16 chars of hex */
577
578 static const char hexchars[] = "0123456789abcdef";
579
580 static int
581 ishex (ch, val)
582      int ch;
583      int *val;
584 {
585   if ((ch >= 'a') && (ch <= 'f'))
586     {
587       *val = ch - 'a' + 10;
588       return 1;
589     }
590   if ((ch >= 'A') && (ch <= 'F'))
591     {
592       *val = ch - 'A' + 10;
593       return 1;
594     }
595   if ((ch >= '0') && (ch <= '9'))
596     {
597       *val = ch - '0';
598       return 1;
599     }
600   return 0;
601 }
602
603 static int
604 stubhex (ch)
605      int ch;
606 {
607   if (ch >= 'a' && ch <= 'f')
608     return ch - 'a' + 10;
609   if (ch >= '0' && ch <= '9')
610     return ch - '0';
611   if (ch >= 'A' && ch <= 'F')
612     return ch - 'A' + 10;
613   return -1;
614 }
615
616 static int
617 stub_unpack_int (buff, fieldlength)
618      char *buff;
619      int fieldlength;
620 {
621   int nibble;
622   int retval = 0;
623
624   while (fieldlength)
625     {
626       nibble = stubhex (*buff++);
627       retval |= nibble;
628       fieldlength--;
629       if (fieldlength)
630         retval = retval << 4;
631     }
632   return retval;
633 }
634
635 char *
636 unpack_varlen_hex (buff, result)
637      char *buff;                /* packet to parse */
638      int *result;
639 {
640   int nibble;
641   int retval = 0;
642
643   while (ishex (*buff, &nibble))
644     {
645       buff++;
646       retval = retval << 4;
647       retval |= nibble & 0x0f;
648     }
649   *result = retval;
650   return buff;
651 }
652
653 static char *
654 unpack_nibble (buf, val)
655      char *buf;
656      int *val;
657 {
658   ishex (*buf++, val);
659   return buf;
660 }
661
662 static char *
663 pack_nibble (buf, nibble)
664      char *buf;
665      int nibble;
666 {
667   *buf++ = hexchars[(nibble & 0x0f)];
668   return buf;
669 }
670
671 static char *
672 pack_hex_byte (pkt, byte)
673      char *pkt;
674      unsigned char byte;
675 {
676   *pkt++ = hexchars[(byte >> 4) & 0xf];
677   *pkt++ = hexchars[(byte & 0xf)];
678   return pkt;
679 }
680
681 static char *
682 unpack_byte (buf, value)
683      char *buf;
684      int *value;
685 {
686   *value = stub_unpack_int (buf, 2);
687   return buf + 2;
688 }
689
690 static char *
691 pack_int (buf, value)
692      char *buf;
693      int value;
694 {
695   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
696   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
697   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
698   buf = pack_hex_byte (buf, (value & 0xff));
699   return buf;
700 }
701
702 static char *
703 unpack_int (buf, value)
704      char *buf;
705      int *value;
706 {
707   *value = stub_unpack_int (buf, 8);
708   return buf + 8;
709 }
710
711 #if 0 /* currently unused, uncomment when needed */
712 static char *pack_string PARAMS ((char *pkt, char *string));
713
714 static char *
715 pack_string (pkt, string)
716      char *pkt;
717      char *string;
718 {
719   char ch;
720   int len;
721
722   len = strlen (string);
723   if (len > 200)
724     len = 200;                  /* Bigger than most GDB packets, junk??? */
725   pkt = pack_hex_byte (pkt, len);
726   while (len-- > 0)
727     {
728       ch = *string++;
729       if ((ch == '\0') || (ch == '#'))
730         ch = '*';               /* Protect encapsulation */
731       *pkt++ = ch;
732     }
733   return pkt;
734 }
735 #endif /* 0 (unused) */
736
737 static char *
738 unpack_string (src, dest, length)
739      char *src;
740      char *dest;
741      int length;
742 {
743   while (length--)
744     *dest++ = *src++;
745   *dest = '\0';
746   return src;
747 }
748
749 static char *
750 pack_threadid (pkt, id)
751      char *pkt;
752      threadref *id;
753 {
754   char *limit;
755   unsigned char *altid;
756
757   altid = (unsigned char *) id;
758   limit = pkt + BUF_THREAD_ID_SIZE;
759   while (pkt < limit)
760     pkt = pack_hex_byte (pkt, *altid++);
761   return pkt;
762 }
763
764
765 static char *
766 unpack_threadid (inbuf, id)
767      char *inbuf;
768      threadref *id;
769 {
770   char *altref;
771   char *limit = inbuf + BUF_THREAD_ID_SIZE;
772   int x, y;
773
774   altref = (char *) id;
775
776   while (inbuf < limit)
777     {
778       x = stubhex (*inbuf++);
779       y = stubhex (*inbuf++);
780       *altref++ = (x << 4) | y;
781     }
782   return inbuf;
783 }
784
785 /* Externally, threadrefs are 64 bits but internally, they are still
786    ints. This is due to a mismatch of specifications.  We would like
787    to use 64bit thread references internally.  This is an adapter
788    function.  */
789
790 void
791 int_to_threadref (id, value)
792      threadref *id;
793      int value;
794 {
795   unsigned char *scan;
796
797   scan = (unsigned char *) id;
798   {
799     int i = 4;
800     while (i--)
801       *scan++ = 0;
802   }
803   *scan++ = (value >> 24) & 0xff;
804   *scan++ = (value >> 16) & 0xff;
805   *scan++ = (value >> 8) & 0xff;
806   *scan++ = (value & 0xff);
807 }
808
809 static int
810 threadref_to_int (ref)
811      threadref *ref;
812 {
813   int i, value = 0;
814   unsigned char *scan;
815
816   scan = (char *) ref;
817   scan += 4;
818   i = 4;
819   while (i-- > 0)
820     value = (value << 8) | ((*scan++) & 0xff);
821   return value;
822 }
823
824 static void
825 copy_threadref (dest, src)
826      threadref *dest;
827      threadref *src;
828 {
829   int i;
830   unsigned char *csrc, *cdest;
831
832   csrc = (unsigned char *) src;
833   cdest = (unsigned char *) dest;
834   i = 8;
835   while (i--)
836     *cdest++ = *csrc++;
837 }
838
839 static int
840 threadmatch (dest, src)
841      threadref *dest;
842      threadref *src;
843 {
844   /* things are broken right now, so just assume we got a match */
845 #if 0
846   unsigned char *srcp, *destp;
847   int i, result;
848   srcp = (char *) src;
849   destp = (char *) dest;
850
851   result = 1;
852   while (i-- > 0)
853     result &= (*srcp++ == *destp++) ? 1 : 0;
854   return result;
855 #endif
856   return 1;
857 }
858
859 /*
860   threadid:1,        # always request threadid
861   context_exists:2,
862   display:4,
863   unique_name:8,
864   more_display:16
865 */
866
867 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
868
869 static char *
870 pack_threadinfo_request (pkt, mode, id)
871      char *pkt;
872      int mode;
873      threadref *id;
874 {
875   *pkt++ = 'q';                 /* Info Query */
876   *pkt++ = 'P';                 /* process or thread info */
877   pkt = pack_int (pkt, mode);   /* mode */
878   pkt = pack_threadid (pkt, id);        /* threadid */
879   *pkt = '\0';                  /* terminate */
880   return pkt;
881 }
882
883 /* These values tag the fields in a thread info response packet */
884 /* Tagging the fields allows us to request specific fields and to
885    add more fields as time goes by */
886
887 #define TAG_THREADID 1      /* Echo the thread identifier */
888 #define TAG_EXISTS 2        /* Is this process defined enough to
889                                fetch registers and its stack */
890 #define TAG_DISPLAY 4       /* A short thing maybe to put on a window */
891 #define TAG_THREADNAME 8    /* string, maps 1-to-1 with a thread is */
892 #define TAG_MOREDISPLAY 16  /* Whatever the kernel wants to say about 
893                                the process*/
894
895 static int
896 remote_unpack_thread_info_response (pkt, expectedref, info)
897      char *pkt;
898      threadref *expectedref;
899      struct gdb_ext_thread_info *info;
900 {
901   int mask, length;
902   unsigned int tag;
903   threadref ref;
904   char *limit = pkt + PBUFSIZ;  /* plausable parsing limit */
905   int retval = 1;
906
907   /* info->threadid = 0; FIXME: implement zero_threadref */
908   info->active = 0;
909   info->display[0] = '\0';
910   info->shortname[0] = '\0';
911   info->more_display[0] = '\0';
912
913   /* Assume the characters indicating the packet type have been stripped */
914   pkt = unpack_int (pkt, &mask);        /* arg mask */
915   pkt = unpack_threadid (pkt, &ref);
916
917   if (mask == 0)
918     warning ("Incomplete response to threadinfo request\n");
919   if (!threadmatch (&ref, expectedref))
920     {                           /* This is an answer to a different request */
921       warning ("ERROR RMT Thread info mismatch\n");
922       return 0;
923     }
924   copy_threadref (&info->threadid, &ref);
925
926   /* Loop on tagged fields , try to bail if somthing goes wrong */
927
928   while ((pkt < limit) && mask && *pkt) /* packets are terminated with nulls */
929     {
930       pkt = unpack_int (pkt, &tag);     /* tag */
931       pkt = unpack_byte (pkt, &length);         /* length */
932       if (!(tag & mask))        /* tags out of synch with mask */
933         {
934           warning ("ERROR RMT: threadinfo tag mismatch\n");
935           retval = 0;
936           break;
937         }
938       if (tag == TAG_THREADID)
939         {
940           if (length != 16)
941             {
942               warning ("ERROR RMT: length of threadid is not 16\n");
943               retval = 0;
944               break;
945             }
946           pkt = unpack_threadid (pkt, &ref);
947           mask = mask & ~TAG_THREADID;
948           continue;
949         }
950       if (tag == TAG_EXISTS)
951         {
952           info->active = stub_unpack_int (pkt, length);
953           pkt += length;
954           mask = mask & ~(TAG_EXISTS);
955           if (length > 8)
956             {
957               warning ("ERROR RMT: 'exists' length too long\n");
958               retval = 0;
959               break;
960             }
961           continue;
962         }
963       if (tag == TAG_THREADNAME)
964         {
965           pkt = unpack_string (pkt, &info->shortname[0], length);
966           mask = mask & ~TAG_THREADNAME;
967           continue;
968         }
969       if (tag == TAG_DISPLAY)
970         {
971           pkt = unpack_string (pkt, &info->display[0], length);
972           mask = mask & ~TAG_DISPLAY;
973           continue;
974         }
975       if (tag == TAG_MOREDISPLAY)
976         {
977           pkt = unpack_string (pkt, &info->more_display[0], length);
978           mask = mask & ~TAG_MOREDISPLAY;
979           continue;
980         }
981       warning ("ERROR RMT: unknown thread info tag\n");
982       break;                    /* Not a tag we know about */
983     }
984   return retval;
985 }
986
987 static int
988 remote_get_threadinfo (threadid, fieldset, info)
989      threadref *threadid;
990      int fieldset;              /* TAG mask */
991      struct gdb_ext_thread_info *info;
992 {
993   int result;
994   char threadinfo_pkt[PBUFSIZ];
995
996   pack_threadinfo_request (threadinfo_pkt, fieldset, threadid);
997   putpkt (threadinfo_pkt);
998   getpkt (threadinfo_pkt, 0);
999   result = remote_unpack_thread_info_response (threadinfo_pkt + 2, threadid,
1000                                                info);
1001   return result;
1002 }
1003
1004 /* Unfortunately, 61 bit thread-ids are bigger than the internal
1005    representation of a threadid.  */
1006
1007 static int
1008 adapt_remote_get_threadinfo (ref, selection, info)
1009      gdb_threadref *ref;
1010      int selection;
1011      struct gdb_ext_thread_info *info;
1012 {
1013   threadref lclref;
1014
1015   int_to_threadref (&lclref, *ref);
1016   return remote_get_threadinfo (&lclref, selection, info);
1017 }
1018
1019 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
1020
1021 static char *
1022 pack_threadlist_request (pkt, startflag, threadcount, nextthread)
1023      char *pkt;
1024      int startflag;
1025      int threadcount;
1026      threadref *nextthread;
1027 {
1028   *pkt++ = 'q';                 /* info query packet */
1029   *pkt++ = 'L';                 /* Process LIST or threadLIST request */
1030   pkt = pack_nibble (pkt, startflag);   /* initflag 1 bytes */
1031   pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
1032   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
1033   *pkt = '\0';
1034   return pkt;
1035 }
1036
1037 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
1038
1039 static int
1040 parse_threadlist_response (pkt, result_limit, original_echo, resultlist,
1041                            doneflag)
1042      char *pkt;
1043      int result_limit;
1044      threadref *original_echo;
1045      threadref *resultlist;
1046      int *doneflag;
1047 {
1048   char *limit;
1049   int count, resultcount, done;
1050
1051   resultcount = 0;
1052   /* Assume the 'q' and 'M chars have been stripped.  */
1053   limit = pkt + (PBUFSIZ - BUF_THREAD_ID_SIZE); /* done parse past here */
1054   pkt = unpack_byte (pkt, &count);      /* count field */
1055   pkt = unpack_nibble (pkt, &done);
1056   /* The first threadid is the argument threadid.  */
1057   pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
1058   while ((count-- > 0) && (pkt < limit))
1059     {
1060       pkt = unpack_threadid (pkt, resultlist++);
1061       if (resultcount++ >= result_limit)
1062         break;
1063     }
1064   if (doneflag)
1065     *doneflag = done;
1066   return resultcount;
1067 }
1068
1069 static int
1070 remote_get_threadlist (startflag, nextthread, result_limit,
1071                        done, result_count, threadlist)
1072      int startflag;
1073      threadref *nextthread;
1074      int result_limit;
1075      int *done;
1076      int *result_count;
1077      threadref *threadlist;
1078
1079 {
1080   static threadref echo_nextthread;
1081   char threadlist_packet[PBUFSIZ];
1082   char t_response[PBUFSIZ];
1083   int result = 1;
1084
1085   /* Trancate result limit to be smaller than the packet size */
1086   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10) >= PBUFSIZ)
1087     result_limit = (PBUFSIZ / BUF_THREAD_ID_SIZE) - 2;
1088
1089   pack_threadlist_request (threadlist_packet,
1090                            startflag, result_limit, nextthread);
1091   putpkt (threadlist_packet);
1092   getpkt (t_response, 0);
1093
1094   *result_count =
1095     parse_threadlist_response (t_response + 2, result_limit, &echo_nextthread,
1096                                threadlist, done);
1097
1098   if (!threadmatch (&echo_nextthread, nextthread))
1099     {
1100       /* FIXME: This is a good reason to drop the packet */
1101       /* Possably, there is a duplicate response */
1102       /* Possabilities :
1103          retransmit immediatly - race conditions
1104          retransmit after timeout - yes
1105          exit
1106          wait for packet, then exit
1107        */
1108       warning ("HMM: threadlist did not echo arg thread, dropping it\n");
1109       return 0;                 /* I choose simply exiting */
1110     }
1111   if (*result_count <= 0)
1112     {
1113       if (*done != 1)
1114         {
1115           warning ("RMT ERROR : failed to get remote thread list\n");
1116           result = 0;
1117         }
1118       return result;            /* break; */
1119     }
1120   if (*result_count > result_limit)
1121     {
1122       *result_count = 0;
1123       warning ("RMT ERROR: threadlist response longer than requested\n");
1124       return 0;
1125     }
1126   return result;
1127 }
1128
1129 /* This is the interface between remote and threads, remotes upper interface */
1130
1131 /* remote_find_new_threads retrieves the thread list and for each
1132    thread in the list, looks up the thread in GDB's internal list,
1133    ading the thread if it does not already exist.  This involves
1134    getting partial thread lists from the remote target so, polling the
1135    quit_flag is required.  */
1136
1137
1138 /* About this many threadisds fit in a packet. */
1139
1140 #define MAXTHREADLISTRESULTS 32
1141
1142 static int
1143 remote_threadlist_iterator (stepfunction, context, looplimit)
1144      rmt_thread_action stepfunction;
1145      void *context;
1146      int looplimit;
1147 {
1148   int done, i, result_count;
1149   int startflag = 1;
1150   int result = 1;
1151   int loopcount = 0;
1152   static threadref nextthread;
1153   static threadref resultthreadlist[MAXTHREADLISTRESULTS];
1154
1155   done = 0;
1156   while (!done)
1157     {
1158       if (loopcount++ > looplimit)
1159         {
1160           result = 0;
1161           warning ("Remote fetch threadlist -infinite loop-\n");
1162           break;
1163         }
1164       if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
1165                                   &done, &result_count, resultthreadlist))
1166         {
1167           result = 0;
1168           break;
1169         }
1170       /* clear for later iterations */
1171       startflag = 0;
1172       /* Setup to resume next batch of thread references, set nextthread.  */
1173       if (result_count >= 1)
1174         copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
1175       i = 0;
1176       while (result_count--)
1177         if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
1178           break;
1179     }
1180   return result;
1181 }
1182
1183 static int
1184 remote_newthread_step (ref, context)
1185      threadref *ref;
1186      void *context;
1187 {
1188   int pid;
1189
1190   pid = threadref_to_int (ref);
1191   if (!in_thread_list (pid))
1192     add_thread (pid);
1193   return 1;                     /* continue iterator */
1194 }
1195
1196 #define CRAZY_MAX_THREADS 1000
1197
1198 static int
1199 remote_current_thread (oldpid)
1200      int oldpid;
1201 {
1202   char buf[PBUFSIZ];
1203
1204   putpkt ("qC");
1205   getpkt (buf, 0);
1206   if (buf[0] == 'Q' && buf[1] == 'C')
1207     return strtol (&buf[2], NULL, 16);
1208   else
1209     return oldpid;
1210 }
1211
1212 int
1213 remote_find_new_threads ()
1214 {
1215   int ret;
1216
1217   ret = remote_threadlist_iterator (remote_newthread_step, 0, 
1218                                     CRAZY_MAX_THREADS);
1219   if (inferior_pid == MAGIC_NULL_PID)   /* ack ack ack */
1220     inferior_pid = remote_current_thread (inferior_pid);
1221   return ret;
1222 }
1223
1224 /* Initialize the thread vector which is used by threads.c */
1225 /* The thread stub is a package, it has an initializer */
1226
1227 static void
1228 init_remote_threads ()
1229 {
1230   remote_thread_vec.find_new_threads = remote_find_new_threads;
1231   remote_thread_vec.get_thread_info = adapt_remote_get_threadinfo;
1232 }
1233
1234 \f
1235 /*  Restart the remote side; this is an extended protocol operation.  */
1236
1237 static void
1238 extended_remote_restart ()
1239 {
1240   char buf[PBUFSIZ];
1241
1242   /* Send the restart command; for reasons I don't understand the
1243      remote side really expects a number after the "R".  */
1244   buf[0] = 'R';
1245   sprintf (&buf[1], "%x", 0);
1246   putpkt (buf);
1247
1248   /* Now query for status so this looks just like we restarted
1249      gdbserver from scratch.  */
1250   putpkt ("?");
1251   getpkt (buf, 0);
1252 }
1253 \f
1254 /* Clean up connection to a remote debugger.  */
1255
1256 /* ARGSUSED */
1257 static void
1258 remote_close (quitting)
1259      int quitting;
1260 {
1261   if (remote_desc)
1262     SERIAL_CLOSE (remote_desc);
1263   remote_desc = NULL;
1264 }
1265
1266 /* Query the remote side for the text, data and bss offsets. */
1267
1268 static void
1269 get_offsets ()
1270 {
1271   char buf[PBUFSIZ], *ptr;
1272   int lose;
1273   CORE_ADDR text_addr, data_addr, bss_addr;
1274   struct section_offsets *offs;
1275
1276   putpkt ("qOffsets");
1277
1278   getpkt (buf, 0);
1279
1280   if (buf[0] == '\000')
1281     return;                     /* Return silently.  Stub doesn't support
1282                                    this command. */
1283   if (buf[0] == 'E')
1284     {
1285       warning ("Remote failure reply: %s", buf);
1286       return;
1287     }
1288
1289   /* Pick up each field in turn.  This used to be done with scanf, but
1290      scanf will make trouble if CORE_ADDR size doesn't match
1291      conversion directives correctly.  The following code will work
1292      with any size of CORE_ADDR.  */
1293   text_addr = data_addr = bss_addr = 0;
1294   ptr = buf;
1295   lose = 0;
1296
1297   if (strncmp (ptr, "Text=", 5) == 0)
1298     {
1299       ptr += 5;
1300       /* Don't use strtol, could lose on big values.  */
1301       while (*ptr && *ptr != ';')
1302         text_addr = (text_addr << 4) + fromhex (*ptr++);
1303     }
1304   else
1305     lose = 1;
1306
1307   if (!lose && strncmp (ptr, ";Data=", 6) == 0)
1308     {
1309       ptr += 6;
1310       while (*ptr && *ptr != ';')
1311         data_addr = (data_addr << 4) + fromhex (*ptr++);
1312     }
1313   else
1314     lose = 1;
1315
1316   if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
1317     {
1318       ptr += 5;
1319       while (*ptr && *ptr != ';')
1320         bss_addr = (bss_addr << 4) + fromhex (*ptr++);
1321     }
1322   else
1323     lose = 1;
1324
1325   if (lose)
1326     error ("Malformed response to offset query, %s", buf);
1327
1328   if (symfile_objfile == NULL)
1329     return;
1330
1331   offs = (struct section_offsets *) alloca (sizeof (struct section_offsets)
1332                                             + symfile_objfile->num_sections
1333                                             * sizeof (offs->offsets));
1334   memcpy (offs, symfile_objfile->section_offsets,
1335           sizeof (struct section_offsets)
1336           + symfile_objfile->num_sections
1337           * sizeof (offs->offsets));
1338
1339   ANOFFSET (offs, SECT_OFF_TEXT) = text_addr;
1340
1341   /* This is a temporary kludge to force data and bss to use the same offsets
1342      because that's what nlmconv does now.  The real solution requires changes
1343      to the stub and remote.c that I don't have time to do right now.  */
1344
1345   ANOFFSET (offs, SECT_OFF_DATA) = data_addr;
1346   ANOFFSET (offs, SECT_OFF_BSS) = data_addr;
1347
1348   objfile_relocate (symfile_objfile, offs);
1349 }
1350
1351 /* Stub for catch_errors.  */
1352
1353 static int
1354 remote_start_remote (dummy)
1355      char *dummy;
1356 {
1357   immediate_quit = 1;           /* Allow user to interrupt it */
1358
1359   /* Ack any packet which the remote side has already sent.  */
1360   SERIAL_WRITE (remote_desc, "+", 1);
1361
1362   /* Let the stub know that we want it to return the thread.  */
1363   set_thread (-1, 0);
1364
1365   inferior_pid = remote_current_thread (inferior_pid);
1366
1367   get_offsets ();               /* Get text, data & bss offsets */
1368
1369   putpkt ("?");                 /* initiate a query from remote machine */
1370   immediate_quit = 0;
1371
1372   start_remote ();              /* Initialize gdb process mechanisms */
1373   return 1;
1374 }
1375
1376 /* Open a connection to a remote debugger.
1377    NAME is the filename used for communication.  */
1378
1379 static void
1380 remote_open (name, from_tty)
1381      char *name;
1382      int from_tty;
1383 {
1384   remote_open_1 (name, from_tty, &remote_ops, 0);
1385 }
1386
1387 /* Open a connection to a remote debugger using the extended
1388    remote gdb protocol.  NAME is the filename used for communication.  */
1389
1390 static void
1391 extended_remote_open (name, from_tty)
1392      char *name;
1393      int from_tty;
1394 {
1395   remote_open_1 (name, from_tty, &extended_remote_ops, 1/*extended_p*/);
1396 }
1397
1398 /* Generic code for opening a connection to a remote target.  */
1399
1400 static DCACHE *remote_dcache;
1401
1402 static void
1403 remote_open_1 (name, from_tty, target, extended_p)
1404      char *name;
1405      int from_tty;
1406      struct target_ops *target;
1407      int extended_p;
1408 {
1409   if (name == 0)
1410     error ("To open a remote debug connection, you need to specify what\n\
1411 serial device is attached to the remote system (e.g. /dev/ttya).");
1412
1413   target_preopen (from_tty);
1414
1415   unpush_target (target);
1416
1417   remote_dcache = dcache_init (remote_read_bytes, remote_write_bytes);
1418
1419   remote_desc = SERIAL_OPEN (name);
1420   if (!remote_desc)
1421     perror_with_name (name);
1422
1423   if (baud_rate != -1)
1424     {
1425       if (SERIAL_SETBAUDRATE (remote_desc, baud_rate))
1426         {
1427           SERIAL_CLOSE (remote_desc);
1428           perror_with_name (name);
1429         }
1430     }
1431
1432
1433   SERIAL_RAW (remote_desc);
1434
1435   /* If there is something sitting in the buffer we might take it as a
1436      response to a command, which would be bad.  */
1437   SERIAL_FLUSH_INPUT (remote_desc);
1438
1439   if (from_tty)
1440     {
1441       puts_filtered ("Remote debugging using ");
1442       puts_filtered (name);
1443       puts_filtered ("\n");
1444     }
1445   push_target (target); /* Switch to using remote target now */
1446
1447   /* The target vector does not have the thread functions in it yet,
1448      so we use this function to call back into the thread module and
1449      register the thread vector and its contained functions. */
1450   bind_target_thread_vector (&remote_thread_vec);
1451
1452   /* Start out by trying the 'P' request to set registers.  We set
1453      this each time that we open a new target so that if the user
1454      switches from one stub to another, we can (if the target is
1455      closed and reopened) cope.  */
1456   stub_supports_P = 1;
1457
1458   general_thread = -2;
1459   cont_thread = -2;
1460
1461   /* Without this, some commands which require an active target (such
1462      as kill) won't work.  This variable serves (at least) double duty
1463      as both the pid of the target process (if it has such), and as a
1464      flag indicating that a target is active.  These functions should
1465      be split out into seperate variables, especially since GDB will
1466      someday have a notion of debugging several processes.  */
1467
1468   inferior_pid = MAGIC_NULL_PID;
1469   /* Start the remote connection; if error (0), discard this target.
1470      In particular, if the user quits, be sure to discard it
1471      (we'd be in an inconsistent state otherwise).  */
1472   if (!catch_errors (remote_start_remote, (char *)0, 
1473                      "Couldn't establish connection to remote target\n", 
1474                      RETURN_MASK_ALL))
1475     {
1476       pop_target ();
1477       return;
1478     }
1479
1480   if (extended_p)
1481     {
1482       /* tell the remote that we're using the extended protocol.  */
1483       char buf[PBUFSIZ];
1484       putpkt ("!");
1485       getpkt (buf, 0);
1486     }
1487 }
1488
1489 /* This takes a program previously attached to and detaches it.  After
1490    this is done, GDB can be used to debug some other program.  We
1491    better not have left any breakpoints in the target program or it'll
1492    die when it hits one.  */
1493
1494 static void
1495 remote_detach (args, from_tty)
1496      char *args;
1497      int from_tty;
1498 {
1499   char buf[PBUFSIZ];
1500
1501   if (args)
1502     error ("Argument given to \"detach\" when remotely debugging.");
1503
1504   /* Tell the remote target to detach.  */
1505   strcpy (buf, "D");
1506   remote_send (buf);
1507
1508   pop_target ();
1509   if (from_tty)
1510     puts_filtered ("Ending remote debugging.\n");
1511 }
1512
1513 /* Convert hex digit A to a number.  */
1514
1515 int
1516 fromhex (a)
1517      int a;
1518 {
1519   if (a >= '0' && a <= '9')
1520     return a - '0';
1521   else if (a >= 'a' && a <= 'f')
1522     return a - 'a' + 10;
1523   else if (a >= 'A' && a <= 'F')
1524     return a - 'A' + 10;
1525   else 
1526     error ("Reply contains invalid hex digit %d", a);
1527 }
1528
1529 /* Convert number NIB to a hex digit.  */
1530
1531 static int
1532 tohex (nib)
1533      int nib;
1534 {
1535   if (nib < 10)
1536     return '0'+nib;
1537   else
1538     return 'a'+nib-10;
1539 }
1540 \f
1541 /* Tell the remote machine to resume.  */
1542
1543 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
1544
1545 static int last_sent_step;
1546
1547 static void
1548 remote_resume (pid, step, siggnal)
1549      int pid, step;
1550      enum target_signal siggnal;
1551 {
1552   char buf[PBUFSIZ];
1553
1554   if (pid == -1)
1555     set_thread (0, 0);          /* run any thread */
1556   else
1557     set_thread (pid, 0);        /* run this thread */
1558
1559   dcache_flush (remote_dcache);
1560
1561   last_sent_signal = siggnal;
1562   last_sent_step = step;
1563
1564   /* A hook for when we need to do something at the last moment before
1565      resumption.  */
1566   if (target_resume_hook)
1567     (*target_resume_hook) ();
1568
1569   if (siggnal != TARGET_SIGNAL_0)
1570     {
1571       buf[0] = step ? 'S' : 'C';
1572       buf[1] = tohex (((int)siggnal >> 4) & 0xf);
1573       buf[2] = tohex ((int)siggnal & 0xf);
1574       buf[3] = '\0';
1575     }
1576   else
1577     strcpy (buf, step ? "s": "c");
1578
1579   putpkt (buf);
1580 }
1581 \f
1582 /* Send ^C to target to halt it.  Target will respond, and send us a
1583    packet.  */
1584
1585 static void (*ofunc) PARAMS ((int));
1586
1587 static void
1588 remote_interrupt (signo)
1589      int signo;
1590 {
1591   remote_stop ();
1592   signal (signo, remote_interrupt);
1593 }
1594   
1595 static void
1596 remote_stop ()
1597 {
1598   if (!interrupted_already)
1599     {
1600       /* Send a break or a ^C, depending on user preference.  */
1601       interrupted_already = 1;
1602
1603       if (remote_debug)
1604         printf_unfiltered ("remote_stop called\n");
1605
1606       if (remote_break)
1607         SERIAL_SEND_BREAK (remote_desc);
1608       else
1609         SERIAL_WRITE (remote_desc, "\003", 1);
1610     }
1611   else
1612     {
1613       signal (SIGINT, ofunc);
1614       interrupt_query ();
1615       signal (SIGINT, remote_interrupt);
1616       interrupted_already = 0;
1617     }
1618 }
1619
1620 /* Ask the user what to do when an interrupt is received.  */
1621
1622 static void
1623 interrupt_query ()
1624 {
1625   target_terminal_ours ();
1626
1627   if (query ("Interrupted while waiting for the program.\n\
1628 Give up (and stop debugging it)? "))
1629     {
1630       target_mourn_inferior ();
1631       return_to_top_level (RETURN_QUIT);
1632     }
1633
1634   target_terminal_inferior ();
1635 }
1636
1637 /* If nonzero, ignore the next kill.  */
1638
1639 int kill_kludge;
1640
1641 void
1642 remote_console_output (msg)
1643      char *msg;
1644 {
1645   char *p;
1646
1647   for (p = msg; *p; p +=2) 
1648     {
1649       char tb[2];
1650       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
1651       tb[0] = c;
1652       tb[1] = 0;
1653       if (target_output_hook)
1654         target_output_hook (tb);
1655       else 
1656         fputs_filtered (tb, gdb_stdout);
1657     }
1658 }
1659
1660 /* Wait until the remote machine stops, then return, storing status in
1661    STATUS just as `wait' would.  Returns "pid" (though it's not clear
1662    what, if anything, that means in the case of this target).  */
1663
1664 static int
1665 remote_wait (pid, status)
1666      int pid;
1667      struct target_waitstatus *status;
1668 {
1669   unsigned char buf[PBUFSIZ];
1670   int thread_num = -1;
1671
1672   status->kind = TARGET_WAITKIND_EXITED;
1673   status->value.integer = 0;
1674
1675   while (1)
1676     {
1677       unsigned char *p;
1678
1679       interrupted_already = 0;
1680       ofunc = signal (SIGINT, remote_interrupt);
1681       getpkt ((char *) buf, 1);
1682       signal (SIGINT, ofunc);
1683
1684       /* This is a hook for when we need to do something (perhaps the
1685          collection of trace data) every time the target stops.  */
1686       if (target_wait_loop_hook)
1687         (*target_wait_loop_hook) ();
1688
1689       switch (buf[0])
1690         {
1691         case 'E':               /* Error of some sort */
1692           warning ("Remote failure reply: %s", buf);
1693           continue;
1694         case 'T':               /* Status with PC, SP, FP, ... */
1695           {
1696             int i;
1697             long regno;
1698             char regs[MAX_REGISTER_RAW_SIZE];
1699
1700             /* Expedited reply, containing Signal, {regno, reg} repeat */
1701             /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
1702                 ss = signal number
1703                 n... = register number
1704                 r... = register contents
1705                 */
1706             p = &buf[3];        /* after Txx */
1707
1708             while (*p)
1709               {
1710                 unsigned char *p1;
1711                 char *p_temp;
1712
1713                 /* Read the register number */
1714                 regno = strtol ((const char *) p, &p_temp, 16);
1715                 p1 = (unsigned char *)p_temp;
1716
1717                 if (p1 == p) /* No register number present here */
1718                   {
1719                     p1 = (unsigned char *) strchr ((const char *) p, ':');
1720                     if (p1 == NULL)
1721                       warning ("Malformed packet(a) (missing colon): %s\n\
1722 Packet: '%s'\n",
1723                                p, buf);
1724                     if (strncmp ((const char *) p, "thread", p1 - p) == 0)
1725                       {
1726                         p_temp = unpack_varlen_hex (++p1, &thread_num);
1727                         record_currthread (thread_num);
1728                         p = (unsigned char *) p_temp;
1729                       }
1730                   }
1731                 else
1732                   {
1733                     p = p1;
1734
1735                     if (*p++ != ':')
1736                       warning ("Malformed packet(b) (missing colon): %s\n\
1737 Packet: '%s'\n",
1738                                p, buf);
1739
1740                     if (regno >= NUM_REGS)
1741                       warning ("Remote sent bad register number %ld: %s\n\
1742 Packet: '%s'\n",
1743                                regno, p, buf);
1744
1745                     for (i = 0; i < REGISTER_RAW_SIZE (regno); i++)
1746                       {
1747                         if (p[0] == 0 || p[1] == 0)
1748                           warning ("Remote reply is too short: %s", buf);
1749                         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
1750                         p += 2;
1751                       }
1752                     supply_register (regno, regs);
1753                   }
1754
1755                 if (*p++ != ';')
1756                   {
1757                     warning ("Remote register badly formatted: %s", buf);
1758                     warning ("            here: %s",p);
1759                   }
1760               }
1761           }
1762           /* fall through */
1763         case 'S':               /* Old style status, just signal only */
1764           status->kind = TARGET_WAITKIND_STOPPED;
1765           status->value.sig = (enum target_signal)
1766             (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
1767
1768           goto got_status;
1769         case 'W':               /* Target exited */
1770           {
1771             /* The remote process exited.  */
1772             status->kind = TARGET_WAITKIND_EXITED;
1773             status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
1774             goto got_status;
1775           }
1776         case 'X':
1777           status->kind = TARGET_WAITKIND_SIGNALLED;
1778           status->value.sig = (enum target_signal)
1779             (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
1780           kill_kludge = 1;
1781
1782           goto got_status;
1783         case 'O':               /* Console output */
1784           remote_console_output (buf + 1);
1785           continue;
1786         case '\0':
1787           if (last_sent_signal != TARGET_SIGNAL_0)
1788             {
1789               /* Zero length reply means that we tried 'S' or 'C' and
1790                  the remote system doesn't support it.  */
1791               target_terminal_ours_for_output ();
1792               printf_filtered
1793                 ("Can't send signals to this remote system.  %s not sent.\n",
1794                  target_signal_to_name (last_sent_signal));
1795               last_sent_signal = TARGET_SIGNAL_0;
1796               target_terminal_inferior ();
1797
1798               strcpy ((char *) buf, last_sent_step ? "s" : "c");
1799               putpkt ((char *) buf);
1800               continue;
1801             }
1802           /* else fallthrough */
1803         default:
1804           warning ("Invalid remote reply: %s", buf);
1805           continue;
1806         }
1807     }
1808  got_status:
1809   if (thread_num != -1)
1810     {
1811       /* Initial thread value can only be acquired via wait, so deal with
1812          this marker which is used before the first thread value is
1813          acquired.  */
1814       if (inferior_pid == MAGIC_NULL_PID)
1815         {
1816           inferior_pid = thread_num;
1817           if (!in_thread_list (inferior_pid))
1818             add_thread (inferior_pid);
1819         }
1820       return thread_num;
1821     }
1822   return inferior_pid;
1823 }
1824
1825 /* Number of bytes of registers this stub implements.  */
1826
1827 static int register_bytes_found;
1828
1829 /* Read the remote registers into the block REGS.  */
1830 /* Currently we just read all the registers, so we don't use regno.  */
1831
1832 /* ARGSUSED */
1833 static void
1834 remote_fetch_registers (regno)
1835      int regno;
1836 {
1837   char buf[PBUFSIZ];
1838   int i;
1839   char *p;
1840   char regs[REGISTER_BYTES];
1841
1842   set_thread (inferior_pid, 1);
1843
1844   sprintf (buf, "g");
1845   remote_send (buf);
1846
1847   if (remote_register_buf_size == 0)
1848     remote_register_buf_size = strlen (buf);
1849
1850   /* Unimplemented registers read as all bits zero.  */
1851   memset (regs, 0, REGISTER_BYTES);
1852
1853   /* We can get out of synch in various cases.  If the first character
1854      in the buffer is not a hex character, assume that has happened
1855      and try to fetch another packet to read.  */
1856   while ((buf[0] < '0' || buf[0] > '9')
1857          && (buf[0] < 'a' || buf[0] > 'f')
1858          && buf[0] != 'x')      /* New: unavailable register value */
1859     {
1860       if (remote_debug)
1861         printf_unfiltered ("Bad register packet; fetching a new packet\n");
1862       getpkt (buf, 0);
1863     }
1864
1865   /* Reply describes registers byte by byte, each byte encoded as two
1866      hex characters.  Suck them all up, then supply them to the
1867      register cacheing/storage mechanism.  */
1868
1869   p = buf;
1870   for (i = 0; i < REGISTER_BYTES; i++)
1871     {
1872       if (p[0] == 0)
1873         break;
1874       if (p[1] == 0)
1875         {
1876           warning ("Remote reply is of odd length: %s", buf);
1877           /* Don't change register_bytes_found in this case, and don't
1878              print a second warning.  */
1879           goto supply_them;
1880         }
1881       if (p[0] == 'x' && p[1] == 'x')
1882         regs[i] = 0;    /* 'x' */
1883       else
1884         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
1885       p += 2;
1886     }
1887
1888   if (i != register_bytes_found)
1889     {
1890       register_bytes_found = i;
1891 #ifdef REGISTER_BYTES_OK
1892       if (!REGISTER_BYTES_OK (i))
1893         warning ("Remote reply is too short: %s", buf);
1894 #endif
1895     }
1896   
1897   supply_them:
1898   for (i = 0; i < NUM_REGS; i++)
1899   {
1900     supply_register (i, &regs[REGISTER_BYTE(i)]);
1901     if (buf[REGISTER_BYTE(i) * 2] == 'x')
1902       register_valid[i] = -1;   /* register value not available */
1903   }
1904 }
1905
1906 /* Prepare to store registers.  Since we may send them all (using a
1907    'G' request), we have to read out the ones we don't want to change
1908    first.  */
1909
1910 static void 
1911 remote_prepare_to_store ()
1912 {
1913   /* Make sure the entire registers array is valid.  */
1914   read_register_bytes (0, (char *)NULL, REGISTER_BYTES);
1915 }
1916
1917 /* Store register REGNO, or all registers if REGNO == -1, from the contents
1918    of REGISTERS.  FIXME: ignores errors.  */
1919
1920 static void
1921 remote_store_registers (regno)
1922      int regno;
1923 {
1924   char buf[PBUFSIZ];
1925   int i;
1926   char *p;
1927
1928   set_thread (inferior_pid, 1);
1929
1930   if (regno >= 0 && stub_supports_P)
1931     {
1932       /* Try storing a single register.  */
1933       char *regp;
1934
1935       sprintf (buf, "P%x=", regno);
1936       p = buf + strlen (buf);
1937       regp = &registers[REGISTER_BYTE (regno)];
1938       for (i = 0; i < REGISTER_RAW_SIZE (regno); ++i)
1939         {
1940           *p++ = tohex ((regp[i] >> 4) & 0xf);
1941           *p++ = tohex (regp[i] & 0xf);
1942         }
1943       *p = '\0';
1944       remote_send (buf);
1945       if (buf[0] != '\0')
1946         {
1947           /* The stub understands the 'P' request.  We are done.  */
1948           return;
1949         }
1950
1951       /* The stub does not support the 'P' request.  Use 'G' instead,
1952          and don't try using 'P' in the future (it will just waste our
1953          time).  */
1954       stub_supports_P = 0;
1955     }
1956
1957   buf[0] = 'G';
1958
1959   /* Command describes registers byte by byte,
1960      each byte encoded as two hex characters.  */
1961
1962   p = buf + 1;
1963   /* remote_prepare_to_store insures that register_bytes_found gets set.  */
1964   for (i = 0; i < register_bytes_found; i++)
1965     {
1966       *p++ = tohex ((registers[i] >> 4) & 0xf);
1967       *p++ = tohex (registers[i] & 0xf);
1968     }
1969   *p = '\0';
1970
1971   remote_send (buf);
1972 }
1973
1974 /* Use of the data cache *used* to be disabled because it loses for looking
1975    at and changing hardware I/O ports and the like.  Accepting `volatile'
1976    would perhaps be one way to fix it.  Another idea would be to use the
1977    executable file for the text segment (for all SEC_CODE sections?
1978    For all SEC_READONLY sections?).  This has problems if you want to
1979    actually see what the memory contains (e.g. self-modifying code,
1980    clobbered memory, user downloaded the wrong thing).  
1981
1982    Because it speeds so much up, it's now enabled, if you're playing
1983    with registers you turn it of (set remotecache 0).  */
1984
1985 /* Read a word from remote address ADDR and return it.
1986    This goes through the data cache.  */
1987
1988 #if 0   /* unused? */
1989 static int
1990 remote_fetch_word (addr)
1991      CORE_ADDR addr;
1992 {
1993   return dcache_fetch (remote_dcache, addr);
1994 }
1995
1996 /* Write a word WORD into remote address ADDR.
1997    This goes through the data cache.  */
1998
1999 static void
2000 remote_store_word (addr, word)
2001      CORE_ADDR addr;
2002      int word;
2003 {
2004   dcache_poke (remote_dcache, addr, word);
2005 }
2006 #endif  /* 0 (unused?) */
2007
2008 \f
2009
2010 /* Return the number of hex digits in num.  */
2011
2012 static int
2013 hexnumlen (num)
2014      ULONGEST num;
2015 {
2016   int i;
2017
2018   for (i = 0; num != 0; i++)
2019     num >>= 4;
2020
2021   return max (i, 1);
2022 }
2023
2024 /* Set BUF to the hex digits representing NUM.  */
2025
2026 static int
2027 hexnumstr (buf, num)
2028      char *buf;
2029      ULONGEST num;
2030 {
2031   int i;
2032   int len = hexnumlen (num);
2033
2034   buf[len] = '\0';
2035
2036   for (i = len - 1; i >= 0; i--)
2037     {
2038       buf[i] = "0123456789abcdef" [(num & 0xf)];
2039       num >>= 4;
2040     }
2041
2042   return len;
2043 }
2044
2045 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
2046
2047 static CORE_ADDR
2048 remote_address_masked (addr)
2049      CORE_ADDR addr;
2050 {
2051   if (remote_address_size > 0
2052       && remote_address_size < (sizeof (ULONGEST) * 8))
2053     {
2054       /* Only create a mask when that mask can safely be constructed
2055          in a ULONGEST variable. */
2056       ULONGEST mask = 1;
2057       mask = (mask << remote_address_size) - 1;
2058       addr &= mask;
2059     }
2060   return addr;
2061 }
2062
2063 /* Write memory data directly to the remote machine.
2064    This does not inform the data cache; the data cache uses this.
2065    MEMADDR is the address in the remote memory space.
2066    MYADDR is the address of the buffer in our space.
2067    LEN is the number of bytes.
2068
2069    Returns number of bytes transferred, or 0 for error.  */
2070
2071 static int
2072 remote_write_bytes (memaddr, myaddr, len)
2073      CORE_ADDR memaddr;
2074      char *myaddr;
2075      int len;
2076 {
2077   int max_buf_size;             /* Max size of packet output buffer */
2078   int origlen;
2079
2080   /* Chop the transfer down if necessary */
2081
2082   max_buf_size = min (remote_write_size, PBUFSIZ);
2083   if (remote_register_buf_size != 0)
2084     max_buf_size = min (max_buf_size, remote_register_buf_size);
2085
2086   /* Subtract header overhead from max payload size -  $M<memaddr>,<len>:#nn */
2087   max_buf_size -= 2 + hexnumlen (memaddr + len - 1) + 1 + hexnumlen (len) + 4;
2088
2089   origlen = len;
2090   while (len > 0)
2091     {
2092       char buf[PBUFSIZ];
2093       char *p;
2094       int todo;
2095       int i;
2096
2097       todo = min (len, max_buf_size / 2); /* num bytes that will fit */
2098
2099       /* construct "M"<memaddr>","<len>":" */
2100       /* sprintf (buf, "M%lx,%x:", (unsigned long) memaddr, todo); */
2101       memaddr = remote_address_masked (memaddr);
2102       p = buf;
2103       *p++ = 'M';
2104       p += hexnumstr (p, (ULONGEST) memaddr);
2105       *p++ = ',';
2106       p += hexnumstr (p, (ULONGEST) todo);
2107       *p++ = ':';
2108       *p = '\0';
2109
2110       /* We send target system values byte by byte, in increasing byte
2111          addresses, each byte encoded as two hex characters.  */
2112
2113       for (i = 0; i < todo; i++)
2114         {
2115           *p++ = tohex ((myaddr[i] >> 4) & 0xf);
2116           *p++ = tohex (myaddr[i] & 0xf);
2117         }
2118       *p = '\0';
2119
2120       putpkt (buf);
2121       getpkt (buf, 0);
2122
2123       if (buf[0] == 'E')
2124         {
2125           /* There is no correspondance between what the remote protocol uses
2126              for errors and errno codes.  We would like a cleaner way of
2127              representing errors (big enough to include errno codes, bfd_error
2128              codes, and others).  But for now just return EIO.  */
2129           errno = EIO;
2130           return 0;
2131         }
2132       myaddr += todo;
2133       memaddr += todo;
2134       len -= todo;
2135     }
2136   return origlen;
2137 }
2138
2139 /* Read memory data directly from the remote machine.
2140    This does not use the data cache; the data cache uses this.
2141    MEMADDR is the address in the remote memory space.
2142    MYADDR is the address of the buffer in our space.
2143    LEN is the number of bytes.
2144
2145    Returns number of bytes transferred, or 0 for error.  */
2146
2147 static int
2148 remote_read_bytes (memaddr, myaddr, len)
2149      CORE_ADDR memaddr;
2150      char *myaddr;
2151      int len;
2152 {
2153   int max_buf_size;             /* Max size of packet output buffer */
2154   int origlen;
2155
2156   /* Chop the transfer down if necessary */
2157
2158   max_buf_size = min (remote_write_size, PBUFSIZ);
2159   if (remote_register_buf_size != 0)
2160     max_buf_size = min (max_buf_size, remote_register_buf_size);
2161
2162   origlen = len;
2163   while (len > 0)
2164     {
2165       char buf[PBUFSIZ];
2166       char *p;
2167       int todo;
2168       int i;
2169
2170       todo = min (len, max_buf_size / 2); /* num bytes that will fit */
2171
2172       /* construct "m"<memaddr>","<len>" */
2173       /* sprintf (buf, "m%lx,%x", (unsigned long) memaddr, todo); */
2174       memaddr = remote_address_masked (memaddr);
2175       p = buf;
2176       *p++ = 'm';
2177       p += hexnumstr (p, (ULONGEST) memaddr);
2178       *p++ = ',';
2179       p += hexnumstr (p, (ULONGEST) todo);
2180       *p = '\0';
2181
2182       putpkt (buf);
2183       getpkt (buf, 0);
2184
2185       if (buf[0] == 'E')
2186         {
2187           /* There is no correspondance between what the remote protocol uses
2188              for errors and errno codes.  We would like a cleaner way of
2189              representing errors (big enough to include errno codes, bfd_error
2190              codes, and others).  But for now just return EIO.  */
2191           errno = EIO;
2192           return 0;
2193         }
2194
2195   /* Reply describes memory byte by byte,
2196      each byte encoded as two hex characters.  */
2197
2198       p = buf;
2199       for (i = 0; i < todo; i++)
2200         {
2201           if (p[0] == 0 || p[1] == 0)
2202             /* Reply is short.  This means that we were able to read
2203                only part of what we wanted to.  */
2204             return i + (origlen - len);
2205           myaddr[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
2206           p += 2;
2207         }
2208       myaddr += todo;
2209       memaddr += todo;
2210       len -= todo;
2211     }
2212   return origlen;
2213 }
2214 \f
2215 /* Read or write LEN bytes from inferior memory at MEMADDR,
2216    transferring to or from debugger address MYADDR.  Write to inferior
2217    if SHOULD_WRITE is nonzero.  Returns length of data written or
2218    read; 0 for error.  */
2219
2220 /* ARGSUSED */
2221 static int
2222 remote_xfer_memory (memaddr, myaddr, len, should_write, target)
2223      CORE_ADDR memaddr;
2224      char *myaddr;
2225      int len;
2226      int should_write;
2227      struct target_ops *target;                 /* ignored */
2228 {
2229 #ifdef REMOTE_TRANSLATE_XFER_ADDRESS
2230   CORE_ADDR targaddr;
2231   int targlen;
2232   REMOTE_TRANSLATE_XFER_ADDRESS (memaddr, len, targaddr, targlen);
2233   if (targlen == 0)
2234     return 0;
2235   memaddr = targaddr;
2236   len = targlen;
2237 #endif
2238
2239   return dcache_xfer_memory (remote_dcache, memaddr, myaddr,
2240                              len, should_write);
2241 }
2242
2243    
2244 #if 0
2245 /* Enable after 4.12.  */
2246
2247 void
2248 remote_search (len, data, mask, startaddr, increment, lorange, hirange
2249                addr_found, data_found)
2250      int len;
2251      char *data;
2252      char *mask;
2253      CORE_ADDR startaddr;
2254      int increment;
2255      CORE_ADDR lorange;
2256      CORE_ADDR hirange;
2257      CORE_ADDR *addr_found;
2258      char *data_found;
2259 {
2260   if (increment == -4 && len == 4)
2261     {
2262       long mask_long, data_long;
2263       long data_found_long;
2264       CORE_ADDR addr_we_found;
2265       char buf[PBUFSIZ];
2266       long returned_long[2];
2267       char *p;
2268
2269       mask_long = extract_unsigned_integer (mask, len);
2270       data_long = extract_unsigned_integer (data, len);
2271       sprintf (buf, "t%x:%x,%x", startaddr, data_long, mask_long);
2272       putpkt (buf);
2273       getpkt (buf, 0);
2274       if (buf[0] == '\0')
2275         {
2276           /* The stub doesn't support the 't' request.  We might want to
2277              remember this fact, but on the other hand the stub could be
2278              switched on us.  Maybe we should remember it only until
2279              the next "target remote".  */
2280           generic_search (len, data, mask, startaddr, increment, lorange,
2281                           hirange, addr_found, data_found);
2282           return;
2283         }
2284
2285       if (buf[0] == 'E')
2286         /* There is no correspondance between what the remote protocol uses
2287            for errors and errno codes.  We would like a cleaner way of
2288            representing errors (big enough to include errno codes, bfd_error
2289            codes, and others).  But for now just use EIO.  */
2290         memory_error (EIO, startaddr);
2291       p = buf;
2292       addr_we_found = 0;
2293       while (*p != '\0' && *p != ',')
2294         addr_we_found = (addr_we_found << 4) + fromhex (*p++);
2295       if (*p == '\0')
2296         error ("Protocol error: short return for search");
2297
2298       data_found_long = 0;
2299       while (*p != '\0' && *p != ',')
2300         data_found_long = (data_found_long << 4) + fromhex (*p++);
2301       /* Ignore anything after this comma, for future extensions.  */
2302
2303       if (addr_we_found < lorange || addr_we_found >= hirange)
2304         {
2305           *addr_found = 0;
2306           return;
2307         }
2308
2309       *addr_found = addr_we_found;
2310       *data_found = store_unsigned_integer (data_we_found, len);
2311       return;
2312     }
2313   generic_search (len, data, mask, startaddr, increment, lorange,
2314                   hirange, addr_found, data_found);
2315 }
2316 #endif /* 0 */
2317 \f
2318 static void
2319 remote_files_info (ignore)
2320      struct target_ops *ignore;
2321 {
2322   puts_filtered ("Debugging a target over a serial line.\n");
2323 }
2324 \f
2325 /* Stuff for dealing with the packets which are part of this protocol.
2326    See comment at top of file for details.  */
2327
2328 /* Read a single character from the remote end, masking it down to 7 bits. */
2329
2330 static int
2331 readchar (timeout)
2332      int timeout;
2333 {
2334   int ch;
2335
2336   ch = SERIAL_READCHAR (remote_desc, timeout);
2337
2338   switch (ch)
2339     {
2340     case SERIAL_EOF:
2341       error ("Remote connection closed");
2342     case SERIAL_ERROR:
2343       perror_with_name ("Remote communication error");
2344     case SERIAL_TIMEOUT:
2345       return ch;
2346     default:
2347       return ch & 0x7f;
2348     }
2349 }
2350
2351 /* Send the command in BUF to the remote machine, and read the reply
2352    into BUF.  Report an error if we get an error reply.  */
2353
2354 static void
2355 remote_send (buf)
2356      char *buf;
2357 {
2358   putpkt (buf);
2359   getpkt (buf, 0);
2360
2361   if (buf[0] == 'E')
2362     error ("Remote failure reply: %s", buf);
2363 }
2364
2365 /* Display a null-terminated packet on stdout, for debugging, using C
2366    string notation.  */
2367
2368 static void
2369 print_packet (buf)
2370      char *buf;
2371 {
2372   puts_filtered ("\"");
2373   while (*buf)
2374     gdb_printchar (*buf++, gdb_stdout, '"');
2375   puts_filtered ("\"");
2376 }
2377
2378
2379 /* Send a packet to the remote machine, with error checking.  The data
2380    of the packet is in BUF.  */
2381
2382 int
2383 putpkt (buf)
2384      char *buf;
2385 {
2386   int i;
2387   unsigned char csum = 0;
2388   char buf2[PBUFSIZ];
2389   int cnt = strlen (buf);
2390   int ch;
2391   int tcount = 0;
2392   char *p;
2393
2394   /* Copy the packet into buffer BUF2, encapsulating it
2395      and giving it a checksum.  */
2396
2397   if (cnt > (int) sizeof (buf2) - 5)            /* Prosanity check */
2398     abort ();
2399
2400   p = buf2;
2401   *p++ = '$';
2402
2403   for (i = 0; i < cnt; i++)
2404     {
2405       csum += buf[i];
2406       *p++ = buf[i];
2407     }
2408   *p++ = '#';
2409   *p++ = tohex ((csum >> 4) & 0xf);
2410   *p++ = tohex (csum & 0xf);
2411
2412   /* Send it over and over until we get a positive ack.  */
2413
2414   while (1)
2415     {
2416       int started_error_output = 0;
2417
2418       if (remote_debug)
2419         {
2420           *p = '\0';
2421           printf_unfiltered ("Sending packet: %s...", buf2);
2422           gdb_flush (gdb_stdout);
2423         }
2424       if (SERIAL_WRITE (remote_desc, buf2, p - buf2))
2425         perror_with_name ("putpkt: write failed");
2426
2427       /* read until either a timeout occurs (-2) or '+' is read */
2428       while (1)
2429         {
2430           ch = readchar (remote_timeout);
2431
2432           if (remote_debug)
2433             {
2434               switch (ch)
2435                 {
2436                 case '+':
2437                 case SERIAL_TIMEOUT:
2438                 case '$':
2439                   if (started_error_output)
2440                     {
2441                       putchar_unfiltered ('\n');
2442                       started_error_output = 0;
2443                     }
2444                 }
2445             }
2446
2447           switch (ch)
2448             {
2449             case '+':
2450               if (remote_debug)
2451                 printf_unfiltered ("Ack\n");
2452               return 1;
2453             case SERIAL_TIMEOUT:
2454               tcount ++;
2455               if (tcount > 3)
2456                 return 0;
2457               break;            /* Retransmit buffer */
2458             case '$':
2459               {
2460                 char junkbuf[PBUFSIZ];
2461
2462               /* It's probably an old response, and we're out of sync.
2463                  Just gobble up the packet and ignore it.  */
2464                 getpkt (junkbuf, 0);
2465                 continue;               /* Now, go look for + */
2466               }
2467             default:
2468               if (remote_debug)
2469                 {
2470                   if (!started_error_output)
2471                     {
2472                       started_error_output = 1;
2473                       printf_unfiltered ("putpkt: Junk: ");
2474                     }
2475                   putchar_unfiltered (ch & 0177);
2476                 }
2477               continue;
2478             }
2479           break;                /* Here to retransmit */
2480         }
2481
2482 #if 0
2483       /* This is wrong.  If doing a long backtrace, the user should be
2484          able to get out next time we call QUIT, without anything as
2485          violent as interrupt_query.  If we want to provide a way out of
2486          here without getting to the next QUIT, it should be based on
2487          hitting ^C twice as in remote_wait.  */
2488       if (quit_flag)
2489         {
2490           quit_flag = 0;
2491           interrupt_query ();
2492         }
2493 #endif
2494     }
2495 }
2496
2497 /* Come here after finding the start of the frame.  Collect the rest
2498    into BUF, verifying the checksum, length, and handling run-length
2499    compression.  Returns 0 on any error, 1 on success.  */
2500
2501 static int
2502 read_frame (buf)
2503      char *buf;
2504 {
2505   unsigned char csum;
2506   char *bp;
2507   int c;
2508
2509   csum = 0;
2510   bp = buf;
2511
2512   while (1)
2513     {
2514       c = readchar (remote_timeout);
2515
2516       switch (c)
2517         {
2518         case SERIAL_TIMEOUT:
2519           if (remote_debug)
2520             puts_filtered ("Timeout in mid-packet, retrying\n");
2521           return 0;
2522         case '$':
2523           if (remote_debug)
2524             puts_filtered ("Saw new packet start in middle of old one\n");
2525           return 0;             /* Start a new packet, count retries */
2526         case '#':
2527           {
2528             unsigned char pktcsum;
2529
2530             *bp = '\000';
2531
2532             pktcsum = fromhex (readchar (remote_timeout)) << 4;
2533             pktcsum |= fromhex (readchar (remote_timeout));
2534
2535             if (csum == pktcsum)
2536               return 1;
2537
2538             if (remote_debug) 
2539               {
2540                 printf_filtered ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
2541                                  pktcsum, csum);
2542                 puts_filtered (buf);
2543                 puts_filtered ("\n");
2544               }
2545             return 0;
2546           }
2547         case '*':               /* Run length encoding */
2548           csum += c;
2549           c = readchar (remote_timeout);
2550           csum += c;
2551           c = c - ' ' + 3;      /* Compute repeat count */
2552
2553
2554           if (c > 0 && c < 255 && bp + c - 1 < buf + PBUFSIZ - 1)
2555             {
2556               memset (bp, *(bp - 1), c);
2557               bp += c;
2558               continue;
2559             }
2560
2561           *bp = '\0';
2562           printf_filtered ("Repeat count %d too large for buffer: ", c);
2563           puts_filtered (buf);
2564           puts_filtered ("\n");
2565           return 0;
2566
2567         default:
2568           if (bp < buf + PBUFSIZ - 1)
2569             {
2570               *bp++ = c;
2571               csum += c;
2572               continue;
2573             }
2574
2575           *bp = '\0';
2576           puts_filtered ("Remote packet too long: ");
2577           puts_filtered (buf);
2578           puts_filtered ("\n");
2579
2580           return 0;
2581         }
2582     }
2583 }
2584
2585 /* Read a packet from the remote machine, with error checking, and
2586    store it in BUF.  BUF is expected to be of size PBUFSIZ.  If
2587    FOREVER, wait forever rather than timing out; this is used while
2588    the target is executing user code.  */
2589
2590 void
2591 getpkt (buf, forever)
2592      char *buf;
2593      int forever;
2594 {
2595   int c;
2596   int tries;
2597   int timeout;
2598   int val;
2599
2600   strcpy (buf,"timeout");
2601
2602   if (forever)
2603     {
2604 #ifdef MAINTENANCE_CMDS
2605       timeout = watchdog > 0 ? watchdog : -1;
2606 #else
2607       timeout = -1;
2608 #endif
2609     }
2610
2611   else
2612     timeout = remote_timeout;
2613
2614 #define MAX_TRIES 3
2615
2616   for (tries = 1; tries <= MAX_TRIES; tries++)
2617     {
2618       /* This can loop forever if the remote side sends us characters
2619          continuously, but if it pauses, we'll get a zero from readchar
2620          because of timeout.  Then we'll count that as a retry.  */
2621
2622       /* Note that we will only wait forever prior to the start of a packet.
2623          After that, we expect characters to arrive at a brisk pace.  They
2624          should show up within remote_timeout intervals.  */
2625
2626       do
2627         {
2628           c = readchar (timeout);
2629
2630           if (c == SERIAL_TIMEOUT)
2631             {
2632 #ifdef MAINTENANCE_CMDS
2633               if (forever)      /* Watchdog went off.  Kill the target. */
2634                 {
2635                   target_mourn_inferior ();
2636                   error ("Watchdog has expired.  Target detached.\n");
2637                 }
2638 #endif
2639               if (remote_debug)
2640                 puts_filtered ("Timed out.\n");
2641               goto retry;
2642             }
2643         }
2644       while (c != '$');
2645
2646       /* We've found the start of a packet, now collect the data.  */
2647
2648       val = read_frame (buf);
2649
2650       if (val == 1)
2651         {
2652           if (remote_debug)
2653             fprintf_unfiltered (gdb_stdout, "Packet received: %s\n", buf);
2654           SERIAL_WRITE (remote_desc, "+", 1);
2655           return;
2656         }
2657
2658       /* Try the whole thing again.  */
2659     retry:
2660       SERIAL_WRITE (remote_desc, "-", 1);
2661     }
2662
2663   /* We have tried hard enough, and just can't receive the packet.  Give up. */
2664
2665   printf_unfiltered ("Ignoring packet error, continuing...\n");
2666   SERIAL_WRITE (remote_desc, "+", 1);
2667 }
2668 \f
2669 static void
2670 remote_kill ()
2671 {
2672   /* For some mysterious reason, wait_for_inferior calls kill instead of
2673      mourn after it gets TARGET_WAITKIND_SIGNALLED.  Work around it.  */
2674   if (kill_kludge)
2675     {
2676       kill_kludge = 0;
2677       target_mourn_inferior ();
2678       return;
2679     }
2680
2681   /* Use catch_errors so the user can quit from gdb even when we aren't on
2682      speaking terms with the remote system.  */
2683   catch_errors (putpkt, "k", "", RETURN_MASK_ERROR);
2684
2685   /* Don't wait for it to die.  I'm not really sure it matters whether
2686      we do or not.  For the existing stubs, kill is a noop.  */
2687   target_mourn_inferior ();
2688 }
2689
2690 static void
2691 remote_mourn ()
2692 {
2693   remote_mourn_1 (&remote_ops);
2694 }
2695
2696 static void
2697 extended_remote_mourn ()
2698 {
2699   /* We do _not_ want to mourn the target like this; this will
2700      remove the extended remote target  from the target stack,
2701      and the next time the user says "run" it'll fail. 
2702
2703      FIXME: What is the right thing to do here?  */
2704 #if 0
2705   remote_mourn_1 (&extended_remote_ops);
2706 #endif
2707 }
2708
2709 /* Worker function for remote_mourn.  */
2710 static void
2711 remote_mourn_1 (target)
2712      struct target_ops *target;
2713 {
2714   unpush_target (target);
2715   generic_mourn_inferior ();
2716 }
2717
2718 /* In the extended protocol we want to be able to do things like
2719    "run" and have them basically work as expected.  So we need
2720    a special create_inferior function. 
2721
2722    FIXME: One day add support for changing the exec file
2723    we're debugging, arguments and an environment.  */
2724
2725 static void
2726 extended_remote_create_inferior (exec_file, args, env)
2727      char *exec_file;
2728      char *args;
2729      char **env;
2730 {
2731   /* Rip out the breakpoints; we'll reinsert them after restarting
2732      the remote server.  */
2733   remove_breakpoints ();
2734
2735   /* Now restart the remote server.  */
2736   extended_remote_restart ();
2737
2738   /* Now put the breakpoints back in.  This way we're safe if the
2739      restart function works via a unix fork on the remote side.  */
2740   insert_breakpoints ();
2741
2742   /* Clean up from the last time we were running.  */
2743   clear_proceed_status ();
2744
2745   /* Let the remote process run.  */
2746   proceed (-1, TARGET_SIGNAL_0, 0);
2747 }
2748
2749 \f
2750 /* On some machines, e.g. 68k, we may use a different breakpoint instruction
2751    than other targets; in those use REMOTE_BREAKPOINT instead of just
2752    BREAKPOINT.  Also, bi-endian targets may define LITTLE_REMOTE_BREAKPOINT
2753    and BIG_REMOTE_BREAKPOINT.  If none of these are defined, we just call
2754    the standard routines that are in mem-break.c.  */
2755
2756 /* FIXME, these ought to be done in a more dynamic fashion.  For instance,
2757    the choice of breakpoint instruction affects target program design and
2758    vice versa, and by making it user-tweakable, the special code here
2759    goes away and we need fewer special GDB configurations.  */
2760
2761 #if defined (LITTLE_REMOTE_BREAKPOINT) && defined (BIG_REMOTE_BREAKPOINT) && !defined(REMOTE_BREAKPOINT)
2762 #define REMOTE_BREAKPOINT
2763 #endif
2764
2765 #ifdef REMOTE_BREAKPOINT
2766
2767 /* If the target isn't bi-endian, just pretend it is.  */
2768 #if !defined (LITTLE_REMOTE_BREAKPOINT) && !defined (BIG_REMOTE_BREAKPOINT)
2769 #define LITTLE_REMOTE_BREAKPOINT REMOTE_BREAKPOINT
2770 #define BIG_REMOTE_BREAKPOINT REMOTE_BREAKPOINT
2771 #endif
2772
2773 static unsigned char big_break_insn[] = BIG_REMOTE_BREAKPOINT;
2774 static unsigned char little_break_insn[] = LITTLE_REMOTE_BREAKPOINT;
2775
2776 #endif /* REMOTE_BREAKPOINT */
2777
2778 /* Insert a breakpoint on targets that don't have any better breakpoint
2779    support.  We read the contents of the target location and stash it,
2780    then overwrite it with a breakpoint instruction.  ADDR is the target
2781    location in the target machine.  CONTENTS_CACHE is a pointer to 
2782    memory allocated for saving the target contents.  It is guaranteed
2783    by the caller to be long enough to save sizeof BREAKPOINT bytes (this
2784    is accomplished via BREAKPOINT_MAX).  */
2785
2786 static int
2787 remote_insert_breakpoint (addr, contents_cache)
2788      CORE_ADDR addr;
2789      char *contents_cache;
2790 {
2791 #ifdef REMOTE_BREAKPOINT
2792   int val;
2793
2794   val = target_read_memory (addr, contents_cache, sizeof big_break_insn);
2795
2796   if (val == 0)
2797     {
2798       if (TARGET_BYTE_ORDER == BIG_ENDIAN)
2799         val = target_write_memory (addr, (char *) big_break_insn,
2800                                    sizeof big_break_insn);
2801       else
2802         val = target_write_memory (addr, (char *) little_break_insn,
2803                                    sizeof little_break_insn);
2804     }
2805
2806   return val;
2807 #else
2808   return memory_insert_breakpoint (addr, contents_cache);
2809 #endif /* REMOTE_BREAKPOINT */
2810 }
2811
2812 static int
2813 remote_remove_breakpoint (addr, contents_cache)
2814      CORE_ADDR addr;
2815      char *contents_cache;
2816 {
2817 #ifdef REMOTE_BREAKPOINT
2818   return target_write_memory (addr, contents_cache, sizeof big_break_insn);
2819 #else
2820   return memory_remove_breakpoint (addr, contents_cache);
2821 #endif /* REMOTE_BREAKPOINT */
2822 }
2823
2824 /* Some targets are only capable of doing downloads, and afterwards
2825    they switch to the remote serial protocol.  This function provides
2826    a clean way to get from the download target to the remote target.
2827    It's basically just a wrapper so that we don't have to expose any
2828    of the internal workings of remote.c.
2829
2830    Prior to calling this routine, you should shutdown the current
2831    target code, else you will get the "A program is being debugged
2832    already..." message.  Usually a call to pop_target() suffices.  */
2833
2834 void
2835 push_remote_target (name, from_tty)
2836      char *name;
2837      int from_tty;
2838 {
2839   printf_filtered ("Switching to remote protocol\n");
2840   remote_open (name, from_tty);
2841 }
2842
2843 /* Other targets want to use the entire remote serial module but with
2844    certain remote_ops overridden. */
2845
2846 void
2847 open_remote_target (name, from_tty, target, extended_p)
2848      char *name;
2849      int from_tty;
2850      struct target_ops *target;
2851      int extended_p;
2852 {
2853   printf_filtered ("Selecting the %sremote protocol\n",
2854                    (extended_p ? "extended-" : ""));
2855   remote_open_1 (name, from_tty, target, extended_p);
2856 }
2857
2858 /* Table used by the crc32 function to calcuate the checksum. */
2859
2860 static unsigned long crc32_table[256] = {0, 0};
2861
2862 static unsigned long
2863 crc32 (buf, len, crc)
2864      unsigned char *buf;
2865      int len;
2866      unsigned int crc;
2867 {
2868   if (! crc32_table[1])
2869     {
2870       /* Initialize the CRC table and the decoding table. */
2871       int i, j;
2872       unsigned int c;
2873
2874       for (i = 0; i < 256; i++)
2875         {
2876           for (c = i << 24, j = 8; j > 0; --j)
2877             c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
2878           crc32_table[i] = c;
2879         }
2880     }
2881
2882   while (len--)
2883     {
2884       crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
2885       buf++;
2886     }
2887   return crc;
2888 }
2889
2890 /* compare-sections command
2891
2892    With no arguments, compares each loadable section in the exec bfd
2893    with the same memory range on the target, and reports mismatches.
2894    Useful for verifying the image on the target against the exec file.
2895    Depends on the target understanding the new "qCRC:" request.  */
2896
2897 static void
2898 compare_sections_command (args, from_tty)
2899      char *args;
2900      int from_tty;
2901 {
2902   asection *s;
2903   unsigned long host_crc, target_crc;
2904   extern bfd *exec_bfd;
2905   struct cleanup *old_chain;
2906   char *tmp, *sectdata, *sectname, buf[PBUFSIZ];
2907   bfd_size_type size;
2908   bfd_vma lma;
2909   int matched = 0;
2910   int mismatched = 0;
2911
2912   if (!exec_bfd)
2913     error ("command cannot be used without an exec file");
2914   if (!current_target.to_shortname ||
2915       strcmp (current_target.to_shortname, "remote") != 0)
2916     error ("command can only be used with remote target");
2917
2918   for (s = exec_bfd->sections; s; s = s->next) 
2919     {
2920       if (!(s->flags & SEC_LOAD))
2921         continue;       /* skip non-loadable section */
2922
2923       size = bfd_get_section_size_before_reloc (s);
2924       if (size == 0)
2925         continue;       /* skip zero-length section */
2926
2927       sectname = (char *) bfd_get_section_name (exec_bfd, s);
2928       if (args && strcmp (args, sectname) != 0)
2929         continue;       /* not the section selected by user */
2930
2931       matched = 1;      /* do this section */
2932       lma = s->lma;
2933       /* FIXME: assumes lma can fit into long */
2934       sprintf (buf, "qCRC:%lx,%lx", (long) lma, (long) size);
2935       putpkt (buf);
2936
2937       /* be clever; compute the host_crc before waiting for target reply */
2938       sectdata = xmalloc (size);
2939       old_chain = make_cleanup (free, sectdata);
2940       bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
2941       host_crc = crc32 ((unsigned char *) sectdata, size, 0xffffffff);
2942
2943       getpkt (buf, 0);
2944       if (buf[0] == 'E')
2945         error ("target memory fault, section %s, range 0x%08x -- 0x%08x",
2946                sectname, lma, lma + size);
2947       if (buf[0] != 'C')
2948         error ("remote target does not support this operation");
2949
2950       for (target_crc = 0, tmp = &buf[1]; *tmp; tmp++)
2951         target_crc = target_crc * 16 + fromhex (*tmp);
2952
2953       printf_filtered ("Section %s, range 0x%08x -- 0x%08x: ",
2954                        sectname, lma, lma + size);
2955       if (host_crc == target_crc)
2956         printf_filtered ("matched.\n");
2957       else
2958        {
2959          printf_filtered ("MIS-MATCHED!\n");
2960          mismatched++;
2961        }
2962
2963       do_cleanups (old_chain);
2964     }
2965   if (mismatched > 0)
2966     warning ("One or more sections of the remote executable does not match\n\
2967 the loaded file\n");
2968   if (args && !matched)
2969     printf_filtered ("No loaded section named '%s'.\n", args);
2970 }
2971
2972 static void
2973 packet_command (args, from_tty)
2974      char *args;
2975      int from_tty;
2976 {
2977   char buf[PBUFSIZ];
2978
2979   if (! remote_desc)
2980     error ("command can only be used with remote target");
2981
2982   if (! args)
2983     error ("remote-packet command requires packet text as argument");
2984
2985   puts_filtered ("sending: ");
2986   print_packet (args);
2987   puts_filtered ("\n");
2988   putpkt (args);
2989
2990   getpkt (buf, 0);
2991   puts_filtered ("received: ");
2992   print_packet (buf);
2993   puts_filtered ("\n");
2994 }
2995
2996 #if 0
2997 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------------- */
2998
2999 static void display_thread_info PARAMS ((struct gdb_ext_thread_info *info));
3000
3001 static void threadset_test_cmd PARAMS ((char *cmd, int tty));
3002
3003 static void threadalive_test PARAMS ((char *cmd, int tty));
3004
3005 static void threadlist_test_cmd PARAMS ((char *cmd, int tty));
3006
3007 int get_and_display_threadinfo PARAMS ((threadref *ref));
3008
3009 static void threadinfo_test_cmd PARAMS ((char *cmd, int tty));
3010
3011 static int thread_display_step PARAMS ((threadref *ref, void *context));
3012
3013 static void threadlist_update_test_cmd PARAMS ((char *cmd, int tty));
3014
3015 static void init_remote_threadtests PARAMS ((void));
3016
3017 #define SAMPLE_THREAD  0x05060708  /* Truncated 64 bit threadid */
3018
3019 static void
3020 threadset_test_cmd (cmd, tty)
3021      char *cmd;
3022      int tty;
3023 {
3024   int sample_thread = SAMPLE_THREAD;
3025
3026   printf_filtered ("Remote threadset test\n");
3027   set_thread (sample_thread, 1);
3028 }
3029
3030
3031 static void
3032 threadalive_test (cmd, tty)
3033      char *cmd;
3034      int tty;
3035 {
3036   int sample_thread = SAMPLE_THREAD;
3037
3038   if (remote_thread_alive (sample_thread))
3039     printf_filtered ("PASS: Thread alive test\n");
3040   else
3041     printf_filtered ("FAIL: Thread alive test\n");
3042 }
3043
3044 void output_threadid PARAMS ((char *title, threadref * ref));
3045
3046 void
3047 output_threadid (title, ref)
3048      char *title;
3049      threadref *ref;
3050 {
3051   char hexid[20];
3052
3053   pack_threadid (&hexid[0], ref);       /* Convert threead id into hex */
3054   hexid[16] = 0;
3055   printf_filtered ("%s  %s\n", title, (&hexid[0]));
3056 }
3057
3058 static void
3059 threadlist_test_cmd (cmd, tty)
3060      char *cmd;
3061      int tty;
3062 {
3063   int startflag = 1;
3064   threadref nextthread;
3065   int done, result_count;
3066   threadref threadlist[3];
3067
3068   printf_filtered ("Remote Threadlist test\n");
3069   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
3070                               &result_count, &threadlist[0]))
3071     printf_filtered ("FAIL: threadlist test\n");
3072   else
3073     {
3074       threadref *scan = threadlist;
3075       threadref *limit = scan + result_count;
3076
3077       while (scan < limit)
3078         output_threadid (" thread ", scan++);
3079     }
3080 }
3081
3082 void
3083 display_thread_info (info)
3084      struct gdb_ext_thread_info *info;
3085 {
3086   output_threadid ("Threadid: ", &info->threadid);
3087   printf_filtered ("Name: %s\n ", info->shortname);
3088   printf_filtered ("State: %s\n", info->display);
3089   printf_filtered ("other: %s\n\n", info->more_display);
3090 }
3091
3092 int
3093 get_and_display_threadinfo (ref)
3094      threadref *ref;
3095 {
3096   int result;
3097   int set;
3098   struct gdb_ext_thread_info threadinfo;
3099
3100   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3101     | TAG_MOREDISPLAY | TAG_DISPLAY;
3102   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
3103     display_thread_info (&threadinfo);
3104   return result;
3105 }
3106
3107 static void
3108 threadinfo_test_cmd (cmd, tty)
3109      char *cmd;
3110      int tty;
3111 {
3112   int athread = SAMPLE_THREAD;
3113   threadref thread;
3114   int set;
3115
3116   int_to_threadref (&thread, athread);
3117   printf_filtered ("Remote Threadinfo test\n");
3118   if (!get_and_display_threadinfo (&thread))
3119     printf_filtered ("FAIL cannot get thread info\n");
3120 }
3121
3122 static int
3123 thread_display_step (ref, context)
3124      threadref *ref;
3125      void *context;
3126 {
3127   /* output_threadid(" threadstep ",ref); *//* simple test */
3128   return get_and_display_threadinfo (ref);
3129 }
3130
3131 static void
3132 threadlist_update_test_cmd (cmd, tty)
3133      char *cmd;
3134      int tty;
3135 {
3136   printf_filtered ("Remote Threadlist update test\n");
3137   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
3138 }
3139
3140 static void
3141 init_remote_threadtests (void)
3142 {
3143   add_com ("tlist", class_obscure, threadlist_test_cmd,
3144      "Fetch and print the remote list of thread identifiers, one pkt only");
3145   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
3146            "Fetch and display info about one thread");
3147   add_com ("tset", class_obscure, threadset_test_cmd,
3148            "Test setting to a different thread");
3149   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
3150            "Iterate through updating all remote thread info");
3151   add_com ("talive", class_obscure, threadalive_test,
3152            " Remote thread alive test ");
3153 }
3154
3155 #endif /* 0 */
3156
3157 static void
3158 init_remote_ops ()
3159 {
3160   remote_ops.to_shortname = "remote";           
3161   remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
3162   remote_ops.to_doc = 
3163     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
3164 Specify the serial device it is connected to (e.g. /dev/ttya).";  
3165   remote_ops.to_open = remote_open;             
3166   remote_ops.to_close = remote_close;           
3167   remote_ops.to_detach = remote_detach;
3168   remote_ops.to_resume = remote_resume; 
3169   remote_ops.to_wait = remote_wait;
3170   remote_ops.to_fetch_registers = remote_fetch_registers;
3171   remote_ops.to_store_registers = remote_store_registers;
3172   remote_ops.to_prepare_to_store = remote_prepare_to_store;
3173   remote_ops.to_xfer_memory = remote_xfer_memory;       
3174   remote_ops.to_files_info = remote_files_info; 
3175   remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
3176   remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
3177   remote_ops.to_kill = remote_kill;             
3178   remote_ops.to_load = generic_load;            
3179   remote_ops.to_mourn_inferior = remote_mourn;
3180   remote_ops.to_thread_alive = remote_thread_alive;
3181   remote_ops.to_stop = remote_stop;
3182   remote_ops.to_stratum = process_stratum;
3183   remote_ops.to_has_all_memory = 1;     
3184   remote_ops.to_has_memory = 1; 
3185   remote_ops.to_has_stack = 1;  
3186   remote_ops.to_has_registers = 1;      
3187   remote_ops.to_has_execution = 1;      
3188   remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
3189   remote_ops.to_magic = OPS_MAGIC;      
3190 }
3191
3192 /* Set up the extended remote vector by making a copy of the standard
3193    remote vector and adding to it.  */
3194
3195 static void
3196 init_extended_remote_ops ()
3197 {
3198   extended_remote_ops = remote_ops;
3199
3200   extended_remote_ops.to_shortname = "extended-remote"; 
3201   extended_remote_ops.to_longname = 
3202     "Extended remote serial target in gdb-specific protocol";
3203   extended_remote_ops.to_doc = 
3204     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
3205 Specify the serial device it is connected to (e.g. /dev/ttya).",
3206   extended_remote_ops.to_open = extended_remote_open;   
3207   extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
3208   extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
3209
3210
3211 void
3212 _initialize_remote ()
3213 {
3214   init_remote_ops ();
3215   add_target (&remote_ops);
3216
3217   init_extended_remote_ops ();
3218   add_target (&extended_remote_ops);
3219   init_remote_threads ();
3220 #if 0
3221   init_remote_threadtests ();
3222 #endif
3223
3224   add_cmd ("compare-sections", class_obscure, compare_sections_command, 
3225            "Compare section data on target to the exec file.\n\
3226 Argument is a single section name (default: all loaded sections).", 
3227            &cmdlist);
3228
3229   add_cmd ("packet", class_maintenance, packet_command,
3230            "Send an arbitrary packet to a remote target.\n\
3231    maintenance packet TEXT\n\
3232 If GDB is talking to an inferior via the GDB serial protocol, then\n\
3233 this command sends the string TEXT to the inferior, and displays the\n\
3234 response packet.  GDB supplies the initial `$' character, and the\n\
3235 terminating `#' character and checksum.",
3236            &maintenancelist);
3237
3238   add_show_from_set 
3239     (add_set_cmd ("remotetimeout", no_class,
3240                   var_integer, (char *)&remote_timeout,
3241                   "Set timeout value for remote read.\n",
3242                   &setlist),
3243      &showlist);
3244
3245   add_show_from_set 
3246     (add_set_cmd ("remotebreak", no_class,
3247                   var_integer, (char *)&remote_break,
3248                   "Set whether to send break if interrupted.\n",
3249                   &setlist),
3250      &showlist);
3251
3252   add_show_from_set 
3253     (add_set_cmd ("remotewritesize", no_class,
3254                   var_integer, (char *)&remote_write_size,
3255                   "Set the maximum number of bytes per memory write packet.\n",
3256                   &setlist),
3257      &showlist);
3258
3259   remote_address_size = TARGET_PTR_BIT;
3260   add_show_from_set 
3261     (add_set_cmd ("remoteaddresssize", class_obscure,
3262                   var_integer, (char *)&remote_address_size,
3263                   "Set the maximum size of the address (in bits) \
3264 in a memory packet.\n",
3265                   &setlist),
3266      &showlist);  
3267 }