Trying to fix repository after cvs breakage...
[external/binutils.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2    Copyright 1988, 1991, 1992, 1993 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., 675 Mass Ave, Cambridge, MA 02139, 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 '#'
29
30         CSUM1 and CSUM2 are ascii hex representation of an 8-bit 
31         checksum of <data>, the most significant nibble is sent first.
32         the hex digits 0-9,a-f are used.
33
34    Receiver responds with:
35
36         +       - if CSUM is correct and ready for next packet
37         -       - if CSUM is incorrect
38
39    <data> is as follows:
40    All values are encoded in ascii hex digits.
41
42         Request         Packet
43
44         read registers  g
45         reply           XX....X         Each byte of register data
46                                         is described by two hex digits.
47                                         Registers are in the internal order
48                                         for GDB, and the bytes in a register
49                                         are in the same order the machine uses.
50                         or ENN          for an error.
51
52         write regs      GXX..XX         Each byte of register data
53                                         is described by two hex digits.
54         reply           OK              for success
55                         ENN             for an error
56
57         read mem        mAA..AA,LLLL    AA..AA is address, LLLL is length.
58         reply           XX..XX          XX..XX is mem contents
59                                         Can be fewer bytes than requested
60                                         if able to read only part of the data.
61                         or ENN          NN is errno
62
63         write mem       MAA..AA,LLLL:XX..XX
64                                         AA..AA is address,
65                                         LLLL is number of bytes,
66                                         XX..XX is data
67         reply           OK              for success
68                         ENN             for an error (this includes the case
69                                         where only part of the data was
70                                         written).
71
72         cont            cAA..AA         AA..AA is address to resume
73                                         If AA..AA is omitted,
74                                         resume at same address.
75
76         step            sAA..AA         AA..AA is address to resume
77                                         If AA..AA is omitted,
78                                         resume at same address.
79
80         last signal     ?               Reply the current reason for stopping.
81                                         This is the same reply as is generated
82                                         for step or cont : SAA where AA is the
83                                         signal number.
84
85         There is no immediate reply to step or cont.
86         The reply comes when the machine stops.
87         It is           SAA             AA is the "signal number"
88
89         or...           TAAn...:r...;n:r...;n...:r...;
90                                         AA = signal number
91                                         n... = register number
92                                         r... = register contents
93         or...           WAA             The process extited, and AA is
94                                         the exit status.  This is only
95                                         applicable for certains sorts of
96                                         targets.
97         or...           NAATT;DD;BB     Relocate the object file.
98                                         AA = signal number
99                                         TT = text address
100                                         DD = data address
101                                         BB = bss address
102                                         This is used by the NLM stub,
103                                         which is why it only has three
104                                         addresses rather than one per
105                                         section: the NLM stub always
106                                         sees only three sections, even
107                                         though gdb may see more.
108
109         kill request    k
110
111         toggle debug    d               toggle debug flag (see 386 & 68k stubs)
112         reset           r               reset -- see sparc stub.
113         reserved        <other>         On other requests, the stub should
114                                         ignore the request and send an empty
115                                         response ($#<checksum>).  This way
116                                         we can extend the protocol and GDB
117                                         can tell whether the stub it is
118                                         talking to uses the old or the new.
119 */
120
121 #include "defs.h"
122 #include <string.h>
123 #include <fcntl.h>
124 #include "frame.h"
125 #include "inferior.h"
126 #include "bfd.h"
127 #include "symfile.h"
128 #include "target.h"
129 #include "wait.h"
130 #include "terminal.h"
131 #include "gdbcmd.h"
132 #include "objfiles.h"
133 #include "gdb-stabs.h"
134
135 #include "dcache.h"
136
137 #if !defined(DONT_USE_REMOTE)
138 #ifdef USG
139 #include <sys/types.h>
140 #endif
141
142 #include <signal.h>
143 #include "serial.h"
144
145 /* Prototypes for local functions */
146
147 static int
148 remote_write_bytes PARAMS ((CORE_ADDR memaddr, unsigned char *myaddr, int len));
149
150 static int
151 remote_read_bytes PARAMS ((CORE_ADDR memaddr, unsigned char *myaddr, int len));
152
153 static void
154 remote_files_info PARAMS ((struct target_ops *ignore));
155
156 static int
157 remote_xfer_memory PARAMS ((CORE_ADDR memaddr, char *myaddr, int len,
158                             int should_write, struct target_ops *target));
159
160 static void 
161 remote_prepare_to_store PARAMS ((void));
162
163 static void
164 remote_fetch_registers PARAMS ((int regno));
165
166 static void
167 remote_resume PARAMS ((int pid, int step, int siggnal));
168
169 static int
170 remote_start_remote PARAMS ((char *dummy));
171
172 static void
173 remote_open PARAMS ((char *name, int from_tty));
174
175 static void
176 remote_close PARAMS ((int quitting));
177
178 static void
179 remote_store_registers PARAMS ((int regno));
180
181 static void
182 getpkt PARAMS ((char *buf, int forever));
183
184 static void
185 putpkt PARAMS ((char *buf));
186
187 static void
188 remote_send PARAMS ((char *buf));
189
190 static int
191 readchar PARAMS ((void));
192
193 static int
194 remote_wait PARAMS ((int pid, WAITTYPE *status));
195
196 static int
197 tohex PARAMS ((int nib));
198
199 static int
200 fromhex PARAMS ((int a));
201
202 static void
203 remote_detach PARAMS ((char *args, int from_tty));
204
205 static void
206 remote_interrupt PARAMS ((int signo));
207
208 static void
209 remote_interrupt_twice PARAMS ((int signo));
210
211 static void
212 interrupt_query PARAMS ((void));
213
214 extern struct target_ops remote_ops;    /* Forward decl */
215
216 /* This was 5 seconds, which is a long time to sit and wait.
217    Unless this is going though some terminal server or multiplexer or
218    other form of hairy serial connection, I would think 2 seconds would
219    be plenty.  */
220 static int timeout = 2;
221
222 #if 0
223 int icache;
224 #endif
225
226 /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
227    remote_open knows that we don't have a file open when the program
228    starts.  */
229 serial_t remote_desc = NULL;
230
231 /* Having this larger than 400 causes us to be incompatible with m68k-stub.c
232    and i386-stub.c.  Normally, no one would notice because it only matters
233    for writing large chunks of memory (e.g. in downloads).  Also, this needs
234    to be more than 400 if required to hold the registers (see below, where
235    we round it up based on REGISTER_BYTES).  */
236 #define PBUFSIZ 400
237
238 /* Maximum number of bytes to read/write at once.  The value here
239    is chosen to fill up a packet (the headers account for the 32).  */
240 #define MAXBUFBYTES ((PBUFSIZ-32)/2)
241
242 /* Round up PBUFSIZ to hold all the registers, at least.  */
243 #if REGISTER_BYTES > MAXBUFBYTES
244 #undef  PBUFSIZ
245 #define PBUFSIZ (REGISTER_BYTES * 2 + 32)
246 #endif
247 \f
248 /* Clean up connection to a remote debugger.  */
249
250 /* ARGSUSED */
251 static void
252 remote_close (quitting)
253      int quitting;
254 {
255   if (remote_desc)
256     SERIAL_CLOSE (remote_desc);
257   remote_desc = NULL;
258 }
259
260 /* Stub for catch_errors.  */
261
262 static int
263 remote_start_remote (dummy)
264      char *dummy;
265 {
266   immediate_quit = 1;           /* Allow user to interrupt it */
267
268   /* Ack any packet which the remote side has already sent.  */
269   /* I'm not sure this \r is needed; we don't use it any other time we
270      send an ack.  */
271   SERIAL_WRITE (remote_desc, "+\r", 2);
272   putpkt ("?");                 /* initiate a query from remote machine */
273   immediate_quit = 0;
274
275   start_remote ();              /* Initialize gdb process mechanisms */
276   return 1;
277 }
278
279 /* Open a connection to a remote debugger.
280    NAME is the filename used for communication.  */
281
282 static DCACHE *remote_dcache;
283
284 static void
285 remote_open (name, from_tty)
286      char *name;
287      int from_tty;
288 {
289   if (name == 0)
290     error (
291 "To open a remote debug connection, you need to specify what serial\n\
292 device is attached to the remote system (e.g. /dev/ttya).");
293
294   target_preopen (from_tty);
295
296   unpush_target (&remote_ops);
297
298   remote_dcache = dcache_init (remote_read_bytes, remote_write_bytes);
299
300   remote_desc = SERIAL_OPEN (name);
301   if (!remote_desc)
302     perror_with_name (name);
303
304   if (SERIAL_SETBAUDRATE (remote_desc, baud_rate))
305     {
306       SERIAL_CLOSE (remote_desc);
307       perror_with_name (name);
308     }
309
310   SERIAL_RAW (remote_desc);
311
312   /* If there is something sitting in the buffer we might take it as a
313      response to a command, which would be bad.  */
314   SERIAL_FLUSH_INPUT (remote_desc);
315
316   if (from_tty)
317     {
318       puts_filtered ("Remote debugging using ");
319       puts_filtered (name);
320       puts_filtered ("\n");
321     }
322   push_target (&remote_ops);    /* Switch to using remote target now */
323
324   /* Start the remote connection; if error (0), discard this target.
325      In particular, if the user quits, be sure to discard it
326      (we'd be in an inconsistent state otherwise).  */
327   if (!catch_errors (remote_start_remote, (char *)0, 
328         "Couldn't establish connection to remote target\n", RETURN_MASK_ALL))
329     pop_target();
330 }
331
332 /* remote_detach()
333    takes a program previously attached to and detaches it.
334    We better not have left any breakpoints
335    in the program or it'll die when it hits one.
336    Close the open connection to the remote debugger.
337    Use this when you want to detach and do something else
338    with your gdb.  */
339
340 static void
341 remote_detach (args, from_tty)
342      char *args;
343      int from_tty;
344 {
345   if (args)
346     error ("Argument given to \"detach\" when remotely debugging.");
347   
348   pop_target ();
349   if (from_tty)
350     puts_filtered ("Ending remote debugging.\n");
351 }
352
353 /* Convert hex digit A to a number.  */
354
355 static int
356 fromhex (a)
357      int a;
358 {
359   if (a >= '0' && a <= '9')
360     return a - '0';
361   else if (a >= 'a' && a <= 'f')
362     return a - 'a' + 10;
363   else
364     error ("Reply contains invalid hex digit");
365   return -1;
366 }
367
368 /* Convert number NIB to a hex digit.  */
369
370 static int
371 tohex (nib)
372      int nib;
373 {
374   if (nib < 10)
375     return '0'+nib;
376   else
377     return 'a'+nib-10;
378 }
379 \f
380 /* Tell the remote machine to resume.  */
381
382 static void
383 remote_resume (pid, step, siggnal)
384      int pid, step, siggnal;
385 {
386   char buf[PBUFSIZ];
387
388   if (siggnal)
389     {
390       char *name;
391       target_terminal_ours_for_output ();
392       printf_filtered ("Can't send signals to a remote system.  ");
393       name = strsigno (siggnal);
394       if (name)
395         printf_filtered (name);
396       else
397         printf_filtered ("Signal %d", siggnal);
398       printf_filtered (" not sent.\n");
399       target_terminal_inferior ();
400     }
401
402   dcache_flush (remote_dcache);
403
404   strcpy (buf, step ? "s": "c");
405
406   putpkt (buf);
407 }
408 \f
409 /* Send ^C to target to halt it.  Target will respond, and send us a
410    packet.  */
411
412 static void
413 remote_interrupt (signo)
414      int signo;
415 {
416   /* If this doesn't work, try more severe steps.  */
417   signal (signo, remote_interrupt_twice);
418   
419   if (remote_debug)
420     printf_unfiltered ("remote_interrupt called\n");
421
422   SERIAL_WRITE (remote_desc, "\003", 1); /* Send a ^C */
423 }
424
425 static void (*ofunc)();
426
427 /* The user typed ^C twice.  */
428 static void
429 remote_interrupt_twice (signo)
430      int signo;
431 {
432   signal (signo, ofunc);
433   
434   interrupt_query ();
435
436   signal (signo, remote_interrupt);
437 }
438
439 /* Ask the user what to do when an interrupt is received.  */
440
441 static void
442 interrupt_query ()
443 {
444   target_terminal_ours ();
445
446   if (query ("Interrupted while waiting for the program.\n\
447 Give up (and stop debugging it)? "))
448     {
449       target_mourn_inferior ();
450       return_to_top_level (RETURN_QUIT);
451     }
452
453   target_terminal_inferior ();
454 }
455
456 /* Wait until the remote machine stops, then return,
457    storing status in STATUS just as `wait' would.
458    Returns "pid" (though it's not clear what, if anything, that
459    means in the case of this target).  */
460
461 static int
462 remote_wait (pid, status)
463      int pid;
464      WAITTYPE *status;
465 {
466   unsigned char buf[PBUFSIZ];
467
468   WSETEXIT ((*status), 0);
469
470   while (1)
471     {
472       unsigned char *p;
473
474       ofunc = (void (*)()) signal (SIGINT, remote_interrupt);
475       getpkt ((char *) buf, 1);
476       signal (SIGINT, ofunc);
477
478       if (buf[0] == 'E')
479         warning ("Remote failure reply: %s", buf);
480       else if (buf[0] == 'T')
481         {
482           int i;
483           long regno;
484           char regs[MAX_REGISTER_RAW_SIZE];
485
486           /* Expedited reply, containing Signal, {regno, reg} repeat */
487           /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
488               ss = signal number
489               n... = register number
490               r... = register contents
491               */
492
493           p = &buf[3];          /* after Txx */
494
495           while (*p)
496             {
497               unsigned char *p1;
498
499               regno = strtol (p, &p1, 16); /* Read the register number */
500
501               if (p1 == p)
502                 warning ("Remote sent badly formed register number: %s\nPacket: '%s'\n",
503                          p1, buf);
504
505               p = p1;
506
507               if (*p++ != ':')
508                 warning ("Malformed packet (missing colon): %s\nPacket: '%s'\n",
509                          p, buf);
510
511               if (regno >= NUM_REGS)
512                 warning ("Remote sent bad register number %d: %s\nPacket: '%s'\n",
513                          regno, p, buf);
514
515               for (i = 0; i < REGISTER_RAW_SIZE (regno); i++)
516                 {
517                   if (p[0] == 0 || p[1] == 0)
518                     warning ("Remote reply is too short: %s", buf);
519                   regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
520                   p += 2;
521                 }
522
523               if (*p++ != ';')
524                 warning ("Remote register badly formatted: %s", buf);
525
526               supply_register (regno, regs);
527             }
528           break;
529         }
530       else if (buf[0] == 'N')
531         {
532           unsigned char *p1;
533           bfd_vma text_addr, data_addr, bss_addr;
534
535           /* Relocate object file.  Format is NAATT;DD;BB where AA is
536              the signal number, TT is the new text address, DD is the
537              new data address, and BB is the new bss address.  This is
538              used by the NLM stub; gdb may see more sections.  */
539           p = &buf[3];
540           text_addr = strtoul (p, &p1, 16);
541           if (p1 == p || *p1 != ';')
542             warning ("Malformed relocation packet: Packet '%s'", buf);
543           p = p1 + 1;
544           data_addr = strtoul (p, &p1, 16);
545           if (p1 == p || *p1 != ';')
546             warning ("Malformed relocation packet: Packet '%s'", buf);
547           p = p1 + 1;
548           bss_addr = strtoul (p, &p1, 16);
549           if (p1 == p)
550             warning ("Malformed relocation packet: Packet '%s'", buf);
551
552           if (symfile_objfile != NULL
553               && (ANOFFSET (symfile_objfile->section_offsets,
554                             SECT_OFF_TEXT) != text_addr
555                   || ANOFFSET (symfile_objfile->section_offsets,
556                                SECT_OFF_DATA) != data_addr
557                   || ANOFFSET (symfile_objfile->section_offsets,
558                                SECT_OFF_BSS) != bss_addr))
559             {
560               struct section_offsets *offs;
561
562               /* FIXME: This code assumes gdb-stabs.h is being used;
563                  it's broken for xcoff, dwarf, sdb-coff, etc.  But
564                  there is no simple canonical representation for this
565                  stuff.  (Just what does "text" as seen by the stub
566                  mean, anyway?).  */
567
568               offs = ((struct section_offsets *)
569                       alloca (sizeof (struct section_offsets)
570                               + (symfile_objfile->num_sections
571                                  * sizeof (offs->offsets))));
572               memcpy (offs, symfile_objfile->section_offsets,
573                       (sizeof (struct section_offsets)
574                        + (symfile_objfile->num_sections
575                           * sizeof (offs->offsets))));
576               ANOFFSET (offs, SECT_OFF_TEXT) = text_addr;
577               ANOFFSET (offs, SECT_OFF_DATA) = data_addr;
578               ANOFFSET (offs, SECT_OFF_BSS) = bss_addr;
579
580               objfile_relocate (symfile_objfile, offs);
581               {
582                 struct obj_section *s;
583                 bfd *abfd;
584
585                 abfd = symfile_objfile->obfd;
586
587                 for (s = symfile_objfile->sections;
588                      s < symfile_objfile->sections_end; ++s)
589                   {
590                     flagword flags;
591
592                     flags = bfd_get_section_flags (abfd, s->sec_ptr);
593
594                     if (flags & SEC_CODE)
595                       {
596                         s->addr += text_addr;
597                         s->endaddr += text_addr;
598                       }
599                     else if (flags & (SEC_DATA | SEC_LOAD))
600                       {
601                         s->addr += data_addr;
602                         s->endaddr += data_addr;
603                       }
604                     else if (flags & SEC_ALLOC)
605                       {
606                         s->addr += bss_addr;
607                         s->endaddr += bss_addr;
608                       }
609                   }
610               }
611             }
612           break;
613         }
614       else if (buf[0] == 'W')
615         {
616           /* The remote process exited.  */
617           WSETEXIT (*status, (fromhex (buf[1]) << 4) + fromhex (buf[2]));
618           return 0;
619         }
620       else if (buf[0] == 'S')
621         break;
622       else
623         warning ("Invalid remote reply: %s", buf);
624     }
625
626   WSETSTOP ((*status), (((fromhex (buf[1])) << 4) + (fromhex (buf[2]))));
627
628   return 0;
629 }
630
631 /* Number of bytes of registers this stub implements.  */
632 static int register_bytes_found;
633
634 /* Read the remote registers into the block REGS.  */
635 /* Currently we just read all the registers, so we don't use regno.  */
636 /* ARGSUSED */
637 static void
638 remote_fetch_registers (regno)
639      int regno;
640 {
641   char buf[PBUFSIZ];
642   int i;
643   char *p;
644   char regs[REGISTER_BYTES];
645
646   sprintf (buf, "g");
647   remote_send (buf);
648
649   /* Unimplemented registers read as all bits zero.  */
650   memset (regs, 0, REGISTER_BYTES);
651
652   /* We can get out of synch in various cases.  If the first character
653      in the buffer is not a hex character, assume that has happened
654      and try to fetch another packet to read.  */
655   while ((buf[0] < '0' || buf[0] > '9')
656          && (buf[0] < 'a' || buf[0] > 'f'))
657     {
658       if (remote_debug)
659         printf_unfiltered ("Bad register packet; fetching a new packet\n");
660       getpkt (buf, 0);
661     }
662
663   /* Reply describes registers byte by byte, each byte encoded as two
664      hex characters.  Suck them all up, then supply them to the
665      register cacheing/storage mechanism.  */
666
667   p = buf;
668   for (i = 0; i < REGISTER_BYTES; i++)
669     {
670       if (p[0] == 0)
671         break;
672       if (p[1] == 0)
673         {
674           warning ("Remote reply is of odd length: %s", buf);
675           /* Don't change register_bytes_found in this case, and don't
676              print a second warning.  */
677           goto supply_them;
678         }
679       regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
680       p += 2;
681     }
682
683   if (i != register_bytes_found)
684     {
685       register_bytes_found = i;
686 #ifdef REGISTER_BYTES_OK
687       if (!REGISTER_BYTES_OK (i))
688         warning ("Remote reply is too short: %s", buf);
689 #endif
690     }
691
692  supply_them:
693   for (i = 0; i < NUM_REGS; i++)
694     supply_register (i, &regs[REGISTER_BYTE(i)]);
695 }
696
697 /* Prepare to store registers.  Since we send them all, we have to
698    read out the ones we don't want to change first.  */
699
700 static void 
701 remote_prepare_to_store ()
702 {
703   /* Make sure the entire registers array is valid.  */
704   read_register_bytes (0, (char *)NULL, REGISTER_BYTES);
705 }
706
707 /* Store the remote registers from the contents of the block REGISTERS. 
708    FIXME, eventually just store one register if that's all that is needed.  */
709
710 /* ARGSUSED */
711 static void
712 remote_store_registers (regno)
713      int regno;
714 {
715   char buf[PBUFSIZ];
716   int i;
717   char *p;
718
719   buf[0] = 'G';
720   
721   /* Command describes registers byte by byte,
722      each byte encoded as two hex characters.  */
723
724   p = buf + 1;
725   /* remote_prepare_to_store insures that register_bytes_found gets set.  */
726   for (i = 0; i < register_bytes_found; i++)
727     {
728       *p++ = tohex ((registers[i] >> 4) & 0xf);
729       *p++ = tohex (registers[i] & 0xf);
730     }
731   *p = '\0';
732
733   remote_send (buf);
734 }
735
736 #if 0
737
738 /* Use of the data cache is disabled because it loses for looking at
739    and changing hardware I/O ports and the like.  Accepting `volatile'
740    would perhaps be one way to fix it, but a better way which would
741    win for more cases would be to use the executable file for the text
742    segment, like the `icache' code below but done cleanly (in some
743    target-independent place, perhaps in target_xfer_memory, perhaps
744    based on assigning each target a speed or perhaps by some simpler
745    mechanism).  */
746
747 /* Read a word from remote address ADDR and return it.
748    This goes through the data cache.  */
749
750 static int
751 remote_fetch_word (addr)
752      CORE_ADDR addr;
753 {
754 #if 0
755   if (icache)
756     {
757       extern CORE_ADDR text_start, text_end;
758
759       if (addr >= text_start && addr < text_end)
760         {
761           int buffer;
762           xfer_core_file (addr, &buffer, sizeof (int));
763           return buffer;
764         }
765     }
766 #endif
767   return dcache_fetch (remote_dcache, addr);
768 }
769
770 /* Write a word WORD into remote address ADDR.
771    This goes through the data cache.  */
772
773 static void
774 remote_store_word (addr, word)
775      CORE_ADDR addr;
776      int word;
777 {
778   dcache_poke (remote_dcache, addr, word);
779 }
780 #endif /* 0 */
781 \f
782 /* Write memory data directly to the remote machine.
783    This does not inform the data cache; the data cache uses this.
784    MEMADDR is the address in the remote memory space.
785    MYADDR is the address of the buffer in our space.
786    LEN is the number of bytes.
787
788    Returns number of bytes transferred, or 0 for error.  */
789
790 static int
791 remote_write_bytes (memaddr, myaddr, len)
792      CORE_ADDR memaddr;
793      unsigned char *myaddr;
794      int len;
795 {
796   char buf[PBUFSIZ];
797   int i;
798   char *p;
799
800   sprintf (buf, "M%x,%x:", memaddr, len);
801
802   /* We send target system values byte by byte, in increasing byte addresses,
803      each byte encoded as two hex characters.  */
804
805   p = buf + strlen (buf);
806   for (i = 0; i < len; i++)
807     {
808       *p++ = tohex ((myaddr[i] >> 4) & 0xf);
809       *p++ = tohex (myaddr[i] & 0xf);
810     }
811   *p = '\0';
812
813   putpkt (buf);
814   getpkt (buf, 0);
815
816   if (buf[0] == 'E')
817     {
818       /* There is no correspondance between what the remote protocol uses
819          for errors and errno codes.  We would like a cleaner way of
820          representing errors (big enough to include errno codes, bfd_error
821          codes, and others).  But for now just return EIO.  */
822       errno = EIO;
823       return 0;
824     }
825   return len;
826 }
827
828 /* Read memory data directly from the remote machine.
829    This does not use the data cache; the data cache uses this.
830    MEMADDR is the address in the remote memory space.
831    MYADDR is the address of the buffer in our space.
832    LEN is the number of bytes.
833
834    Returns number of bytes transferred, or 0 for error.  */
835
836 static int
837 remote_read_bytes (memaddr, myaddr, len)
838      CORE_ADDR memaddr;
839      unsigned char *myaddr;
840      int len;
841 {
842   char buf[PBUFSIZ];
843   int i;
844   char *p;
845
846   if (len > PBUFSIZ / 2 - 1)
847     abort ();
848
849   sprintf (buf, "m%x,%x", memaddr, len);
850   putpkt (buf);
851   getpkt (buf, 0);
852
853   if (buf[0] == 'E')
854     {
855       /* There is no correspondance between what the remote protocol uses
856          for errors and errno codes.  We would like a cleaner way of
857          representing errors (big enough to include errno codes, bfd_error
858          codes, and others).  But for now just return EIO.  */
859       errno = EIO;
860       return 0;
861     }
862
863   /* Reply describes memory byte by byte,
864      each byte encoded as two hex characters.  */
865
866   p = buf;
867   for (i = 0; i < len; i++)
868     {
869       if (p[0] == 0 || p[1] == 0)
870         /* Reply is short.  This means that we were able to read only part
871            of what we wanted to.  */
872         break;
873       myaddr[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
874       p += 2;
875     }
876   return i;
877 }
878 \f
879 /* Read or write LEN bytes from inferior memory at MEMADDR, transferring
880    to or from debugger address MYADDR.  Write to inferior if SHOULD_WRITE is
881    nonzero.  Returns length of data written or read; 0 for error.  */
882
883 /* ARGSUSED */
884 static int
885 remote_xfer_memory(memaddr, myaddr, len, should_write, target)
886      CORE_ADDR memaddr;
887      char *myaddr;
888      int len;
889      int should_write;
890      struct target_ops *target;                 /* ignored */
891 {
892   int xfersize;
893   int bytes_xferred;
894   int total_xferred = 0;
895
896   while (len > 0)
897     {
898       if (len > MAXBUFBYTES)
899         xfersize = MAXBUFBYTES;
900       else
901         xfersize = len;
902
903       if (should_write)
904         bytes_xferred = remote_write_bytes (memaddr, myaddr, xfersize);
905       else
906         bytes_xferred = remote_read_bytes (memaddr, myaddr, xfersize);
907
908       /* If we get an error, we are done xferring.  */
909       if (bytes_xferred == 0)
910         break;
911
912       memaddr += bytes_xferred;
913       myaddr  += bytes_xferred;
914       len     -= bytes_xferred;
915       total_xferred += bytes_xferred;
916     }
917   return total_xferred;
918 }
919
920 static void
921 remote_files_info (ignore)
922      struct target_ops *ignore;
923 {
924   puts_filtered ("Debugging a target over a serial line.\n");
925 }
926 \f
927 /* Stuff for dealing with the packets which are part of this protocol.
928    See comment at top of file for details.  */
929
930 /* Read a single character from the remote end, masking it down to 7 bits. */
931
932 static int
933 readchar ()
934 {
935   int ch;
936
937   ch = SERIAL_READCHAR (remote_desc, timeout);
938
939   if (ch < 0)
940     return ch;
941
942   return ch & 0x7f;
943 }
944
945 /* Send the command in BUF to the remote machine,
946    and read the reply into BUF.
947    Report an error if we get an error reply.  */
948
949 static void
950 remote_send (buf)
951      char *buf;
952 {
953
954   putpkt (buf);
955   getpkt (buf, 0);
956
957   if (buf[0] == 'E')
958     error ("Remote failure reply: %s", buf);
959 }
960
961 /* Send a packet to the remote machine, with error checking.
962    The data of the packet is in BUF.  */
963
964 static void
965 putpkt (buf)
966      char *buf;
967 {
968   int i;
969   unsigned char csum = 0;
970   char buf2[PBUFSIZ];
971   int cnt = strlen (buf);
972   int ch;
973   char *p;
974
975   /* Copy the packet into buffer BUF2, encapsulating it
976      and giving it a checksum.  */
977
978   if (cnt > sizeof(buf2) - 5)           /* Prosanity check */
979     abort();
980
981   p = buf2;
982   *p++ = '$';
983
984   for (i = 0; i < cnt; i++)
985     {
986       csum += buf[i];
987       *p++ = buf[i];
988     }
989   *p++ = '#';
990   *p++ = tohex ((csum >> 4) & 0xf);
991   *p++ = tohex (csum & 0xf);
992
993   /* Send it over and over until we get a positive ack.  */
994
995   while (1)
996     {
997       if (remote_debug)
998         {
999           *p = '\0';
1000           printf_unfiltered ("Sending packet: %s...", buf2);  gdb_flush(gdb_stdout);
1001         }
1002       if (SERIAL_WRITE (remote_desc, buf2, p - buf2))
1003         perror_with_name ("putpkt: write failed");
1004
1005       /* read until either a timeout occurs (-2) or '+' is read */
1006       while (1)
1007         {
1008           ch = readchar ();
1009
1010           switch (ch)
1011             {
1012             case '+':
1013               if (remote_debug)
1014                 printf_unfiltered("Ack\n");
1015               return;
1016             case SERIAL_TIMEOUT:
1017               break;            /* Retransmit buffer */
1018             case SERIAL_ERROR:
1019               perror_with_name ("putpkt: couldn't read ACK");
1020             case SERIAL_EOF:
1021               error ("putpkt: EOF while trying to read ACK");
1022             default:
1023               if (remote_debug)
1024                 printf_unfiltered ("%02X %c ", ch&0xFF, ch);
1025               continue;
1026             }
1027           break;                /* Here to retransmit */
1028         }
1029
1030       if (quit_flag)
1031         {
1032           quit_flag = 0;
1033           interrupt_query ();
1034         }
1035     }
1036 }
1037
1038 /* Read a packet from the remote machine, with error checking,
1039    and store it in BUF.  BUF is expected to be of size PBUFSIZ.
1040    If FOREVER, wait forever rather than timing out; this is used
1041    while the target is executing user code.  */
1042
1043 static void
1044 getpkt (buf, forever)
1045      char *buf;
1046      int forever;
1047 {
1048   char *bp;
1049   unsigned char csum;
1050   int c = 0;
1051   unsigned char c1, c2;
1052   int retries = 0;
1053 #define MAX_RETRIES     10
1054
1055   while (1)
1056     {
1057       if (quit_flag)
1058         {
1059           quit_flag = 0;
1060           interrupt_query ();
1061         }
1062
1063       /* This can loop forever if the remote side sends us characters
1064          continuously, but if it pauses, we'll get a zero from readchar
1065          because of timeout.  Then we'll count that as a retry.  */
1066
1067       c = readchar();
1068       if (c > 0 && c != '$')
1069         continue;
1070
1071       if (c == SERIAL_TIMEOUT)
1072         {
1073           if (forever)
1074             continue;
1075           if (++retries >= MAX_RETRIES)
1076             if (remote_debug) puts_filtered ("Timed out.\n");
1077           goto out;
1078         }
1079
1080       if (c == SERIAL_EOF)
1081         error ("Remote connection closed");
1082       if (c == SERIAL_ERROR)
1083         perror_with_name ("Remote communication error");
1084
1085       /* Force csum to be zero here because of possible error retry.  */
1086       csum = 0;
1087       bp = buf;
1088
1089       while (1)
1090         {
1091           c = readchar ();
1092           if (c == SERIAL_TIMEOUT)
1093             {
1094               if (remote_debug)
1095                 puts_filtered ("Timeout in mid-packet, retrying\n");
1096               goto whole;               /* Start a new packet, count retries */
1097             } 
1098           if (c == '$')
1099             {
1100               if (remote_debug)
1101                 puts_filtered ("Saw new packet start in middle of old one\n");
1102               goto whole;               /* Start a new packet, count retries */
1103             }
1104           if (c == '#')
1105             break;
1106           if (bp >= buf+PBUFSIZ-1)
1107           {
1108             *bp = '\0';
1109             puts_filtered ("Remote packet too long: ");
1110             puts_filtered (buf);
1111             puts_filtered ("\n");
1112             goto whole;
1113           }
1114           *bp++ = c;
1115           csum += c;
1116         }
1117       *bp = 0;
1118
1119       c1 = fromhex (readchar ());
1120       c2 = fromhex (readchar ());
1121       if ((csum & 0xff) == (c1 << 4) + c2)
1122         break;
1123       printf_filtered ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
1124               (c1 << 4) + c2, csum & 0xff);
1125       puts_filtered (buf);
1126       puts_filtered ("\n");
1127
1128       /* Try the whole thing again.  */
1129 whole:
1130       if (++retries < MAX_RETRIES)
1131         {
1132           SERIAL_WRITE (remote_desc, "-", 1);
1133         }
1134       else
1135         {
1136           printf_unfiltered ("Ignoring packet error, continuing...\n");
1137           break;
1138         }
1139     }
1140
1141 out:
1142
1143   SERIAL_WRITE (remote_desc, "+", 1);
1144
1145   if (remote_debug)
1146     fprintf_unfiltered (gdb_stderr,"Packet received: %s\n", buf);
1147 }
1148 \f
1149 static void
1150 remote_kill ()
1151 {
1152   putpkt ("k");
1153   /* Don't wait for it to die.  I'm not really sure it matters whether
1154      we do or not.  For the existing stubs, kill is a noop.  */
1155   target_mourn_inferior ();
1156 }
1157
1158 static void
1159 remote_mourn ()
1160 {
1161   unpush_target (&remote_ops);
1162   generic_mourn_inferior ();
1163 }
1164 \f
1165 #ifdef REMOTE_BREAKPOINT
1166
1167 /* On some machines, e.g. 68k, we may use a different breakpoint instruction
1168    than other targets.  */
1169 static unsigned char break_insn[] = REMOTE_BREAKPOINT;
1170
1171 /* Check that it fits in BREAKPOINT_MAX bytes.  */
1172 static unsigned char check_break_insn_size[BREAKPOINT_MAX] = REMOTE_BREAKPOINT;
1173
1174 #else /* No REMOTE_BREAKPOINT.  */
1175
1176 /* Same old breakpoint instruction.  This code does nothing different
1177    than mem-break.c.  */
1178 static unsigned char break_insn[] = BREAKPOINT;
1179
1180 #endif /* No REMOTE_BREAKPOINT.  */
1181
1182 /* Insert a breakpoint on targets that don't have any better breakpoint
1183    support.  We read the contents of the target location and stash it,
1184    then overwrite it with a breakpoint instruction.  ADDR is the target
1185    location in the target machine.  CONTENTS_CACHE is a pointer to 
1186    memory allocated for saving the target contents.  It is guaranteed
1187    by the caller to be long enough to save sizeof BREAKPOINT bytes (this
1188    is accomplished via BREAKPOINT_MAX).  */
1189
1190 static int
1191 remote_insert_breakpoint (addr, contents_cache)
1192      CORE_ADDR addr;
1193      char *contents_cache;
1194 {
1195   int val;
1196
1197   val = target_read_memory (addr, contents_cache, sizeof break_insn);
1198
1199   if (val == 0)
1200     val = target_write_memory (addr, (char *)break_insn, sizeof break_insn);
1201
1202   return val;
1203 }
1204
1205 static int
1206 remote_remove_breakpoint (addr, contents_cache)
1207      CORE_ADDR addr;
1208      char *contents_cache;
1209 {
1210   return target_write_memory (addr, contents_cache, sizeof break_insn);
1211 }
1212 \f
1213 /* Define the target subroutine names */
1214
1215 struct target_ops remote_ops = {
1216   "remote",                     /* to_shortname */
1217   "Remote serial target in gdb-specific protocol",      /* to_longname */
1218   "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
1219 Specify the serial device it is connected to (e.g. /dev/ttya).",  /* to_doc */
1220   remote_open,                  /* to_open */
1221   remote_close,                 /* to_close */
1222   NULL,                         /* to_attach */
1223   remote_detach,                /* to_detach */
1224   remote_resume,                /* to_resume */
1225   remote_wait,                  /* to_wait */
1226   remote_fetch_registers,       /* to_fetch_registers */
1227   remote_store_registers,       /* to_store_registers */
1228   remote_prepare_to_store,      /* to_prepare_to_store */
1229   remote_xfer_memory,           /* to_xfer_memory */
1230   remote_files_info,            /* to_files_info */
1231
1232   remote_insert_breakpoint,     /* to_insert_breakpoint */
1233   remote_remove_breakpoint,     /* to_remove_breakpoint */
1234
1235   NULL,                         /* to_terminal_init */
1236   NULL,                         /* to_terminal_inferior */
1237   NULL,                         /* to_terminal_ours_for_output */
1238   NULL,                         /* to_terminal_ours */
1239   NULL,                         /* to_terminal_info */
1240   remote_kill,                  /* to_kill */
1241   generic_load,                 /* to_load */
1242   NULL,                         /* to_lookup_symbol */
1243   NULL,                         /* to_create_inferior */
1244   remote_mourn,                 /* to_mourn_inferior */
1245   0,                            /* to_can_run */
1246   0,                            /* to_notice_signals */
1247   process_stratum,              /* to_stratum */
1248   NULL,                         /* to_next */
1249   1,                            /* to_has_all_memory */
1250   1,                            /* to_has_memory */
1251   1,                            /* to_has_stack */
1252   1,                            /* to_has_registers */
1253   1,                            /* to_has_execution */
1254   NULL,                         /* sections */
1255   NULL,                         /* sections_end */
1256   OPS_MAGIC                     /* to_magic */
1257 };
1258 #endif /* Use remote.  */
1259
1260 void
1261 _initialize_remote ()
1262 {
1263 #if !defined(DONT_USE_REMOTE)
1264   add_target (&remote_ops);
1265 #endif
1266 }