2004-07-21 Andrew Cagney <cagney@gnu.org>
[platform/upstream/binutils.git] / 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     regcache_raw_supply (current_regcache, i,
486                          &regs[DEPRECATED_REGISTER_BYTE (i)]);
487 }
488
489 /* Prepare to store registers.  Since we may send them all, we have to
490    read out the ones we don't want to change first.  */
491
492 static void
493 sds_prepare_to_store (void)
494 {
495   /* Make sure the entire registers array is valid.  */
496   deprecated_read_register_bytes (0, (char *) NULL, DEPRECATED_REGISTER_BYTES);
497 }
498
499 /* Store register REGNO, or all registers if REGNO == -1, from the contents
500    of REGISTERS.  FIXME: ignores errors.  */
501
502 static void
503 sds_store_registers (int regno)
504 {
505   unsigned char *p, buf[PBUFSIZ];
506   int i;
507
508   /* Store all the special-purpose registers.  */
509   p = buf;
510   *p++ = 19;
511   *p++ = 1;
512   *p++ = 0;
513   *p++ = 0;
514   for (i = 0; i < 4 * 6; i++)
515     *p++ = deprecated_registers[i + 4 * 32 + 8 * 32];
516   for (i = 0; i < 4 * 1; i++)
517     *p++ = 0;
518   for (i = 0; i < 4 * 4; i++)
519     *p++ = sprs[i];
520
521   sds_send (buf, p - buf);
522
523   /* Store all the general-purpose registers.  */
524   p = buf;
525   *p++ = 19;
526   *p++ = 2;
527   *p++ = 0;
528   *p++ = 0;
529   for (i = 0; i < 4 * 32; i++)
530     *p++ = deprecated_registers[i];
531
532   sds_send (buf, p - buf);
533
534 }
535 \f
536 /* Write memory data directly to the remote machine.  This does not
537    inform the data cache; the data cache uses this.  MEMADDR is the
538    address in the remote memory space.  MYADDR is the address of the
539    buffer in our space.  LEN is the number of bytes.
540
541    Returns number of bytes transferred, or 0 for error.  */
542
543 static int
544 sds_write_bytes (CORE_ADDR memaddr, char *myaddr, int len)
545 {
546   int max_buf_size;             /* Max size of packet output buffer */
547   int origlen;
548   unsigned char buf[PBUFSIZ];
549   int todo;
550   int i;
551
552   /* Chop the transfer down if necessary */
553
554   max_buf_size = 150;
555
556   origlen = len;
557   while (len > 0)
558     {
559       todo = min (len, max_buf_size);
560
561       buf[0] = 13;
562       buf[1] = 0;
563       buf[2] = (int) (memaddr >> 24) & 0xff;
564       buf[3] = (int) (memaddr >> 16) & 0xff;
565       buf[4] = (int) (memaddr >> 8) & 0xff;
566       buf[5] = (int) (memaddr) & 0xff;
567       buf[6] = 1;
568       buf[7] = 0;
569
570       for (i = 0; i < todo; i++)
571         buf[i + 8] = myaddr[i];
572
573       sds_send (buf, 8 + todo);
574
575       /* (should look at result) */
576
577       myaddr += todo;
578       memaddr += todo;
579       len -= todo;
580     }
581   return origlen;
582 }
583
584 /* Read memory data directly from the remote machine.  This does not
585    use the data cache; the data cache uses this.  MEMADDR is the
586    address in the remote memory space.  MYADDR is the address of the
587    buffer in our space.  LEN is the number of bytes.
588
589    Returns number of bytes transferred, or 0 for error.  */
590
591 static int
592 sds_read_bytes (CORE_ADDR memaddr, char *myaddr, int len)
593 {
594   int max_buf_size;             /* Max size of packet output buffer */
595   int origlen, retlen;
596   unsigned char buf[PBUFSIZ];
597   int todo;
598   int i;
599
600   /* Chop the transfer down if necessary */
601
602   max_buf_size = 150;
603
604   origlen = len;
605   while (len > 0)
606     {
607       todo = min (len, max_buf_size);
608
609       buf[0] = 12;
610       buf[1] = 0;
611       buf[2] = (int) (memaddr >> 24) & 0xff;
612       buf[3] = (int) (memaddr >> 16) & 0xff;
613       buf[4] = (int) (memaddr >> 8) & 0xff;
614       buf[5] = (int) (memaddr) & 0xff;
615       buf[6] = (int) (todo >> 8) & 0xff;
616       buf[7] = (int) (todo) & 0xff;
617       buf[8] = 1;
618
619       retlen = sds_send (buf, 9);
620
621       if (retlen - 2 != todo)
622         {
623           return 0;
624         }
625
626       /* Reply describes memory byte by byte. */
627
628       for (i = 0; i < todo; i++)
629         myaddr[i] = buf[i + 2];
630
631       myaddr += todo;
632       memaddr += todo;
633       len -= todo;
634     }
635
636   return origlen;
637 }
638 \f
639 /* Read or write LEN bytes from inferior memory at MEMADDR,
640    transferring to or from debugger address MYADDR.  Write to inferior
641    if SHOULD_WRITE is nonzero.  Returns length of data written or
642    read; 0 for error.  TARGET is unused.  */
643
644 static int
645 sds_xfer_memory (CORE_ADDR memaddr, char *myaddr, int len, int should_write,
646                  struct mem_attrib *attrib, struct target_ops *target)
647 {
648   int res;
649
650   if (should_write)
651     res = sds_write_bytes (memaddr, myaddr, len);
652   else
653     res = sds_read_bytes (memaddr, myaddr, len);
654   
655   return res;
656 }
657 \f
658
659 static void
660 sds_files_info (struct target_ops *ignore)
661 {
662   puts_filtered ("Debugging over a serial connection, using SDS protocol.\n");
663 }
664 \f
665 /* Stuff for dealing with the packets which are part of this protocol.
666    See comment at top of file for details.  */
667
668 /* Read a single character from the remote end, masking it down to 7 bits. */
669
670 static int
671 readchar (int timeout)
672 {
673   int ch;
674
675   ch = serial_readchar (sds_desc, timeout);
676
677   if (remote_debug > 1 && ch >= 0)
678     fprintf_unfiltered (gdb_stdlog, "%c(%x)", ch, ch);
679
680   switch (ch)
681     {
682     case SERIAL_EOF:
683       error ("Remote connection closed");
684     case SERIAL_ERROR:
685       perror_with_name ("Remote communication error");
686     case SERIAL_TIMEOUT:
687       return ch;
688     default:
689       return ch & 0x7f;
690     }
691 }
692
693 /* An SDS-style checksum is a sum of the bytes modulo 253.  (Presumably
694    because 253, 254, and 255 are special flags in the protocol.)  */
695
696 static int
697 compute_checksum (int csum, char *buf, int len)
698 {
699   int i;
700
701   for (i = 0; i < len; ++i)
702     csum += (unsigned char) buf[i];
703
704   csum %= 253;
705   return csum;
706 }
707
708 /* Send the command in BUF to the remote machine, and read the reply
709    into BUF also.  */
710
711 static int
712 sds_send (unsigned char *buf, int len)
713 {
714   putmessage (buf, len);
715
716   return getmessage (buf, 0);
717 }
718
719 /* Send a message to the remote machine.  */
720
721 static int
722 putmessage (unsigned char *buf, int len)
723 {
724   int i, enclen;
725   unsigned char csum = 0;
726   char buf2[PBUFSIZ], buf3[PBUFSIZ];
727   unsigned char header[3];
728   char *p;
729
730   /* Copy the packet into buffer BUF2, encapsulating it
731      and giving it a checksum.  */
732
733   if (len > 170)                /* Prosanity check */
734     internal_error (__FILE__, __LINE__, "failed internal consistency check");
735
736   if (remote_debug)
737     {
738       fprintf_unfiltered (gdb_stdlog, "Message to send: \"");
739       for (i = 0; i < len; ++i)
740         fprintf_unfiltered (gdb_stdlog, "%02x", buf[i]);
741       fprintf_unfiltered (gdb_stdlog, "\"\n");
742     }
743
744   p = buf2;
745   *p++ = '$';
746
747   if (len % 3 != 0)
748     {
749       buf[len] = '\0';
750       buf[len + 1] = '\0';
751     }
752
753   header[1] = next_msg_id;
754
755   header[2] = len;
756
757   csum = compute_checksum (csum, buf, len);
758   csum = compute_checksum (csum, header + 1, 2);
759
760   header[0] = csum;
761
762   tob64 (header, p, 3);
763   p += 4;
764   enclen = tob64 (buf, buf3, ((len + 2) / 3) * 3);
765
766   for (i = 0; i < enclen; ++i)
767     *p++ = buf3[i];
768   *p++ = '\r';
769   *p++ = '\n';
770
771   next_msg_id = (next_msg_id + 3) % 245;
772
773   /* Send it over and over until we get a positive ack.  */
774
775   while (1)
776     {
777       if (remote_debug)
778         {
779           *p = '\0';
780           fprintf_unfiltered (gdb_stdlog, "Sending encoded: \"%s\"", buf2);
781           fprintf_unfiltered (gdb_stdlog,
782                               "  (Checksum %d, id %d, length %d)\n",
783                               header[0], header[1], header[2]);
784           gdb_flush (gdb_stdlog);
785         }
786       if (serial_write (sds_desc, buf2, p - buf2))
787         perror_with_name ("putmessage: write failed");
788
789       return 1;
790     }
791 }
792
793 /* Come here after finding the start of the frame.  Collect the rest
794    into BUF.  Returns 0 on any error, 1 on success.  */
795
796 static int
797 read_frame (char *buf)
798 {
799   char *bp;
800   int c;
801
802   bp = buf;
803
804   while (1)
805     {
806       c = readchar (sds_timeout);
807
808       switch (c)
809         {
810         case SERIAL_TIMEOUT:
811           if (remote_debug)
812             fputs_filtered ("Timeout in mid-message, retrying\n", gdb_stdlog);
813           return 0;
814         case '$':
815           if (remote_debug)
816             fputs_filtered ("Saw new packet start in middle of old one\n",
817                             gdb_stdlog);
818           return 0;             /* Start a new packet, count retries */
819         case '\r':
820           break;
821
822         case '\n':
823           {
824             *bp = '\000';
825             if (remote_debug)
826               fprintf_unfiltered (gdb_stdlog, "Received encoded: \"%s\"\n",
827                                   buf);
828             return 1;
829           }
830
831         default:
832           if (bp < buf + PBUFSIZ - 1)
833             {
834               *bp++ = c;
835               continue;
836             }
837
838           *bp = '\0';
839           puts_filtered ("Message too long: ");
840           puts_filtered (buf);
841           puts_filtered ("\n");
842
843           return 0;
844         }
845     }
846 }
847
848 /* Read a packet from the remote machine, with error checking,
849    and store it in BUF.  BUF is expected to be of size PBUFSIZ.
850    If FOREVER, wait forever rather than timing out; this is used
851    while the target is executing user code.  */
852
853 static int
854 getmessage (unsigned char *buf, int forever)
855 {
856   int c, c2, c3;
857   int tries;
858   int timeout;
859   int val, i, len, csum;
860   unsigned char header[3];
861   unsigned char inbuf[500];
862
863   strcpy (buf, "timeout");
864
865   if (forever)
866     {
867       timeout = watchdog > 0 ? watchdog : -1;
868     }
869
870   else
871     timeout = sds_timeout;
872
873 #define MAX_TRIES 3
874
875   for (tries = 1; tries <= MAX_TRIES; tries++)
876     {
877       /* This can loop forever if the remote side sends us characters
878          continuously, but if it pauses, we'll get a zero from readchar
879          because of timeout.  Then we'll count that as a retry.  */
880
881       /* Note that we will only wait forever prior to the start of a packet.
882          After that, we expect characters to arrive at a brisk pace.  They
883          should show up within sds_timeout intervals.  */
884
885       do
886         {
887           c = readchar (timeout);
888
889           if (c == SERIAL_TIMEOUT)
890             {
891               if (forever)      /* Watchdog went off.  Kill the target. */
892                 {
893                   target_mourn_inferior ();
894                   error ("Watchdog has expired.  Target detached.\n");
895                 }
896               if (remote_debug)
897                 fputs_filtered ("Timed out.\n", gdb_stdlog);
898               goto retry;
899             }
900         }
901       while (c != '$' && c != '{');
902
903       /* We might have seen a "trigraph", a sequence of three characters
904          that indicate various sorts of communication state.  */
905
906       if (c == '{')
907         {
908           /* Read the other two chars of the trigraph. */
909           c2 = readchar (timeout);
910           c3 = readchar (timeout);
911           if (remote_debug)
912             fprintf_unfiltered (gdb_stdlog, "Trigraph %c%c%c received\n",
913                                 c, c2, c3);
914           if (c3 == '+')
915             {
916               message_pending = 1;
917               return 0;         /*???? */
918             }
919           continue;
920         }
921
922       val = read_frame (inbuf);
923
924       if (val == 1)
925         {
926           fromb64 (inbuf, header, 4);
927           /* (should check out other bits) */
928           fromb64 (inbuf + 4, buf, strlen (inbuf) - 4);
929
930           len = header[2];
931
932           csum = 0;
933           csum = compute_checksum (csum, buf, len);
934           csum = compute_checksum (csum, header + 1, 2);
935
936           if (csum != header[0])
937             fprintf_unfiltered (gdb_stderr,
938                             "Checksum mismatch: computed %d, received %d\n",
939                                 csum, header[0]);
940
941           if (header[2] == 0xff)
942             fprintf_unfiltered (gdb_stderr, "Requesting resend...\n");
943
944           if (remote_debug)
945             {
946               fprintf_unfiltered (gdb_stdlog,
947                                 "... (Got checksum %d, id %d, length %d)\n",
948                                   header[0], header[1], header[2]);
949               fprintf_unfiltered (gdb_stdlog, "Message received: \"");
950               for (i = 0; i < len; ++i)
951                 {
952                   fprintf_unfiltered (gdb_stdlog, "%02x", (unsigned char) buf[i]);
953                 }
954               fprintf_unfiltered (gdb_stdlog, "\"\n");
955             }
956
957           /* no ack required? */
958           return len;
959         }
960
961       /* Try the whole thing again.  */
962     retry:
963       /* need to do something here */
964       ;
965     }
966
967   /* We have tried hard enough, and just can't receive the packet.  Give up. */
968
969   printf_unfiltered ("Ignoring packet error, continuing...\n");
970   return 0;
971 }
972 \f
973 static void
974 sds_kill (void)
975 {
976   /* Don't try to do anything to the target.  */
977 }
978
979 static void
980 sds_mourn (void)
981 {
982   unpush_target (&sds_ops);
983   generic_mourn_inferior ();
984 }
985
986 static void
987 sds_create_inferior (char *exec_file, char *args, char **env, int from_tty)
988 {
989   inferior_ptid = pid_to_ptid (42000);
990
991   /* Clean up from the last time we were running.  */
992   clear_proceed_status ();
993
994   /* Let the remote process run.  */
995   proceed (bfd_get_start_address (exec_bfd), TARGET_SIGNAL_0, 0);
996 }
997
998 static void
999 sds_load (char *filename, int from_tty)
1000 {
1001   generic_load (filename, from_tty);
1002
1003   inferior_ptid = null_ptid;
1004 }
1005 \f
1006 /* The SDS monitor has commands for breakpoint insertion, although it
1007    it doesn't actually manage the breakpoints, it just returns the
1008    replaced instruction back to the debugger.  */
1009
1010 static int
1011 sds_insert_breakpoint (CORE_ADDR addr, char *contents_cache)
1012 {
1013   int i, retlen;
1014   unsigned char *p, buf[PBUFSIZ];
1015
1016   p = buf;
1017   *p++ = 16;
1018   *p++ = 0;
1019   *p++ = (int) (addr >> 24) & 0xff;
1020   *p++ = (int) (addr >> 16) & 0xff;
1021   *p++ = (int) (addr >> 8) & 0xff;
1022   *p++ = (int) (addr) & 0xff;
1023
1024   retlen = sds_send (buf, p - buf);
1025
1026   for (i = 0; i < 4; ++i)
1027     contents_cache[i] = buf[i + 2];
1028
1029   return 0;
1030 }
1031
1032 static int
1033 sds_remove_breakpoint (CORE_ADDR addr, char *contents_cache)
1034 {
1035   int i, retlen;
1036   unsigned char *p, buf[PBUFSIZ];
1037
1038   p = buf;
1039   *p++ = 17;
1040   *p++ = 0;
1041   *p++ = (int) (addr >> 24) & 0xff;
1042   *p++ = (int) (addr >> 16) & 0xff;
1043   *p++ = (int) (addr >> 8) & 0xff;
1044   *p++ = (int) (addr) & 0xff;
1045   for (i = 0; i < 4; ++i)
1046     *p++ = contents_cache[i];
1047
1048   retlen = sds_send (buf, p - buf);
1049
1050   return 0;
1051 }
1052 \f
1053 static void
1054 init_sds_ops (void)
1055 {
1056   sds_ops.to_shortname = "sds";
1057   sds_ops.to_longname = "Remote serial target with SDS protocol";
1058   sds_ops.to_doc = "Use a remote computer via a serial line; using the SDS protocol.\n\
1059 Specify the serial device it is connected to (e.g. /dev/ttya).";
1060   sds_ops.to_open = sds_open;
1061   sds_ops.to_close = sds_close;
1062   sds_ops.to_detach = sds_detach;
1063   sds_ops.to_resume = sds_resume;
1064   sds_ops.to_wait = sds_wait;
1065   sds_ops.to_fetch_registers = sds_fetch_registers;
1066   sds_ops.to_store_registers = sds_store_registers;
1067   sds_ops.to_prepare_to_store = sds_prepare_to_store;
1068   sds_ops.to_xfer_memory = sds_xfer_memory;
1069   sds_ops.to_files_info = sds_files_info;
1070   sds_ops.to_insert_breakpoint = sds_insert_breakpoint;
1071   sds_ops.to_remove_breakpoint = sds_remove_breakpoint;
1072   sds_ops.to_kill = sds_kill;
1073   sds_ops.to_load = sds_load;
1074   sds_ops.to_create_inferior = sds_create_inferior;
1075   sds_ops.to_mourn_inferior = sds_mourn;
1076   sds_ops.to_stratum = process_stratum;
1077   sds_ops.to_has_all_memory = 1;
1078   sds_ops.to_has_memory = 1;
1079   sds_ops.to_has_stack = 1;
1080   sds_ops.to_has_registers = 1;
1081   sds_ops.to_has_execution = 1;
1082   sds_ops.to_magic = OPS_MAGIC;
1083 }
1084
1085 /* Put a command string, in args, out to the monitor and display the
1086    reply message.  */
1087
1088 static void
1089 sds_command (char *args, int from_tty)
1090 {
1091   char *p;
1092   int i, len, retlen;
1093   unsigned char buf[1000];
1094
1095   /* Convert hexadecimal chars into a byte buffer.  */
1096   p = args;
1097   len = 0;
1098   while (*p != '\0')
1099     {
1100       buf[len++] = fromhex (p[0]) * 16 + fromhex (p[1]);
1101       if (p[1] == '\0')
1102         break;
1103       p += 2;
1104     }
1105
1106   retlen = sds_send (buf, len);
1107
1108   printf_filtered ("Reply is ");
1109   for (i = 0; i < retlen; ++i)
1110     {
1111       printf_filtered ("%02x", buf[i]);
1112     }
1113   printf_filtered ("\n");
1114 }
1115
1116 void
1117 _initialize_remote_sds (void)
1118 {
1119   init_sds_ops ();
1120   add_target (&sds_ops);
1121
1122   add_show_from_set (add_set_cmd ("sdstimeout", no_class,
1123                                   var_integer, (char *) &sds_timeout,
1124                              "Set timeout value for sds read.\n", &setlist),
1125                      &showlist);
1126
1127   add_com ("sds", class_obscure, sds_command,
1128            "Send a command to the SDS monitor.");
1129 }