Support for bi-endian remote breakpoints.
[platform/upstream/binutils.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2    Copyright 1988, 1991, 1992, 1993, 1994, 1995, 1996 Free Software Foundation, Inc.
3
4 This file is part of GDB.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
19
20 /* Remote communication protocol.
21
22    A debug packet whose contents are <data>
23    is encapsulated for transmission in the form:
24
25         $ <data> # CSUM1 CSUM2
26
27         <data> must be ASCII alphanumeric and cannot include characters
28         '$' or '#'.  If <data> starts with two characters followed by
29         ':', then the existing stubs interpret this as a sequence number.
30
31         CSUM1 and CSUM2 are ascii hex representation of an 8-bit 
32         checksum of <data>, the most significant nibble is sent first.
33         the hex digits 0-9,a-f are used.
34
35    Receiver responds with:
36
37         +       - if CSUM is correct and ready for next packet
38         -       - if CSUM is incorrect
39
40    <data> is as follows:
41    Most values are encoded in ascii hex digits.  Signal numbers are according
42    to the numbering in target.h.
43
44         Request         Packet
45
46         set thread      Hct...          Set thread for subsequent operations.
47                                         c = 'c' for thread used in step and 
48                                         continue; t... can be -1 for all
49                                         threads.
50                                         c = 'g' for thread used in other
51                                         operations.  If zero, pick a thread,
52                                         any thread.
53         reply           OK              for success
54                         ENN             for an error.
55
56         read registers  g
57         reply           XX....X         Each byte of register data
58                                         is described by two hex digits.
59                                         Registers are in the internal order
60                                         for GDB, and the bytes in a register
61                                         are in the same order the machine uses.
62                         or ENN          for an error.
63
64         write regs      GXX..XX         Each byte of register data
65                                         is described by two hex digits.
66         reply           OK              for success
67                         ENN             for an error
68
69         write reg       Pn...=r...      Write register n... with value r...,
70                                         which contains two hex digits for each
71                                         byte in the register (target byte
72                                         order).
73         reply           OK              for success
74                         ENN             for an error
75         (not supported by all stubs).
76
77         read mem        mAA..AA,LLLL    AA..AA is address, LLLL is length.
78         reply           XX..XX          XX..XX is mem contents
79                                         Can be fewer bytes than requested
80                                         if able to read only part of the data.
81                         or ENN          NN is errno
82
83         write mem       MAA..AA,LLLL:XX..XX
84                                         AA..AA is address,
85                                         LLLL is number of bytes,
86                                         XX..XX is data
87         reply           OK              for success
88                         ENN             for an error (this includes the case
89                                         where only part of the data was
90                                         written).
91
92         continue        cAA..AA         AA..AA is address to resume
93                                         If AA..AA is omitted,
94                                         resume at same address.
95
96         step            sAA..AA         AA..AA is address to resume
97                                         If AA..AA is omitted,
98                                         resume at same address.
99
100         continue with   Csig;AA         Continue with signal sig (hex signal
101         signal                          number).
102
103         step with       Ssig;AA         Like 'C' but step not continue.
104         signal
105
106         last signal     ?               Reply the current reason for stopping.
107                                         This is the same reply as is generated
108                                         for step or cont : SAA where AA is the
109                                         signal number.
110
111         detach          D               Reply OK.
112
113         There is no immediate reply to step or cont.
114         The reply comes when the machine stops.
115         It is           SAA             AA is the signal number.
116
117         or...           TAAn...:r...;n...:r...;n...:r...;
118                                         AA = signal number
119                                         n... = register number (hex)
120                                           r... = register contents
121                                         n... = `thread'
122                                           r... = thread process ID.  This is
123                                                  a hex integer.
124                                         n... = other string not starting 
125                                             with valid hex digit.
126                                           gdb should ignore this n,r pair
127                                           and go on to the next.  This way
128                                           we can extend the protocol.
129         or...           WAA             The process exited, and AA is
130                                         the exit status.  This is only
131                                         applicable for certains sorts of
132                                         targets.
133         or...           XAA             The process terminated with signal
134                                         AA.
135         or...           OXX..XX XX..XX  is hex encoding of ASCII data. This
136                                         can happen at any time while the program is
137                                         running and the debugger should
138                                         continue to wait for 'W', 'T', etc.
139
140         thread alive    TXX             Find out if the thread XX is alive.
141         reply           OK              thread is still alive
142                         ENN             thread is dead
143         
144         remote restart  RXX             Restart the remote server
145
146         extended ops    !               Use the extended remote protocol.
147                                         Sticky -- only needs to be set once.
148
149         kill request    k
150
151         toggle debug    d               toggle debug flag (see 386 & 68k stubs)
152         reset           r               reset -- see sparc stub.
153         reserved        <other>         On other requests, the stub should
154                                         ignore the request and send an empty
155                                         response ($#<checksum>).  This way
156                                         we can extend the protocol and GDB
157                                         can tell whether the stub it is
158                                         talking to uses the old or the new.
159         search          tAA:PP,MM       Search backwards starting at address
160                                         AA for a match with pattern PP and
161                                         mask MM.  PP and MM are 4 bytes.
162                                         Not supported by all stubs.
163
164         general query   qXXXX           Request info about XXXX.
165         general set     QXXXX=yyyy      Set value of XXXX to yyyy.
166         query sect offs qOffsets        Get section offsets.  Reply is
167                                         Text=xxx;Data=yyy;Bss=zzz
168
169         Responses can be run-length encoded to save space.  A '*' means that
170         the next character is an ASCII encoding giving a repeat count which
171         stands for that many repititions of the character preceding the '*'.
172         The encoding is n+29, yielding a printable character where n >=3 
173         (which is where rle starts to win).  Don't use an n > 126.
174
175         So 
176         "0* " means the same as "0000".  */
177
178 #include "defs.h"
179 #include "gdb_string.h"
180 #include <fcntl.h>
181 #include "frame.h"
182 #include "inferior.h"
183 #include "bfd.h"
184 #include "symfile.h"
185 #include "target.h"
186 #include "wait.h"
187 /*#include "terminal.h"*/
188 #include "gdbcmd.h"
189 #include "objfiles.h"
190 #include "gdb-stabs.h"
191 #include "thread.h"
192
193 #include "dcache.h"
194
195 #ifdef USG
196 #include <sys/types.h>
197 #endif
198
199 #include <signal.h>
200 #include "serial.h"
201
202 /* Prototypes for local functions */
203
204 static int remote_write_bytes PARAMS ((CORE_ADDR memaddr,
205                                        char *myaddr, int len));
206
207 static int remote_read_bytes PARAMS ((CORE_ADDR memaddr,
208                                       char *myaddr, int len));
209
210 static void remote_files_info PARAMS ((struct target_ops *ignore));
211
212 static int remote_xfer_memory PARAMS ((CORE_ADDR memaddr, char *myaddr,
213                                        int len, int should_write,
214                                        struct target_ops *target));
215
216 static void remote_prepare_to_store PARAMS ((void));
217
218 static void remote_fetch_registers PARAMS ((int regno));
219
220 static void remote_resume PARAMS ((int pid, int step,
221                                    enum target_signal siggnal));
222
223 static int remote_start_remote PARAMS ((char *dummy));
224
225 static void remote_open PARAMS ((char *name, int from_tty));
226
227 static void extended_remote_open PARAMS ((char *name, int from_tty));
228
229 static void remote_open_1 PARAMS ((char *, int, struct target_ops *));
230
231 static void remote_close PARAMS ((int quitting));
232
233 static void remote_store_registers PARAMS ((int regno));
234
235 static void remote_mourn PARAMS ((void));
236
237 static void extended_remote_restart PARAMS ((void));
238
239 static void extended_remote_mourn PARAMS ((void));
240
241 static void extended_remote_create_inferior PARAMS ((char *, char *, char **));
242
243 static void remote_mourn_1 PARAMS ((struct target_ops *));
244
245 static void getpkt PARAMS ((char *buf, int forever));
246
247 static int putpkt PARAMS ((char *buf));
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 int fromhex PARAMS ((int a));
260
261 static void remote_detach PARAMS ((char *args, int from_tty));
262
263 static void remote_interrupt PARAMS ((int signo));
264
265 static void remote_interrupt_twice PARAMS ((int signo));
266
267 static void interrupt_query PARAMS ((void));
268
269 extern struct target_ops remote_ops;    /* Forward decl */
270 extern struct target_ops extended_remote_ops;   /* Forward decl */
271
272 /* This was 5 seconds, which is a long time to sit and wait.
273    Unless this is going though some terminal server or multiplexer or
274    other form of hairy serial connection, I would think 2 seconds would
275    be plenty.  */
276
277 static int remote_timeout = 2;
278
279 /* This variable chooses whether to send a ^C or a break when the user
280    requests program interruption.  Although ^C is usually what remote
281    systems expect, and that is the default here, sometimes a break is
282    preferable instead.  */
283
284 static int remote_break;
285
286 /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
287    remote_open knows that we don't have a file open when the program
288    starts.  */
289 serial_t remote_desc = NULL;
290
291 /* Having this larger than 400 causes us to be incompatible with m68k-stub.c
292    and i386-stub.c.  Normally, no one would notice because it only matters
293    for writing large chunks of memory (e.g. in downloads).  Also, this needs
294    to be more than 400 if required to hold the registers (see below, where
295    we round it up based on REGISTER_BYTES).  */
296 #define PBUFSIZ 400
297
298 /* Maximum number of bytes to read/write at once.  The value here
299    is chosen to fill up a packet (the headers account for the 32).  */
300 #define MAXBUFBYTES ((PBUFSIZ-32)/2)
301
302 /* Round up PBUFSIZ to hold all the registers, at least.  */
303 /* The blank line after the #if seems to be required to work around a
304    bug in HP's PA compiler.  */
305 #if REGISTER_BYTES > MAXBUFBYTES
306
307 #undef PBUFSIZ
308 #define PBUFSIZ (REGISTER_BYTES * 2 + 32)
309 #endif
310
311 /* This variable sets the number of bytes to be written to the target
312    in a single packet.  Normally PBUFSIZ is satisfactory, but some
313    targets need smaller values (perhaps because the receiving end
314    is slow).  */
315
316 static int remote_write_size = PBUFSIZ;
317
318 /* Should we try the 'P' request?  If this is set to one when the stub
319    doesn't support 'P', the only consequence is some unnecessary traffic.  */
320 static int stub_supports_P = 1;
321
322 \f
323 /* These are the threads which we last sent to the remote system.  -1 for all
324    or -2 for not sent yet.  */
325 int general_thread;
326 int cont_thread;
327
328 static void
329 set_thread (th, gen)
330      int th;
331      int gen;
332 {
333   char buf[PBUFSIZ];
334   int state = gen ? general_thread : cont_thread;
335   if (state == th)
336     return;
337   buf[0] = 'H';
338   buf[1] = gen ? 'g' : 'c';
339   if (th == 42000)
340     {
341       buf[2] = '0';
342       buf[3] = '\0';
343     }
344   else if (th < 0)
345     sprintf (&buf[2], "-%x", -th);
346   else
347     sprintf (&buf[2], "%x", th);
348   putpkt (buf);
349   getpkt (buf, 0);
350   if (gen)
351     general_thread = th;
352   else
353     cont_thread = th;
354 }
355 \f
356 /*  Return nonzero if the thread TH is still alive on the remote system.  */
357
358 static int
359 remote_thread_alive (th)
360      int th;
361 {
362   char buf[PBUFSIZ];
363
364   buf[0] = 'T';
365   if (th < 0)
366     sprintf (&buf[1], "-%x", -th);
367   else
368     sprintf (&buf[1], "%x", th);
369   putpkt (buf);
370   getpkt (buf, 0);
371   return (buf[0] == 'O' && buf[1] == 'K');
372 }
373
374 /*  Restart the remote side; this is an extended protocol operation.  */
375
376 static void
377 extended_remote_restart ()
378 {
379   char buf[PBUFSIZ];
380
381   /* Send the restart command; for reasons I don't understand the
382      remote side really expects a number after the "R".  */
383   buf[0] = 'R';
384   sprintf (&buf[1], "%x", 0);
385   putpkt (buf);
386
387   /* Now query for status so this looks just like we restarted
388      gdbserver from scratch.  */
389   putpkt ("?");
390   getpkt (buf, 0);
391 }
392 \f
393 /* Clean up connection to a remote debugger.  */
394
395 /* ARGSUSED */
396 static void
397 remote_close (quitting)
398      int quitting;
399 {
400   if (remote_desc)
401     SERIAL_CLOSE (remote_desc);
402   remote_desc = NULL;
403 }
404
405 /* Query the remote side for the text, data and bss offsets. */
406
407 static void
408 get_offsets ()
409 {
410   char buf[PBUFSIZ];
411   int nvals;
412   CORE_ADDR text_addr, data_addr, bss_addr;
413   struct section_offsets *offs;
414
415   putpkt ("qOffsets");
416
417   getpkt (buf, 0);
418
419   if (buf[0] == '\000')
420     return;                     /* Return silently.  Stub doesn't support this
421                                    command. */
422   if (buf[0] == 'E')
423     {
424       warning ("Remote failure reply: %s", buf);
425       return;
426     }
427
428   nvals = sscanf (buf, "Text=%lx;Data=%lx;Bss=%lx", &text_addr, &data_addr,
429                   &bss_addr);
430   if (nvals != 3)
431     error ("Malformed response to offset query, %s", buf);
432
433   if (symfile_objfile == NULL)
434     return;
435
436   offs = (struct section_offsets *) alloca (sizeof (struct section_offsets)
437                                             + symfile_objfile->num_sections
438                                             * sizeof (offs->offsets));
439   memcpy (offs, symfile_objfile->section_offsets,
440           sizeof (struct section_offsets)
441           + symfile_objfile->num_sections
442           * sizeof (offs->offsets));
443
444   ANOFFSET (offs, SECT_OFF_TEXT) = text_addr;
445
446   /* This is a temporary kludge to force data and bss to use the same offsets
447      because that's what nlmconv does now.  The real solution requires changes
448      to the stub and remote.c that I don't have time to do right now.  */
449
450   ANOFFSET (offs, SECT_OFF_DATA) = data_addr;
451   ANOFFSET (offs, SECT_OFF_BSS) = data_addr;
452
453   objfile_relocate (symfile_objfile, offs);
454 }
455
456 /* Stub for catch_errors.  */
457
458 static int
459 remote_start_remote (dummy)
460      char *dummy;
461 {
462   immediate_quit = 1;           /* Allow user to interrupt it */
463
464   /* Ack any packet which the remote side has already sent.  */
465   SERIAL_WRITE (remote_desc, "+", 1);
466
467   /* Let the stub know that we want it to return the thread.  */
468   set_thread (-1, 0);
469
470   get_offsets ();               /* Get text, data & bss offsets */
471
472   putpkt ("?");                 /* initiate a query from remote machine */
473   immediate_quit = 0;
474
475   start_remote ();              /* Initialize gdb process mechanisms */
476   return 1;
477 }
478
479 /* Open a connection to a remote debugger.
480    NAME is the filename used for communication.  */
481
482 static void
483 remote_open (name, from_tty)
484      char *name;
485      int from_tty;
486 {
487   remote_open_1 (name, from_tty, &remote_ops);
488 }
489
490 /* Open a connection to a remote debugger using the extended
491    remote gdb protocol.  NAME is the filename used for communication.  */
492
493 static void
494 extended_remote_open (name, from_tty)
495      char *name;
496      int from_tty;
497 {
498   char buf[PBUFSIZ];
499
500   /* Do the basic remote open stuff.  */
501   remote_open_1 (name, from_tty, &extended_remote_ops);
502
503   /* Now tell the remote that we're using the extended protocol.  */
504   putpkt ("!");
505   getpkt (buf, 0);
506
507 }
508
509 /* Generic code for opening a connection to a remote target.  */
510 static DCACHE *remote_dcache;
511
512 static void
513 remote_open_1 (name, from_tty, target)
514      char *name;
515      int from_tty;
516      struct target_ops *target;
517 {
518   if (name == 0)
519     error ("To open a remote debug connection, you need to specify what serial\n\
520 device is attached to the remote system (e.g. /dev/ttya).");
521
522   target_preopen (from_tty);
523
524   unpush_target (target);
525
526   remote_dcache = dcache_init (remote_read_bytes, remote_write_bytes);
527
528   remote_desc = SERIAL_OPEN (name);
529   if (!remote_desc)
530     perror_with_name (name);
531
532   if (baud_rate != -1)
533     {
534       if (SERIAL_SETBAUDRATE (remote_desc, baud_rate))
535         {
536           SERIAL_CLOSE (remote_desc);
537           perror_with_name (name);
538         }
539     }
540
541
542   SERIAL_RAW (remote_desc);
543
544   /* If there is something sitting in the buffer we might take it as a
545      response to a command, which would be bad.  */
546   SERIAL_FLUSH_INPUT (remote_desc);
547
548   if (from_tty)
549     {
550       puts_filtered ("Remote debugging using ");
551       puts_filtered (name);
552       puts_filtered ("\n");
553     }
554   push_target (target); /* Switch to using remote target now */
555
556   /* Start out by trying the 'P' request to set registers.  We set this each
557      time that we open a new target so that if the user switches from one
558      stub to another, we can (if the target is closed and reopened) cope.  */
559   stub_supports_P = 1;
560
561   general_thread = -2;
562   cont_thread = -2;
563
564   /* Without this, some commands which require an active target (such as kill)
565      won't work.  This variable serves (at least) double duty as both the pid
566      of the target process (if it has such), and as a flag indicating that a
567      target is active.  These functions should be split out into seperate
568      variables, especially since GDB will someday have a notion of debugging
569      several processes.  */
570
571   inferior_pid = 42000;
572   /* Start the remote connection; if error (0), discard this target.
573      In particular, if the user quits, be sure to discard it
574      (we'd be in an inconsistent state otherwise).  */
575   if (!catch_errors (remote_start_remote, (char *)0, 
576                      "Couldn't establish connection to remote target\n", RETURN_MASK_ALL))
577     pop_target();
578 }
579
580 /* This takes a program previously attached to and detaches it.  After
581    this is done, GDB can be used to debug some other program.  We
582    better not have left any breakpoints in the target program or it'll
583    die when it hits one.  */
584
585 static void
586 remote_detach (args, from_tty)
587      char *args;
588      int from_tty;
589 {
590   char buf[PBUFSIZ];
591
592   if (args)
593     error ("Argument given to \"detach\" when remotely debugging.");
594
595   /* Tell the remote target to detach.  */
596   strcpy (buf, "D");
597   remote_send (buf);
598
599   pop_target ();
600   if (from_tty)
601     puts_filtered ("Ending remote debugging.\n");
602 }
603
604 /* Convert hex digit A to a number.  */
605
606 static int
607 fromhex (a)
608      int a;
609 {
610   if (a >= '0' && a <= '9')
611     return a - '0';
612   else if (a >= 'a' && a <= 'f')
613     return a - 'a' + 10;
614   else 
615     error ("Reply contains invalid hex digit %d", a);
616 }
617
618 /* Convert number NIB to a hex digit.  */
619
620 static int
621 tohex (nib)
622      int nib;
623 {
624   if (nib < 10)
625     return '0'+nib;
626   else
627     return 'a'+nib-10;
628 }
629 \f
630 /* Tell the remote machine to resume.  */
631
632 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
633 int last_sent_step;
634
635 static void
636 remote_resume (pid, step, siggnal)
637      int pid, step;
638      enum target_signal siggnal;
639 {
640   char buf[PBUFSIZ];
641
642   if (pid == -1)
643     set_thread (inferior_pid, 0);
644   else
645     set_thread (pid, 0);
646
647   dcache_flush (remote_dcache);
648
649   last_sent_signal = siggnal;
650   last_sent_step = step;
651
652   if (siggnal != TARGET_SIGNAL_0)
653     {
654       buf[0] = step ? 'S' : 'C';
655       buf[1] = tohex (((int)siggnal >> 4) & 0xf);
656       buf[2] = tohex ((int)siggnal & 0xf);
657       buf[3] = '\0';
658     }
659   else
660     strcpy (buf, step ? "s": "c");
661
662   putpkt (buf);
663 }
664 \f
665 /* Send ^C to target to halt it.  Target will respond, and send us a
666    packet.  */
667
668 static void
669 remote_interrupt (signo)
670      int signo;
671 {
672   /* If this doesn't work, try more severe steps.  */
673   signal (signo, remote_interrupt_twice);
674   
675   if (remote_debug)
676     printf_unfiltered ("remote_interrupt called\n");
677
678   /* Send a break or a ^C, depending on user preference.  */
679   if (remote_break)
680     SERIAL_SEND_BREAK (remote_desc);
681   else
682     SERIAL_WRITE (remote_desc, "\003", 1);
683 }
684
685 static void (*ofunc)();
686
687 /* The user typed ^C twice.  */
688 static void
689 remote_interrupt_twice (signo)
690      int signo;
691 {
692   signal (signo, ofunc);
693   
694   interrupt_query ();
695
696   signal (signo, remote_interrupt);
697 }
698
699 /* Ask the user what to do when an interrupt is received.  */
700
701 static void
702 interrupt_query ()
703 {
704   target_terminal_ours ();
705
706   if (query ("Interrupted while waiting for the program.\n\
707 Give up (and stop debugging it)? "))
708     {
709       target_mourn_inferior ();
710       return_to_top_level (RETURN_QUIT);
711     }
712
713   target_terminal_inferior ();
714 }
715
716 /* If nonzero, ignore the next kill.  */
717 int kill_kludge;
718
719 /* Wait until the remote machine stops, then return,
720    storing status in STATUS just as `wait' would.
721    Returns "pid" (though it's not clear what, if anything, that
722    means in the case of this target).  */
723
724 static int
725 remote_wait (pid, status)
726      int pid;
727      struct target_waitstatus *status;
728 {
729   unsigned char buf[PBUFSIZ];
730   int thread_num = -1;
731
732   status->kind = TARGET_WAITKIND_EXITED;
733   status->value.integer = 0;
734
735   while (1)
736     {
737       unsigned char *p;
738
739       ofunc = (void (*)()) signal (SIGINT, remote_interrupt);
740       getpkt ((char *) buf, 1);
741       signal (SIGINT, ofunc);
742
743       switch (buf[0])
744         {
745         case 'E':               /* Error of some sort */
746           warning ("Remote failure reply: %s", buf);
747           continue;
748         case 'T':               /* Status with PC, SP, FP, ... */
749           {
750             int i;
751             long regno;
752             char regs[MAX_REGISTER_RAW_SIZE];
753
754             /* Expedited reply, containing Signal, {regno, reg} repeat */
755             /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
756                 ss = signal number
757                 n... = register number
758                 r... = register contents
759                 */
760
761             p = &buf[3];        /* after Txx */
762
763             while (*p)
764               {
765                 unsigned char *p1;
766                 char *p_temp;
767
768                 regno = strtol ((const char *) p, &p_temp, 16); /* Read the register number */
769                 p1 = (unsigned char *)p_temp;
770
771                 if (p1 == p)
772                   {
773                     p1 = (unsigned char *) strchr ((const char *) p, ':');
774                     if (p1 == NULL)
775                       warning ("Malformed packet (missing colon): %s\n\
776 Packet: '%s'\n",
777                                p, buf);
778                     if (strncmp ((const char *) p, "thread", p1 - p) == 0)
779                       {
780                         thread_num = strtol ((const char *) ++p1, &p_temp, 16);
781                         p = (unsigned char *)p_temp;
782                       }
783                   }
784                 else
785                   {
786                     p = p1;
787
788                     if (*p++ != ':')
789                       warning ("Malformed packet (missing colon): %s\n\
790 Packet: '%s'\n",
791                                p, buf);
792
793                     if (regno >= NUM_REGS)
794                       warning ("Remote sent bad register number %ld: %s\n\
795 Packet: '%s'\n",
796                                regno, p, buf);
797
798                     for (i = 0; i < REGISTER_RAW_SIZE (regno); i++)
799                       {
800                         if (p[0] == 0 || p[1] == 0)
801                           warning ("Remote reply is too short: %s", buf);
802                         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
803                         p += 2;
804                       }
805                     supply_register (regno, regs);
806                   }
807
808                 if (*p++ != ';')
809                   warning ("Remote register badly formatted: %s", buf);
810               }
811           }
812           /* fall through */
813         case 'S':               /* Old style status, just signal only */
814           status->kind = TARGET_WAITKIND_STOPPED;
815           status->value.sig = (enum target_signal)
816             (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
817
818           goto got_status;
819         case 'W':               /* Target exited */
820           {
821             /* The remote process exited.  */
822             status->kind = TARGET_WAITKIND_EXITED;
823             status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
824             goto got_status;
825           }
826         case 'X':
827           status->kind = TARGET_WAITKIND_SIGNALLED;
828           status->value.sig = (enum target_signal)
829             (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
830           kill_kludge = 1;
831
832           goto got_status;
833         case 'O':               /* Console output */
834           for (p = buf + 1; *p; p +=2) 
835             {
836               char tb[2];
837               char c = fromhex (p[0]) * 16 + fromhex (p[1]);
838               tb[0] = c;
839               tb[1] = 0;
840               if (target_output_hook)
841                 target_output_hook (tb);
842               else 
843                 fputs_filtered (tb, gdb_stdout);
844             }
845           continue;
846         case '\0':
847           if (last_sent_signal != TARGET_SIGNAL_0)
848             {
849               /* Zero length reply means that we tried 'S' or 'C' and
850                  the remote system doesn't support it.  */
851               target_terminal_ours_for_output ();
852               printf_filtered
853                 ("Can't send signals to this remote system.  %s not sent.\n",
854                  target_signal_to_name (last_sent_signal));
855               last_sent_signal = TARGET_SIGNAL_0;
856               target_terminal_inferior ();
857
858               strcpy ((char *) buf, last_sent_step ? "s" : "c");
859               putpkt ((char *) buf);
860               continue;
861             }
862           /* else fallthrough */
863         default:
864           warning ("Invalid remote reply: %s", buf);
865           continue;
866         }
867     }
868  got_status:
869   if (thread_num != -1)
870     {
871       /* Initial thread value can only be acquired via wait, so deal with
872          this marker which is used before the first thread value is
873          acquired.  */
874       if (inferior_pid == 42000)
875         {
876           inferior_pid = thread_num;
877           add_thread (inferior_pid);
878         }
879       return thread_num;
880     }
881   return inferior_pid;
882 }
883
884 /* Number of bytes of registers this stub implements.  */
885 static int register_bytes_found;
886
887 /* Read the remote registers into the block REGS.  */
888 /* Currently we just read all the registers, so we don't use regno.  */
889 /* ARGSUSED */
890 static void
891 remote_fetch_registers (regno)
892      int regno;
893 {
894   char buf[PBUFSIZ];
895   int i;
896   char *p;
897   char regs[REGISTER_BYTES];
898
899   set_thread (inferior_pid, 1);
900
901   sprintf (buf, "g");
902   remote_send (buf);
903
904   /* Unimplemented registers read as all bits zero.  */
905   memset (regs, 0, REGISTER_BYTES);
906
907   /* We can get out of synch in various cases.  If the first character
908      in the buffer is not a hex character, assume that has happened
909      and try to fetch another packet to read.  */
910   while ((buf[0] < '0' || buf[0] > '9')
911          && (buf[0] < 'a' || buf[0] > 'f'))
912     {
913       if (remote_debug)
914         printf_unfiltered ("Bad register packet; fetching a new packet\n");
915       getpkt (buf, 0);
916     }
917
918   /* Reply describes registers byte by byte, each byte encoded as two
919      hex characters.  Suck them all up, then supply them to the
920      register cacheing/storage mechanism.  */
921
922   p = buf;
923   for (i = 0; i < REGISTER_BYTES; i++)
924     {
925       if (p[0] == 0)
926         break;
927       if (p[1] == 0)
928         {
929           warning ("Remote reply is of odd length: %s", buf);
930           /* Don't change register_bytes_found in this case, and don't
931              print a second warning.  */
932           goto supply_them;
933         }
934       regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
935       p += 2;
936     }
937
938   if (i != register_bytes_found)
939     {
940       register_bytes_found = i;
941 #ifdef REGISTER_BYTES_OK
942       if (!REGISTER_BYTES_OK (i))
943         warning ("Remote reply is too short: %s", buf);
944 #endif
945     }
946
947  supply_them:
948   for (i = 0; i < NUM_REGS; i++)
949     supply_register (i, &regs[REGISTER_BYTE(i)]);
950 }
951
952 /* Prepare to store registers.  Since we may send them all (using a
953    'G' request), we have to read out the ones we don't want to change
954    first.  */
955
956 static void 
957 remote_prepare_to_store ()
958 {
959   /* Make sure the entire registers array is valid.  */
960   read_register_bytes (0, (char *)NULL, REGISTER_BYTES);
961 }
962
963 /* Store register REGNO, or all registers if REGNO == -1, from the contents
964    of REGISTERS.  FIXME: ignores errors.  */
965
966 static void
967 remote_store_registers (regno)
968      int regno;
969 {
970   char buf[PBUFSIZ];
971   int i;
972   char *p;
973
974   set_thread (inferior_pid, 1);
975
976   if (regno >= 0 && stub_supports_P)
977     {
978       /* Try storing a single register.  */
979       char *regp;
980
981       sprintf (buf, "P%x=", regno);
982       p = buf + strlen (buf);
983       regp = &registers[REGISTER_BYTE (regno)];
984       for (i = 0; i < REGISTER_RAW_SIZE (regno); ++i)
985         {
986           *p++ = tohex ((regp[i] >> 4) & 0xf);
987           *p++ = tohex (regp[i] & 0xf);
988         }
989       *p = '\0';
990       remote_send (buf);
991       if (buf[0] != '\0')
992         {
993           /* The stub understands the 'P' request.  We are done.  */
994           return;
995         }
996
997       /* The stub does not support the 'P' request.  Use 'G' instead,
998          and don't try using 'P' in the future (it will just waste our
999          time).  */
1000       stub_supports_P = 0;
1001     }
1002
1003   buf[0] = 'G';
1004
1005   /* Command describes registers byte by byte,
1006      each byte encoded as two hex characters.  */
1007
1008   p = buf + 1;
1009   /* remote_prepare_to_store insures that register_bytes_found gets set.  */
1010   for (i = 0; i < register_bytes_found; i++)
1011     {
1012       *p++ = tohex ((registers[i] >> 4) & 0xf);
1013       *p++ = tohex (registers[i] & 0xf);
1014     }
1015   *p = '\0';
1016
1017   remote_send (buf);
1018 }
1019
1020 /* 
1021    Use of the data cache *used* to be disabled because it loses for looking at
1022    and changing hardware I/O ports and the like.  Accepting `volatile'
1023    would perhaps be one way to fix it.  Another idea would be to use the
1024    executable file for the text segment (for all SEC_CODE sections?
1025    For all SEC_READONLY sections?).  This has problems if you want to
1026    actually see what the memory contains (e.g. self-modifying code,
1027    clobbered memory, user downloaded the wrong thing).  
1028
1029    Because it speeds so much up, it's now enabled, if you're playing
1030    with registers you turn it of (set remotecache 0)
1031 */
1032
1033 /* Read a word from remote address ADDR and return it.
1034    This goes through the data cache.  */
1035
1036 #if 0   /* unused? */
1037 static int
1038 remote_fetch_word (addr)
1039      CORE_ADDR addr;
1040 {
1041   return dcache_fetch (remote_dcache, addr);
1042 }
1043
1044 /* Write a word WORD into remote address ADDR.
1045    This goes through the data cache.  */
1046
1047 static void
1048 remote_store_word (addr, word)
1049      CORE_ADDR addr;
1050      int word;
1051 {
1052   dcache_poke (remote_dcache, addr, word);
1053 }
1054 #endif  /* 0 (unused?) */
1055
1056 \f
1057 /* Write memory data directly to the remote machine.
1058    This does not inform the data cache; the data cache uses this.
1059    MEMADDR is the address in the remote memory space.
1060    MYADDR is the address of the buffer in our space.
1061    LEN is the number of bytes.
1062
1063    Returns number of bytes transferred, or 0 for error.  */
1064
1065 static int
1066 remote_write_bytes (memaddr, myaddr, len)
1067      CORE_ADDR memaddr;
1068      char *myaddr;
1069      int len;
1070 {
1071   char buf[PBUFSIZ];
1072   int i;
1073   char *p;
1074   int done;
1075   /* Chop the transfer down if necessary */
1076
1077   done = 0;
1078   while (done < len)
1079     {
1080       int todo = len - done;
1081       int cando = min(remote_write_size, PBUFSIZ) / 2 - 32; /* num bytes that will fit */
1082
1083       if (todo > cando)
1084         todo = cando;
1085
1086       /* FIXME-32x64: Need a version of print_address_numeric which puts the
1087          result in a buffer like sprintf.  */
1088       sprintf (buf, "M%lx,%x:", (unsigned long) memaddr + done, todo);
1089
1090       /* We send target system values byte by byte, in increasing byte addresses,
1091          each byte encoded as two hex characters.  */
1092
1093       p = buf + strlen (buf);
1094       for (i = 0; i < todo; i++)
1095         {
1096           *p++ = tohex ((myaddr[i + done] >> 4) & 0xf);
1097           *p++ = tohex (myaddr[i + done] & 0xf);
1098         }
1099       *p = '\0';
1100
1101       putpkt (buf);
1102       getpkt (buf, 0);
1103
1104       if (buf[0] == 'E')
1105         {
1106           /* There is no correspondance between what the remote protocol uses
1107              for errors and errno codes.  We would like a cleaner way of
1108              representing errors (big enough to include errno codes, bfd_error
1109              codes, and others).  But for now just return EIO.  */
1110           errno = EIO;
1111           return 0;
1112         }
1113       done += todo;
1114     }
1115   return len;
1116 }
1117
1118 /* Read memory data directly from the remote machine.
1119    This does not use the data cache; the data cache uses this.
1120    MEMADDR is the address in the remote memory space.
1121    MYADDR is the address of the buffer in our space.
1122    LEN is the number of bytes.
1123
1124    Returns number of bytes transferred, or 0 for error.  */
1125
1126 static int
1127 remote_read_bytes (memaddr, myaddr, len)
1128      CORE_ADDR memaddr;
1129      char *myaddr;
1130      int len;
1131 {
1132   char buf[PBUFSIZ];
1133   int i;
1134   char *p;
1135   int done;
1136   /* Chop transfer down if neccessary */
1137
1138 #if 0
1139   /* FIXME: This is wrong for larger packets */
1140   if (len > PBUFSIZ / 2 - 1)
1141     abort ();
1142 #endif
1143   done = 0;
1144   while (done < len)
1145     {
1146       int todo = len - done;
1147       int cando = PBUFSIZ / 2 - 32; /* number of bytes that will fit. */
1148       if (todo > cando)
1149         todo = cando;
1150
1151       /* FIXME-32x64: Need a version of print_address_numeric which puts the
1152          result in a buffer like sprintf.  */
1153       sprintf (buf, "m%lx,%x", (unsigned long) memaddr + done, todo);
1154       putpkt (buf);
1155       getpkt (buf, 0);
1156
1157       if (buf[0] == 'E')
1158         {
1159           /* There is no correspondance between what the remote protocol uses
1160              for errors and errno codes.  We would like a cleaner way of
1161              representing errors (big enough to include errno codes, bfd_error
1162              codes, and others).  But for now just return EIO.  */
1163           errno = EIO;
1164           return 0;
1165         }
1166
1167   /* Reply describes memory byte by byte,
1168      each byte encoded as two hex characters.  */
1169
1170       p = buf;
1171       for (i = 0; i < todo; i++)
1172         {
1173           if (p[0] == 0 || p[1] == 0)
1174             /* Reply is short.  This means that we were able to read only part
1175                of what we wanted to.  */
1176             return i + done;
1177           myaddr[i + done] = fromhex (p[0]) * 16 + fromhex (p[1]);
1178           p += 2;
1179         }
1180       done += todo;
1181     }
1182   return len;
1183 }
1184 \f
1185 /* Read or write LEN bytes from inferior memory at MEMADDR, transferring
1186    to or from debugger address MYADDR.  Write to inferior if SHOULD_WRITE is
1187    nonzero.  Returns length of data written or read; 0 for error.  */
1188
1189 /* ARGSUSED */
1190 static int
1191 remote_xfer_memory(memaddr, myaddr, len, should_write, target)
1192      CORE_ADDR memaddr;
1193      char *myaddr;
1194      int len;
1195      int should_write;
1196      struct target_ops *target;                 /* ignored */
1197 {
1198   return dcache_xfer_memory (remote_dcache, memaddr, myaddr, len, should_write);
1199 }
1200
1201    
1202 #if 0
1203 /* Enable after 4.12.  */
1204
1205 void
1206 remote_search (len, data, mask, startaddr, increment, lorange, hirange
1207                addr_found, data_found)
1208      int len;
1209      char *data;
1210      char *mask;
1211      CORE_ADDR startaddr;
1212      int increment;
1213      CORE_ADDR lorange;
1214      CORE_ADDR hirange;
1215      CORE_ADDR *addr_found;
1216      char *data_found;
1217 {
1218   if (increment == -4 && len == 4)
1219     {
1220       long mask_long, data_long;
1221       long data_found_long;
1222       CORE_ADDR addr_we_found;
1223       char buf[PBUFSIZ];
1224       long returned_long[2];
1225       char *p;
1226
1227       mask_long = extract_unsigned_integer (mask, len);
1228       data_long = extract_unsigned_integer (data, len);
1229       sprintf (buf, "t%x:%x,%x", startaddr, data_long, mask_long);
1230       putpkt (buf);
1231       getpkt (buf, 0);
1232       if (buf[0] == '\0')
1233         {
1234           /* The stub doesn't support the 't' request.  We might want to
1235              remember this fact, but on the other hand the stub could be
1236              switched on us.  Maybe we should remember it only until
1237              the next "target remote".  */
1238           generic_search (len, data, mask, startaddr, increment, lorange,
1239                           hirange, addr_found, data_found);
1240           return;
1241         }
1242
1243       if (buf[0] == 'E')
1244         /* There is no correspondance between what the remote protocol uses
1245            for errors and errno codes.  We would like a cleaner way of
1246            representing errors (big enough to include errno codes, bfd_error
1247            codes, and others).  But for now just use EIO.  */
1248         memory_error (EIO, startaddr);
1249       p = buf;
1250       addr_we_found = 0;
1251       while (*p != '\0' && *p != ',')
1252         addr_we_found = (addr_we_found << 4) + fromhex (*p++);
1253       if (*p == '\0')
1254         error ("Protocol error: short return for search");
1255
1256       data_found_long = 0;
1257       while (*p != '\0' && *p != ',')
1258         data_found_long = (data_found_long << 4) + fromhex (*p++);
1259       /* Ignore anything after this comma, for future extensions.  */
1260
1261       if (addr_we_found < lorange || addr_we_found >= hirange)
1262         {
1263           *addr_found = 0;
1264           return;
1265         }
1266
1267       *addr_found = addr_we_found;
1268       *data_found = store_unsigned_integer (data_we_found, len);
1269       return;
1270     }
1271   generic_search (len, data, mask, startaddr, increment, lorange,
1272                   hirange, addr_found, data_found);
1273 }
1274 #endif /* 0 */
1275 \f
1276 static void
1277 remote_files_info (ignore)
1278      struct target_ops *ignore;
1279 {
1280   puts_filtered ("Debugging a target over a serial line.\n");
1281 }
1282 \f
1283 /* Stuff for dealing with the packets which are part of this protocol.
1284    See comment at top of file for details.  */
1285
1286 /* Read a single character from the remote end, masking it down to 7 bits. */
1287
1288 static int
1289 readchar (timeout)
1290      int timeout;
1291 {
1292   int ch;
1293
1294   ch = SERIAL_READCHAR (remote_desc, timeout);
1295
1296   switch (ch)
1297     {
1298     case SERIAL_EOF:
1299       error ("Remote connection closed");
1300     case SERIAL_ERROR:
1301       perror_with_name ("Remote communication error");
1302     case SERIAL_TIMEOUT:
1303       return ch;
1304     default:
1305       return ch & 0x7f;
1306     }
1307 }
1308
1309 /* Send the command in BUF to the remote machine,
1310    and read the reply into BUF.
1311    Report an error if we get an error reply.  */
1312
1313 static void
1314 remote_send (buf)
1315      char *buf;
1316 {
1317   putpkt (buf);
1318   getpkt (buf, 0);
1319
1320   if (buf[0] == 'E')
1321     error ("Remote failure reply: %s", buf);
1322 }
1323
1324 /* Send a packet to the remote machine, with error checking.
1325    The data of the packet is in BUF.  */
1326
1327 static int
1328 putpkt (buf)
1329      char *buf;
1330 {
1331   int i;
1332   unsigned char csum = 0;
1333   char buf2[PBUFSIZ];
1334   int cnt = strlen (buf);
1335   int ch;
1336   int tcount = 0;
1337   char *p;
1338
1339   /* Copy the packet into buffer BUF2, encapsulating it
1340      and giving it a checksum.  */
1341
1342   if (cnt > (int) sizeof (buf2) - 5)            /* Prosanity check */
1343     abort();
1344
1345   p = buf2;
1346   *p++ = '$';
1347
1348   for (i = 0; i < cnt; i++)
1349     {
1350       csum += buf[i];
1351       *p++ = buf[i];
1352     }
1353   *p++ = '#';
1354   *p++ = tohex ((csum >> 4) & 0xf);
1355   *p++ = tohex (csum & 0xf);
1356
1357   /* Send it over and over until we get a positive ack.  */
1358
1359   while (1)
1360     {
1361       int started_error_output = 0;
1362
1363       if (remote_debug)
1364         {
1365           *p = '\0';
1366           printf_unfiltered ("Sending packet: %s...", buf2);
1367           gdb_flush(gdb_stdout);
1368         }
1369       if (SERIAL_WRITE (remote_desc, buf2, p - buf2))
1370         perror_with_name ("putpkt: write failed");
1371
1372       /* read until either a timeout occurs (-2) or '+' is read */
1373       while (1)
1374         {
1375           ch = readchar (remote_timeout);
1376
1377           if (remote_debug)
1378             {
1379               switch (ch)
1380                 {
1381                 case '+':
1382                 case SERIAL_TIMEOUT:
1383                 case '$':
1384                   if (started_error_output)
1385                     {
1386                       putchar_unfiltered ('\n');
1387                       started_error_output = 0;
1388                     }
1389                 }
1390             }
1391
1392           switch (ch)
1393             {
1394             case '+':
1395               if (remote_debug)
1396                 printf_unfiltered("Ack\n");
1397               return 1;
1398             case SERIAL_TIMEOUT:
1399               tcount ++;
1400               if (tcount > 3)
1401                 return 0;
1402               break;            /* Retransmit buffer */
1403             case '$':
1404               {
1405                 char junkbuf[PBUFSIZ];
1406
1407               /* It's probably an old response, and we're out of sync.  Just
1408                  gobble up the packet and ignore it.  */
1409                 getpkt (junkbuf, 0);
1410                 continue;               /* Now, go look for + */
1411               }
1412             default:
1413               if (remote_debug)
1414                 {
1415                   if (!started_error_output)
1416                     {
1417                       started_error_output = 1;
1418                       printf_unfiltered ("putpkt: Junk: ");
1419                     }
1420                   putchar_unfiltered (ch & 0177);
1421                 }
1422               continue;
1423             }
1424           break;                /* Here to retransmit */
1425         }
1426
1427 #if 0
1428       /* This is wrong.  If doing a long backtrace, the user should be
1429          able to get out next time we call QUIT, without anything as violent
1430          as interrupt_query.  If we want to provide a way out of here
1431          without getting to the next QUIT, it should be based on hitting
1432          ^C twice as in remote_wait.  */
1433       if (quit_flag)
1434         {
1435           quit_flag = 0;
1436           interrupt_query ();
1437         }
1438 #endif
1439     }
1440 }
1441
1442 /* Come here after finding the start of the frame.  Collect the rest into BUF,
1443    verifying the checksum, length, and handling run-length compression.
1444    Returns 0 on any error, 1 on success.  */
1445
1446 static int
1447 read_frame (buf)
1448      char *buf;
1449 {
1450   unsigned char csum;
1451   char *bp;
1452   int c;
1453
1454   csum = 0;
1455   bp = buf;
1456
1457   while (1)
1458     {
1459       c = readchar (remote_timeout);
1460
1461       switch (c)
1462         {
1463         case SERIAL_TIMEOUT:
1464           if (remote_debug)
1465             puts_filtered ("Timeout in mid-packet, retrying\n");
1466           return 0;
1467         case '$':
1468           if (remote_debug)
1469             puts_filtered ("Saw new packet start in middle of old one\n");
1470           return 0;             /* Start a new packet, count retries */
1471         case '#':
1472           {
1473             unsigned char pktcsum;
1474
1475             *bp = '\000';
1476
1477             pktcsum = fromhex (readchar (remote_timeout)) << 4;
1478             pktcsum |= fromhex (readchar (remote_timeout));
1479
1480             if (csum == pktcsum)
1481               return 1;
1482
1483             if (remote_debug) 
1484               {
1485                 printf_filtered ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
1486                                  pktcsum, csum);
1487                 puts_filtered (buf);
1488                 puts_filtered ("\n");
1489               }
1490             return 0;
1491           }
1492         case '*':               /* Run length encoding */
1493           csum += c;
1494           c = readchar (remote_timeout);
1495           csum += c;
1496           c = c - ' ' + 3;      /* Compute repeat count */
1497
1498
1499           if (c > 0 && c < 255 && bp + c - 1 < buf + PBUFSIZ - 1)
1500             {
1501               memset (bp, *(bp - 1), c);
1502               bp += c;
1503               continue;
1504             }
1505
1506           *bp = '\0';
1507           printf_filtered ("Repeat count %d too large for buffer: ", c);
1508           puts_filtered (buf);
1509           puts_filtered ("\n");
1510           return 0;
1511
1512         default:
1513           if (bp < buf + PBUFSIZ - 1)
1514             {
1515               *bp++ = c;
1516               csum += c;
1517               continue;
1518             }
1519
1520           *bp = '\0';
1521           puts_filtered ("Remote packet too long: ");
1522           puts_filtered (buf);
1523           puts_filtered ("\n");
1524
1525           return 0;
1526         }
1527     }
1528 }
1529
1530 /* Read a packet from the remote machine, with error checking,
1531    and store it in BUF.  BUF is expected to be of size PBUFSIZ.
1532    If FOREVER, wait forever rather than timing out; this is used
1533    while the target is executing user code.  */
1534
1535 static void
1536 getpkt (buf, forever)
1537      char *buf;
1538      int forever;
1539 {
1540   int c;
1541   int tries;
1542   int timeout;
1543   int val;
1544
1545   strcpy (buf,"timeout");
1546
1547   if (forever)
1548     {
1549 #ifdef MAINTENANCE_CMDS
1550       timeout = watchdog > 0 ? watchdog : -1;
1551 #else
1552       timeout = -1;
1553 #endif
1554     }
1555
1556   else
1557     timeout = remote_timeout;
1558
1559 #define MAX_TRIES 3
1560
1561   for (tries = 1; tries <= MAX_TRIES; tries++)
1562     {
1563       /* This can loop forever if the remote side sends us characters
1564          continuously, but if it pauses, we'll get a zero from readchar
1565          because of timeout.  Then we'll count that as a retry.  */
1566
1567       /* Note that we will only wait forever prior to the start of a packet.
1568          After that, we expect characters to arrive at a brisk pace.  They
1569          should show up within remote_timeout intervals.  */
1570
1571       do
1572         {
1573           c = readchar (timeout);
1574
1575           if (c == SERIAL_TIMEOUT)
1576             {
1577 #ifdef MAINTENANCE_CMDS
1578               if (forever)      /* Watchdog went off.  Kill the target. */
1579                 {
1580                   target_mourn_inferior ();
1581                   error ("Watchdog has expired.  Target detached.\n");
1582                 }
1583 #endif
1584               if (remote_debug)
1585                 puts_filtered ("Timed out.\n");
1586               goto retry;
1587             }
1588         }
1589       while (c != '$');
1590
1591       /* We've found the start of a packet, now collect the data.  */
1592
1593       val = read_frame (buf);
1594
1595       if (val == 1)
1596         {
1597           if (remote_debug)
1598             fprintf_unfiltered (gdb_stderr, "Packet received: %s\n", buf);
1599           SERIAL_WRITE (remote_desc, "+", 1);
1600           return;
1601         }
1602
1603       /* Try the whole thing again.  */
1604     retry:
1605       SERIAL_WRITE (remote_desc, "-", 1);
1606     }
1607
1608   /* We have tried hard enough, and just can't receive the packet.  Give up. */
1609
1610   printf_unfiltered ("Ignoring packet error, continuing...\n");
1611   SERIAL_WRITE (remote_desc, "+", 1);
1612 }
1613 \f
1614 static void
1615 remote_kill ()
1616 {
1617   /* For some mysterious reason, wait_for_inferior calls kill instead of
1618      mourn after it gets TARGET_WAITKIND_SIGNALLED.  Work around it.  */
1619   if (kill_kludge)
1620     {
1621       kill_kludge = 0;
1622       target_mourn_inferior ();
1623       return;
1624     }
1625
1626   /* Use catch_errors so the user can quit from gdb even when we aren't on
1627      speaking terms with the remote system.  */
1628   catch_errors (putpkt, "k", "", RETURN_MASK_ERROR);
1629
1630   /* Don't wait for it to die.  I'm not really sure it matters whether
1631      we do or not.  For the existing stubs, kill is a noop.  */
1632   target_mourn_inferior ();
1633 }
1634
1635 static void
1636 remote_mourn ()
1637 {
1638   remote_mourn_1 (&remote_ops);
1639 }
1640
1641 static void
1642 extended_remote_mourn ()
1643 {
1644   /* We do _not_ want to mourn the target like this; this will
1645      remove the extended remote target  from the target stack,
1646      and the next time the user says "run" it'll fail. 
1647
1648      FIXME: What is the right thing to do here?  */
1649 #if 0
1650   remote_mourn_1 (&extended_remote_ops);
1651 #endif
1652 }
1653
1654 /* Worker function for remote_mourn.  */
1655 static void
1656 remote_mourn_1 (target)
1657      struct target_ops *target;
1658 {
1659   unpush_target (target);
1660   generic_mourn_inferior ();
1661 }
1662
1663 /* In the extended protocol we want to be able to do things like
1664    "run" and have them basically work as expected.  So we need
1665    a special create_inferior function. 
1666
1667    FIXME: One day add support for changing the exec file
1668    we're debugging, arguments and an environment.  */
1669
1670 static void
1671 extended_remote_create_inferior (exec_file, args, env)
1672      char *exec_file;
1673      char *args;
1674      char **env;
1675 {
1676   /* Rip out the breakpoints; we'll reinsert them after restarting
1677      the remote server.  */
1678   remove_breakpoints ();
1679
1680   /* Now restart the remote server.  */
1681   extended_remote_restart ();
1682
1683   /* Now put the breakpoints back in.  This way we're safe if the
1684      restart function works via a unix fork on the remote side.  */
1685   insert_breakpoints ();
1686
1687   /* Clean up from the last time we were running.  */
1688   clear_proceed_status ();
1689
1690   /* Let the remote process run.  */
1691   proceed (-1, TARGET_SIGNAL_0, 0);
1692 }
1693
1694 \f
1695 /* On some machines, e.g. 68k, we may use a different breakpoint instruction
1696    than other targets; in those use REMOTE_BREAKPOINT instead of just
1697    BREAKPOINT.  Also, bi-endian targets may define LITTLE_REMOTE_BREAKPOINT
1698    and BIG_REMOTE_BREAKPOINT.  If none of these are defined, we just call
1699    the standard routines that are in mem-break.c.  */
1700
1701 /* FIXME, these ought to be done in a more dynamic fashion.  For instance,
1702    the choice of breakpoint instruction affects target program design and
1703    vice versa, and by making it user-tweakable, the special code here
1704    goes away and we need fewer special GDB configurations.  */
1705
1706 #if defined (LITTLE_REMOTE_BREAKPOINT) && defined (BIG_REMOTE_BREAKPOINT) && !defined(REMOTE_BREAKPOINT)
1707 #define REMOTE_BREAKPOINT
1708 #endif
1709
1710 #ifdef REMOTE_BREAKPOINT
1711
1712 /* If the target isn't bi-endian, just pretend it is.  */
1713 #if !defined (LITTLE_REMOTE_BREAKPOINT) && !defined (BIG_REMOTE_BREAKPOINT)
1714 #define LITTLE_REMOTE_BREAKPOINT REMOTE_BREAKPOINT
1715 #define BIG_REMOTE_BREAKPOINT REMOTE_BREAKPOINT
1716 #endif
1717
1718 static unsigned char big_break_insn[] = BIG_REMOTE_BREAKPOINT;
1719 static unsigned char little_break_insn[] = LITTLE_REMOTE_BREAKPOINT;
1720
1721 #endif /* REMOTE_BREAKPOINT */
1722
1723 /* Insert a breakpoint on targets that don't have any better breakpoint
1724    support.  We read the contents of the target location and stash it,
1725    then overwrite it with a breakpoint instruction.  ADDR is the target
1726    location in the target machine.  CONTENTS_CACHE is a pointer to 
1727    memory allocated for saving the target contents.  It is guaranteed
1728    by the caller to be long enough to save sizeof BREAKPOINT bytes (this
1729    is accomplished via BREAKPOINT_MAX).  */
1730
1731 static int
1732 remote_insert_breakpoint (addr, contents_cache)
1733      CORE_ADDR addr;
1734      char *contents_cache;
1735 {
1736 #ifdef REMOTE_BREAKPOINT
1737   int val;
1738
1739   val = target_read_memory (addr, contents_cache, sizeof big_break_insn);
1740
1741   if (val == 0)
1742     {
1743       if (TARGET_BYTE_ORDER == BIG_ENDIAN)
1744         val = target_write_memory (addr, (char *) big_break_insn,
1745                                    sizeof big_break_insn);
1746       else
1747         val = target_write_memory (addr, (char *) little_break_insn,
1748                                    sizeof little_break_insn);
1749     }
1750
1751   return val;
1752 #else
1753   return memory_insert_breakpoint (addr, contents_cache);
1754 #endif /* REMOTE_BREAKPOINT */
1755 }
1756
1757 static int
1758 remote_remove_breakpoint (addr, contents_cache)
1759      CORE_ADDR addr;
1760      char *contents_cache;
1761 {
1762 #ifdef REMOTE_BREAKPOINT
1763   return target_write_memory (addr, contents_cache, sizeof big_break_insn);
1764 #else
1765   return memory_remove_breakpoint (addr, contents_cache);
1766 #endif /* REMOTE_BREAKPOINT */
1767 }
1768 \f
1769 /* Define the target subroutine names */
1770
1771 struct target_ops remote_ops = {
1772   "remote",                     /* to_shortname */
1773   "Remote serial target in gdb-specific protocol",      /* to_longname */
1774   "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
1775 Specify the serial device it is connected to (e.g. /dev/ttya).",  /* to_doc */
1776   remote_open,                  /* to_open */
1777   remote_close,                 /* to_close */
1778   NULL,                         /* to_attach */
1779   remote_detach,                /* to_detach */
1780   remote_resume,                /* to_resume */
1781   remote_wait,                  /* to_wait */
1782   remote_fetch_registers,       /* to_fetch_registers */
1783   remote_store_registers,       /* to_store_registers */
1784   remote_prepare_to_store,      /* to_prepare_to_store */
1785   remote_xfer_memory,           /* to_xfer_memory */
1786   remote_files_info,            /* to_files_info */
1787   remote_insert_breakpoint,     /* to_insert_breakpoint */
1788   remote_remove_breakpoint,     /* to_remove_breakpoint */
1789   NULL,                         /* to_terminal_init */
1790   NULL,                         /* to_terminal_inferior */
1791   NULL,                         /* to_terminal_ours_for_output */
1792   NULL,                         /* to_terminal_ours */
1793   NULL,                         /* to_terminal_info */
1794   remote_kill,                  /* to_kill */
1795   generic_load,                 /* to_load */
1796   NULL,                         /* to_lookup_symbol */
1797   NULL,                         /* to_create_inferior */
1798   remote_mourn,                 /* to_mourn_inferior */
1799   0,                            /* to_can_run */
1800   0,                            /* to_notice_signals */
1801   remote_thread_alive,          /* to_thread_alive */
1802   0,                            /* to_stop */
1803   process_stratum,              /* to_stratum */
1804   NULL,                         /* to_next */
1805   1,                            /* to_has_all_memory */
1806   1,                            /* to_has_memory */
1807   1,                            /* to_has_stack */
1808   1,                            /* to_has_registers */
1809   1,                            /* to_has_execution */
1810   NULL,                         /* sections */
1811   NULL,                         /* sections_end */
1812   OPS_MAGIC                     /* to_magic */
1813 };
1814
1815 struct target_ops extended_remote_ops = {
1816   "extended-remote",                    /* to_shortname */
1817   "Extended remote serial target in gdb-specific protocol",/* to_longname */
1818   "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
1819 Specify the serial device it is connected to (e.g. /dev/ttya).",  /* to_doc */
1820   extended_remote_open,                 /* to_open */
1821   remote_close,                 /* to_close */
1822   NULL,                         /* to_attach */
1823   remote_detach,                /* to_detach */
1824   remote_resume,                /* to_resume */
1825   remote_wait,                  /* to_wait */
1826   remote_fetch_registers,       /* to_fetch_registers */
1827   remote_store_registers,       /* to_store_registers */
1828   remote_prepare_to_store,      /* to_prepare_to_store */
1829   remote_xfer_memory,           /* to_xfer_memory */
1830   remote_files_info,            /* to_files_info */
1831
1832   remote_insert_breakpoint,     /* to_insert_breakpoint */
1833   remote_remove_breakpoint,     /* to_remove_breakpoint */
1834
1835   NULL,                         /* to_terminal_init */
1836   NULL,                         /* to_terminal_inferior */
1837   NULL,                         /* to_terminal_ours_for_output */
1838   NULL,                         /* to_terminal_ours */
1839   NULL,                         /* to_terminal_info */
1840   remote_kill,                  /* to_kill */
1841   generic_load,                 /* to_load */
1842   NULL,                         /* to_lookup_symbol */
1843   extended_remote_create_inferior,/* to_create_inferior */
1844   extended_remote_mourn,        /* to_mourn_inferior */
1845   0,                            /* to_can_run */
1846   0,                            /* to_notice_signals */
1847   remote_thread_alive,          /* to_thread_alive */
1848   0,                            /* to_stop */
1849   process_stratum,              /* to_stratum */
1850   NULL,                         /* to_next */
1851   1,                            /* to_has_all_memory */
1852   1,                            /* to_has_memory */
1853   1,                            /* to_has_stack */
1854   1,                            /* to_has_registers */
1855   1,                            /* to_has_execution */
1856   NULL,                         /* sections */
1857   NULL,                         /* sections_end */
1858   OPS_MAGIC                     /* to_magic */
1859 };
1860
1861 void
1862 _initialize_remote ()
1863 {
1864   add_target (&remote_ops);
1865   add_target (&extended_remote_ops);
1866
1867   add_show_from_set (add_set_cmd ("remotetimeout", no_class,
1868                                   var_integer, (char *)&remote_timeout,
1869                                   "Set timeout value for remote read.\n", &setlist),
1870                      &showlist);
1871
1872   add_show_from_set (add_set_cmd ("remotebreak", no_class,
1873                                   var_integer, (char *)&remote_break,
1874                                   "Set whether to send break if interrupted.\n", &setlist),
1875                      &showlist);
1876
1877   add_show_from_set (add_set_cmd ("remotewritesize", no_class,
1878                                   var_integer, (char *)&remote_write_size,
1879                                   "Set the maximum number of bytes in each memory write packet.\n", &setlist),
1880                      &showlist);
1881 }