Import GDB 6.2.1 as obtained from ftp.gnu.org without the files in
[dragonfly.git] / contrib / gdb-6.2.1 / gdb / remote-sds.c
1 /* Remote target communications for serial-line targets using SDS' protocol.
2
3    Copyright 1997, 1998, 1999, 2000, 2001, 2002, 2004 Free Software
4    Foundation, Inc.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 59 Temple Place - Suite 330,
21    Boston, MA 02111-1307, USA.  */
22
23 /* This interface was written by studying the behavior of the SDS
24    monitor on an ADS 821/860 board, and by consulting the
25    documentation of the monitor that is available on Motorola's web
26    site.  -sts 8/13/97 */
27
28 #include "defs.h"
29 #include "gdb_string.h"
30 #include <fcntl.h>
31 #include "frame.h"
32 #include "inferior.h"
33 #include "bfd.h"
34 #include "symfile.h"
35 #include "target.h"
36 #include "gdbcmd.h"
37 #include "objfiles.h"
38 #include "gdb-stabs.h"
39 #include "gdbthread.h"
40 #include "gdbcore.h"
41 #include "regcache.h"
42
43 #ifdef USG
44 #include <sys/types.h>
45 #endif
46
47 #include <signal.h>
48 #include "serial.h"
49
50 extern void _initialize_remote_sds (void);
51
52 /* Declarations of local functions. */
53
54 static int sds_write_bytes (CORE_ADDR, char *, int);
55
56 static int sds_read_bytes (CORE_ADDR, char *, int);
57
58 static void sds_files_info (struct target_ops *ignore);
59
60 static int sds_xfer_memory (CORE_ADDR, char *, int, int, 
61                             struct mem_attrib *, struct target_ops *);
62
63 static void sds_prepare_to_store (void);
64
65 static void sds_fetch_registers (int);
66
67 static void sds_resume (ptid_t, int, enum target_signal);
68
69 static int sds_start_remote (void *);
70
71 static void sds_open (char *, int);
72
73 static void sds_close (int);
74
75 static void sds_store_registers (int);
76
77 static void sds_mourn (void);
78
79 static void sds_load (char *, int);
80
81 static int getmessage (unsigned char *, int);
82
83 static int putmessage (unsigned char *, int);
84
85 static int sds_send (unsigned char *, int);
86
87 static int readchar (int);
88
89 static ptid_t sds_wait (ptid_t, struct target_waitstatus *);
90
91 static void sds_kill (void);
92
93 static int fromhex (int);
94
95 static void sds_detach (char *, int);
96
97 static void sds_interrupt (int);
98
99 static void sds_interrupt_twice (int);
100
101 static void interrupt_query (void);
102
103 static int read_frame (char *);
104
105 static int sds_insert_breakpoint (CORE_ADDR, char *);
106
107 static int sds_remove_breakpoint (CORE_ADDR, char *);
108
109 static void init_sds_ops (void);
110
111 static void sds_command (char *args, int from_tty);
112
113 /* Define the target operations vector. */
114
115 static struct target_ops sds_ops;
116
117 /* This was 5 seconds, which is a long time to sit and wait.
118    Unless this is going though some terminal server or multiplexer or
119    other form of hairy serial connection, I would think 2 seconds would
120    be plenty.  */
121
122 static int sds_timeout = 2;
123
124 /* Descriptor for I/O to remote machine.  Initialize it to NULL so
125    that sds_open knows that we don't have a file open when the program
126    starts.  */
127
128 static struct serial *sds_desc = NULL;
129
130 /* This limit comes from the monitor.  */
131
132 #define PBUFSIZ 250
133
134 /* Maximum number of bytes to read/write at once.  The value here
135    is chosen to fill up a packet (the headers account for the 32).  */
136 #define MAXBUFBYTES ((PBUFSIZ-32)/2)
137
138 static int next_msg_id;
139
140 static int just_started;
141
142 static int message_pending;
143 \f
144
145 /* Clean up connection to a remote debugger.  */
146
147 static void
148 sds_close (int quitting)
149 {
150   if (sds_desc)
151     serial_close (sds_desc);
152   sds_desc = NULL;
153 }
154
155 /* Stub for catch_errors.  */
156
157 static int
158 sds_start_remote (void *dummy)
159 {
160   int c;
161   unsigned char buf[200];
162
163   immediate_quit++;             /* Allow user to interrupt it */
164
165   /* Ack any packet which the remote side has already sent.  */
166   serial_write (sds_desc, "{#*\r\n", 5);
167   serial_write (sds_desc, "{#}\r\n", 5);
168
169   while ((c = readchar (1)) >= 0)
170     printf_unfiltered ("%c", c);
171   printf_unfiltered ("\n");
172
173   next_msg_id = 251;
174
175   buf[0] = 26;
176   sds_send (buf, 1);
177
178   buf[0] = 0;
179   sds_send (buf, 1);
180
181   immediate_quit--;
182
183   start_remote ();              /* Initialize gdb process mechanisms */
184   return 1;
185 }
186
187 /* Open a connection to a remote debugger.
188    NAME is the filename used for communication.  */
189
190 static void
191 sds_open (char *name, int from_tty)
192 {
193   if (name == 0)
194     error ("To open a remote debug connection, you need to specify what serial\n\
195 device is attached to the remote system (e.g. /dev/ttya).");
196
197   target_preopen (from_tty);
198
199   unpush_target (&sds_ops);
200
201   sds_desc = serial_open (name);
202   if (!sds_desc)
203     perror_with_name (name);
204
205   if (baud_rate != -1)
206     {
207       if (serial_setbaudrate (sds_desc, baud_rate))
208         {
209           serial_close (sds_desc);
210           perror_with_name (name);
211         }
212     }
213
214
215   serial_raw (sds_desc);
216
217   /* If there is something sitting in the buffer we might take it as a
218      response to a command, which would be bad.  */
219   serial_flush_input (sds_desc);
220
221   if (from_tty)
222     {
223       puts_filtered ("Remote debugging using ");
224       puts_filtered (name);
225       puts_filtered ("\n");
226     }
227   push_target (&sds_ops);       /* Switch to using remote target now */
228
229   just_started = 1;
230
231   /* Start the remote connection; if error (0), discard this target.
232      In particular, if the user quits, be sure to discard it (we'd be
233      in an inconsistent state otherwise).  */
234   if (!catch_errors (sds_start_remote, NULL,
235                      "Couldn't establish connection to remote target\n",
236                      RETURN_MASK_ALL))
237     pop_target ();
238 }
239
240 /* This takes a program previously attached to and detaches it.  After
241    this is done, GDB can be used to debug some other program.  We
242    better not have left any breakpoints in the target program or it'll
243    die when it hits one.  */
244
245 static void
246 sds_detach (char *args, int from_tty)
247 {
248   char buf[PBUFSIZ];
249
250   if (args)
251     error ("Argument given to \"detach\" when remotely debugging.");
252
253 #if 0
254   /* Tell the remote target to detach.  */
255   strcpy (buf, "D");
256   sds_send (buf, 1);
257 #endif
258
259   pop_target ();
260   if (from_tty)
261     puts_filtered ("Ending remote debugging.\n");
262 }
263
264 /* Convert hex digit A to a number.  */
265
266 static int
267 fromhex (int a)
268 {
269   if (a >= '0' && a <= '9')
270     return a - '0';
271   else if (a >= 'a' && a <= 'f')
272     return a - 'a' + 10;
273   else
274     error ("Reply contains invalid hex digit %d", a);
275 }
276
277 static int
278 tob64 (unsigned char *inbuf, char *outbuf, int len)
279 {
280   int i, sum;
281   char *p;
282
283   if (len % 3 != 0)
284     error ("bad length");
285
286   p = outbuf;
287   for (i = 0; i < len; i += 3)
288     {
289       /* Collect the next three bytes into a number.  */
290       sum = ((long) *inbuf++) << 16;
291       sum |= ((long) *inbuf++) << 8;
292       sum |= ((long) *inbuf++);
293
294       /* Spit out 4 6-bit encodings.  */
295       *p++ = ((sum >> 18) & 0x3f) + '0';
296       *p++ = ((sum >> 12) & 0x3f) + '0';
297       *p++ = ((sum >> 6) & 0x3f) + '0';
298       *p++ = (sum & 0x3f) + '0';
299     }
300   return (p - outbuf);
301 }
302
303 static int
304 fromb64 (char *inbuf, char *outbuf, int len)
305 {
306   int i, sum;
307
308   if (len % 4 != 0)
309     error ("bad length");
310
311   for (i = 0; i < len; i += 4)
312     {
313       /* Collect 4 6-bit digits.  */
314       sum = (*inbuf++ - '0') << 18;
315       sum |= (*inbuf++ - '0') << 12;
316       sum |= (*inbuf++ - '0') << 6;
317       sum |= (*inbuf++ - '0');
318
319       /* Now take the resulting 24-bit number and get three bytes out
320          of it.  */
321       *outbuf++ = (sum >> 16) & 0xff;
322       *outbuf++ = (sum >> 8) & 0xff;
323       *outbuf++ = sum & 0xff;
324     }
325
326   return (len / 4) * 3;
327 }
328 \f
329
330 /* Tell the remote machine to resume.  */
331
332 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
333 int last_sent_step;
334
335 static void
336 sds_resume (ptid_t ptid, int step, enum target_signal siggnal)
337 {
338   unsigned char buf[PBUFSIZ];
339
340   last_sent_signal = siggnal;
341   last_sent_step = step;
342
343   buf[0] = (step ? 21 : 20);
344   buf[1] = 0;                   /* (should be signal?) */
345
346   sds_send (buf, 2);
347 }
348 \f
349 /* Send a message to target to halt it.  Target will respond, and send
350    us a message pending notice.  */
351
352 static void
353 sds_interrupt (int signo)
354 {
355   unsigned char buf[PBUFSIZ];
356
357   /* If this doesn't work, try more severe steps.  */
358   signal (signo, sds_interrupt_twice);
359
360   if (remote_debug)
361     fprintf_unfiltered (gdb_stdlog, "sds_interrupt called\n");
362
363   buf[0] = 25;
364   sds_send (buf, 1);
365 }
366
367 static void (*ofunc) ();
368
369 /* The user typed ^C twice.  */
370
371 static void
372 sds_interrupt_twice (int signo)
373 {
374   signal (signo, ofunc);
375
376   interrupt_query ();
377
378   signal (signo, sds_interrupt);
379 }
380
381 /* Ask the user what to do when an interrupt is received.  */
382
383 static void
384 interrupt_query (void)
385 {
386   target_terminal_ours ();
387
388   if (query ("Interrupted while waiting for the program.\n\
389 Give up (and stop debugging it)? "))
390     {
391       target_mourn_inferior ();
392       throw_exception (RETURN_QUIT);
393     }
394
395   target_terminal_inferior ();
396 }
397
398 /* If nonzero, ignore the next kill.  */
399 int kill_kludge;
400
401 /* Wait until the remote machine stops, then return, storing status in
402    STATUS just as `wait' would.  Returns "pid" (though it's not clear
403    what, if anything, that means in the case of this target).  */
404
405 static ptid_t
406 sds_wait (ptid_t ptid, struct target_waitstatus *status)
407 {
408   unsigned char buf[PBUFSIZ];
409   int retlen;
410
411   status->kind = TARGET_WAITKIND_EXITED;
412   status->value.integer = 0;
413
414   ofunc = (void (*)()) signal (SIGINT, sds_interrupt);
415
416   signal (SIGINT, ofunc);
417
418   if (just_started)
419     {
420       just_started = 0;
421       status->kind = TARGET_WAITKIND_STOPPED;
422       return inferior_ptid;
423     }
424
425   while (1)
426     {
427       getmessage (buf, 1);
428
429       if (message_pending)
430         {
431           buf[0] = 26;
432           retlen = sds_send (buf, 1);
433           if (remote_debug)
434             {
435               fprintf_unfiltered (gdb_stdlog, "Signals: %02x%02x %02x %02x\n",
436                                   buf[0], buf[1],
437                                   buf[2], buf[3]);
438             }
439           message_pending = 0;
440           status->kind = TARGET_WAITKIND_STOPPED;
441           status->value.sig = TARGET_SIGNAL_TRAP;
442           goto got_status;
443         }
444     }
445 got_status:
446   return inferior_ptid;
447 }
448
449 static unsigned char sprs[16];
450
451 /* Read the remote registers into the block REGS.  */
452 /* Currently we just read all the registers, so we don't use regno.  */
453
454 static void
455 sds_fetch_registers (int regno)
456 {
457   unsigned char buf[PBUFSIZ];
458   int i, retlen;
459   char *regs = alloca (DEPRECATED_REGISTER_BYTES);
460
461   /* Unimplemented registers read as all bits zero.  */
462   memset (regs, 0, DEPRECATED_REGISTER_BYTES);
463
464   buf[0] = 18;
465   buf[1] = 1;
466   buf[2] = 0;
467   retlen = sds_send (buf, 3);
468
469   for (i = 0; i < 4 * 6; ++i)
470     regs[i + 4 * 32 + 8 * 32] = buf[i];
471   for (i = 0; i < 4 * 4; ++i)
472     sprs[i] = buf[i + 4 * 7];
473
474   buf[0] = 18;
475   buf[1] = 2;
476   buf[2] = 0;
477   retlen = sds_send (buf, 3);
478
479   for (i = 0; i < retlen; i++)
480     regs[i] = buf[i];
481
482   /* (should warn about reply too short) */
483
484   for (i = 0; i < NUM_REGS; i++)
485     supply_register (i, &regs[DEPRECATED_REGISTER_BYTE (i)]);
486 }
487
488 /* Prepare to store registers.  Since we may send them all, we have to
489    read out the ones we don't want to change first.  */
490
491 static void
492 sds_prepare_to_store (void)
493 {
494   /* Make sure the entire registers array is valid.  */
495   deprecated_read_register_bytes (0, (char *) NULL, DEPRECATED_REGISTER_BYTES);
496 }
497
498 /* Store register REGNO, or all registers if REGNO == -1, from the contents
499    of REGISTERS.  FIXME: ignores errors.  */
500
501 static void
502 sds_store_registers (int regno)
503 {
504   unsigned char *p, buf[PBUFSIZ];
505   int i;
506
507   /* Store all the special-purpose registers.  */
508   p = buf;
509   *p++ = 19;
510   *p++ = 1;
511   *p++ = 0;
512   *p++ = 0;
513   for (i = 0; i < 4 * 6; i++)
514     *p++ = deprecated_registers[i + 4 * 32 + 8 * 32];
515   for (i = 0; i < 4 * 1; i++)
516     *p++ = 0;
517   for (i = 0; i < 4 * 4; i++)
518     *p++ = sprs[i];
519
520   sds_send (buf, p - buf);
521
522   /* Store all the general-purpose registers.  */
523   p = buf;
524   *p++ = 19;
525   *p++ = 2;
526   *p++ = 0;
527   *p++ = 0;
528   for (i = 0; i < 4 * 32; i++)
529     *p++ = deprecated_registers[i];
530
531   sds_send (buf, p - buf);
532
533 }
534 \f
535 /* Write memory data directly to the remote machine.  This does not
536    inform the data cache; the data cache uses this.  MEMADDR is the
537    address in the remote memory space.  MYADDR is the address of the
538    buffer in our space.  LEN is the number of bytes.
539
540    Returns number of bytes transferred, or 0 for error.  */
541
542 static int
543 sds_write_bytes (CORE_ADDR memaddr, char *myaddr, int len)
544 {
545   int max_buf_size;             /* Max size of packet output buffer */
546   int origlen;
547   unsigned char buf[PBUFSIZ];
548   int todo;
549   int i;
550
551   /* Chop the transfer down if necessary */
552
553   max_buf_size = 150;
554
555   origlen = len;
556   while (len > 0)
557     {
558       todo = min (len, max_buf_size);
559
560       buf[0] = 13;
561       buf[1] = 0;
562       buf[2] = (int) (memaddr >> 24) & 0xff;
563       buf[3] = (int) (memaddr >> 16) & 0xff;
564       buf[4] = (int) (memaddr >> 8) & 0xff;
565       buf[5] = (int) (memaddr) & 0xff;
566       buf[6] = 1;
567       buf[7] = 0;
568
569       for (i = 0; i < todo; i++)
570         buf[i + 8] = myaddr[i];
571
572       sds_send (buf, 8 + todo);
573
574       /* (should look at result) */
575
576       myaddr += todo;
577       memaddr += todo;
578       len -= todo;
579     }
580   return origlen;
581 }
582
583 /* Read memory data directly from the remote machine.  This does not
584    use the data cache; the data cache uses this.  MEMADDR is the
585    address in the remote memory space.  MYADDR is the address of the
586    buffer in our space.  LEN is the number of bytes.
587
588    Returns number of bytes transferred, or 0 for error.  */
589
590 static int
591 sds_read_bytes (CORE_ADDR memaddr, char *myaddr, int len)
592 {
593   int max_buf_size;             /* Max size of packet output buffer */
594   int origlen, retlen;
595   unsigned char buf[PBUFSIZ];
596   int todo;
597   int i;
598
599   /* Chop the transfer down if necessary */
600
601   max_buf_size = 150;
602
603   origlen = len;
604   while (len > 0)
605     {
606       todo = min (len, max_buf_size);
607
608       buf[0] = 12;
609       buf[1] = 0;
610       buf[2] = (int) (memaddr >> 24) & 0xff;
611       buf[3] = (int) (memaddr >> 16) & 0xff;
612       buf[4] = (int) (memaddr >> 8) & 0xff;
613       buf[5] = (int) (memaddr) & 0xff;
614       buf[6] = (int) (todo >> 8) & 0xff;
615       buf[7] = (int) (todo) & 0xff;
616       buf[8] = 1;
617
618       retlen = sds_send (buf, 9);
619
620       if (retlen - 2 != todo)
621         {
622           return 0;
623         }
624
625       /* Reply describes memory byte by byte. */
626
627       for (i = 0; i < todo; i++)
628         myaddr[i] = buf[i + 2];
629
630       myaddr += todo;
631       memaddr += todo;
632       len -= todo;
633     }
634
635   return origlen;
636 }
637 \f
638 /* Read or write LEN bytes from inferior memory at MEMADDR,
639    transferring to or from debugger address MYADDR.  Write to inferior
640    if SHOULD_WRITE is nonzero.  Returns length of data written or
641    read; 0 for error.  TARGET is unused.  */
642
643 static int
644 sds_xfer_memory (CORE_ADDR memaddr, char *myaddr, int len, int should_write,
645                  struct mem_attrib *attrib, struct target_ops *target)
646 {
647   int res;
648
649   if (should_write)
650     res = sds_write_bytes (memaddr, myaddr, len);
651   else
652     res = sds_read_bytes (memaddr, myaddr, len);
653   
654   return res;
655 }
656 \f
657
658 static void
659 sds_files_info (struct target_ops *ignore)
660 {
661   puts_filtered ("Debugging over a serial connection, using SDS protocol.\n");
662 }
663 \f
664 /* Stuff for dealing with the packets which are part of this protocol.
665    See comment at top of file for details.  */
666
667 /* Read a single character from the remote end, masking it down to 7 bits. */
668
669 static int
670 readchar (int timeout)
671 {
672   int ch;
673
674   ch = serial_readchar (sds_desc, timeout);
675
676   if (remote_debug > 1 && ch >= 0)
677     fprintf_unfiltered (gdb_stdlog, "%c(%x)", ch, ch);
678
679   switch (ch)
680     {
681     case SERIAL_EOF:
682       error ("Remote connection closed");
683     case SERIAL_ERROR:
684       perror_with_name ("Remote communication error");
685     case SERIAL_TIMEOUT:
686       return ch;
687     default:
688       return ch & 0x7f;
689     }
690 }
691
692 /* An SDS-style checksum is a sum of the bytes modulo 253.  (Presumably
693    because 253, 254, and 255 are special flags in the protocol.)  */
694
695 static int
696 compute_checksum (int csum, char *buf, int len)
697 {
698   int i;
699
700   for (i = 0; i < len; ++i)
701     csum += (unsigned char) buf[i];
702
703   csum %= 253;
704   return csum;
705 }
706
707 /* Send the command in BUF to the remote machine, and read the reply
708    into BUF also.  */
709
710 static int
711 sds_send (unsigned char *buf, int len)
712 {
713   putmessage (buf, len);
714
715   return getmessage (buf, 0);
716 }
717
718 /* Send a message to the remote machine.  */
719
720 static int
721 putmessage (unsigned char *buf, int len)
722 {
723   int i, enclen;
724   unsigned char csum = 0;
725   char buf2[PBUFSIZ], buf3[PBUFSIZ];
726   unsigned char header[3];
727   char *p;
728
729   /* Copy the packet into buffer BUF2, encapsulating it
730      and giving it a checksum.  */
731
732   if (len > 170)                /* Prosanity check */
733     internal_error (__FILE__, __LINE__, "failed internal consistency check");
734
735   if (remote_debug)
736     {
737       fprintf_unfiltered (gdb_stdlog, "Message to send: \"");
738       for (i = 0; i < len; ++i)
739         fprintf_unfiltered (gdb_stdlog, "%02x", buf[i]);
740       fprintf_unfiltered (gdb_stdlog, "\"\n");
741     }
742
743   p = buf2;
744   *p++ = '$';
745
746   if (len % 3 != 0)
747     {
748       buf[len] = '\0';
749       buf[len + 1] = '\0';
750     }
751
752   header[1] = next_msg_id;
753
754   header[2] = len;
755
756   csum = compute_checksum (csum, buf, len);
757   csum = compute_checksum (csum, header + 1, 2);
758
759   header[0] = csum;
760
761   tob64 (header, p, 3);
762   p += 4;
763   enclen = tob64 (buf, buf3, ((len + 2) / 3) * 3);
764
765   for (i = 0; i < enclen; ++i)
766     *p++ = buf3[i];
767   *p++ = '\r';
768   *p++ = '\n';
769
770   next_msg_id = (next_msg_id + 3) % 245;
771
772   /* Send it over and over until we get a positive ack.  */
773
774   while (1)
775     {
776       if (remote_debug)
777         {
778           *p = '\0';
779           fprintf_unfiltered (gdb_stdlog, "Sending encoded: \"%s\"", buf2);
780           fprintf_unfiltered (gdb_stdlog,
781                               "  (Checksum %d, id %d, length %d)\n",
782                               header[0], header[1], header[2]);
783           gdb_flush (gdb_stdlog);
784         }
785       if (serial_write (sds_desc, buf2, p - buf2))
786         perror_with_name ("putmessage: write failed");
787
788       return 1;
789     }
790 }
791
792 /* Come here after finding the start of the frame.  Collect the rest
793    into BUF.  Returns 0 on any error, 1 on success.  */
794
795 static int
796 read_frame (char *buf)
797 {
798   char *bp;
799   int c;
800
801   bp = buf;
802
803   while (1)
804     {
805       c = readchar (sds_timeout);
806
807       switch (c)
808         {
809         case SERIAL_TIMEOUT:
810           if (remote_debug)
811             fputs_filtered ("Timeout in mid-message, retrying\n", gdb_stdlog);
812           return 0;
813         case '$':
814           if (remote_debug)
815             fputs_filtered ("Saw new packet start in middle of old one\n",
816                             gdb_stdlog);
817           return 0;             /* Start a new packet, count retries */
818         case '\r':
819           break;
820
821         case '\n':
822           {
823             *bp = '\000';
824             if (remote_debug)
825               fprintf_unfiltered (gdb_stdlog, "Received encoded: \"%s\"\n",
826                                   buf);
827             return 1;
828           }
829
830         default:
831           if (bp < buf + PBUFSIZ - 1)
832             {
833               *bp++ = c;
834               continue;
835             }
836
837           *bp = '\0';
838           puts_filtered ("Message too long: ");
839           puts_filtered (buf);
840           puts_filtered ("\n");
841
842           return 0;
843         }
844     }
845 }
846
847 /* Read a packet from the remote machine, with error checking,
848    and store it in BUF.  BUF is expected to be of size PBUFSIZ.
849    If FOREVER, wait forever rather than timing out; this is used
850    while the target is executing user code.  */
851
852 static int
853 getmessage (unsigned char *buf, int forever)
854 {
855   int c, c2, c3;
856   int tries;
857   int timeout;
858   int val, i, len, csum;
859   unsigned char header[3];
860   unsigned char inbuf[500];
861
862   strcpy (buf, "timeout");
863
864   if (forever)
865     {
866       timeout = watchdog > 0 ? watchdog : -1;
867     }
868
869   else
870     timeout = sds_timeout;
871
872 #define MAX_TRIES 3
873
874   for (tries = 1; tries <= MAX_TRIES; tries++)
875     {
876       /* This can loop forever if the remote side sends us characters
877          continuously, but if it pauses, we'll get a zero from readchar
878          because of timeout.  Then we'll count that as a retry.  */
879
880       /* Note that we will only wait forever prior to the start of a packet.
881          After that, we expect characters to arrive at a brisk pace.  They
882          should show up within sds_timeout intervals.  */
883
884       do
885         {
886           c = readchar (timeout);
887
888           if (c == SERIAL_TIMEOUT)
889             {
890               if (forever)      /* Watchdog went off.  Kill the target. */
891                 {
892                   target_mourn_inferior ();
893                   error ("Watchdog has expired.  Target detached.\n");
894                 }
895               if (remote_debug)
896                 fputs_filtered ("Timed out.\n", gdb_stdlog);
897               goto retry;
898             }
899         }
900       while (c != '$' && c != '{');
901
902       /* We might have seen a "trigraph", a sequence of three characters
903          that indicate various sorts of communication state.  */
904
905       if (c == '{')
906         {
907           /* Read the other two chars of the trigraph. */
908           c2 = readchar (timeout);
909           c3 = readchar (timeout);
910           if (remote_debug)
911             fprintf_unfiltered (gdb_stdlog, "Trigraph %c%c%c received\n",
912                                 c, c2, c3);
913           if (c3 == '+')
914             {
915               message_pending = 1;
916               return 0;         /*???? */
917             }
918           continue;
919         }
920
921       val = read_frame (inbuf);
922
923       if (val == 1)
924         {
925           fromb64 (inbuf, header, 4);
926           /* (should check out other bits) */
927           fromb64 (inbuf + 4, buf, strlen (inbuf) - 4);
928
929           len = header[2];
930
931           csum = 0;
932           csum = compute_checksum (csum, buf, len);
933           csum = compute_checksum (csum, header + 1, 2);
934
935           if (csum != header[0])
936             fprintf_unfiltered (gdb_stderr,
937                             "Checksum mismatch: computed %d, received %d\n",
938                                 csum, header[0]);
939
940           if (header[2] == 0xff)
941             fprintf_unfiltered (gdb_stderr, "Requesting resend...\n");
942
943           if (remote_debug)
944             {
945               fprintf_unfiltered (gdb_stdlog,
946                                 "... (Got checksum %d, id %d, length %d)\n",
947                                   header[0], header[1], header[2]);
948               fprintf_unfiltered (gdb_stdlog, "Message received: \"");
949               for (i = 0; i < len; ++i)
950                 {
951                   fprintf_unfiltered (gdb_stdlog, "%02x", (unsigned char) buf[i]);
952                 }
953               fprintf_unfiltered (gdb_stdlog, "\"\n");
954             }
955
956           /* no ack required? */
957           return len;
958         }
959
960       /* Try the whole thing again.  */
961     retry:
962       /* need to do something here */
963       ;
964     }
965
966   /* We have tried hard enough, and just can't receive the packet.  Give up. */
967
968   printf_unfiltered ("Ignoring packet error, continuing...\n");
969   return 0;
970 }
971 \f
972 static void
973 sds_kill (void)
974 {
975   /* Don't try to do anything to the target.  */
976 }
977
978 static void
979 sds_mourn (void)
980 {
981   unpush_target (&sds_ops);
982   generic_mourn_inferior ();
983 }
984
985 static void
986 sds_create_inferior (char *exec_file, char *args, char **env, int from_tty)
987 {
988   inferior_ptid = pid_to_ptid (42000);
989
990   /* Clean up from the last time we were running.  */
991   clear_proceed_status ();
992
993   /* Let the remote process run.  */
994   proceed (bfd_get_start_address (exec_bfd), TARGET_SIGNAL_0, 0);
995 }
996
997 static void
998 sds_load (char *filename, int from_tty)
999 {
1000   generic_load (filename, from_tty);
1001
1002   inferior_ptid = null_ptid;
1003 }
1004 \f
1005 /* The SDS monitor has commands for breakpoint insertion, although it
1006    it doesn't actually manage the breakpoints, it just returns the
1007    replaced instruction back to the debugger.  */
1008
1009 static int
1010 sds_insert_breakpoint (CORE_ADDR addr, char *contents_cache)
1011 {
1012   int i, retlen;
1013   unsigned char *p, buf[PBUFSIZ];
1014
1015   p = buf;
1016   *p++ = 16;
1017   *p++ = 0;
1018   *p++ = (int) (addr >> 24) & 0xff;
1019   *p++ = (int) (addr >> 16) & 0xff;
1020   *p++ = (int) (addr >> 8) & 0xff;
1021   *p++ = (int) (addr) & 0xff;
1022
1023   retlen = sds_send (buf, p - buf);
1024
1025   for (i = 0; i < 4; ++i)
1026     contents_cache[i] = buf[i + 2];
1027
1028   return 0;
1029 }
1030
1031 static int
1032 sds_remove_breakpoint (CORE_ADDR addr, char *contents_cache)
1033 {
1034   int i, retlen;
1035   unsigned char *p, buf[PBUFSIZ];
1036
1037   p = buf;
1038   *p++ = 17;
1039   *p++ = 0;
1040   *p++ = (int) (addr >> 24) & 0xff;
1041   *p++ = (int) (addr >> 16) & 0xff;
1042   *p++ = (int) (addr >> 8) & 0xff;
1043   *p++ = (int) (addr) & 0xff;
1044   for (i = 0; i < 4; ++i)
1045     *p++ = contents_cache[i];
1046
1047   retlen = sds_send (buf, p - buf);
1048
1049   return 0;
1050 }
1051 \f
1052 static void
1053 init_sds_ops (void)
1054 {
1055   sds_ops.to_shortname = "sds";
1056   sds_ops.to_longname = "Remote serial target with SDS protocol";
1057   sds_ops.to_doc = "Use a remote computer via a serial line; using the SDS protocol.\n\
1058 Specify the serial device it is connected to (e.g. /dev/ttya).";
1059   sds_ops.to_open = sds_open;
1060   sds_ops.to_close = sds_close;
1061   sds_ops.to_detach = sds_detach;
1062   sds_ops.to_resume = sds_resume;
1063   sds_ops.to_wait = sds_wait;
1064   sds_ops.to_fetch_registers = sds_fetch_registers;
1065   sds_ops.to_store_registers = sds_store_registers;
1066   sds_ops.to_prepare_to_store = sds_prepare_to_store;
1067   sds_ops.to_xfer_memory = sds_xfer_memory;
1068   sds_ops.to_files_info = sds_files_info;
1069   sds_ops.to_insert_breakpoint = sds_insert_breakpoint;
1070   sds_ops.to_remove_breakpoint = sds_remove_breakpoint;
1071   sds_ops.to_kill = sds_kill;
1072   sds_ops.to_load = sds_load;
1073   sds_ops.to_create_inferior = sds_create_inferior;
1074   sds_ops.to_mourn_inferior = sds_mourn;
1075   sds_ops.to_stratum = process_stratum;
1076   sds_ops.to_has_all_memory = 1;
1077   sds_ops.to_has_memory = 1;
1078   sds_ops.to_has_stack = 1;
1079   sds_ops.to_has_registers = 1;
1080   sds_ops.to_has_execution = 1;
1081   sds_ops.to_magic = OPS_MAGIC;
1082 }
1083
1084 /* Put a command string, in args, out to the monitor and display the
1085    reply message.  */
1086
1087 static void
1088 sds_command (char *args, int from_tty)
1089 {
1090   char *p;
1091   int i, len, retlen;
1092   unsigned char buf[1000];
1093
1094   /* Convert hexadecimal chars into a byte buffer.  */
1095   p = args;
1096   len = 0;
1097   while (*p != '\0')
1098     {
1099       buf[len++] = fromhex (p[0]) * 16 + fromhex (p[1]);
1100       if (p[1] == '\0')
1101         break;
1102       p += 2;
1103     }
1104
1105   retlen = sds_send (buf, len);
1106
1107   printf_filtered ("Reply is ");
1108   for (i = 0; i < retlen; ++i)
1109     {
1110       printf_filtered ("%02x", buf[i]);
1111     }
1112   printf_filtered ("\n");
1113 }
1114
1115 void
1116 _initialize_remote_sds (void)
1117 {
1118   init_sds_ops ();
1119   add_target (&sds_ops);
1120
1121   add_show_from_set (add_set_cmd ("sdstimeout", no_class,
1122                                   var_integer, (char *) &sds_timeout,
1123                              "Set timeout value for sds read.\n", &setlist),
1124                      &showlist);
1125
1126   add_com ("sds", class_obscure, sds_command,
1127            "Send a command to the SDS monitor.");
1128 }