1 /* remotegdb.cc - GNU Debugger glue for VMIPS remote debugger interface.
2     Based on
3    gdb/remote.c - Remote target communications for serial-line targets
4      in custom GDB protocol.
5 
6    Copyright 1988, 1991, 1992, 1993, 1994, 1995, 1996, 1997 Free Software
7      Foundation, Inc.
8    Copyright 2001, 2002, 2003 Brian R. Gaeke.
9 
10 This file is part of GDB and VMIPS.
11 
12 VMIPS is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation; either version 2 of the License, or
15 (at your option) any later version.
16 
17 VMIPS is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 GNU General Public License for more details.
21 
22 You should have received a copy of the GNU General Public License
23 along with this program; if not, write to the Free Software
24 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
25 
26 /* This file consists almost entirely of code taken from the GNU debugger
27    (gdb) version 4.17, from file gdb/remote.c.  Additions by me (brg) have
28    been tagged with my initials.
29 
30    See the GDB User Guide for the definitive details of the GDB remote
31    protocol.  The following notes correspond to the protocol for GDB
32    version 4.17.
33 
34    Remote communication protocol.
35 
36    A debug packet whose contents are <data>
37    is encapsulated for transmission in the form:
38 
39 	$ <data> # CSUM1 CSUM2
40 
41 	<data> must be ASCII alphanumeric and cannot include characters
42 	'$' or '#'.  If <data> starts with two characters followed by
43 	':', then the existing stubs interpret this as a sequence number.
44 
45 	CSUM1 and CSUM2 are ascii hex representation of an 8-bit
46 	checksum of <data>, the most significant nibble is sent first.
47 	the hex digits 0-9,a-f are used.
48 
49    Receiver responds with:
50 
51 	+	- if CSUM is correct and ready for next packet
52 	-	- if CSUM is incorrect
53 
54    <data> is as follows:
55    Most values are encoded in ascii hex digits.  Signal numbers are according
56    to the numbering in target.h.
57 
58 	Request		Packet
59 
60 	set thread	Hct...		Set thread for subsequent operations.
61 					c = 'c' for thread used in step and
62 					continue; t... can be -1 for all
63 					threads.
64 					c = 'g' for thread used in other
65 					operations.  If zero, pick a thread,
66 					any thread.
67 	reply		OK		for success
68 			ENN		for an error.
69 
70 	read registers  g
71 	reply		XX....X		Each byte of register data
72 					is described by two hex digits.
73 					Registers are in the internal order
74 					for GDB, and the bytes in a register
75 					are in the same order the machine uses.
76 			or ENN		for an error.
77 
78 	write regs	GXX..XX		Each byte of register data
79 					is described by two hex digits.
80 	reply		OK		for success
81 			ENN		for an error
82 
83         write reg	Pn...=r...	Write register n... with value r...,
84 					which contains two hex digits for each
85 					byte in the register (target byte
86 					order).
87 	reply		OK		for success
88 			ENN		for an error
89 	(not supported by all stubs).
90 
91 	read mem	mAA..AA,LLLL	AA..AA is address, LLLL is length.
92 	reply		XX..XX		XX..XX is mem contents
93 					Can be fewer bytes than requested
94 					if able to read only part of the data.
95 			or ENN		NN is errno
96 
97 	write mem	MAA..AA,LLLL:XX..XX
98 					AA..AA is address,
99 					LLLL is number of bytes,
100 					XX..XX is data
101 	reply		OK		for success
102 			ENN		for an error (this includes the case
103 					where only part of the data was
104 					written).
105 
106 	continue	cAA..AA		AA..AA is address to resume
107 					If AA..AA is omitted,
108 					resume at same address.
109 
110 	step		sAA..AA		AA..AA is address to resume
111 					If AA..AA is omitted,
112 					resume at same address.
113 
114 	continue with	Csig;AA..AA	Continue with signal sig (hex signal
115 	signal				number).  If ;AA..AA is omitted, resume
116 					at same address.
117 
118 	step with	Ssig;AA..AA	Like 'C' but step not continue.
119 	signal
120 
121 	last signal     ?               Reply the current reason for stopping.
122                                         This is the same reply as is generated
123 					for step or cont : SAA where AA is the
124 					signal number.
125 
126 	detach          D               Reply OK.
127 
128 	There is no immediate reply to step or cont.
129 	The reply comes when the machine stops.
130 	It is		SAA		AA is the signal number.
131 
132 	or...		TAAn...:r...;n...:r...;n...:r...;
133 					AA = signal number
134 					n... = register number (hex)
135 					  r... = register contents
136 					n... = `thread'
137 					  r... = thread process ID.  This is
138 						 a hex integer.
139 					n... = other string not starting
140 					    with valid hex digit.
141 					  gdb should ignore this n,r pair
142 					  and go on to the next.  This way
143 					  we can extend the protocol.
144 	or...		WAA		The process exited, and AA is
145 					the exit status.  This is only
146 					applicable for certains sorts of
147 					targets.
148 	or...		XAA		The process terminated with signal
149 					AA.
150         or...           OXX..XX	XX..XX  is hex encoding of ASCII data. This
151 					can happen at any time while the program is
152 					running and the debugger should
153 					continue to wait for 'W', 'T', etc.
154 
155 	thread alive	TXX		Find out if the thread XX is alive.
156 	reply		OK		thread is still alive
157 			ENN		thread is dead
158 
159 	remote restart	RXX		Restart the remote server
160 
161 	extended ops 	!		Use the extended remote protocol.
162 					Sticky -- only needs to be set once.
163 
164 	kill request	k
165 
166 	toggle debug	d		toggle debug flag (see 386 & 68k stubs)
167 	reset		r		reset -- see sparc stub.
168 	reserved	<other>		On other requests, the stub should
169 					ignore the request and send an empty
170 					response ($#<checksum>).  This way
171 					we can extend the protocol and GDB
172 					can tell whether the stub it is
173 					talking to uses the old or the new.
174 	search		tAA:PP,MM	Search backwards starting at address
175 					AA for a match with pattern PP and
176 					mask MM.  PP and MM are 4 bytes.
177 					Not supported by all stubs.
178 
179 	general query	qXXXX		Request info about XXXX.
180 	general set	QXXXX=yyyy	Set value of XXXX to yyyy.
181 	query sect offs	qOffsets	Get section offsets.  Reply is
182 					Text=xxx;Data=yyy;Bss=zzz
183 
184 	Responses can be run-length encoded to save space.  A '*' means that
185 	the next character is an ASCII encoding giving a repeat count which
186 	stands for that many repititions of the character preceding the '*'.
187 	The encoding is n+29, yielding a printable character where n >=3
188 	(which is where rle starts to win).  Don't use an n > 126.
189 
190 	So
191 	"0* " means the same as "0000".  */
192 
193 /* brg - I have tried to minimize changes to the original gdb source,
194  * with the exception of changes necessary to compile the file with a
195  * C++ compiler (e.g., function declarations have been revised to use
196  * new-style prototypes instead of K&R 1st edition prototypes.)
197  *
198  * A comment with an ellipse, such as the following, means
199  * stuff which was in gdb/remote.c has been omitted. */
200 
201 /* ... */
202 
203 /* brg - added glue */
204 #include <cstdarg>
205 #include <cstdio>
206 #include <cerrno>
207 #include <cstring>
208 #include <cstdlib>
209 #include <unistd.h>
210 #include <sys/time.h>
211 #include "remotegdb.h"
212 int remote_debug = 0;
213 int remote_desc;
214 int remote_timeout = 2;
215 
216 int
serial_readchar(int fd,int timeout)217 serial_readchar(int fd, int timeout)
218 {
219 	int rv = 0, errcode;
220 	char buf[2];
221 	struct timeval tv_timeout;
222 	fd_set readfds;
223 
224 	FD_ZERO(&readfds);
225 	FD_SET(fd, &readfds);
226 
227 	tv_timeout.tv_sec = timeout;
228 	tv_timeout.tv_usec = 0;
229 
230 	errcode = select(fd + 1, &readfds, NULL, NULL,
231 		(timeout<0) ? NULL : &tv_timeout);
232 	if (errcode < 0) {
233 		rv = SERIAL_ERROR;
234 	} else if (errcode == 0) {
235 		rv = SERIAL_TIMEOUT;
236 	} else if (errcode > 0) {
237 		if (FD_ISSET(fd, &readfds))
238 		{
239 			errcode = read(fd, &buf, 1);
240 			if (errcode < 0) {
241 				rv = SERIAL_ERROR;
242 			} else if (errcode == 0) {
243 				rv = SERIAL_EOF;
244 			} else if (errcode > 0) {
245 				rv = buf[0];
246 			}
247 		} else {
248 			rv = SERIAL_ERROR;
249 		}
250 	}
251 	return rv;
252 
253 }
254 
255 int
serial_write(int fd,const char * buf,int len)256 serial_write(int fd, const char *buf, int len)
257 {
258 	return ((write(fd, buf, len) == len) ? 0 : -1);
259 }
260 static FILE *gdb_stdout = stderr;
261 int remotegdb_backend_error = 0;
gdb_flush(FILE * f)262 static inline int gdb_flush(FILE *f) { return fflush(f); }
max(int i,int j)263 static inline int max(int i, int j) { return ((i>j) ? i : j); }
perror_with_name(const char * str)264 static inline void perror_with_name(const char *str) {
265   fprintf(gdb_stdout, "%s: %s\n", str, strerror(errno));
266   remotegdb_backend_error++;
267 }
puts_filtered(const char * str)268 static inline void puts_filtered(const char *str) {
269   fputs(str, gdb_stdout); fputc('\n', gdb_stdout);
270 }
putchar_unfiltered(int c)271 static inline int putchar_unfiltered(int c) { return fputc(c, gdb_stdout); }
272 #define printf_filtered printf_unfiltered
fprintf_unfiltered(FILE * f,const char * fmt,...)273 static inline int fprintf_unfiltered(FILE *f, const char *fmt, ...) {
274   va_list ap;
275   int rv;
276   va_start(ap, fmt);
277   rv = vfprintf(f, fmt, ap);
278   va_end(ap);
279   return rv;
280 }
printf_unfiltered(const char * fmt,...)281 static inline int printf_unfiltered(const char *fmt, ...) {
282   va_list ap;
283   int rv;
284   va_start(ap, fmt);
285   rv = vfprintf(gdb_stdout, fmt, ap);
286   va_end(ap);
287   return rv;
288 }
289 /* This should not cause an abort, but it will cause a halt. */
290 /* Someday we will try to support disconnect/reconnect. */
error(const char * fmt,...)291 static inline void error(const char *fmt, ...) {
292   va_list ap;
293   int rv;
294   va_start(ap, fmt);
295   rv = vfprintf(gdb_stdout, fmt, ap);
296   va_end(ap);
297   fprintf(gdb_stdout, "Debugger halting simulation.\n");
298   remotegdb_backend_error++;
299 }
300 /* brg - end added glue */
301 
302 /* This was 5 seconds, which is a long time to sit and wait.
303    Unless this is going though some terminal server or multiplexer or
304    other form of hairy serial connection, I would think 2 seconds would
305    be plenty.  */
306 
307 /* Changed to allow option to set timeout value.
308    was static int remote_timeout = 2; */
309 extern int remote_timeout;
310 
311 /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
312    remote_open knows that we don't have a file open when the program
313    starts.  */
314 /* brg - This is specified by the backend now; use an extern variable. */
315 extern int remote_desc;
316 
317 /* ... */
318 
319 /* Convert hex digit A to a number.  */
320 
fromhex(int a)321 int fromhex (int a)
322 {
323   if (a >= '0' && a <= '9')
324     return a - '0';
325   else if (a >= 'a' && a <= 'f')
326     return a - 'a' + 10;
327   else if (a >= 'A' && a <= 'F')
328     return a - 'A' + 10;
329   else {
330     error ("Reply contains invalid hex digit %d", a);
331     return a;
332   }
333 }
334 
335 /* Convert number NIB to a hex digit.  */
336 
tohex(int nib)337 int tohex (int nib)
338 {
339   if (nib < 10)
340     return '0'+nib;
341   else
342     return 'a'+nib-10;
343 }
344 
345 /* ... */
346 
347 /* Return the number of hex digits in num.  */
348 
hexnumlen(ULONGEST num)349 int hexnumlen (ULONGEST num)
350 {
351   int i;
352 
353   for (i = 0; num != 0; i++)
354     num >>= 4;
355 
356   return max (i, 1);
357 }
358 
359 /* ... */
360 
361 /* Read a single character from the remote end, masking it down to 7 bits. */
362 
readchar(int timeout)363 int readchar (int timeout)
364 {
365   int ch;
366 
367   ch = SERIAL_READCHAR (remote_desc, timeout);
368 
369   switch (ch)
370     {
371     case SERIAL_EOF:
372       error ("Debugger disconnected.\n");
373       return ch;
374     case SERIAL_ERROR:
375       perror_with_name ("Debugger communication error");
376       return ch;
377     case SERIAL_TIMEOUT:
378       return ch;
379     default:
380       return ch & 0x7f;
381     }
382 }
383 
384 /* Send the command in BUF to the remote machine,
385    and read the reply into BUF.
386    Report an error if we get an error reply.  */
387 
remote_send(char * buf)388 void remote_send (char *buf)
389 {
390   putpkt (buf);
391   getpkt (buf, 0);
392 
393   if (buf[0] == 'E')
394     error ("Remote failure reply: %s", buf);
395 }
396 
397 /* Send a packet to the remote machine, with error checking.
398    The data of the packet is in BUF.  */
399 
putpkt(char * buf)400 int putpkt (char *buf)
401 {
402   int i;
403   unsigned char csum = 0;
404   char buf2[PBUFSIZ];
405   int cnt = strlen (buf);
406   int ch;
407   int tcount = 0;
408   char *p;
409 
410   /* Copy the packet into buffer BUF2, encapsulating it
411      and giving it a checksum.  */
412 
413   if (cnt > (int) sizeof (buf2) - 5)		/* Prosanity check */
414     abort();
415 
416   p = buf2;
417   *p++ = '$';
418 
419   for (i = 0; i < cnt; i++)
420     {
421       csum += buf[i];
422       *p++ = buf[i];
423     }
424   *p++ = '#';
425   *p++ = tohex ((csum >> 4) & 0xf);
426   *p++ = tohex (csum & 0xf);
427 
428   /* Send it over and over until we get a positive ack.  */
429 
430   while (1)
431     {
432       int started_error_output = 0;
433 
434       if (remote_debug)
435 	{
436 	  *p = '\0';
437 	  printf_unfiltered ("Sending packet: %s...", buf2);
438 	  gdb_flush(gdb_stdout);
439 	}
440       if (SERIAL_WRITE (remote_desc, buf2, p - buf2))
441 	perror_with_name ("putpkt: write failed");
442 
443       /* read until either a timeout occurs (-2) or '+' is read */
444       while (1)
445 	{
446 	  ch = readchar (remote_timeout);
447 
448  	  if (remote_debug)
449 	    {
450 	      switch (ch)
451 		{
452 	    case SERIAL_EOF:
453 		return 0;
454 		case '+':
455 		case SERIAL_TIMEOUT:
456 		case '$':
457 		  if (started_error_output)
458 		    {
459 		      putchar_unfiltered ('\n');
460 		      started_error_output = 0;
461 		    }
462 		}
463 	    }
464 
465 	  switch (ch)
466 	    {
467 	    case '+':
468 	      if (remote_debug)
469 		printf_unfiltered("Ack\n");
470 	      return 1;
471 	    case SERIAL_EOF:
472 		return 0;
473 	    case SERIAL_TIMEOUT:
474 	      tcount ++;
475 	      if (tcount > 3)
476 		return 0;
477 	      break;		/* Retransmit buffer */
478 	    case '$':
479 	      {
480 		char junkbuf[PBUFSIZ];
481 
482 	      /* It's probably an old response, and we're out of sync.  Just
483 		 gobble up the packet and ignore it.  */
484 		getpkt (junkbuf, 0);
485 		continue;		/* Now, go look for + */
486 	      }
487 	    default:
488 	      if (remote_debug)
489 		{
490 		  if (!started_error_output)
491 		    {
492 		      started_error_output = 1;
493 		      printf_unfiltered ("putpkt: Junk: ");
494 		    }
495 		  putchar_unfiltered (ch & 0177);
496 		}
497 	      continue;
498 	    }
499 	  break;		/* Here to retransmit */
500 	}
501 
502 #if 0
503       /* This is wrong.  If doing a long backtrace, the user should be
504 	 able to get out next time we call QUIT, without anything as violent
505 	 as interrupt_query.  If we want to provide a way out of here
506 	 without getting to the next QUIT, it should be based on hitting
507 	 ^C twice as in remote_wait.  */
508       if (quit_flag)
509 	{
510 	  quit_flag = 0;
511 	  interrupt_query ();
512 	}
513 #endif
514     }
515 }
516 
517 /* Come here after finding the start of the frame.  Collect the rest into BUF,
518    verifying the checksum, length, and handling run-length compression.
519    Returns 0 on any error, 1 on success.  */
520 
read_frame(char * buf)521 int read_frame (char *buf)
522 {
523   unsigned char csum;
524   char *bp;
525   int c;
526 
527   csum = 0;
528   bp = buf;
529 
530   while (1)
531     {
532       c = readchar (remote_timeout);
533 
534       switch (c)
535 	{
536 	case SERIAL_TIMEOUT:
537 	  if (remote_debug)
538 	    puts_filtered ("Timeout in mid-packet, retrying\n");
539 	  return 0;
540 	case '$':
541 	  if (remote_debug)
542 	    puts_filtered ("Saw new packet start in middle of old one\n");
543 	  return 0;		/* Start a new packet, count retries */
544 	case '#':
545 	  {
546 	    unsigned char pktcsum;
547 
548 	    *bp = '\000';
549 
550 	    pktcsum = fromhex (readchar (remote_timeout)) << 4;
551 	    pktcsum |= fromhex (readchar (remote_timeout));
552 
553 	    if (csum == pktcsum)
554 	      return 1;
555 
556 	    if (remote_debug)
557 	      {
558 		printf_filtered ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
559 				 pktcsum, csum);
560 		puts_filtered (buf);
561 		puts_filtered ("\n");
562 	      }
563 	    return 0;
564 	  }
565 	case '*':		/* Run length encoding */
566 	  csum += c;
567 	  c = readchar (remote_timeout);
568 	  csum += c;
569 	  c = c - ' ' + 3;	/* Compute repeat count */
570 
571 
572 	  if (c > 0 && c < 255 && bp + c - 1 < buf + PBUFSIZ - 1)
573 	    {
574 	      memset (bp, *(bp - 1), c);
575 	      bp += c;
576 	      continue;
577 	    }
578 
579 	  *bp = '\0';
580 	  printf_filtered ("Repeat count %d too large for buffer: ", c);
581 	  puts_filtered (buf);
582 	  puts_filtered ("\n");
583 	  return 0;
584 
585 	default:
586 	  if (bp < buf + PBUFSIZ - 1)
587 	    {
588 	      *bp++ = c;
589 	      csum += c;
590 	      continue;
591 	    }
592 
593 	  *bp = '\0';
594 	  puts_filtered ("Remote packet too long: ");
595 	  puts_filtered (buf);
596 	  puts_filtered ("\n");
597 
598 	  return 0;
599 	}
600     }
601 }
602 
603 /* Read a packet from the remote machine, with error checking,
604    and store it in BUF.  BUF is expected to be of size PBUFSIZ.
605    If FOREVER, wait forever rather than timing out; this is used
606    while the target is executing user code.  */
607 
getpkt(char * buf,int forever)608 void getpkt (char *buf, int forever)
609 {
610   int c;
611   int tries;
612   int timeout;
613   int val;
614 
615   strcpy (buf,"timeout");
616 
617   if (forever)
618     {
619 #ifdef MAINTENANCE_CMDS
620       timeout = watchdog > 0 ? watchdog : -1;
621 #else
622       timeout = -1;
623 #endif
624     }
625 
626   else
627     timeout = remote_timeout;
628 
629 #define MAX_TRIES 3
630 
631   for (tries = 1; tries <= MAX_TRIES; tries++)
632     {
633       /* This can loop forever if the remote side sends us characters
634 	 continuously, but if it pauses, we'll get a zero from readchar
635 	 because of timeout.  Then we'll count that as a retry.  */
636 
637       /* Note that we will only wait forever prior to the start of a packet.
638 	 After that, we expect characters to arrive at a brisk pace.  They
639 	 should show up within remote_timeout intervals.  */
640 
641       do
642 	{
643 	  c = readchar (timeout);
644 
645 	  if (c == SERIAL_TIMEOUT)
646 	    {
647 #ifdef MAINTENANCE_CMDS
648 	      if (forever)	/* Watchdog went off.  Kill the target. */
649 		{
650 		  target_mourn_inferior ();
651 		  error ("Watchdog has expired.  Target detached.\n");
652 		}
653 #endif
654 	      if (remote_debug)
655 		puts_filtered ("Timed out.\n");
656 	      goto retry;
657 	    }
658 	  if (c == SERIAL_EOF)
659 	    {
660 	      return;
661 	    }
662 	}
663       while (c != '$');
664 
665       /* We've found the start of a packet, now collect the data.  */
666 
667       val = read_frame (buf);
668 
669       if (val == 1)
670 	{
671 	  if (remote_debug)
672 	    fprintf_unfiltered (gdb_stdout, "Packet received: %s\n", buf);
673 	  SERIAL_WRITE (remote_desc, "+", 1);
674 	  return;
675 	}
676 
677       /* Try the whole thing again.  */
678     retry:
679       SERIAL_WRITE (remote_desc, "-", 1);
680     }
681 
682   /* We have tried hard enough, and just can't receive the packet.  Give up. */
683 
684   printf_unfiltered ("Ignoring packet error, continuing...\n");
685   SERIAL_WRITE (remote_desc, "+", 1);
686 }
687 
688 /* ... */
689