Timer8 now has a variable amount of output compare units.
[avr-sim.git] / src / GdbServer.cpp
blob9f9ab93afae847d79622fc5e909fb8dad3903231
1 /*
2 * avr-sim: An atmel AVR simulator
3 * Copyright (C) 2008 Tom Haber
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 #include "GdbServer.h"
20 #include "Format.h"
21 #include "Device.h"
22 #include "DebugInterface.h"
23 #include "AccessViolation.h"
24 #include "Instruction.h"
26 #include <iostream>
28 #ifdef WINDOWS
29 # include <winsock.h>
30 # pragma comment(lib, "wsock32.lib")
31 #else
32 # include <errno.h>
33 # include <signal.h>
34 # include <sys/socket.h>
35 # include <netinet/in.h>
36 # include <fcntl.h>
37 # include <netinet/tcp.h>
38 # include <netdb.h>
39 # include <arpa/inet.h>
40 # define closesocket(a) close( (a) )
41 #endif
43 enum {
44 BUF_SIZ = 400, /* Buffering size for read operations. */
45 MAX_BUF = 400, /* Maximum size of read/write buffers. */
46 MAX_READ_RETRY = 50, /* Maximum number of retries if a read is incomplete. */
48 MEM_SPACE_MASK = 0x00ff0000, /* mask to get bits which determine memory space */
49 FLASH_OFFSET = 0x00000000, /* Data in flash has this offset from gdb */
50 SRAM_OFFSET = 0x00800000, /* Data in sram has this offset from gdb */
51 EEPROM_OFFSET = 0x00810000, /* Data in eeprom has this offset from gdb */
53 GDB_BLOCKING_OFF = 0, /* Signify that a read is non-blocking. */
54 GDB_BLOCKING_ON = 1, /* Signify that a read will block. */
56 GDB_RET_NOTHING_RECEIVED = 5, /* if the read in non blocking receives nothing, we have nothing to do */
57 GDB_RET_SINGLE_STEP = 4, /* do one single step in gdb loop */
58 GDB_RET_CONTINUE = 3, /* step until another command from gdb is received */
59 GDB_RET_CTRL_C = 2, /* gdb has sent Ctrl-C to interrupt what is doing */
60 GDB_RET_KILL_REQUEST = 1, /* gdb has requested that sim be killed */
61 GDB_RET_OK = 0 /* continue normal processing of gdb requests */
62 /* means that we should NOT execute any step!!! */
65 namespace avr {
67 GdbServer::GdbServer(SimulationClock & clock, int port)
68 : clock(clock), current(0), sock(-1), conn(-1) {
70 openSocket(port);
71 runMode = GDB_RET_OK;
74 GdbServer::~GdbServer() {
75 closeSocket();
78 void GdbServer::add(Device *dev) {
79 DebugInterface *dbgi = dev->debugInterface();
80 devices.push_back( dbgi );
83 void GdbServer::openSocket(int port) {
84 if( (sock = socket(PF_INET, SOCK_STREAM, 0)) < 0 )
85 throw GdbException( "Can't create socket" );
87 int i = 1;
88 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
89 //fcntl(sock, F_SETFL, fcntl(sock, F_GETFL, 0) | O_NONBLOCK);
91 struct sockaddr_in address;
92 address.sin_family = AF_INET;
93 address.sin_port = htons(port);
94 memset( &address.sin_addr, 0, sizeof(address.sin_addr) );
96 if( bind( sock, (struct sockaddr *)&address, sizeof(address) ) < 0 )
97 throw GdbException( "Can't bind socket" );
99 if( listen(sock, 1) < 0 )
100 throw GdbException( "Can't listen on socket" );
102 std::cout << "Waiting on port " << port
103 << " for gdb client to connect..." << std::endl;
105 blockingOn = true;
108 void GdbServer::closeSocket() {
109 if( conn != -1 ) {
110 closesocket(conn);
111 conn = -1;
114 if( sock != -1 ) {
115 closesocket(sock);
116 sock = -1;
121 void GdbServer::acceptClient() {
122 struct sockaddr_in address;
123 socklen_t addrLength = sizeof(struct sockaddr *);
125 conn = accept( sock, (struct sockaddr *)&address, &addrLength );
126 if( conn > 0 ) {
127 /* Tell TCP not to delay small packets. This greatly speeds up
128 interactive response. WARNING: If TCP_NODELAY is set on, then gdb
129 may timeout in mid-packet if the (gdb)packet is not sent within a
130 single (tcp)packet, thus all outgoing (gdb)packets _must_ be sent
131 with a single call to write. (see Stevens "Unix Network
132 Programming", Vol 1, 2nd Ed, page 202 for more info) */
134 int i = 1;
135 setsockopt(conn, IPPROTO_TCP, TCP_NODELAY, &i, sizeof (i));
137 std::cout << "Connection opened by host "
138 << inet_ntoa( address.sin_addr )
139 << ", port " << ntohs( address.sin_port )
140 << std::endl;
144 int GdbServer::readByte() {
145 static char buf[BUFSIZ];
146 static int bufcnt = 0;
147 static char *bufp;
149 if (bufcnt-- > 0)
150 return *bufp++ & 0x7f;
152 bufcnt = read( conn, buf, sizeof(buf) );
154 if( bufcnt <= 0 ) {
155 if( bufcnt == 0 )
156 throw GdbException( "Read failed: Got EOF" );
158 if( errno == EAGAIN )
159 return -1;
161 throw GdbException( "Read failed" );
164 bufp = buf;
165 bufcnt--;
166 return *bufp++ & 0x7f;
169 void GdbServer::write( const void *buf, size_t count ) {
170 int res = ::write( conn, buf, count );
172 if( res < 0 )
173 throw GdbException( "write failed" );
175 if( (unsigned int)res != count )
176 throw GdbException( util::format("wrote only wrote %d of %d bytes") % res % count );
179 /* Acknowledge a packet from GDB */
180 void GdbServer::sendAck() {
181 write( "+", 1 );
184 void GdbServer::saveLastReply( char *reply ) {
185 if( lastReply != 0 )
186 delete [] lastReply;
188 int len = strlen( reply );
189 lastReply = new char[len];
190 strcpy( lastReply, reply );
193 static char HEX_DIGIT[] = "0123456789abcdef";
195 /* Send a reply to GDB. */
196 void GdbServer::sendReply( char *reply ) {
197 int cksum = 0;
198 int bytes;
200 /* Save the reply to last reply so we can resend if need be. */
201 if( reply != lastReply )
202 saveLastReply( reply );
204 if( *reply == '\0' ) {
205 write( "$#00", 4 );
206 } else {
207 char buf[MAX_BUF];
208 memset( buf, '\0', sizeof(buf) );
210 buf[0] = '$';
211 bytes = 1;
213 while( *reply ) {
214 cksum += (unsigned char)*reply;
215 buf[bytes] = *reply;
216 bytes++;
217 reply++;
219 /* must account for "#cc" to be added */
220 if( bytes == (MAX_BUF-3) ) {
221 /* FIXME: TRoth 2002/02/18 - splitting reply would be better */
222 throw GdbException( "buffer overflow" );
226 buf[bytes++] = '#';
227 buf[bytes++] = HEX_DIGIT[(cksum >> 4) & 0xf];
228 buf[bytes++] = HEX_DIGIT[cksum & 0xf];
230 #ifdef DEBUG
231 std::cout << util::format("Send: \"%s\"") % buf << std::endl;
232 #endif
233 write( buf, bytes );
237 void GdbServer::setBlockingMode( bool blocking ) {
238 if( blocking == blockingOn )
239 return;
241 int flags = fcntl(conn, F_GETFL, 0);
242 if( blocking ) {
243 /* turn non-blocking mode off */
244 if( fcntl( conn, F_SETFL, flags & ~O_NONBLOCK) < 0 )
245 throw GdbException( "fcntl failed" );
246 } else {
247 /* turn non-blocking mode on */
248 if (fcntl( conn, F_SETFL, flags | O_NONBLOCK) < 0)
249 throw GdbException( "fcntl failed" );
252 blockingOn = blocking;
255 /* Convert a hexidecimal digit to a 4 bit nibble. */
256 static int hex2nib( char hex ) {
257 if( (hex >= 'A') && (hex <= 'F') )
258 return (10 + (hex - 'A'));
260 else if( (hex >= 'a') && (hex <= 'f') )
261 return (10 + (hex - 'a'));
263 else if( (hex >= '0') && (hex <= '9') )
264 return (hex - '0');
266 throw GdbException( "Invalid hexidecimal digit" );
269 static byte hex2byte( char **pkt ) {
270 char *p = *pkt;
271 byte val = hex2nib(*p++);
272 val = (val << 4) | hex2nib(*p++);
273 *pkt = p;
274 return val;
277 static void putHex( char **pkt, byte val ) {
278 char *p = *pkt;
279 *p++ = HEX_DIGIT[(val >> 4) & 0xf];
280 *p++ = HEX_DIGIT[val & 0xf];
281 *pkt = p;
284 static int extractHexNum( char **pkt, char stop = '\0' ) {
285 int num = 0;
286 char *p = *pkt;
287 int max_shifts = sizeof(int)*2-1; /* max number of nibbles to shift through */
289 int i = 0;
290 while ( (*p != stop) && (*p != '\0') ) {
291 if( i > max_shifts )
292 throw GdbException( "number too large" );
294 num = (num << 4) | hex2nib(*p);
295 i++;
296 p++;
299 *pkt = p;
300 return num;
303 static void getAddrLen( char **pkt, char a_end, char l_end,
304 unsigned int & addr, int & len ) {
305 char *p = *pkt;
307 addr = 0;
308 len = 0;
310 /* Get the addr from the packet */
311 while( *p != a_end )
312 addr = (addr << 4) + hex2nib(*p++);
313 p++; /* skip over a_end */
315 /* Get the length from the packet */
316 while( *p != l_end )
317 len = (len << 4) + hex2nib(*p++);
318 p++; /* skip over l_end */
320 *pkt = p;
323 void GdbServer::queryPacket( char *pkt ) {
324 char reply[MAX_BUF];
325 memset(reply, '\0', sizeof(reply));
327 if( strcmp(pkt, "C") == 0 ) {
329 * `qC'
330 * Return the current thread id.
331 * Reply:
332 * `QC pid'
334 snprintf( reply, sizeof(reply)-1, "%02x", current );
335 } else if( strcmp(pkt, "qfThreadInfo") == 0 ) {
337 * `qfThreadInfo'
338 * `qsThreadInfo'
339 * Obtain a list of all active thread ids from the target (OS).
340 * Since there may be too many active threads to fit into one
341 * reply packet, this query works iteratively: it may require more
342 * than one query/reply sequence to obtain the entire list of threads.
343 * The first query of the sequence will be the `qfThreadInfo' query;
344 * subsequent queries in the sequence will be the `qsThreadInfo' query.
347 int n;
348 n = snprintf( reply, sizeof(reply)-1, "m %02x", 0 );
349 for(size_t i = 1; i < devices.size(); ++i)
350 snprintf( reply + n, sizeof(reply)-n-1, ",%02x", 0 );
351 } else if( strcmp(pkt, "qsThreadInfo") == 0 ) {
352 reply[0] = 'l';
355 sendReply( reply );
358 void GdbServer::readRegisters() {
359 /* (32 gpwr, SREG, SP, PC) * 2 hex bytes + terminator */
360 size_t buf_sz = (32 + 1 + 2 + 4)*2 + 1;
361 char buf[ buf_sz ];
363 char *p = buf;
364 /* 32 gen purpose working registers */
365 for( int i = 0; i<32; i++ ) {
366 byte val = devices[current]->reg(i);
367 putHex( &p, val );
371 /* GDB thinks SREG is register number 32 */
372 byte val = devices[current]->status();
373 putHex( &p, val );
377 /* GDB thinks SP is register number 33 */
378 word sp = devices[current]->stackPointer();
379 putHex( &p, sp & 0xff );
380 putHex( &p, (sp >> 8) & 0xff );
384 dword pc = devices[current]->programCounter();
385 /* GDB thinks PC is register number 34.
386 * GDB stores PC in a 32 bit value (only uses 23 bits though).
389 putHex( &p, pc & 0xff );
390 putHex( &p, (pc >> 8) & 0xff );
391 putHex( &p, (pc >> 16) & 0xff );
392 putHex( &p, (pc >> 24) & 0xff );
395 *p = '\0';
396 sendReply( buf );
399 void GdbServer::writeRegisters( char *pkt ) {
400 /* 32 gen purpose working registers */
401 for(int i = 0; i < 32; i++) {
402 byte val = hex2byte( &pkt );
403 devices[current]->setReg( i, val );
407 /* GDB thinks SREG is register number 32 */
408 byte val = hex2byte( &pkt );
409 devices[current]->setStatus( val );
413 /* GDB thinks SP is register number 33 */
414 word sp = (hex2byte( &pkt ) << 8) | hex2byte( &pkt );
415 devices[current]->setStackPointer( sp );
420 * GDB thinks PC is register number 34.
421 * GDB stores PC in a 32 bit value (only uses 23 bits though).
423 dword pc = hex2byte( &pkt ) |
424 hex2byte( &pkt ) << 8 |
425 hex2byte( &pkt ) << 16 |
426 hex2byte( &pkt ) << 24;
427 devices[current]->setProgramCounter( pc );
430 sendReply( "OK" );
433 void GdbServer::readRegister( char *pkt ) {
434 char reply[MAX_BUF];
435 memset(reply, '\0', sizeof(reply));
437 int reg = extractHexNum(&pkt, '\0');
438 if( reg < 32 ) {
439 byte val = devices[current]->reg(reg);
440 snprintf( reply, sizeof(reply)-1, "%02x", val );
441 } else if( reg == 32 ) {
442 byte val = devices[current]->status();
443 snprintf( reply, sizeof(reply)-1, "%02x", val );
444 } else if( reg == 33 ) {
445 /* SP */
446 word sp = devices[current]->stackPointer();
447 snprintf( reply, sizeof(reply)-1, "%02x%02x",
448 sp & 0xff, (sp >> 8) & 0xff );
449 } else if (reg == 34) {
450 /* PC */
451 dword val = devices[current]->programCounter();
452 snprintf( reply, sizeof(reply)-1,
453 "%02x%02x" "%02x%02x",
454 val & 0xff, (val >> 8) & 0xff,
455 (val >> 16) & 0xff, (val >> 24) & 0xff );
456 } else {
457 sendReply( "E00" );
458 return;
461 sendReply( reply );
464 void GdbServer::writeRegister( char *pkt ) {
465 int reg = extractHexNum(&pkt, '=');
466 pkt++; /* skip over '=' character */
468 /* extract the low byte of value from pkt */
469 byte val = hex2byte( &pkt );
470 if( (reg >= 0) && (reg < 33) ) {
471 /* r0 to r31 */
472 devices[current]->setReg( reg, val );
473 } else if( reg == 32 ) {
474 /* SREG is register 32 */
475 devices[current]->setStatus( val );
476 } else if( reg == 33 ) {
477 /* SP is 2 bytes long so extract upper byte */
478 byte hval = hex2byte( &pkt );
479 word sp = (hval << 8) | val;
480 devices[current]->setStackPointer( sp );
481 } else if( reg == 34 ) {
482 /* GDB thinks PC is register number 34.
483 GDB stores PC in a 32 bit value (only uses 23 bits though).
484 GDB thinks PC is bytes into flash, not words like in simulavr.
486 Must cast to dword so as not to get mysterious truncation. */
488 dword pc = val |
489 hex2byte( &pkt ) << 8 |
490 hex2byte( &pkt ) << 16 |
491 hex2byte( &pkt ) << 24;
492 devices[current]->setProgramCounter( pc );
493 } else {
494 sendReply( "E00" );
495 return;
498 sendReply( "OK" );
501 void GdbServer::readMemory( char *pkt ) {
502 unsigned int addr;
503 int len;
504 getAddrLen( &pkt, ',', '\0', addr, len );
506 char *buf = 0;
507 try {
508 const unsigned char *data;
509 if( (addr & MEM_SPACE_MASK) == EEPROM_OFFSET ) {
510 /* addressing eeprom */
511 addr = addr & ~MEM_SPACE_MASK; /* remove the offset bits */
512 data = devices[current]->readEeprom( addr, len );
513 } else if ( (addr & MEM_SPACE_MASK) == SRAM_OFFSET ) {
514 /* addressing sram */
515 addr = addr & ~MEM_SPACE_MASK; /* remove the offset bits */
517 /* Return an error to gdb if it tries to read or write any of the 32
518 general purpse registers. This allows gdb to know when a zero
519 pointer has been dereferenced. */
520 data = devices[current]->readRam( addr, len );
521 } else if ( (addr & MEM_SPACE_MASK) == FLASH_OFFSET ) {
522 /* addressing flash */
523 addr = addr & ~MEM_SPACE_MASK; /* remove the offset bits */
524 data = devices[current]->readFlash( addr, len );
525 } else {
526 throw AccessViolation( "memory space does not exist " );
529 buf = new char[len*2+1];
530 int i;
531 for(i = 0; i < len; i++) {
532 byte bval = data[i];
533 buf[i*2] = HEX_DIGIT[bval >> 4];
534 buf[i*2+1] = HEX_DIGIT[bval & 0xf];
536 buf[i*2] = '\0';
537 } catch( util::Exception & ex ) {
538 std::cerr << ex.message() << std::endl;
540 char reply[10];
541 snprintf( reply, sizeof(reply), "E%02x", EIO );
542 sendReply( reply );
543 return;
544 } catch( std::exception & ex ) {
545 std::cerr << ex.what() << std::endl;
547 char reply[10];
548 snprintf( reply, sizeof(reply), "E%02x", EIO );
549 sendReply( reply );
550 return;
553 sendReply( buf );
555 if( buf != 0 )
556 delete [] buf;
559 void GdbServer::writeMemory( char *pkt ) {
560 unsigned int addr;
561 int len;
562 getAddrLen( &pkt, ',', ':', addr, len );
564 try {
565 unsigned char *data = new unsigned char[len];
566 for(int i = 0; i < len; ++i) {
567 byte val = hex2byte( &pkt );
568 data[i] = val;
571 if( (addr & MEM_SPACE_MASK) == EEPROM_OFFSET ) {
572 /* addressing eeprom */
573 addr = addr & ~MEM_SPACE_MASK; /* remove the offset bits */
574 devices[current]->writeEeprom(data, addr, len);
575 } else if ( (addr & MEM_SPACE_MASK) == SRAM_OFFSET ) {
576 /* addressing sram */
577 addr = addr & ~MEM_SPACE_MASK; /* remove the offset bits */
578 devices[current]->writeRam(data, addr, len);
579 } else if ( (addr & MEM_SPACE_MASK) == FLASH_OFFSET ) {
580 /* addressing flash */
581 addr = addr & ~MEM_SPACE_MASK; /* remove the offset bits */
582 devices[current]->writeFlash(data, addr, len);
583 } else {
584 throw AccessViolation( "memory space does not exist " );
586 } catch( util::Exception & ex ) {
587 std::cerr << ex.message() << std::endl;
589 char reply[10];
590 snprintf( reply, sizeof(reply), "E%02x", EIO );
591 sendReply( reply );
592 return;
593 } catch( std::exception & ex ) {
594 std::cerr << ex.what() << std::endl;
596 char reply[10];
597 snprintf( reply, sizeof(reply), "E%02x", EIO );
598 sendReply( reply );
599 return;
602 sendReply( "OK" );
605 int GdbServer::getSignal( char *pkt ) {
606 int signo = hex2byte( &pkt );
609 * Process signals send via remote protocol from gdb.
610 * Signals really don't make sense to the program running
611 * in the simulator, so we are using them sort of as
612 * an 'out of band' data.
615 switch (signo) {
616 case SIGHUP:
617 /* Gdb user issuing the 'signal SIGHUP' command tells sim to reset
618 itself. We reply with a SIGTRAP the same as we do when gdb
619 makes first connection with simulator. */
620 devices[current]->reset();
621 sendReply( "S05" );
624 return signo;
628 /* Format of breakpoint commands (both insert and remove):
630 "z<t>,<addr>,<length>" - remove break/watch point
631 "Z<t>,<add>r,<length>" - insert break/watch point
633 In both cases t can be the following:
634 t = '0' - software breakpoint
635 t = '1' - hardware breakpoint
636 t = '2' - write watch point
637 t = '3' - read watch point
638 t = '4' - access watch point
640 addr is address.
641 length is in bytes
643 For a software breakpoint, length specifies the size of the instruction to
644 be patched. For hardware breakpoints and watchpoints, length specifies the
645 memory region to be monitored. To avoid potential problems, the operations
646 should be implemented in an idempotent way. -- GDB 5.0 manual.
648 void GdbServer::breakPoint( char *pkt ) {
649 char z = *(pkt-1); /* get char parser already looked at */
650 char t = *pkt++;
651 pkt++; /* skip over first ',' */
653 unsigned int addr;
654 int len;
655 getAddrLen( &pkt, ',', '\0', addr, len );
657 try {
658 switch( t ) {
659 case '0': /* software breakpoint */
660 case '1': /* hardware breakpoint */
661 if( z == 'z' )
662 devices[current]->removeBreak( addr );
663 else
664 devices[current]->insertBreak( addr );
665 break;
667 case '2': /* write watchpoint */
668 sendReply( "" );
669 return;
671 case '3': /* read watchpoint */
672 sendReply( "" );
673 return;
675 case '4': /* access watchpoint */
676 sendReply( "" );
677 return; /* unsupported yet */
680 sendReply( "OK" );
681 } catch( util::Exception & ex ) {
682 std::cerr << ex.message() << std::endl;
683 sendReply( "E01" );
687 int GdbServer::parsePacket( char *pkt ) {
688 switch( *pkt++ ) {
689 case '?': /* last signal */
690 sendReply( "S05" ); /* signal # 5 is SIGTRAP */
691 break;
693 case 'g': /* read registers */
694 readRegisters( );
695 break;
697 case 'G': /* write registers */
698 writeRegisters( pkt );
699 break;
701 case 'p': /* read a single register */
702 readRegister( pkt );
703 break;
705 case 'P': /* write single register */
706 writeRegister( pkt );
707 break;
709 case 'm': /* read memory */
710 readMemory( pkt );
711 break;
713 case 'M': /* write memory */
714 writeMemory( pkt );
715 break;
717 case 'D': /* detach the debugger */
718 case 'k': /* kill request */
719 sendReply( "OK" );
720 return GDB_RET_KILL_REQUEST;
722 case 'c': /* continue */
723 return GDB_RET_CONTINUE;
725 case 'C': /* continue with signal */
726 return GDB_RET_CONTINUE;
728 case 's': /* step */
729 return GDB_RET_SINGLE_STEP;
731 case 'S': /* step with signal */
732 getSignal(pkt);
733 return GDB_RET_SINGLE_STEP;
735 case 'z': /* remove break/watch point */
736 case 'Z': /* insert break/watch point */
737 breakPoint( pkt );
738 break;
740 case 'H': /* Set thread for subsequent operations */
742 * `H c t'
743 * Set thread for subsequent operations (`m', `M', `g', `G', et.al.).
744 * c depends on the operation to be performed: it should be `c'
745 * for step and continue operations, `g' for other operations.
746 * The thread designator t may be `-1', meaning all the threads,
747 * a thread number, or `0' which means pick any thread.
749 pkt++;
750 current = strtoul(pkt, 0, 16);
751 sendReply("OK");
752 break;
754 case 'q': /* query requests */
755 queryPacket(pkt);
756 break;
758 default:
759 sendReply( "" );
762 return GDB_RET_OK;
765 int GdbServer::readPacket() {
766 char pkt_buf[MAX_BUF];
768 memset( pkt_buf, 0, sizeof(pkt_buf) );
769 setBlockingMode( true );
771 int pkt_cksum = 0, i = 0;
772 int c = readByte();
773 while ( (c != '#') && (i < MAX_BUF) ) {
774 pkt_buf[i++] = c;
775 pkt_cksum += (unsigned char)c;
776 c = readByte();
779 int cksum;
780 cksum = hex2nib( readByte() ) << 4;
781 cksum |= hex2nib( readByte() );
783 /* FIXME: Should send "-" (Nak) instead of aborting when we get
784 checksum errors. Leave this as an error until it is actually
785 seen (I've yet to see a bad checksum - TRoth). It's not a simple
786 matter of sending (Nak) since you don't want to get into an
787 infinite loop of (bad cksum, nak, resend, repeat).*/
789 if( (pkt_cksum & 0xff) != cksum )
790 throw GdbException(
791 util::format("Bad checksum: sent 0x%x <--> computed 0x%x") % cksum % pkt_cksum );
793 #ifdef DEBUG
794 std::cout << util::format("Recv: \"$%s#%02x\"") % pkt_buf % cksum << std::endl;
795 #endif
797 /* always acknowledge a well formed packet immediately */
798 sendAck();
800 return parsePacket( pkt_buf );
803 int GdbServer::preParsePacket(bool blocking) {
804 setBlockingMode(blocking);
806 int c = readByte( );
807 switch (c) {
808 case '$': /* read a packet */
809 return readPacket();
811 case '-': // Nack
812 sendReply( lastReply );
813 break;
815 case '+': // Ack
816 break;
818 case 0x03:
819 /* Gdb sends this when the user hits C-c. This is gdb's way of
820 telling the simulator to interrupt what it is doing and return
821 control back to gdb. */
822 return GDB_RET_CTRL_C;
824 case -1:
825 /* fd is non-blocking and no data to read */
826 return GDB_RET_NOTHING_RECEIVED;
828 default:
829 std::cout << "Unknown request from gdb: "
830 << std::hex << c << std::dec << std::endl;
833 return GDB_RET_OK;
836 void GdbServer::sendPosition(int signo) {
837 /* status */
838 byte status = devices[current]->status();
839 /* SP */
840 word sp = devices[current]->stackPointer();
841 /* PC */
842 dword val = devices[current]->programCounter();
844 char reply[MAX_BUF];
845 snprintf( reply, sizeof(reply),
846 "T%02x20:%02x;21:%02x%02x;22:%02x%02x%02x%02x;",
847 signo,
848 status,
849 sp & 0xff, (sp >> 8) & 0xff,
850 val & 0xff, (val >> 8) & 0xff,
851 (val >> 16) & 0xff, (val >> 24) & 0xff);
853 sendReply(reply);
856 void GdbServer::exec() {
857 while( true ) {
858 if( conn < 0 )
859 acceptClient();
861 try {
862 if( lastReply != 0 ) {
863 delete [] lastReply;
864 lastReply = 0;
867 handleClient();
868 } catch( GdbException & ex ) {
869 std::cerr << "GdbServer " << ex.message() << std::endl;
871 devices[current]->deleteAllBreakpoints();
872 devices[current]->reset();
874 if( conn != -1 ) {
875 closesocket(conn);
876 conn = -1;
882 void GdbServer::handleClient() {
883 do {
884 int gdbRet = preParsePacket( runMode != GDB_RET_CONTINUE );
885 switch( gdbRet ) {
886 case GDB_RET_NOTHING_RECEIVED:
887 break;
889 case GDB_RET_OK:
890 runMode = GDB_RET_OK;
891 break;
893 case GDB_RET_CONTINUE:
894 runMode = GDB_RET_CONTINUE;
895 break;
897 case GDB_RET_SINGLE_STEP:
898 runMode = GDB_RET_SINGLE_STEP;
899 break;
901 case GDB_RET_CTRL_C:
902 runMode = GDB_RET_CTRL_C;
903 sendPosition(SIGINT);
904 break;
906 case GDB_RET_KILL_REQUEST:
907 devices[current]->deleteAllBreakpoints();
908 devices[current]->reset();
910 if( conn != -1 ) {
911 closesocket(conn);
912 conn = -1;
914 return;
917 } while( (runMode != GDB_RET_SINGLE_STEP ) &&
918 ( runMode != GDB_RET_CONTINUE) );
920 try {
921 do {
922 devices[current]->step();
923 } while( (runMode == GDB_RET_SINGLE_STEP )
924 && ! devices[current]->stepDone() );
926 if( devices[current]->hasBreaked() ) {
927 runMode = GDB_RET_OK;
928 sendPosition(SIGTRAP);
930 } catch( IllegalInstruction & ex ) {
931 char reply[10];
932 snprintf( reply, sizeof(reply), "S%02x", SIGILL );
933 sendReply( reply );
934 runMode = GDB_RET_OK;
935 sendPosition(SIGILL);
938 if( runMode == GDB_RET_SINGLE_STEP ) {
939 runMode = GDB_RET_OK;
940 sendPosition(SIGTRAP);