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