xref: /openbmc/u-boot/tools/gdb/remote.c (revision 9ee16897)
1 /*
2  * taken from gdb/remote.c
3  *
4  * I am only interested in the write to memory stuff - everything else
5  * has been ripped out
6  *
7  * all the copyright notices etc have been left in
8  */
9 
10 /* enough so that it will compile */
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <errno.h>
15 
16 /*nicked from gcc..*/
17 
18 #ifndef alloca
19 #ifdef __GNUC__
20 #define alloca __builtin_alloca
21 #else /* not GNU C.  */
22 #if (!defined (__STDC__) && defined (sparc)) || defined (__sparc__) || defined (__sparc) || defined (__sgi)
23 #include <alloca.h>
24 #else /* not sparc */
25 #if defined (MSDOS) && !defined (__TURBOC__)
26 #include <malloc.h>
27 #else /* not MSDOS, or __TURBOC__ */
28 #if defined(_AIX)
29 #include <malloc.h>
30  #pragma alloca
31 #else /* not MSDOS, __TURBOC__, or _AIX */
32 #ifdef __hpux
33 #endif /* __hpux */
34 #endif /* not _AIX */
35 #endif /* not MSDOS, or __TURBOC__ */
36 #endif /* not sparc.  */
37 #endif /* not GNU C.  */
38 #ifdef __cplusplus
39 extern "C" {
40 #endif
41     void* alloca(size_t);
42 #ifdef __cplusplus
43 }
44 #endif
45 #endif /* alloca not defined.  */
46 
47 
48 #include "serial.h"
49 #include "error.h"
50 #include "remote.h"
51 #define REGISTER_BYTES 0
52 #define fprintf_unfiltered fprintf
53 #define fprintf_filtered fprintf
54 #define fputs_unfiltered fputs
55 #define fputs_filtered fputs
56 #define fputc_unfiltered fputc
57 #define fputc_filtered fputc
58 #define printf_unfiltered printf
59 #define printf_filtered printf
60 #define puts_unfiltered puts
61 #define puts_filtered puts
62 #define putchar_unfiltered putchar
63 #define putchar_filtered putchar
64 #define fputstr_unfiltered(a,b,c) fputs((a), (c))
65 #define gdb_stdlog stderr
66 #define SERIAL_READCHAR(fd,timo)	serialreadchar((fd), (timo))
67 #define SERIAL_WRITE(fd, addr, len)	serialwrite((fd), (addr), (len))
68 #define error Error
69 #define perror_with_name Perror
70 #define gdb_flush fflush
71 #define max(a,b) (((a)>(b))?(a):(b))
72 #define min(a,b) (((a)<(b))?(a):(b))
73 #define target_mourn_inferior() {}
74 #define ULONGEST unsigned long
75 #define CORE_ADDR unsigned long
76 
77 static int putpkt (char *);
78 static int putpkt_binary(char *, int);
79 static void getpkt (char *, int);
80 
81 static int remote_debug = 0, remote_register_buf_size = 0, watchdog = 0;
82 
83 int remote_desc = -1, remote_timeout = 10;
84 
85 static void
86 fputstrn_unfiltered(char *s, int n, int x, FILE *fp)
87 {
88     while (n-- > 0)
89 	fputc(*s++, fp);
90 }
91 
92 void
93 remote_reset(void)
94 {
95     SERIAL_WRITE(remote_desc, "+", 1);
96 }
97 
98 void
99 remote_continue(void)
100 {
101     putpkt("c");
102 }
103 
104 /* Remote target communications for serial-line targets in custom GDB protocol
105    Copyright 1988, 91, 92, 93, 94, 95, 96, 97, 98, 1999
106    Free Software Foundation, Inc.
107 
108    This file is part of GDB.
109 
110  * SPDX-License-Identifier:	GPL-2.0+
111  */
112 /* *INDENT-OFF* */
113 /* Remote communication protocol.
114 
115    A debug packet whose contents are <data>
116    is encapsulated for transmission in the form:
117 
118 	$ <data> # CSUM1 CSUM2
119 
120 	<data> must be ASCII alphanumeric and cannot include characters
121 	'$' or '#'.  If <data> starts with two characters followed by
122 	':', then the existing stubs interpret this as a sequence number.
123 
124 	CSUM1 and CSUM2 are ascii hex representation of an 8-bit
125 	checksum of <data>, the most significant nibble is sent first.
126 	the hex digits 0-9,a-f are used.
127 
128    Receiver responds with:
129 
130 	+	- if CSUM is correct and ready for next packet
131 	-	- if CSUM is incorrect
132 
133    <data> is as follows:
134    Most values are encoded in ascii hex digits.  Signal numbers are according
135    to the numbering in target.h.
136 
137 	Request		Packet
138 
139 	set thread	Hct...		Set thread for subsequent operations.
140 					c = 'c' for thread used in step and
141 					continue; t... can be -1 for all
142 					threads.
143 					c = 'g' for thread used in other
144 					operations.  If zero, pick a thread,
145 					any thread.
146 	reply		OK		for success
147 			ENN		for an error.
148 
149 	read registers  g
150 	reply		XX....X		Each byte of register data
151 					is described by two hex digits.
152 					Registers are in the internal order
153 					for GDB, and the bytes in a register
154 					are in the same order the machine uses.
155 			or ENN		for an error.
156 
157 	write regs	GXX..XX		Each byte of register data
158 					is described by two hex digits.
159 	reply		OK		for success
160 			ENN		for an error
161 
162 	write reg	Pn...=r...	Write register n... with value r...,
163 					which contains two hex digits for each
164 					byte in the register (target byte
165 					order).
166 	reply		OK		for success
167 			ENN		for an error
168 	(not supported by all stubs).
169 
170 	read mem	mAA..AA,LLLL	AA..AA is address, LLLL is length.
171 	reply		XX..XX		XX..XX is mem contents
172 					Can be fewer bytes than requested
173 					if able to read only part of the data.
174 			or ENN		NN is errno
175 
176 	write mem	MAA..AA,LLLL:XX..XX
177 					AA..AA is address,
178 					LLLL is number of bytes,
179 					XX..XX is data
180 	reply		OK		for success
181 			ENN		for an error (this includes the case
182 					where only part of the data was
183 					written).
184 
185 	write mem       XAA..AA,LLLL:XX..XX
186 	 (binary)                       AA..AA is address,
187 					LLLL is number of bytes,
188 					XX..XX is binary data
189 	reply           OK              for success
190 			ENN             for an error
191 
192 	continue	cAA..AA		AA..AA is address to resume
193 					If AA..AA is omitted,
194 					resume at same address.
195 
196 	step		sAA..AA		AA..AA is address to resume
197 					If AA..AA is omitted,
198 					resume at same address.
199 
200 	continue with	Csig;AA..AA	Continue with signal sig (hex signal
201 	signal				number).  If ;AA..AA is omitted,
202 					resume at same address.
203 
204 	step with	Ssig;AA..AA	Like 'C' but step not continue.
205 	signal
206 
207 	last signal     ?               Reply the current reason for stopping.
208 					This is the same reply as is generated
209 					for step or cont : SAA where AA is the
210 					signal number.
211 
212 	detach          D               Reply OK.
213 
214 	There is no immediate reply to step or cont.
215 	The reply comes when the machine stops.
216 	It is		SAA		AA is the signal number.
217 
218 	or...		TAAn...:r...;n...:r...;n...:r...;
219 					AA = signal number
220 					n... = register number (hex)
221 					  r... = register contents
222 					n... = `thread'
223 					  r... = thread process ID.  This is
224 						 a hex integer.
225 					n... = other string not starting
226 					    with valid hex digit.
227 					  gdb should ignore this n,r pair
228 					  and go on to the next.  This way
229 					  we can extend the protocol.
230 	or...		WAA		The process exited, and AA is
231 					the exit status.  This is only
232 					applicable for certains sorts of
233 					targets.
234 	or...		XAA		The process terminated with signal
235 					AA.
236 	or (obsolete)	NAA;tttttttt;dddddddd;bbbbbbbb
237 					AA = signal number
238 					tttttttt = address of symbol "_start"
239 					dddddddd = base of data section
240 					bbbbbbbb = base of bss  section.
241 					Note: only used by Cisco Systems
242 					targets.  The difference between this
243 					reply and the "qOffsets" query is that
244 					the 'N' packet may arrive spontaneously
245 					whereas the 'qOffsets' is a query
246 					initiated by the host debugger.
247 	or...           OXX..XX	XX..XX  is hex encoding of ASCII data. This
248 					can happen at any time while the
249 					program is running and the debugger
250 					should continue to wait for
251 					'W', 'T', etc.
252 
253 	thread alive	TXX		Find out if the thread XX is alive.
254 	reply		OK		thread is still alive
255 			ENN		thread is dead
256 
257 	remote restart	RXX		Restart the remote server
258 
259 	extended ops	!		Use the extended remote protocol.
260 					Sticky -- only needs to be set once.
261 
262 	kill request	k
263 
264 	toggle debug	d		toggle debug flag (see 386 & 68k stubs)
265 	reset		r		reset -- see sparc stub.
266 	reserved	<other>		On other requests, the stub should
267 					ignore the request and send an empty
268 					response ($#<checksum>).  This way
269 					we can extend the protocol and GDB
270 					can tell whether the stub it is
271 					talking to uses the old or the new.
272 	search		tAA:PP,MM	Search backwards starting at address
273 					AA for a match with pattern PP and
274 					mask MM.  PP and MM are 4 bytes.
275 					Not supported by all stubs.
276 
277 	general query	qXXXX		Request info about XXXX.
278 	general set	QXXXX=yyyy	Set value of XXXX to yyyy.
279 	query sect offs	qOffsets	Get section offsets.  Reply is
280 					Text=xxx;Data=yyy;Bss=zzz
281 
282 	Responses can be run-length encoded to save space.  A '*' means that
283 	the next character is an ASCII encoding giving a repeat count which
284 	stands for that many repititions of the character preceding the '*'.
285 	The encoding is n+29, yielding a printable character where n >=3
286 	(which is where rle starts to win).  Don't use an n > 126.
287 
288 	So
289 	"0* " means the same as "0000".  */
290 /* *INDENT-ON* */
291 
292 /* This variable (available to the user via "set remotebinarydownload")
293    dictates whether downloads are sent in binary (via the 'X' packet).
294    We assume that the stub can, and attempt to do it. This will be cleared if
295    the stub does not understand it. This switch is still needed, though
296    in cases when the packet is supported in the stub, but the connection
297    does not allow it (i.e., 7-bit serial connection only). */
298 static int remote_binary_download = 1;
299 
300 /* Have we already checked whether binary downloads work? */
301 static int remote_binary_checked;
302 
303 /* Maximum number of bytes to read/write at once.  The value here
304    is chosen to fill up a packet (the headers account for the 32).  */
305 #define MAXBUFBYTES(N) (((N)-32)/2)
306 
307 /* Having this larger than 400 causes us to be incompatible with m68k-stub.c
308    and i386-stub.c.  Normally, no one would notice because it only matters
309    for writing large chunks of memory (e.g. in downloads).  Also, this needs
310    to be more than 400 if required to hold the registers (see below, where
311    we round it up based on REGISTER_BYTES).  */
312 /* Round up PBUFSIZ to hold all the registers, at least.  */
313 #define	PBUFSIZ ((REGISTER_BYTES > MAXBUFBYTES (400)) \
314 		 ? (REGISTER_BYTES * 2 + 32) \
315 		 : 400)
316 
317 
318 /* This variable sets the number of bytes to be written to the target
319    in a single packet.  Normally PBUFSIZ is satisfactory, but some
320    targets need smaller values (perhaps because the receiving end
321    is slow).  */
322 
323 static int remote_write_size = 0x7fffffff;
324 
325 /* This variable sets the number of bits in an address that are to be
326    sent in a memory ("M" or "m") packet.  Normally, after stripping
327    leading zeros, the entire address would be sent. This variable
328    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
329    initial implementation of remote.c restricted the address sent in
330    memory packets to ``host::sizeof long'' bytes - (typically 32
331    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
332    address was never sent.  Since fixing this bug may cause a break in
333    some remote targets this variable is principly provided to
334    facilitate backward compatibility. */
335 
336 static int remote_address_size;
337 
338 /* Convert hex digit A to a number.  */
339 
340 static int
341 fromhex (int a)
342 {
343   if (a >= '0' && a <= '9')
344     return a - '0';
345   else if (a >= 'a' && a <= 'f')
346     return a - 'a' + 10;
347   else if (a >= 'A' && a <= 'F')
348     return a - 'A' + 10;
349   else {
350     error ("Reply contains invalid hex digit %d", a);
351     return -1;
352   }
353 }
354 
355 /* Convert number NIB to a hex digit.  */
356 
357 static int
358 tohex (int nib)
359 {
360   if (nib < 10)
361     return '0' + nib;
362   else
363     return 'a' + nib - 10;
364 }
365 
366 /* Return the number of hex digits in num.  */
367 
368 static int
369 hexnumlen (ULONGEST num)
370 {
371   int i;
372 
373   for (i = 0; num != 0; i++)
374     num >>= 4;
375 
376   return max (i, 1);
377 }
378 
379 /* Set BUF to the hex digits representing NUM.  */
380 
381 static int
382 hexnumstr (char *buf, ULONGEST num)
383 {
384   int i;
385   int len = hexnumlen (num);
386 
387   buf[len] = '\0';
388 
389   for (i = len - 1; i >= 0; i--)
390     {
391       buf[i] = "0123456789abcdef"[(num & 0xf)];
392       num >>= 4;
393     }
394 
395   return len;
396 }
397 
398 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
399 
400 static CORE_ADDR
401 remote_address_masked (CORE_ADDR addr)
402 {
403   if (remote_address_size > 0
404       && remote_address_size < (sizeof (ULONGEST) * 8))
405     {
406       /* Only create a mask when that mask can safely be constructed
407 	 in a ULONGEST variable. */
408       ULONGEST mask = 1;
409       mask = (mask << remote_address_size) - 1;
410       addr &= mask;
411     }
412   return addr;
413 }
414 
415 /* Determine whether the remote target supports binary downloading.
416    This is accomplished by sending a no-op memory write of zero length
417    to the target at the specified address. It does not suffice to send
418    the whole packet, since many stubs strip the eighth bit and subsequently
419    compute a wrong checksum, which causes real havoc with remote_write_bytes.
420 
421    NOTE: This can still lose if the serial line is not eight-bit clean. In
422    cases like this, the user should clear "remotebinarydownload". */
423 static void
424 check_binary_download (CORE_ADDR addr)
425 {
426   if (remote_binary_download && !remote_binary_checked)
427     {
428       char *buf = alloca (PBUFSIZ);
429       char *p;
430       remote_binary_checked = 1;
431 
432       p = buf;
433       *p++ = 'X';
434       p += hexnumstr (p, (ULONGEST) addr);
435       *p++ = ',';
436       p += hexnumstr (p, (ULONGEST) 0);
437       *p++ = ':';
438       *p = '\0';
439 
440       putpkt_binary (buf, (int) (p - buf));
441       getpkt (buf, 0);
442 
443       if (buf[0] == '\0')
444 	remote_binary_download = 0;
445     }
446 
447   if (remote_debug)
448     {
449       if (remote_binary_download)
450 	fprintf_unfiltered (gdb_stdlog,
451 			    "binary downloading suppported by target\n");
452       else
453 	fprintf_unfiltered (gdb_stdlog,
454 			    "binary downloading NOT suppported by target\n");
455     }
456 }
457 
458 /* Write memory data directly to the remote machine.
459    This does not inform the data cache; the data cache uses this.
460    MEMADDR is the address in the remote memory space.
461    MYADDR is the address of the buffer in our space.
462    LEN is the number of bytes.
463 
464    Returns number of bytes transferred, or 0 for error.  */
465 
466 int
467 remote_write_bytes (memaddr, myaddr, len)
468      CORE_ADDR memaddr;
469      char *myaddr;
470      int len;
471 {
472   unsigned char *buf = alloca (PBUFSIZ);
473   int max_buf_size;		/* Max size of packet output buffer */
474   int origlen;
475   extern int verbose;
476 
477   /* Verify that the target can support a binary download */
478   check_binary_download (memaddr);
479 
480   /* Chop the transfer down if necessary */
481 
482   max_buf_size = min (remote_write_size, PBUFSIZ);
483   if (remote_register_buf_size != 0)
484     max_buf_size = min (max_buf_size, remote_register_buf_size);
485 
486   /* Subtract header overhead from max payload size -  $M<memaddr>,<len>:#nn */
487   max_buf_size -= 2 + hexnumlen (memaddr + len - 1) + 1 + hexnumlen (len) + 4;
488 
489   origlen = len;
490   while (len > 0)
491     {
492       unsigned char *p, *plen;
493       int todo;
494       int i;
495 
496       /* construct "M"<memaddr>","<len>":" */
497       /* sprintf (buf, "M%lx,%x:", (unsigned long) memaddr, todo); */
498       memaddr = remote_address_masked (memaddr);
499       p = buf;
500       if (remote_binary_download)
501 	{
502 	  *p++ = 'X';
503 	  todo = min (len, max_buf_size);
504 	}
505       else
506 	{
507 	  *p++ = 'M';
508 	  todo = min (len, max_buf_size / 2);	/* num bytes that will fit */
509 	}
510 
511       p += hexnumstr ((char *)p, (ULONGEST) memaddr);
512       *p++ = ',';
513 
514       plen = p;			/* remember where len field goes */
515       p += hexnumstr ((char *)p, (ULONGEST) todo);
516       *p++ = ':';
517       *p = '\0';
518 
519       /* We send target system values byte by byte, in increasing byte
520 	 addresses, each byte encoded as two hex characters (or one
521 	 binary character).  */
522       if (remote_binary_download)
523 	{
524 	  int escaped = 0;
525 	  for (i = 0;
526 	       (i < todo) && (i + escaped) < (max_buf_size - 2);
527 	       i++)
528 	    {
529 	      switch (myaddr[i] & 0xff)
530 		{
531 		case '$':
532 		case '#':
533 		case 0x7d:
534 		  /* These must be escaped */
535 		  escaped++;
536 		  *p++ = 0x7d;
537 		  *p++ = (myaddr[i] & 0xff) ^ 0x20;
538 		  break;
539 		default:
540 		  *p++ = myaddr[i] & 0xff;
541 		  break;
542 		}
543 	    }
544 
545 	  if (i < todo)
546 	    {
547 	      /* Escape chars have filled up the buffer prematurely,
548 		 and we have actually sent fewer bytes than planned.
549 		 Fix-up the length field of the packet.  */
550 
551 	      /* FIXME: will fail if new len is a shorter string than
552 		 old len.  */
553 
554 	      plen += hexnumstr ((char *)plen, (ULONGEST) i);
555 	      *plen++ = ':';
556 	    }
557 	}
558       else
559 	{
560 	  for (i = 0; i < todo; i++)
561 	    {
562 	      *p++ = tohex ((myaddr[i] >> 4) & 0xf);
563 	      *p++ = tohex (myaddr[i] & 0xf);
564 	    }
565 	  *p = '\0';
566 	}
567 
568       putpkt_binary ((char *)buf, (int) (p - buf));
569       getpkt ((char *)buf, 0);
570 
571       if (buf[0] == 'E')
572 	{
573 	  /* There is no correspondance between what the remote protocol uses
574 	     for errors and errno codes.  We would like a cleaner way of
575 	     representing errors (big enough to include errno codes, bfd_error
576 	     codes, and others).  But for now just return EIO.  */
577 	  errno = EIO;
578 	  return 0;
579 	}
580 
581       /* Increment by i, not by todo, in case escape chars
582 	 caused us to send fewer bytes than we'd planned.  */
583       myaddr += i;
584       memaddr += i;
585       len -= i;
586 
587       if (verbose)
588 	putc('.', stderr);
589     }
590   return origlen;
591 }
592 
593 /* Stuff for dealing with the packets which are part of this protocol.
594    See comment at top of file for details.  */
595 
596 /* Read a single character from the remote end, masking it down to 7 bits. */
597 
598 static int
599 readchar (int timeout)
600 {
601   int ch;
602 
603   ch = SERIAL_READCHAR (remote_desc, timeout);
604 
605   switch (ch)
606     {
607     case SERIAL_EOF:
608       error ("Remote connection closed");
609     case SERIAL_ERROR:
610       perror_with_name ("Remote communication error");
611     case SERIAL_TIMEOUT:
612       return ch;
613     default:
614       return ch & 0x7f;
615     }
616 }
617 
618 static int
619 putpkt (buf)
620      char *buf;
621 {
622   return putpkt_binary (buf, strlen (buf));
623 }
624 
625 /* Send a packet to the remote machine, with error checking.  The data
626    of the packet is in BUF.  The string in BUF can be at most  PBUFSIZ - 5
627    to account for the $, # and checksum, and for a possible /0 if we are
628    debugging (remote_debug) and want to print the sent packet as a string */
629 
630 static int
631 putpkt_binary (buf, cnt)
632      char *buf;
633      int cnt;
634 {
635   int i;
636   unsigned char csum = 0;
637   char *buf2 = alloca (PBUFSIZ);
638   char *junkbuf = alloca (PBUFSIZ);
639 
640   int ch;
641   int tcount = 0;
642   char *p;
643 
644   /* Copy the packet into buffer BUF2, encapsulating it
645      and giving it a checksum.  */
646 
647   if (cnt > BUFSIZ - 5)		/* Prosanity check */
648     abort ();
649 
650   p = buf2;
651   *p++ = '$';
652 
653   for (i = 0; i < cnt; i++)
654     {
655       csum += buf[i];
656       *p++ = buf[i];
657     }
658   *p++ = '#';
659   *p++ = tohex ((csum >> 4) & 0xf);
660   *p++ = tohex (csum & 0xf);
661 
662   /* Send it over and over until we get a positive ack.  */
663 
664   while (1)
665     {
666       int started_error_output = 0;
667 
668       if (remote_debug)
669 	{
670 	  *p = '\0';
671 	  fprintf_unfiltered (gdb_stdlog, "Sending packet: ");
672 	  fputstrn_unfiltered (buf2, p - buf2, 0, gdb_stdlog);
673 	  fprintf_unfiltered (gdb_stdlog, "...");
674 	  gdb_flush (gdb_stdlog);
675 	}
676       if (SERIAL_WRITE (remote_desc, buf2, p - buf2))
677 	perror_with_name ("putpkt: write failed");
678 
679       /* read until either a timeout occurs (-2) or '+' is read */
680       while (1)
681 	{
682 	  ch = readchar (remote_timeout);
683 
684 	  if (remote_debug)
685 	    {
686 	      switch (ch)
687 		{
688 		case '+':
689 		case SERIAL_TIMEOUT:
690 		case '$':
691 		  if (started_error_output)
692 		    {
693 		      putchar_unfiltered ('\n');
694 		      started_error_output = 0;
695 		    }
696 		}
697 	    }
698 
699 	  switch (ch)
700 	    {
701 	    case '+':
702 	      if (remote_debug)
703 		fprintf_unfiltered (gdb_stdlog, "Ack\n");
704 	      return 1;
705 	    case SERIAL_TIMEOUT:
706 	      tcount++;
707 	      if (tcount > 3)
708 		return 0;
709 	      break;		/* Retransmit buffer */
710 	    case '$':
711 	      {
712 		/* It's probably an old response, and we're out of sync.
713 		   Just gobble up the packet and ignore it.  */
714 		getpkt (junkbuf, 0);
715 		continue;	/* Now, go look for + */
716 	      }
717 	    default:
718 	      if (remote_debug)
719 		{
720 		  if (!started_error_output)
721 		    {
722 		      started_error_output = 1;
723 		      fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
724 		    }
725 		  fputc_unfiltered (ch & 0177, gdb_stdlog);
726 		}
727 	      continue;
728 	    }
729 	  break;		/* Here to retransmit */
730 	}
731 
732 #if 0
733       /* This is wrong.  If doing a long backtrace, the user should be
734 	 able to get out next time we call QUIT, without anything as
735 	 violent as interrupt_query.  If we want to provide a way out of
736 	 here without getting to the next QUIT, it should be based on
737 	 hitting ^C twice as in remote_wait.  */
738       if (quit_flag)
739 	{
740 	  quit_flag = 0;
741 	  interrupt_query ();
742 	}
743 #endif
744     }
745 }
746 
747 /* Come here after finding the start of the frame.  Collect the rest
748    into BUF, verifying the checksum, length, and handling run-length
749    compression.  Returns 0 on any error, 1 on success.  */
750 
751 static int
752 read_frame (char *buf)
753 {
754   unsigned char csum;
755   char *bp;
756   int c;
757 
758   csum = 0;
759   bp = buf;
760 
761   while (1)
762     {
763       c = readchar (remote_timeout);
764 
765       switch (c)
766 	{
767 	case SERIAL_TIMEOUT:
768 	  if (remote_debug)
769 	    fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
770 	  return 0;
771 	case '$':
772 	  if (remote_debug)
773 	    fputs_filtered ("Saw new packet start in middle of old one\n",
774 			    gdb_stdlog);
775 	  return 0;		/* Start a new packet, count retries */
776 	case '#':
777 	  {
778 	    unsigned char pktcsum;
779 
780 	    *bp = '\000';
781 
782 	    pktcsum = fromhex (readchar (remote_timeout)) << 4;
783 	    pktcsum |= fromhex (readchar (remote_timeout));
784 
785 	    if (csum == pktcsum)
786 	      {
787 		return 1;
788 	      }
789 
790 	    if (remote_debug)
791 	      {
792 		fprintf_filtered (gdb_stdlog,
793 			      "Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
794 				  pktcsum, csum);
795 		fputs_filtered (buf, gdb_stdlog);
796 		fputs_filtered ("\n", gdb_stdlog);
797 	      }
798 	    return 0;
799 	  }
800 	case '*':		/* Run length encoding */
801 	  csum += c;
802 	  c = readchar (remote_timeout);
803 	  csum += c;
804 	  c = c - ' ' + 3;	/* Compute repeat count */
805 
806 	  if (c > 0 && c < 255 && bp + c - 1 < buf + PBUFSIZ - 1)
807 	    {
808 	      memset (bp, *(bp - 1), c);
809 	      bp += c;
810 	      continue;
811 	    }
812 
813 	  *bp = '\0';
814 	  printf_filtered ("Repeat count %d too large for buffer: ", c);
815 	  puts_filtered (buf);
816 	  puts_filtered ("\n");
817 	  return 0;
818 	default:
819 	  if (bp < buf + PBUFSIZ - 1)
820 	    {
821 	      *bp++ = c;
822 	      csum += c;
823 	      continue;
824 	    }
825 
826 	  *bp = '\0';
827 	  puts_filtered ("Remote packet too long: ");
828 	  puts_filtered (buf);
829 	  puts_filtered ("\n");
830 
831 	  return 0;
832 	}
833     }
834 }
835 
836 /* Read a packet from the remote machine, with error checking, and
837    store it in BUF.  BUF is expected to be of size PBUFSIZ.  If
838    FOREVER, wait forever rather than timing out; this is used while
839    the target is executing user code.  */
840 
841 static void
842 getpkt (buf, forever)
843      char *buf;
844      int forever;
845 {
846   int c;
847   int tries;
848   int timeout;
849   int val;
850 
851   strcpy (buf, "timeout");
852 
853   if (forever)
854     {
855       timeout = watchdog > 0 ? watchdog : -1;
856     }
857 
858   else
859     timeout = remote_timeout;
860 
861 #define MAX_TRIES 3
862 
863   for (tries = 1; tries <= MAX_TRIES; tries++)
864     {
865       /* This can loop forever if the remote side sends us characters
866 	 continuously, but if it pauses, we'll get a zero from readchar
867 	 because of timeout.  Then we'll count that as a retry.  */
868 
869       /* Note that we will only wait forever prior to the start of a packet.
870 	 After that, we expect characters to arrive at a brisk pace.  They
871 	 should show up within remote_timeout intervals.  */
872 
873       do
874 	{
875 	  c = readchar (timeout);
876 
877 	  if (c == SERIAL_TIMEOUT)
878 	    {
879 	      if (forever)	/* Watchdog went off.  Kill the target. */
880 		{
881 		  target_mourn_inferior ();
882 		  error ("Watchdog has expired.  Target detached.\n");
883 		}
884 	      if (remote_debug)
885 		fputs_filtered ("Timed out.\n", gdb_stdlog);
886 	      goto retry;
887 	    }
888 	}
889       while (c != '$');
890 
891       /* We've found the start of a packet, now collect the data.  */
892 
893       val = read_frame (buf);
894 
895       if (val == 1)
896 	{
897 	  if (remote_debug)
898 	    {
899 	      fprintf_unfiltered (gdb_stdlog, "Packet received: ");
900 	      fputstr_unfiltered (buf, 0, gdb_stdlog);
901 	      fprintf_unfiltered (gdb_stdlog, "\n");
902 	    }
903 	  SERIAL_WRITE (remote_desc, "+", 1);
904 	  return;
905 	}
906 
907       /* Try the whole thing again.  */
908     retry:
909       SERIAL_WRITE (remote_desc, "-", 1);
910     }
911 
912   /* We have tried hard enough, and just can't receive the packet.  Give up. */
913 
914   printf_unfiltered ("Ignoring packet error, continuing...\n");
915   SERIAL_WRITE (remote_desc, "+", 1);
916 }
917