4 #include "DebugInterface.h"
5 #include "AccessViolation.h"
6 #include "Instruction.h"
12 # pragma comment(lib, "wsock32.lib")
16 # include <sys/socket.h>
17 # include <netinet/in.h>
19 # include <netinet/tcp.h>
21 # include <arpa/inet.h>
22 # define closesocket(a) close( (a) )
26 BUF_SIZ
= 400, /* Buffering size for read operations. */
27 MAX_BUF
= 400, /* Maximum size of read/write buffers. */
28 MAX_READ_RETRY
= 50, /* Maximum number of retries if a read is incomplete. */
30 MEM_SPACE_MASK
= 0x00ff0000, /* mask to get bits which determine memory space */
31 FLASH_OFFSET
= 0x00000000, /* Data in flash has this offset from gdb */
32 SRAM_OFFSET
= 0x00800000, /* Data in sram has this offset from gdb */
33 EEPROM_OFFSET
= 0x00810000, /* Data in eeprom has this offset from gdb */
35 GDB_BLOCKING_OFF
= 0, /* Signify that a read is non-blocking. */
36 GDB_BLOCKING_ON
= 1, /* Signify that a read will block. */
38 GDB_RET_NOTHING_RECEIVED
= 5, /* if the read in non blocking receives nothing, we have nothing to do */
39 GDB_RET_SINGLE_STEP
= 4, /* do one single step in gdb loop */
40 GDB_RET_CONTINUE
= 3, /* step until another command from gdb is received */
41 GDB_RET_CTRL_C
= 2, /* gdb has sent Ctrl-C to interrupt what is doing */
42 GDB_RET_KILL_REQUEST
= 1, /* gdb has requested that sim be killed */
43 GDB_RET_OK
= 0 /* continue normal processing of gdb requests */
44 /* means that we should NOT execute any step!!! */
49 GdbServer::GdbServer(SimulationClock
& clock
, int port
)
50 : clock(clock
), current(0), sock(-1), conn(-1) {
56 GdbServer::~GdbServer() {
60 void GdbServer::add(Device
*dev
) {
61 DebugInterface
*dbgi
= dev
->debugInterface();
62 devices
.push_back( dbgi
);
65 void GdbServer::openSocket(int port
) {
66 if( (sock
= socket(PF_INET
, SOCK_STREAM
, 0)) < 0 )
67 throw GdbException( "Can't create socket" );
70 setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, &i
, sizeof(i
));
71 //fcntl(sock, F_SETFL, fcntl(sock, F_GETFL, 0) | O_NONBLOCK);
73 struct sockaddr_in address
;
74 address
.sin_family
= AF_INET
;
75 address
.sin_port
= htons(port
);
76 memset( &address
.sin_addr
, 0, sizeof(address
.sin_addr
) );
78 if( bind( sock
, (struct sockaddr
*)&address
, sizeof(address
) ) < 0 )
79 throw GdbException( "Can't bind socket" );
81 if( listen(sock
, 1) < 0 )
82 throw GdbException( "Can't listen on socket" );
84 std::cout
<< "Waiting on port " << port
85 << " for gdb client to connect..." << std::endl
;
90 void GdbServer::closeSocket() {
103 void GdbServer::acceptClient() {
104 struct sockaddr_in address
;
105 socklen_t addrLength
= sizeof(struct sockaddr
*);
107 conn
= accept( sock
, (struct sockaddr
*)&address
, &addrLength
);
109 /* Tell TCP not to delay small packets. This greatly speeds up
110 interactive response. WARNING: If TCP_NODELAY is set on, then gdb
111 may timeout in mid-packet if the (gdb)packet is not sent within a
112 single (tcp)packet, thus all outgoing (gdb)packets _must_ be sent
113 with a single call to write. (see Stevens "Unix Network
114 Programming", Vol 1, 2nd Ed, page 202 for more info) */
117 setsockopt(conn
, IPPROTO_TCP
, TCP_NODELAY
, &i
, sizeof (i
));
119 std::cout
<< "Connection opened by host "
120 << inet_ntoa( address
.sin_addr
)
121 << ", port " << ntohs( address
.sin_port
)
126 int GdbServer::readByte() {
127 static char buf
[BUFSIZ
];
128 static int bufcnt
= 0;
132 return *bufp
++ & 0x7f;
134 bufcnt
= read( conn
, buf
, sizeof(buf
) );
138 throw GdbException( "Read failed: Got EOF" );
140 if( errno
== EAGAIN
)
143 throw GdbException( "Read failed" );
148 return *bufp
++ & 0x7f;
151 void GdbServer::write( const void *buf
, size_t count
) {
152 int res
= ::write( conn
, buf
, count
);
155 throw GdbException( "write failed" );
157 if( (unsigned int)res
!= count
)
158 throw GdbException( util::format("wrote only wrote %d of %d bytes") % res
% count
);
161 /* Acknowledge a packet from GDB */
162 void GdbServer::sendAck() {
166 void GdbServer::saveLastReply( char *reply
) {
170 int len
= strlen( reply
);
171 lastReply
= new char[len
];
172 strcpy( lastReply
, reply
);
175 static char HEX_DIGIT
[] = "0123456789abcdef";
177 /* Send a reply to GDB. */
178 void GdbServer::sendReply( char *reply
) {
182 /* Save the reply to last reply so we can resend if need be. */
183 if( reply
!= lastReply
)
184 saveLastReply( reply
);
186 if( *reply
== '\0' ) {
190 memset( buf
, '\0', sizeof(buf
) );
196 cksum
+= (unsigned char)*reply
;
201 /* must account for "#cc" to be added */
202 if( bytes
== (MAX_BUF
-3) ) {
203 /* FIXME: TRoth 2002/02/18 - splitting reply would be better */
204 throw GdbException( "buffer overflow" );
209 buf
[bytes
++] = HEX_DIGIT
[(cksum
>> 4) & 0xf];
210 buf
[bytes
++] = HEX_DIGIT
[cksum
& 0xf];
213 std::cout
<< util::format("Send: \"%s\"") % buf
<< std::endl
;
219 void GdbServer::setBlockingMode( bool blocking
) {
220 if( blocking
== blockingOn
)
223 int flags
= fcntl(conn
, F_GETFL
, 0);
225 /* turn non-blocking mode off */
226 if( fcntl( conn
, F_SETFL
, flags
& ~O_NONBLOCK
) < 0 )
227 throw GdbException( "fcntl failed" );
229 /* turn non-blocking mode on */
230 if (fcntl( conn
, F_SETFL
, flags
| O_NONBLOCK
) < 0)
231 throw GdbException( "fcntl failed" );
234 blockingOn
= blocking
;
237 /* Convert a hexidecimal digit to a 4 bit nibble. */
238 static int hex2nib( char hex
) {
239 if( (hex
>= 'A') && (hex
<= 'F') )
240 return (10 + (hex
- 'A'));
242 else if( (hex
>= 'a') && (hex
<= 'f') )
243 return (10 + (hex
- 'a'));
245 else if( (hex
>= '0') && (hex
<= '9') )
248 throw GdbException( "Invalid hexidecimal digit" );
251 static byte
hex2byte( char **pkt
) {
253 byte val
= hex2nib(*p
++);
254 val
= (val
<< 4) | hex2nib(*p
++);
259 static void putHex( char **pkt
, byte val
) {
261 *p
++ = HEX_DIGIT
[(val
>> 4) & 0xf];
262 *p
++ = HEX_DIGIT
[val
& 0xf];
266 static int extractHexNum( char **pkt
, char stop
= '\0' ) {
269 int max_shifts
= sizeof(int)*2-1; /* max number of nibbles to shift through */
272 while ( (*p
!= stop
) && (*p
!= '\0') ) {
274 throw GdbException( "number too large" );
276 num
= (num
<< 4) | hex2nib(*p
);
285 static void getAddrLen( char **pkt
, char a_end
, char l_end
,
286 unsigned int & addr
, int & len
) {
292 /* Get the addr from the packet */
294 addr
= (addr
<< 4) + hex2nib(*p
++);
295 p
++; /* skip over a_end */
297 /* Get the length from the packet */
299 len
= (len
<< 4) + hex2nib(*p
++);
300 p
++; /* skip over l_end */
305 void GdbServer::queryPacket( char *pkt
) {
307 memset(reply
, '\0', sizeof(reply
));
309 if( strcmp(pkt
, "C") == 0 ) {
312 * Return the current thread id.
316 snprintf( reply
, sizeof(reply
)-1, "%02x", current
);
317 } else if( strcmp(pkt
, "qfThreadInfo") == 0 ) {
321 * Obtain a list of all active thread ids from the target (OS).
322 * Since there may be too many active threads to fit into one
323 * reply packet, this query works iteratively: it may require more
324 * than one query/reply sequence to obtain the entire list of threads.
325 * The first query of the sequence will be the `qfThreadInfo' query;
326 * subsequent queries in the sequence will be the `qsThreadInfo' query.
330 n
= snprintf( reply
, sizeof(reply
)-1, "m %02x", 0 );
331 for(size_t i
= 1; i
< devices
.size(); ++i
)
332 snprintf( reply
+ n
, sizeof(reply
)-n
-1, ",%02x", 0 );
333 } else if( strcmp(pkt
, "qsThreadInfo") == 0 ) {
340 void GdbServer::readRegisters() {
341 /* (32 gpwr, SREG, SP, PC) * 2 hex bytes + terminator */
342 size_t buf_sz
= (32 + 1 + 2 + 4)*2 + 1;
346 /* 32 gen purpose working registers */
347 for( int i
= 0; i
<32; i
++ ) {
348 byte val
= devices
[current
]->reg(i
);
353 /* GDB thinks SREG is register number 32 */
354 byte val
= devices
[current
]->status();
359 /* GDB thinks SP is register number 33 */
360 word sp
= devices
[current
]->stackPointer();
361 putHex( &p
, sp
& 0xff );
362 putHex( &p
, (sp
>> 8) & 0xff );
366 dword pc
= devices
[current
]->programCounter();
367 /* GDB thinks PC is register number 34.
368 * GDB stores PC in a 32 bit value (only uses 23 bits though).
371 putHex( &p
, pc
& 0xff );
372 putHex( &p
, (pc
>> 8) & 0xff );
373 putHex( &p
, (pc
>> 16) & 0xff );
374 putHex( &p
, (pc
>> 24) & 0xff );
381 void GdbServer::writeRegisters( char *pkt
) {
382 /* 32 gen purpose working registers */
383 for(int i
= 0; i
< 32; i
++) {
384 byte val
= hex2byte( &pkt
);
385 devices
[current
]->setReg( i
, val
);
389 /* GDB thinks SREG is register number 32 */
390 byte val
= hex2byte( &pkt
);
391 devices
[current
]->setStatus( val
);
395 /* GDB thinks SP is register number 33 */
396 word sp
= (hex2byte( &pkt
) << 8) | hex2byte( &pkt
);
397 devices
[current
]->setStackPointer( sp
);
402 * GDB thinks PC is register number 34.
403 * GDB stores PC in a 32 bit value (only uses 23 bits though).
405 dword pc
= hex2byte( &pkt
) |
406 hex2byte( &pkt
) << 8 |
407 hex2byte( &pkt
) << 16 |
408 hex2byte( &pkt
) << 24;
409 devices
[current
]->setProgramCounter( pc
);
415 void GdbServer::readRegister( char *pkt
) {
417 memset(reply
, '\0', sizeof(reply
));
419 int reg
= extractHexNum(&pkt
, '\0');
421 byte val
= devices
[current
]->reg(reg
);
422 snprintf( reply
, sizeof(reply
)-1, "%02x", val
);
423 } else if( reg
== 32 ) {
424 byte val
= devices
[current
]->status();
425 snprintf( reply
, sizeof(reply
)-1, "%02x", val
);
426 } else if( reg
== 33 ) {
428 word sp
= devices
[current
]->stackPointer();
429 snprintf( reply
, sizeof(reply
)-1, "%02x%02x",
430 sp
& 0xff, (sp
>> 8) & 0xff );
431 } else if (reg
== 34) {
433 dword val
= devices
[current
]->programCounter();
434 snprintf( reply
, sizeof(reply
)-1,
435 "%02x%02x" "%02x%02x",
436 val
& 0xff, (val
>> 8) & 0xff,
437 (val
>> 16) & 0xff, (val
>> 24) & 0xff );
446 void GdbServer::writeRegister( char *pkt
) {
447 int reg
= extractHexNum(&pkt
, '=');
448 pkt
++; /* skip over '=' character */
450 /* extract the low byte of value from pkt */
451 byte val
= hex2byte( &pkt
);
452 if( (reg
>= 0) && (reg
< 33) ) {
454 devices
[current
]->setReg( reg
, val
);
455 } else if( reg
== 32 ) {
456 /* SREG is register 32 */
457 devices
[current
]->setStatus( val
);
458 } else if( reg
== 33 ) {
459 /* SP is 2 bytes long so extract upper byte */
460 byte hval
= hex2byte( &pkt
);
461 word sp
= (hval
<< 8) | val
;
462 devices
[current
]->setStackPointer( sp
);
463 } else if( reg
== 34 ) {
464 /* GDB thinks PC is register number 34.
465 GDB stores PC in a 32 bit value (only uses 23 bits though).
466 GDB thinks PC is bytes into flash, not words like in simulavr.
468 Must cast to dword so as not to get mysterious truncation. */
471 hex2byte( &pkt
) << 8 |
472 hex2byte( &pkt
) << 16 |
473 hex2byte( &pkt
) << 24;
474 devices
[current
]->setProgramCounter( pc
);
483 void GdbServer::readMemory( char *pkt
) {
486 getAddrLen( &pkt
, ',', '\0', addr
, len
);
490 const unsigned char *data
;
491 if( (addr
& MEM_SPACE_MASK
) == EEPROM_OFFSET
) {
492 /* addressing eeprom */
493 addr
= addr
& ~MEM_SPACE_MASK
; /* remove the offset bits */
494 data
= devices
[current
]->readEeprom( addr
, len
);
495 } else if ( (addr
& MEM_SPACE_MASK
) == SRAM_OFFSET
) {
496 /* addressing sram */
497 addr
= addr
& ~MEM_SPACE_MASK
; /* remove the offset bits */
499 /* Return an error to gdb if it tries to read or write any of the 32
500 general purpse registers. This allows gdb to know when a zero
501 pointer has been dereferenced. */
502 data
= devices
[current
]->readRam( addr
, len
);
503 } else if ( (addr
& MEM_SPACE_MASK
) == FLASH_OFFSET
) {
504 /* addressing flash */
505 addr
= addr
& ~MEM_SPACE_MASK
; /* remove the offset bits */
506 data
= devices
[current
]->readFlash( addr
, len
);
508 throw AccessViolation( "memory space does not exist " );
511 buf
= new char[len
*2+1];
513 for(i
= 0; i
< len
; i
++) {
515 buf
[i
*2] = HEX_DIGIT
[bval
>> 4];
516 buf
[i
*2+1] = HEX_DIGIT
[bval
& 0xf];
519 } catch( util::Exception
& ex
) {
520 std::cerr
<< ex
.message() << std::endl
;
523 snprintf( reply
, sizeof(reply
), "E%02x", EIO
);
526 } catch( std::exception
& ex
) {
527 std::cerr
<< ex
.what() << std::endl
;
530 snprintf( reply
, sizeof(reply
), "E%02x", EIO
);
541 void GdbServer::writeMemory( char *pkt
) {
544 getAddrLen( &pkt
, ',', ':', addr
, len
);
547 unsigned char *data
= new unsigned char[len
];
548 for(int i
= 0; i
< len
; ++i
) {
549 byte val
= hex2byte( &pkt
);
553 if( (addr
& MEM_SPACE_MASK
) == EEPROM_OFFSET
) {
554 /* addressing eeprom */
555 addr
= addr
& ~MEM_SPACE_MASK
; /* remove the offset bits */
556 devices
[current
]->writeEeprom(data
, addr
, len
);
557 } else if ( (addr
& MEM_SPACE_MASK
) == SRAM_OFFSET
) {
558 /* addressing sram */
559 addr
= addr
& ~MEM_SPACE_MASK
; /* remove the offset bits */
560 devices
[current
]->writeRam(data
, addr
, len
);
561 } else if ( (addr
& MEM_SPACE_MASK
) == FLASH_OFFSET
) {
562 /* addressing flash */
563 addr
= addr
& ~MEM_SPACE_MASK
; /* remove the offset bits */
564 devices
[current
]->writeFlash(data
, addr
, len
);
566 throw AccessViolation( "memory space does not exist " );
568 } catch( util::Exception
& ex
) {
569 std::cerr
<< ex
.message() << std::endl
;
572 snprintf( reply
, sizeof(reply
), "E%02x", EIO
);
575 } catch( std::exception
& ex
) {
576 std::cerr
<< ex
.what() << std::endl
;
579 snprintf( reply
, sizeof(reply
), "E%02x", EIO
);
587 int GdbServer::getSignal( char *pkt
) {
588 int signo
= hex2byte( &pkt
);
591 * Process signals send via remote protocol from gdb.
592 * Signals really don't make sense to the program running
593 * in the simulator, so we are using them sort of as
594 * an 'out of band' data.
599 /* Gdb user issuing the 'signal SIGHUP' command tells sim to reset
600 itself. We reply with a SIGTRAP the same as we do when gdb
601 makes first connection with simulator. */
602 devices
[current
]->reset();
610 /* Format of breakpoint commands (both insert and remove):
612 "z<t>,<addr>,<length>" - remove break/watch point
613 "Z<t>,<add>r,<length>" - insert break/watch point
615 In both cases t can be the following:
616 t = '0' - software breakpoint
617 t = '1' - hardware breakpoint
618 t = '2' - write watch point
619 t = '3' - read watch point
620 t = '4' - access watch point
625 For a software breakpoint, length specifies the size of the instruction to
626 be patched. For hardware breakpoints and watchpoints, length specifies the
627 memory region to be monitored. To avoid potential problems, the operations
628 should be implemented in an idempotent way. -- GDB 5.0 manual.
630 void GdbServer::breakPoint( char *pkt
) {
631 char z
= *(pkt
-1); /* get char parser already looked at */
633 pkt
++; /* skip over first ',' */
637 getAddrLen( &pkt
, ',', '\0', addr
, len
);
641 case '0': /* software breakpoint */
642 case '1': /* hardware breakpoint */
644 devices
[current
]->removeBreak( addr
);
646 devices
[current
]->insertBreak( addr
);
649 case '2': /* write watchpoint */
653 case '3': /* read watchpoint */
657 case '4': /* access watchpoint */
659 return; /* unsupported yet */
663 } catch( util::Exception
& ex
) {
664 std::cerr
<< ex
.message() << std::endl
;
669 int GdbServer::parsePacket( char *pkt
) {
671 case '?': /* last signal */
672 sendReply( "S05" ); /* signal # 5 is SIGTRAP */
675 case 'g': /* read registers */
679 case 'G': /* write registers */
680 writeRegisters( pkt
);
683 case 'p': /* read a single register */
687 case 'P': /* write single register */
688 writeRegister( pkt
);
691 case 'm': /* read memory */
695 case 'M': /* write memory */
699 case 'D': /* detach the debugger */
700 case 'k': /* kill request */
702 return GDB_RET_KILL_REQUEST
;
704 case 'c': /* continue */
705 return GDB_RET_CONTINUE
;
707 case 'C': /* continue with signal */
708 return GDB_RET_CONTINUE
;
711 return GDB_RET_SINGLE_STEP
;
713 case 'S': /* step with signal */
715 return GDB_RET_SINGLE_STEP
;
717 case 'z': /* remove break/watch point */
718 case 'Z': /* insert break/watch point */
722 case 'H': /* Set thread for subsequent operations */
725 * Set thread for subsequent operations (`m', `M', `g', `G', et.al.).
726 * c depends on the operation to be performed: it should be `c'
727 * for step and continue operations, `g' for other operations.
728 * The thread designator t may be `-1', meaning all the threads,
729 * a thread number, or `0' which means pick any thread.
732 current
= strtoul(pkt
, 0, 16);
736 case 'q': /* query requests */
747 int GdbServer::readPacket() {
748 char pkt_buf
[MAX_BUF
];
750 memset( pkt_buf
, 0, sizeof(pkt_buf
) );
751 setBlockingMode( true );
753 int pkt_cksum
= 0, i
= 0;
755 while ( (c
!= '#') && (i
< MAX_BUF
) ) {
757 pkt_cksum
+= (unsigned char)c
;
762 cksum
= hex2nib( readByte() ) << 4;
763 cksum
|= hex2nib( readByte() );
765 /* FIXME: Should send "-" (Nak) instead of aborting when we get
766 checksum errors. Leave this as an error until it is actually
767 seen (I've yet to see a bad checksum - TRoth). It's not a simple
768 matter of sending (Nak) since you don't want to get into an
769 infinite loop of (bad cksum, nak, resend, repeat).*/
771 if( (pkt_cksum
& 0xff) != cksum
)
773 util::format("Bad checksum: sent 0x%x <--> computed 0x%x") % cksum
% pkt_cksum
);
776 std::cout
<< util::format("Recv: \"$%s#%02x\"") % pkt_buf
% cksum
<< std::endl
;
779 /* always acknowledge a well formed packet immediately */
782 return parsePacket( pkt_buf
);
785 int GdbServer::preParsePacket(bool blocking
) {
786 setBlockingMode(blocking
);
790 case '$': /* read a packet */
794 sendReply( lastReply
);
801 /* Gdb sends this when the user hits C-c. This is gdb's way of
802 telling the simulator to interrupt what it is doing and return
803 control back to gdb. */
804 return GDB_RET_CTRL_C
;
807 /* fd is non-blocking and no data to read */
808 return GDB_RET_NOTHING_RECEIVED
;
811 std::cout
<< "Unknown request from gdb: "
812 << std::hex
<< c
<< std::dec
<< std::endl
;
818 void GdbServer::sendPosition(int signo
) {
820 byte status
= devices
[current
]->status();
822 word sp
= devices
[current
]->stackPointer();
824 dword val
= devices
[current
]->programCounter();
827 snprintf( reply
, sizeof(reply
),
828 "T%02x20:%02x;21:%02x%02x;22:%02x%02x%02x%02x;",
831 sp
& 0xff, (sp
>> 8) & 0xff,
832 val
& 0xff, (val
>> 8) & 0xff,
833 (val
>> 16) & 0xff, (val
>> 24) & 0xff);
838 void GdbServer::exec() {
844 if( lastReply
!= 0 ) {
850 } catch( GdbException
& ex
) {
851 std::cerr
<< "GdbServer " << ex
.message() << std::endl
;
856 void GdbServer::handleClient() {
858 int gdbRet
= preParsePacket( runMode
!= GDB_RET_CONTINUE
);
860 case GDB_RET_NOTHING_RECEIVED
:
864 runMode
= GDB_RET_OK
;
867 case GDB_RET_CONTINUE
:
868 runMode
= GDB_RET_CONTINUE
;
871 case GDB_RET_SINGLE_STEP
:
872 runMode
= GDB_RET_SINGLE_STEP
;
876 runMode
= GDB_RET_CTRL_C
;
877 sendPosition(SIGINT
);
880 case GDB_RET_KILL_REQUEST
:
881 devices
[current
]->deleteAllBreakpoints();
882 devices
[current
]->reset();
891 } while( (runMode
!= GDB_RET_SINGLE_STEP
) &&
892 ( runMode
!= GDB_RET_CONTINUE
) );
896 devices
[current
]->step();
897 } while( (runMode
== GDB_RET_SINGLE_STEP
)
898 && ! devices
[current
]->stepDone() );
900 if( devices
[current
]->hasBreaked() ) {
901 runMode
= GDB_RET_OK
;
902 sendPosition(SIGTRAP
);
904 } catch( IllegalInstruction
& ex
) {
906 snprintf( reply
, sizeof(reply
), "S%02x", SIGILL
);
908 runMode
= GDB_RET_OK
;
909 sendPosition(SIGILL
);
912 if( runMode
== GDB_RET_SINGLE_STEP
) {
913 runMode
= GDB_RET_OK
;
914 sendPosition(SIGTRAP
);