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