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