* findvar.c (read_register_gen): Add "target byte-order" comment.
[external/binutils.git] / gdb / remote.c
1 /* Memory-access and commands for inferior process, for GDB.
2    Copyright (C) 1988-1991 Free Software Foundation, Inc.
3
4 This file is part of GDB.
5
6 GDB 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 1, or (at your option)
9 any later version.
10
11 GDB 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 GDB; see the file COPYING.  If not, write to
18 the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
19
20 /* Remote communication protocol.
21    All values are encoded in ascii hex digits.
22
23         Request         Packet
24
25         read registers  g
26         reply           XX....X         Each byte of register data
27                                         is described by two hex digits.
28                                         Registers are in the internal order
29                                         for GDB, and the bytes in a register
30                                         are in the same order the machine uses.
31                         or ENN          for an error.
32
33         write regs      GXX..XX         Each byte of register data
34                                         is described by two hex digits.
35         reply           OK              for success
36                         ENN             for an error
37
38         read mem        mAA..AA,LLLL    AA..AA is address, LLLL is length.
39         reply           XX..XX          XX..XX is mem contents
40                         or ENN          NN is errno
41
42         write mem       MAA..AA,LLLL:XX..XX
43                                         AA..AA is address,
44                                         LLLL is number of bytes,
45                                         XX..XX is data
46         reply           OK              for success
47                         ENN             for an error
48
49         cont            cAA..AA         AA..AA is address to resume
50                                         If AA..AA is omitted,
51                                         resume at same address.
52
53         step            sAA..AA         AA..AA is address to resume
54                                         If AA..AA is omitted,
55                                         resume at same address.
56
57         last signal     ?               Reply the current reason for stopping.
58                                         This is the same reply as is generated
59                                         for step or cont : SAA where AA is the
60                                         signal number.
61
62         There is no immediate reply to step or cont.
63         The reply comes when the machine stops.
64         It is           SAA             AA is the "signal number"
65
66         kill req        k
67 */
68
69 #include <stdio.h>
70 #include <string.h>
71 #include <fcntl.h>
72 #include "defs.h"
73 #include "param.h"
74 #include "frame.h"
75 #include "inferior.h"
76 #include "target.h"
77 #include "wait.h"
78 #include "terminal.h"
79
80 #ifdef USG
81 #include <sys/types.h>
82 #endif
83
84 #include <signal.h>
85
86 extern int memory_insert_breakpoint ();
87 extern int memory_remove_breakpoint ();
88 extern void add_syms_addr_command ();
89 extern struct value *call_function_by_hand();
90 extern void start_remote ();
91
92 extern struct target_ops remote_ops;    /* Forward decl */
93
94 static int kiodebug;
95 static int timeout = 5;
96
97 #if 0
98 int icache;
99 #endif
100
101 /* Descriptor for I/O to remote machine.  Initialize it to -1 so that
102    remote_open knows that we don't have a file open when the program
103    starts.  */
104 int remote_desc = -1;
105
106 #define PBUFSIZ 400
107
108 /* Maximum number of bytes to read/write at once.  The value here
109    is chosen to fill up a packet (the headers account for the 32).  */
110 #define MAXBUFBYTES ((PBUFSIZ-32)/2)
111
112 static void remote_send ();
113 static void putpkt ();
114 static void getpkt ();
115 #if 0
116 static void dcache_flush ();
117 #endif
118
119 \f
120 /* Called when SIGALRM signal sent due to alarm() timeout.  */
121 #ifndef HAVE_TERMIO
122 void
123 remote_timer ()
124 {
125   if (kiodebug)
126     printf ("remote_timer called\n");
127
128   alarm (timeout);
129 }
130 #endif
131
132 /* Initialize remote connection */
133
134 void
135 remote_start()
136 {
137 }
138
139 /* Clean up connection to a remote debugger.  */
140
141 void
142 remote_close (quitting)
143      int quitting;
144 {
145   if (remote_desc >= 0)
146     close (remote_desc);
147   remote_desc = -1;
148 }
149
150 /* Open a connection to a remote debugger.
151    NAME is the filename used for communication.  */
152
153 void
154 remote_open (name, from_tty)
155      char *name;
156      int from_tty;
157 {
158   TERMINAL sg;
159
160   if (name == 0)
161     error (
162 "To open a remote debug connection, you need to specify what serial\n\
163 device is attached to the remote system (e.g. /dev/ttya).");
164
165   target_preopen (from_tty);
166
167   remote_close (0);
168
169 #if 0
170   dcache_init ();
171 #endif
172
173   remote_desc = open (name, O_RDWR);
174   if (remote_desc < 0)
175     perror_with_name (name);
176
177   ioctl (remote_desc, TIOCGETP, &sg);
178 #ifdef HAVE_TERMIO
179   sg.c_cc[VMIN] = 0;            /* read with timeout.  */
180   sg.c_cc[VTIME] = timeout * 10;
181   sg.c_lflag &= ~(ICANON | ECHO);
182 #else
183   sg.sg_flags = RAW;
184 #endif
185   ioctl (remote_desc, TIOCSETP, &sg);
186
187   if (from_tty)
188     printf ("Remote debugging using %s\n", name);
189   push_target (&remote_ops);    /* Switch to using remote target now */
190
191 #ifndef HAVE_TERMIO
192 #ifndef NO_SIGINTERRUPT
193   /* Cause SIGALRM's to make reads fail.  */
194   if (siginterrupt (SIGALRM, 1) != 0)
195     perror ("remote_open: error in siginterrupt");
196 #endif
197
198   /* Set up read timeout timer.  */
199   if ((void (*)) signal (SIGALRM, remote_timer) == (void (*)) -1)
200     perror ("remote_open: error in signal");
201 #endif
202
203   /* Ack any packet which the remote side has already sent.  */
204   write (remote_desc, "+", 1);
205   putpkt ("?");                 /* initiate a query from remote machine */
206
207   start_remote ();              /* Initialize gdb process mechanisms */
208 }
209
210 /* remote_detach()
211    takes a program previously attached to and detaches it.
212    We better not have left any breakpoints
213    in the program or it'll die when it hits one.
214    Close the open connection to the remote debugger.
215    Use this when you want to detach and do something else
216    with your gdb.  */
217
218 static void
219 remote_detach (args, from_tty)
220      char *args;
221      int from_tty;
222 {
223   if (args)
224     error ("Argument given to \"detach\" when remotely debugging.");
225   
226   pop_target ();
227   if (from_tty)
228     printf ("Ending remote debugging.\n");
229 }
230
231 /* Convert hex digit A to a number.  */
232
233 static int
234 fromhex (a)
235      int a;
236 {
237   if (a >= '0' && a <= '9')
238     return a - '0';
239   else if (a >= 'a' && a <= 'f')
240     return a - 'a' + 10;
241   else
242     error ("Reply contains invalid hex digit");
243   return -1;
244 }
245
246 /* Convert number NIB to a hex digit.  */
247
248 static int
249 tohex (nib)
250      int nib;
251 {
252   if (nib < 10)
253     return '0'+nib;
254   else
255     return 'a'+nib-10;
256 }
257 \f
258 /* Tell the remote machine to resume.  */
259
260 void
261 remote_resume (step, siggnal)
262      int step, siggnal;
263 {
264   char buf[PBUFSIZ];
265
266   if (siggnal)
267     error ("Can't send signals to a remote system.");
268
269 #if 0
270   dcache_flush ();
271 #endif
272
273   strcpy (buf, step ? "s": "c");
274
275   putpkt (buf);
276 }
277
278 /* Wait until the remote machine stops, then return,
279    storing status in STATUS just as `wait' would.  */
280
281 int
282 remote_wait (status)
283      WAITTYPE *status;
284 {
285   unsigned char buf[PBUFSIZ];
286
287   WSETEXIT ((*status), 0);
288   getpkt (buf);
289   if (buf[0] == 'E')
290     error ("Remote failure reply: %s", buf);
291   if (buf[0] != 'S')
292     error ("Invalid remote reply: %s", buf);
293   WSETSTOP ((*status), (((fromhex (buf[1])) << 4) + (fromhex (buf[2]))));
294 }
295
296 /* Read the remote registers into the block REGS.  */
297
298 int
299 remote_fetch_registers (regno)
300      int regno;
301 {
302   char buf[PBUFSIZ];
303   int i;
304   char *p;
305   char regs[REGISTER_BYTES];
306
307   sprintf (buf, "g");
308   remote_send (buf);
309
310   /* Reply describes registers byte by byte, each byte encoded as two
311      hex characters.  Suck them all up, then supply them to the
312      register cacheing/storage mechanism.  */
313
314   p = buf;
315   for (i = 0; i < REGISTER_BYTES; i++)
316     {
317       if (p[0] == 0 || p[1] == 0)
318         error ("Remote reply is too short: %s", buf);
319       regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
320       p += 2;
321     }
322   for (i = 0; i < NUM_REGS; i++)
323     supply_register (i, &regs[REGISTER_BYTE(i)]);
324   return 0;
325 }
326
327 /* Prepare to store registers.  Since we send them all, we have to
328    read out the ones we don't want to change first.  */
329
330 void 
331 remote_prepare_to_store ()
332 {
333   remote_fetch_registers (-1);
334 }
335
336 /* Store the remote registers from the contents of the block REGISTERS. 
337    FIXME, eventually just store one register if that's all that is needed.  */
338
339 int
340 remote_store_registers (regno)
341      int regno;
342 {
343   char buf[PBUFSIZ];
344   int i;
345   char *p;
346
347   buf[0] = 'G';
348   
349   /* Command describes registers byte by byte,
350      each byte encoded as two hex characters.  */
351
352   p = buf + 1;
353   for (i = 0; i < REGISTER_BYTES; i++)
354     {
355       *p++ = tohex ((registers[i] >> 4) & 0xf);
356       *p++ = tohex (registers[i] & 0xf);
357     }
358   *p = '\0';
359
360   remote_send (buf);
361   return 0;
362 }
363
364 #if 0
365 /* Read a word from remote address ADDR and return it.
366    This goes through the data cache.  */
367
368 int
369 remote_fetch_word (addr)
370      CORE_ADDR addr;
371 {
372   if (icache)
373     {
374       extern CORE_ADDR text_start, text_end;
375
376       if (addr >= text_start && addr < text_end)
377         {
378           int buffer;
379           xfer_core_file (addr, &buffer, sizeof (int));
380           return buffer;
381         }
382     }
383   return dcache_fetch (addr);
384 }
385
386 /* Write a word WORD into remote address ADDR.
387    This goes through the data cache.  */
388
389 void
390 remote_store_word (addr, word)
391      CORE_ADDR addr;
392      int word;
393 {
394   dcache_poke (addr, word);
395 }
396 #endif /* 0 */
397 \f
398 /* Write memory data directly to the remote machine.
399    This does not inform the data cache; the data cache uses this.
400    MEMADDR is the address in the remote memory space.
401    MYADDR is the address of the buffer in our space.
402    LEN is the number of bytes.  */
403
404 void
405 remote_write_bytes (memaddr, myaddr, len)
406      CORE_ADDR memaddr;
407      char *myaddr;
408      int len;
409 {
410   char buf[PBUFSIZ];
411   int i;
412   char *p;
413
414   if (len > PBUFSIZ / 2 - 20)
415     abort ();
416
417   sprintf (buf, "M%x,%x:", memaddr, len);
418
419   /* Command describes registers byte by byte,
420      each byte encoded as two hex characters.  */
421
422   p = buf + strlen (buf);
423   for (i = 0; i < len; i++)
424     {
425       *p++ = tohex ((myaddr[i] >> 4) & 0xf);
426       *p++ = tohex (myaddr[i] & 0xf);
427     }
428   *p = '\0';
429
430   remote_send (buf);
431 }
432
433 /* Read memory data directly from the remote machine.
434    This does not use the data cache; the data cache uses this.
435    MEMADDR is the address in the remote memory space.
436    MYADDR is the address of the buffer in our space.
437    LEN is the number of bytes.  */
438
439 void
440 remote_read_bytes (memaddr, myaddr, len)
441      CORE_ADDR memaddr;
442      char *myaddr;
443      int len;
444 {
445   char buf[PBUFSIZ];
446   int i;
447   char *p;
448
449   if (len > PBUFSIZ / 2 - 1)
450     abort ();
451
452   sprintf (buf, "m%x,%x", memaddr, len);
453   remote_send (buf);
454
455   /* Reply describes registers byte by byte,
456      each byte encoded as two hex characters.  */
457
458   p = buf;
459   for (i = 0; i < len; i++)
460     {
461       if (p[0] == 0 || p[1] == 0)
462         error ("Remote reply is too short: %s", buf);
463       myaddr[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
464       p += 2;
465     }
466 }
467 \f
468 /* Read or write LEN bytes from inferior memory at MEMADDR, transferring
469    to or from debugger address MYADDR.  Write to inferior if WRITE is
470    nonzero.  Returns length of data written or read; 0 for error.  */
471
472 int
473 remote_xfer_inferior_memory(memaddr, myaddr, len, write)
474      CORE_ADDR memaddr;
475      char *myaddr;
476      int len;
477      int write;
478 {
479   int origlen = len;
480   int xfersize;
481   while (len > 0)
482     {
483       if (len > MAXBUFBYTES)
484         xfersize = MAXBUFBYTES;
485       else
486         xfersize = len;
487
488       if (write)
489         remote_write_bytes(memaddr, myaddr, xfersize);
490       else
491         remote_read_bytes (memaddr, myaddr, xfersize);
492       memaddr += xfersize;
493       myaddr  += xfersize;
494       len     -= xfersize;
495     }
496   return origlen; /* no error possible */
497 }
498
499 void
500 remote_files_info ()
501 {
502   printf ("remote files info missing here.  FIXME.\n");
503 }
504 \f
505 /*
506
507 A debug packet whose contents are <data>
508 is encapsulated for transmission in the form:
509
510         $ <data> # CSUM1 CSUM2
511
512         <data> must be ASCII alphanumeric and cannot include characters
513         '$' or '#'
514
515         CSUM1 and CSUM2 are ascii hex representation of an 8-bit 
516         checksum of <data>, the most significant nibble is sent first.
517         the hex digits 0-9,a-f are used.
518
519 Receiver responds with:
520
521         +       - if CSUM is correct and ready for next packet
522         -       - if CSUM is incorrect
523
524 */
525
526 static int
527 readchar ()
528 {
529   char buf;
530
531   buf = '\0';
532 #ifdef HAVE_TERMIO
533   /* termio does the timeout for us.  */
534   read (remote_desc, &buf, 1);
535 #else
536   alarm (timeout);
537   read (remote_desc, &buf, 1);
538   alarm (0);
539 #endif
540
541   return buf & 0x7f;
542 }
543
544 /* Send the command in BUF to the remote machine,
545    and read the reply into BUF.
546    Report an error if we get an error reply.  */
547
548 static void
549 remote_send (buf)
550      char *buf;
551 {
552
553   putpkt (buf);
554   getpkt (buf);
555
556   if (buf[0] == 'E')
557     error ("Remote failure reply: %s", buf);
558 }
559
560 /* Send a packet to the remote machine, with error checking.
561    The data of the packet is in BUF.  */
562
563 static void
564 putpkt (buf)
565      char *buf;
566 {
567   int i;
568   unsigned char csum = 0;
569   char buf2[500];
570   int cnt = strlen (buf);
571   char ch;
572   char *p;
573
574   /* Copy the packet into buffer BUF2, encapsulating it
575      and giving it a checksum.  */
576
577   p = buf2;
578   *p++ = '$';
579
580   for (i = 0; i < cnt; i++)
581     {
582       csum += buf[i];
583       *p++ = buf[i];
584     }
585   *p++ = '#';
586   *p++ = tohex ((csum >> 4) & 0xf);
587   *p++ = tohex (csum & 0xf);
588
589   /* Send it over and over until we get a positive ack.  */
590
591   do {
592     if (kiodebug)
593       {
594         *p = '\0';
595         printf ("Sending packet: %s (%s)\n", buf2, buf);
596       }
597     write (remote_desc, buf2, p - buf2);
598
599     /* read until either a timeout occurs (\0) or '+' is read */
600     do {
601       ch = readchar ();
602     } while ((ch != '+') && (ch != '\0'));
603   } while (ch != '+');
604 }
605
606 /* Read a packet from the remote machine, with error checking,
607    and store it in BUF.  */
608
609 static void
610 getpkt (buf)
611      char *buf;
612 {
613   char *bp;
614   unsigned char csum;
615   int c;
616   unsigned char c1, c2;
617
618   /* allow immediate quit while reading from device, it could be hung */
619   immediate_quit++;
620
621   while (1)
622     {
623       /* Force csum to be zero here because of possible error retry.  */
624       csum = 0;
625       
626       while ((c = readchar()) != '$');
627
628       bp = buf;
629       while (1)
630         {
631           c = readchar ();
632           if (c == '#')
633             break;
634           *bp++ = c;
635           csum += c;
636         }
637       *bp = 0;
638
639       c1 = fromhex (readchar ());
640       c2 = fromhex (readchar ());
641       if ((csum & 0xff) == (c1 << 4) + c2)
642         break;
643       printf ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
644               (c1 << 4) + c2, csum & 0xff, buf);
645       write (remote_desc, "-", 1);
646     }
647
648   immediate_quit--;
649
650   write (remote_desc, "+", 1);
651
652   if (kiodebug)
653     fprintf (stderr,"Packet received :%s\n", buf);
654 }
655 \f
656 /* The data cache leads to incorrect results because it doesn't know about
657    volatile variables, thus making it impossible to debug functions which
658    use hardware registers.  Therefore it is #if 0'd out.  Effect on
659    performance is some, for backtraces of functions with a few
660    arguments each.  For functions with many arguments, the stack
661    frames don't fit in the cache blocks, which makes the cache less
662    helpful.  Disabling the cache is a big performance win for fetching
663    large structures, because the cache code fetched data in 16-byte
664    chunks.  */
665 #if 0
666 /* The data cache records all the data read from the remote machine
667    since the last time it stopped.
668
669    Each cache block holds 16 bytes of data
670    starting at a multiple-of-16 address.  */
671
672 #define DCACHE_SIZE 64          /* Number of cache blocks */
673
674 struct dcache_block {
675         struct dcache_block *next, *last;
676         unsigned int addr;      /* Address for which data is recorded.  */
677         int data[4];
678 };
679
680 struct dcache_block dcache_free, dcache_valid;
681
682 /* Free all the data cache blocks, thus discarding all cached data.  */ 
683
684 static void
685 dcache_flush ()
686 {
687   register struct dcache_block *db;
688
689   while ((db = dcache_valid.next) != &dcache_valid)
690     {
691       remque (db);
692       insque (db, &dcache_free);
693     }
694 }
695
696 /*
697  * If addr is present in the dcache, return the address of the block 
698  * containing it.
699  */
700
701 struct dcache_block *
702 dcache_hit (addr)
703 {
704   register struct dcache_block *db;
705
706   if (addr & 3)
707     abort ();
708
709   /* Search all cache blocks for one that is at this address.  */
710   db = dcache_valid.next;
711   while (db != &dcache_valid)
712     {
713       if ((addr & 0xfffffff0) == db->addr)
714         return db;
715       db = db->next;
716     }
717   return NULL;
718 }
719
720 /*  Return the int data at address ADDR in dcache block DC.  */
721
722 int
723 dcache_value (db, addr)
724      struct dcache_block *db;
725      unsigned int addr;
726 {
727   if (addr & 3)
728     abort ();
729   return (db->data[(addr>>2)&3]);
730 }
731
732 /* Get a free cache block, put it on the valid list,
733    and return its address.  The caller should store into the block
734    the address and data that it describes.  */
735
736 struct dcache_block *
737 dcache_alloc ()
738 {
739   register struct dcache_block *db;
740
741   if ((db = dcache_free.next) == &dcache_free)
742     /* If we can't get one from the free list, take last valid */
743     db = dcache_valid.last;
744
745   remque (db);
746   insque (db, &dcache_valid);
747   return (db);
748 }
749
750 /* Return the contents of the word at address ADDR in the remote machine,
751    using the data cache.  */
752
753 int
754 dcache_fetch (addr)
755      CORE_ADDR addr;
756 {
757   register struct dcache_block *db;
758
759   db = dcache_hit (addr);
760   if (db == 0)
761     {
762       db = dcache_alloc ();
763       remote_read_bytes (addr & ~0xf, db->data, 16);
764       db->addr = addr & ~0xf;
765     }
766   return (dcache_value (db, addr));
767 }
768
769 /* Write the word at ADDR both in the data cache and in the remote machine.  */
770
771 dcache_poke (addr, data)
772      CORE_ADDR addr;
773      int data;
774 {
775   register struct dcache_block *db;
776
777   /* First make sure the word is IN the cache.  DB is its cache block.  */
778   db = dcache_hit (addr);
779   if (db == 0)
780     {
781       db = dcache_alloc ();
782       remote_read_bytes (addr & ~0xf, db->data, 16);
783       db->addr = addr & ~0xf;
784     }
785
786   /* Modify the word in the cache.  */
787   db->data[(addr>>2)&3] = data;
788
789   /* Send the changed word.  */
790   remote_write_bytes (addr, &data, 4);
791 }
792
793 /* Initialize the data cache.  */
794
795 dcache_init ()
796 {
797   register i;
798   register struct dcache_block *db;
799
800   db = (struct dcache_block *) xmalloc (sizeof (struct dcache_block) * 
801                                         DCACHE_SIZE);
802   dcache_free.next = dcache_free.last = &dcache_free;
803   dcache_valid.next = dcache_valid.last = &dcache_valid;
804   for (i=0;i<DCACHE_SIZE;i++,db++)
805     insque (db, &dcache_free);
806 }
807 #endif /* 0 */
808
809 /* Define the target subroutine names */
810
811 struct target_ops remote_ops = {
812         "remote", "Remote serial target in gdb-specific protocol",
813         "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
814 Specify the serial device it is connected to (e.g. /dev/ttya).",
815         remote_open, remote_close,
816         0, remote_detach, remote_resume, remote_wait,  /* attach */
817         remote_fetch_registers, remote_store_registers,
818         remote_prepare_to_store, 0, 0, /* conv_from, conv_to */
819         remote_xfer_inferior_memory, remote_files_info,
820         0, 0, /* insert_breakpoint, remove_breakpoint, */
821         0, 0, 0, 0, 0,  /* Terminal crud */
822         0, /* kill */
823         0, add_syms_addr_command,  /* load */
824         call_function_by_hand,
825         0, /* lookup_symbol */
826         0, 0, /* create_inferior FIXME, mourn_inferior FIXME */
827         process_stratum, 0, /* next */
828         1, 1, 1, 1, 1,  /* all mem, mem, stack, regs, exec */
829         OPS_MAGIC,              /* Always the last thing */
830 };
831
832 void
833 _initialize_remote ()
834 {
835   add_target (&remote_ops);
836 }