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