1 /* Interface to an external GNU debugger over TCP/IP.
2 Copyright 2001, 2003 Brian R. Gaeke.
3
4 This file is part of VMIPS.
5
6 VMIPS is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2 of the License, or (at your
9 option) any later version.
10
11 VMIPS is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License along
17 with VMIPS; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
19
20 #include "debug.h"
21 #include "remotegdb.h"
22 #include "cpu.h"
23 #include "mapper.h"
24 #include "excnames.h"
25 #include "cpzeroreg.h"
26 #include "vmips.h"
27 #include "options.h"
28 #include <csignal>
29 #include <cstring>
30 #include <cstdlib>
31 #include <cerrno>
32 #include <unistd.h>
33 #include <sys/socket.h>
34 #include <netinet/in.h>
35 #include <arpa/inet.h>
36 #include <fcntl.h>
37
38 extern int remotegdb_backend_error;
39
Debug(CPU & cpu_,Mapper & mem_)40 Debug::Debug (CPU &cpu_, Mapper &mem_)
41 : cpu (&cpu_), mem (&mem_), listener (-1), threadno_step (-1),
42 threadno_gen (-1), rom_baseaddr (0), rom_nwords (0), got_interrupt (false),
43 debug_verbose (false) {
44 /* Upon connecting to our socket, gdb will ask for the current
45 * signal; so we set the current signal to the breakpoint signal.
46 */
47 signo = exccode_to_signal(Bp);
48 opt_bigendian = machine->opt->option("bigendian")->flag;
49 }
50
51 void
exception(uint16 excCode,int mode,int coprocno)52 Debug::exception(uint16 excCode, int mode, int coprocno)
53 {
54 /* Set the exception_pending flag so that target commands (or
55 * their subroutines) can catch errors and pass them back to GDB.
56 */
57 exception_pending = true;
58 }
59
60 void
debugger_interrupt(int sig)61 debugger_interrupt (int sig)
62 {
63 machine->dbgr->got_interrupt = true;
64 }
65
66 int
setup(uint32 baseaddr,uint32 nwords)67 Debug::setup(uint32 baseaddr, uint32 nwords)
68 {
69 rom_baseaddr = baseaddr;
70 rom_nwords = nwords;
71
72 /* Set up a TCP/IP socket to listen for a debugger connection. */
73 listener = setup_listener_socket();
74 if (listener >= 0) {
75 /* Print out where we bound to. */
76 print_local_name(listener);
77 } else {
78 return -1;
79 }
80
81 struct sigaction sa;
82 sa.sa_handler = debugger_interrupt;
83 sa.sa_flags = 0;
84 sigemptyset(&sa.sa_mask);
85
86 if (sigaction(SIGINT, &sa, NULL) < 0) {
87 perror ("sigaction");
88 return -1;
89 }
90 return 0;
91 }
92
93 /* True if a breakpoint has been set for the instruction given in ADDR,
94 * and false otherwise.
95 */
96 bool
breakpoint_exists(uint32 addr)97 Debug::breakpoint_exists(uint32 addr)
98 {
99 return (bp_set.find (addr) != bp_set.end ());
100 }
101
102 /* Set a breakpoint for the instruction given in ADDR. */
103 void
declare_breakpoint(uint32 addr)104 Debug::declare_breakpoint(uint32 addr)
105 {
106 bp_set.insert (addr);
107 }
108
109 /* Unset a breakpoint for the instruction given in ADDR. */
110 void
remove_breakpoint(uint32 addr)111 Debug::remove_breakpoint(uint32 addr)
112 {
113 wordset::iterator i = bp_set.find (addr);
114 if (i != bp_set.end ()) {
115 bp_set.erase (i);
116 }
117 }
118
119 /* True if ADDR is a virtual address within a known ROM block. This is pretty
120 * lame right now; we should really ask the Mapper.
121 */
122 bool
address_in_rom(uint32 addr)123 Debug::address_in_rom(uint32 addr)
124 {
125 return !((addr < rom_baseaddr) || (addr > (rom_baseaddr + 4*rom_nwords)));
126 }
127
128 /* Instructions that gdb uses to set breakpoints.
129 * These are taken from gdb/mips-tdep.c, without modification.
130 */
131 #define BIG_BREAKPOINT {0, 0x5, 0, 0xd}
132 #define LITTLE_BREAKPOINT {0xd, 0, 0x5, 0}
133
134 /* Determine whether the packet pointer passed in points to a (serial-encoded)
135 * GDB break instruction, and return true if this is the case.
136 */
137 bool
is_breakpoint_insn(char * packetptr)138 Debug::is_breakpoint_insn(char *packetptr)
139 {
140 int posn = 0;
141 char big_break_insn[] = BIG_BREAKPOINT;
142 char little_break_insn[] = LITTLE_BREAKPOINT;
143 char *break_insn;
144 int bytes;
145
146 if (opt_bigendian) {
147 break_insn = big_break_insn;
148 bytes = sizeof (big_break_insn);
149 } else /* if MIPS target is little endian */ {
150 break_insn = little_break_insn;
151 bytes = sizeof (little_break_insn);
152 }
153 while (--bytes) {
154 if (packet_pop_byte(&packetptr) != break_insn[posn++])
155 return false;
156 }
157 return true;
158 }
159
160 uint32
packet_pop_word(char ** packet)161 Debug::packet_pop_word(char **packet)
162 {
163 char valstr[10];
164 char *q, *p;
165 int i;
166 uint32 val;
167
168 p = *packet;
169 q = valstr;
170 for (i = 0; i < 8; i++) {
171 *q++ = *p++;
172 }
173 *q++ = '\0';
174 val = strtoul(valstr, NULL, 16);
175 if (!opt_bigendian)
176 val = machine->physmem->swap_word(val);
177 *packet = p;
178 return val;
179 }
180
181 uint8
packet_pop_byte(char ** packet)182 Debug::packet_pop_byte(char **packet)
183 {
184 char valstr[4];
185 char *q, *p;
186 int i;
187 uint8 val;
188
189 p = *packet;
190 q = valstr;
191 for (i = 0; i < 2; i++) {
192 *q++ = *p++;
193 }
194 *q++ = '\0';
195 val = (uint8) strtoul(valstr, NULL, 16);
196 *packet = p;
197 return val;
198 }
199
200 int
setup_listener_socket(void)201 Debug::setup_listener_socket(void)
202 {
203 int sock;
204 struct sockaddr_in addr;
205 int value;
206 unsigned int port;
207
208 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
209 if (sock < 0) {
210 perror("socket");
211 return -1;
212 }
213 memset(&addr, 0, sizeof(struct sockaddr_in));
214 addr.sin_family = AF_INET;
215 port = machine->opt->option("debugport")->num;
216 addr.sin_port = htons(port);
217 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
218 value = 1;
219 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &value,
220 sizeof(value)) < 0) {
221 perror("setsockopt SO_REUSEADDR");
222 return -1;
223 }
224 if (bind(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
225 perror("bind");
226 fprintf(stderr, "Failed bind addr: %s\n",
227 inet_ntoa(addr.sin_addr));
228 return -1;
229 }
230 if (listen(sock, 1) < 0) {
231 perror("listen");
232 return -1;
233 }
234 return sock;
235 }
236
237 int
set_nonblocking(int fd)238 Debug::set_nonblocking(int fd)
239 {
240 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) {
241 perror("fcntl: set O_NONBLOCK");
242 return -1;
243 }
244 return 0;
245 }
246
247 void
print_local_name(int s)248 Debug::print_local_name(int s)
249 {
250 struct sockaddr_in addr;
251 socklen_t addrlen = sizeof(addr);
252
253 if (getsockname(s, (struct sockaddr *) &addr, &addrlen) < 0) {
254 perror("getsockname");
255 return;
256 }
257 fprintf(stderr,
258 "Use this command to attach debugger: target remote %s:%u\n",
259 inet_ntoa(addr.sin_addr),
260 ntohs(addr.sin_port));
261 }
262
263 int
serverloop(void)264 Debug::serverloop(void)
265 {
266 int clientno = 0;
267 struct sockaddr_in clientaddr;
268 int clientsock;
269 socklen_t clientaddrlen = sizeof(clientaddr);
270 extern int remote_desc;
271
272 while (! machine->halted()) {
273 /* Block until a connection is received */
274 fprintf(stderr, "Waiting for connection from debugger.\n");
275 clientsock = accept(listener, (struct sockaddr *) &clientaddr,
276 &clientaddrlen);
277 if (clientsock < 0) {
278 perror ("accept");
279 if (errno == EINTR) {
280 /* Maybe the user attempted a ^C. */
281 machine->halt();
282 }
283 return clientsock;
284 }
285
286 fprintf(stderr, "Debugger connected.\n");
287
288 /* Set the client socket nonblocking */
289 set_nonblocking(clientsock);
290
291 remote_desc = clientsock;
292
293 targetloop();
294
295 /* We halt if the targetloop returned because of a remotegdb
296 * error.
297 */
298 if (remotegdb_backend_error) {
299 remotegdb_backend_error = 0;
300 machine->halt();
301 }
302
303 close(clientsock);
304 clientno++;
305 }
306 close(listener);
307 return 0;
308 }
309
310 void
targetloop(void)311 Debug::targetloop(void)
312 {
313 int packetno = 0;
314 char buf[PBUFSIZ];
315 char *result = NULL;
316
317 while (! machine->halted()) {
318 exception_pending = false;
319 /* Wait for a packet, and when we get it, store it in
320 * BUF. If we get an error trying to receive a packet,
321 * give up.
322 */
323 getpkt(buf, 1); if (remotegdb_backend_error) return;
324 if (debug_verbose) {
325 fprintf(stderr, "<==(%03d) \"%s\"\n", packetno, buf);
326 }
327 switch(buf[0]) {
328 case 'g': result = target_read_registers(buf); break;
329 case 'G': result = target_write_registers(buf); break;
330 case 'm': result = target_read_memory(buf); break;
331 case 'M': result = target_write_memory(buf); break;
332 case 'c': result = target_continue(buf); break;
333 case 'D': result = target_detach(buf); break;
334 case 's': result = target_step(buf); break;
335 case 'k': result = target_kill(buf); break;
336 case 'H': result = target_set_thread(buf); break;
337 case 'T': result = target_poll_thread(buf); break;
338 case '?': result = target_last_signal(buf); break;
339 case 'Z': result = target_set_or_remove_breakpoint(buf, true); break;
340 case 'z': result = target_set_or_remove_breakpoint(buf, false); break;
341 case 'q': result = target_query(buf); break;
342 default: result = target_unimplemented(buf); break;
343 }
344 if (debug_verbose) {
345 fprintf(stderr, "==>(%03d) \"%s\"\n", packetno, result);
346 }
347 packetno++;
348 putpkt(result); if (remotegdb_backend_error) return;
349 free(result);
350 }
351 return;
352 }
353
354 char *
target_query(char * pkt)355 Debug::target_query(char *pkt)
356 {
357 /* Implement just enough of the query packets to make it look like
358 * we have exactly one thread, with an ID of 1, called "Simulated
359 * Thread".
360 */
361 ++pkt;
362 if (strcmp(pkt, "C")==0) {
363 return rawpacket("QC 1");
364 } else if (strcmp(pkt, "fThreadInfo")==0) {
365 return rawpacket("m 1");
366 } else if (strcmp(pkt, "sThreadInfo")==0) {
367 return rawpacket("l");
368 } else if (strcmp(pkt, "ThreadExtraInfo,1")==0) {
369 return hexpacket("Simulated Thread");
370 } else {
371 return rawpacket("");
372 }
373 }
374
375 char *
target_kill(char * pkt)376 Debug::target_kill(char *pkt)
377 {
378 /* This is a request from GDB to kill the process being
379 * debugged. We interpret it as a request to halt the machine.
380 */
381 machine->halt();
382 return rawpacket("OK");
383 }
384
385 char *
target_set_thread(char * pkt)386 Debug::target_set_thread(char *pkt)
387 {
388 int thread_for_step = (pkt[1] == 'c');
389 long threadno;
390
391 threadno = strtol(&pkt[2], NULL, 0);
392 /* This is a request from GDB to change threads. We don't really
393 * have anything to do here, but it needs to be handled without an
394 * error for things to work. If THREAD_FOR_STEP is true, this is
395 * used to control step and continue operations. Otherwise, it is
396 * used to control general operations.
397 */
398 if ((threadno < -1) || (threadno > 1)) {
399 /* We only have one actual thread, and its number is one.
400 * Besides that, the any-thread (0) or all-thread (-1)
401 * designators are ok.
402 */
403 return error_packet(1);
404 }
405 if (thread_for_step) {
406 threadno_step = threadno;
407 } else {
408 threadno_gen = threadno;
409 }
410 return rawpacket("OK");
411 }
412
413 char *
target_poll_thread(char * pkt)414 Debug::target_poll_thread(char *pkt)
415 {
416 long threadno = strtol(&pkt[1], NULL, 16);
417 /* This is a request from GDB to check whether a thread is alive. */
418 if (threadno != 1) {
419 /* We only have one thread, and its number is one. */
420 return error_packet(1);
421 }
422 return rawpacket("OK");
423 }
424
425 char *
target_read_registers(char * pkt)426 Debug::target_read_registers(char *pkt)
427 {
428 return cpu->debug_registers_to_packet();
429 }
430
431 char *
hexpacket(const char * str)432 Debug::hexpacket(const char *str)
433 {
434 int len = strlen(str);
435 char *packet = new char[2 * len + 3];
436 for (int i = 0; i <= len; ++i) {
437 char c = str[i];
438 packet[2*i + 0] = tohex((c>>4) & 0xf);
439 packet[2*i + 1] = tohex((c>>0) & 0xf);
440 }
441 packet[2*len + 2] = '\0';
442 return packet;
443 }
444
445 char *
rawpacket(const char * str)446 Debug::rawpacket(const char *str)
447 {
448 char *packet = new char[1 + strlen(str)];
449 strcpy(packet, str);
450 return packet;
451 }
452
453 char *
target_write_registers(char * pkt)454 Debug::target_write_registers(char *pkt)
455 {
456 cpu->debug_packet_to_registers(&pkt[1]);
457 return rawpacket("OK");
458 }
459
460 char *
error_packet(int error_code)461 Debug::error_packet(int error_code)
462 {
463 char str[10];
464 sprintf(str, "E%02x", error_code);
465 return rawpacket(str);
466 }
467
468 char *
signal_packet(int signal)469 Debug::signal_packet(int signal)
470 {
471 char str[10];
472 sprintf(str, "S%02x", signal);
473 return rawpacket(str);
474 }
475
476 char *
target_read_memory(char * pkt)477 Debug::target_read_memory(char *pkt)
478 {
479 char *addrstr = &pkt[1];
480 char *lenstr = strchr(pkt, ',');
481 uint32 addr, len;
482 char *packet;
483
484 if (! lenstr) {
485 /* This read memory request is malformed, because it
486 * does not contain a comma. Send back an error.
487 */
488 return error_packet(1);
489 }
490 lenstr[0] = 0;
491 lenstr++;
492
493 addr = strtoul(addrstr, NULL, 16);
494 len = strtoul(lenstr, NULL, 16);
495
496 /* Read memory starting from ADDR w/ length LEN and return
497 * it in a packet.
498 */
499 packet = new char[2 * len + 1];
500 packet[0] = '\0';
501
502 if (cpu->debug_fetch_region(addr, len, packet, this) < 0) {
503 /* There was an error fetching memory. We could try to
504 * return a real error code, but GDB will just ignore it
505 * anyway.
506 */
507 delete [] packet;
508 return error_packet(1);
509 } else {
510 return packet;
511 }
512 }
513
514 char *
target_write_memory(char * pkt)515 Debug::target_write_memory(char *pkt)
516 {
517 char *addrstr = &pkt[1];
518 char *lenstr = strchr(pkt, ',');
519 char *datastr = strchr(pkt, ':');
520 uint32 addr, len;
521 if (! lenstr) {
522 /* This write-memory request is malformed, because the comma is
523 * missing. Send back an error packet. */
524 return error_packet(1);
525 }
526 lenstr[0] = 0;
527 lenstr++;
528 if (! datastr) {
529 /* This write-memory request is malformed, because the colon is
530 * missing. Send back an error packet. */
531 return error_packet(1);
532 }
533 datastr[0] = 0;
534 datastr++;
535 /* At this point we have found all the arguments: the address, the
536 * length of data, and the data itself. We must translate the first
537 * two into integers, and then do some special handling for ROM
538 * breakpoint support.
539 */
540 addr = strtoul(addrstr, NULL, 16);
541 len = strtoul(lenstr, NULL, 16);
542
543 if ((len == 4) && address_in_rom(addr) && is_breakpoint_insn(datastr)) {
544 /* If attempting to write a word to ROM which is a breakpoint
545 * instruction, assume GDB is trying to set a breakpoint.
546 */
547 declare_breakpoint(addr);
548 } else if ((len == 4) && address_in_rom(addr) &&
549 breakpoint_exists(addr) && !is_breakpoint_insn(datastr)) {
550 /* If attempting to write a word to ROM which is not a
551 * breakpoint instruction, and GDB previously set a breakpoint
552 * there, assume GDB is trying to clear a breakpoint.
553 */
554 remove_breakpoint(addr);
555 } else {
556 if (cpu->debug_store_region(addr, len, datastr, this) < 0) {
557 return error_packet(1);
558 }
559 }
560 return rawpacket("OK");
561 }
562
563 uint8
single_step(void)564 Debug::single_step(void)
565 {
566 if (breakpoint_exists(cpu->debug_get_pc())) {
567 return Bp; /* Simulate hitting the breakpoint. */
568 }
569 if (got_interrupt == true) {
570 return Bp; /* interrupt. */
571 }
572 machine->step();
573 return cpu->pending_exception();
574 }
575
576 char *
target_continue(char * pkt)577 Debug::target_continue(char *pkt)
578 {
579 char *addrstr = &pkt[1];
580 uint32 addr;
581 int exccode;
582
583 if (addrstr[0] != '\0') {
584 /* The user specified an address to continue from. Continue from the
585 * address given in ADDRSTR by fiddling with the CPU's PC.
586 */
587 addr = strtoul(addrstr, NULL, 16);
588 cpu->debug_set_pc(addr);
589 }
590 do {
591 exccode = single_step();
592 if (machine->halted()) {
593 /* Something happened to terminate execution.
594 * Tell GDB that the program exited.
595 */
596 return rawpacket("W00");
597 } else if (got_interrupt && (exccode == Bp)) {
598 got_interrupt = false;
599 return signal_packet (exccode_to_signal (Bp));
600 } else if (exccode != 0) {
601 signo = exccode_to_signal (exccode);
602 return signal_packet(signo);
603 }
604 } while (true);
605 }
606
607 char *
target_detach(char * pkt)608 Debug::target_detach(char *pkt)
609 {
610 return rawpacket("OK");
611 }
612
613 char *
target_step(char * pkt)614 Debug::target_step(char *pkt)
615 {
616 char *addrstr = &pkt[1];
617 uint32 addr;
618 int exccode;
619
620 if (! addrstr[0]) {
621 /* fprintf(stderr, "STUB: step from last addr\n"); */
622 } else {
623 /* fprintf(stderr, "STUB: step from addr=%s\n", addrstr); */
624 addr = strtoul(addrstr, NULL, 16);
625 cpu->debug_set_pc(addr);
626 }
627 if ((exccode = single_step()) != 0) {
628 signo = exccode_to_signal(exccode);
629 }
630 return signal_packet(signo);
631 }
632
633 char *
target_last_signal(char * pkt)634 Debug::target_last_signal(char *pkt)
635 {
636 return signal_packet(signo);
637 }
638
639 char *
target_set_or_remove_breakpoint(char * pkt,bool setting)640 Debug::target_set_or_remove_breakpoint(char *pkt, bool setting)
641 {
642 char *typestr = &pkt[1];
643 char *addrstr = strchr (pkt, ',');
644 char *lenstr;
645 uint32 type, addr, len;
646 if (!addrstr) {
647 /* Requests must specify address in hex after first comma. */
648 return error_packet(1);
649 }
650 *addrstr++ = '\0';
651 lenstr = strchr (addrstr, ',');
652 if (!lenstr) {
653 /* Requests must specify length in hex after second comma. */
654 return error_packet(1);
655 }
656 *lenstr++ = '\0';
657 type = strtoul(typestr, NULL, 10);
658 addr = strtoul(addrstr, NULL, 16);
659 len = strtoul(lenstr, NULL, 16);
660 switch (type) {
661 case 0: /* software breakpoint */
662 case 1: /* hardware breakpoint */
663 if (setting) {
664 declare_breakpoint (addr);
665 } else {
666 remove_breakpoint (addr);
667 }
668 return rawpacket("OK");
669 case 2: /* write watchpoint */
670 case 3: /* read watchpoint */
671 case 4: /* access watchpoint */
672 default:
673 return rawpacket(""); /* Not supported. */
674 }
675 }
676
677 char *
target_unimplemented(char * pkt)678 Debug::target_unimplemented(char *pkt)
679 {
680 /* fprintf(stderr, "STUB: unimplemented request [%s]\n", pkt); */
681 return rawpacket("");
682 }
683
684 /* Translates between MIPS exception codes and Unix signals (which GDB
685 * likes better.)
686 */
687 int
exccode_to_signal(int exccode)688 Debug::exccode_to_signal(int exccode)
689 {
690 const int signos[] = { 2, /* Int -> SIGINT */
691 11, 11, 11, 11, 11, /* Mod, TLBL, TLBS, AdEL, AdES -> SIGSEGV */
692 7, 7, /* IBE, DBE -> SIGBUS */
693 5, 5, /* Sys, Bp -> SIGTRAP */
694 4, /* RI -> SIGILL */
695 8, 8 }; /* CpU, OV -> SIGFPE */
696 const int defaultsig = 1; /* others -> SIGHUP */
697
698 if (exccode < Int || exccode > Ov) {
699 return defaultsig; /* SIGHUP */
700 } else {
701 return signos[exccode];
702 }
703 }
704