.gitignore ignores tests and eclipse
[avr-sim.git] / src / GdbServer.cpp
bloba42396da7d4ad512a371fc041093cbb68b07bea9
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>
27 #include <stdio.h>
28 #include <string.h>
30 #ifdef WINDOWS
31 # include <winsock.h>
32 # pragma comment(lib, "wsock32.lib")
33 #else
34 # include <errno.h>
35 # include <signal.h>
36 # include <sys/socket.h>
37 # include <netinet/in.h>
38 # include <fcntl.h>
39 # include <netinet/tcp.h>
40 # include <netdb.h>
41 # include <arpa/inet.h>
42 # define closesocket(a) close( (a) )
43 #endif
45 enum {
46 BUF_SIZ = 800, /* Buffering size for read operations. */
47 MAX_BUF = 400, /* Maximum size of read/write buffers. */
48 MAX_READ_RETRY = 50, /* Maximum number of retries if a read is incomplete. */
50 MEM_SPACE_MASK = 0x00ff0000, /* mask to get bits which determine memory space */
51 FLASH_OFFSET = 0x00000000, /* Data in flash has this offset from gdb */
52 SRAM_OFFSET = 0x00800000, /* Data in sram has this offset from gdb */
53 EEPROM_OFFSET = 0x00810000, /* Data in eeprom has this offset from gdb */
55 GDB_BLOCKING_OFF = 0, /* Signify that a read is non-blocking. */
56 GDB_BLOCKING_ON = 1, /* Signify that a read will block. */
58 GDB_RET_NOTHING_RECEIVED = 5, /* if the read in non blocking receives nothing, we have nothing to do */
59 GDB_RET_SINGLE_STEP = 4, /* do one single step in gdb loop */
60 GDB_RET_CONTINUE = 3, /* step until another command from gdb is received */
61 GDB_RET_CTRL_C = 2, /* gdb has sent Ctrl-C to interrupt what is doing */
62 GDB_RET_KILL_REQUEST = 1, /* gdb has requested that sim be killed */
63 GDB_RET_OK = 0 /* continue normal processing of gdb requests */
64 /* means that we should NOT execute any step!!! */
67 namespace avr {
69 GdbServer::GdbServer(SimulationClock & clock, int port)
70 : clock(clock), current(0), sock(-1), conn(-1) {
72 lastReply = 0;
73 openSocket(port);
74 runMode = GDB_RET_OK;
77 GdbServer::~GdbServer() {
78 closeSocket();
81 void GdbServer::add(Device *dev) {
82 DebugInterface *dbgi = dev->debugInterface();
83 devices.push_back( dbgi );
86 void GdbServer::openSocket(int port) {
87 if( (sock = socket(PF_INET, SOCK_STREAM, 0)) < 0 )
88 throw GdbException( "Can't create socket" );
90 int i = 1;
91 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
92 //fcntl(sock, F_SETFL, fcntl(sock, F_GETFL, 0) | O_NONBLOCK);
94 struct sockaddr_in address;
95 address.sin_family = AF_INET;
96 address.sin_port = htons(port);
97 memset( &address.sin_addr, 0, sizeof(address.sin_addr) );
99 if( bind( sock, (struct sockaddr *)&address, sizeof(address) ) < 0 )
100 throw GdbException( "Can't bind socket" );
102 if( listen(sock, 1) < 0 )
103 throw GdbException( "Can't listen on socket" );
105 std::cout << "Waiting on port " << port
106 << " for gdb client to connect..." << std::endl;
108 blockingOn = true;
111 void GdbServer::closeSocket() {
112 if( conn != -1 ) {
113 closesocket(conn);
114 conn = -1;
117 if( sock != -1 ) {
118 closesocket(sock);
119 sock = -1;
124 void GdbServer::acceptClient() {
125 struct sockaddr_in address;
126 socklen_t addrLength = sizeof(struct sockaddr *);
128 conn = accept( sock, (struct sockaddr *)&address, &addrLength );
129 if( conn > 0 ) {
130 /* Tell TCP not to delay small packets. This greatly speeds up
131 interactive response. WARNING: If TCP_NODELAY is set on, then gdb
132 may timeout in mid-packet if the (gdb)packet is not sent within a
133 single (tcp)packet, thus all outgoing (gdb)packets _must_ be sent
134 with a single call to write. (see Stevens "Unix Network
135 Programming", Vol 1, 2nd Ed, page 202 for more info) */
137 int i = 1;
138 setsockopt(conn, IPPROTO_TCP, TCP_NODELAY, &i, sizeof (i));
140 std::cout << "Connection opened by host "
141 << inet_ntoa( address.sin_addr )
142 << ", port " << ntohs( address.sin_port )
143 << std::endl;
147 int GdbServer::readByte() {
148 static char buf[BUF_SIZ];
149 static int bufcnt = 0;
150 static char *bufp;
152 if (bufcnt-- > 0)
153 return *bufp++ & 0x7f;
155 bufcnt = read( conn, buf, sizeof(buf) );
157 if( bufcnt <= 0 ) {
158 if( bufcnt == 0 )
159 throw GdbException( "Read failed: Got EOF" );
161 if( errno == EAGAIN )
162 return -1;
164 throw GdbException( "Read failed" );
167 bufp = buf;
168 bufcnt--;
169 return *bufp++ & 0x7f;
172 void GdbServer::write( const void *buf, size_t count ) {
173 int res = ::write( conn, buf, count );
175 if( res < 0 )
176 throw GdbException( util::format("write failed: %s") % strerror(errno) );
178 if( (size_t)res != count )
179 throw GdbException( util::format("wrote only wrote %d of %d bytes") % res % count );
182 /* Acknowledge a packet from GDB */
183 void GdbServer::sendAck() {
184 write( "+", 1 );
187 void GdbServer::saveLastReply( const char *reply ) {
188 if( lastReply != 0 )
189 delete [] lastReply;
191 int len = strlen( reply );
192 lastReply = new char[len];
193 strcpy( lastReply, reply );
196 static char HEX_DIGIT[] = "0123456789abcdef";
198 /* Send a reply to GDB. */
199 void GdbServer::sendReply( const char *reply ) {
200 int cksum = 0;
201 int bytes;
203 /* Save the reply to last reply so we can resend if need be. */
204 if( reply != lastReply )
205 saveLastReply( reply );
207 if( *reply == '\0' ) {
208 write( "$#00", 4 );
209 } else {
210 char buf[MAX_BUF];
211 memset( buf, '\0', sizeof(buf) );
213 buf[0] = '$';
214 bytes = 1;
216 while( *reply ) {
217 cksum += (unsigned char)*reply;
218 buf[bytes] = *reply;
219 bytes++;
220 reply++;
222 /* must account for "#cc" to be added */
223 if( bytes == (MAX_BUF-3) ) {
224 /* FIXME: TRoth 2002/02/18 - splitting reply would be better */
225 throw GdbException( "buffer overflow" );
229 buf[bytes++] = '#';
230 buf[bytes++] = HEX_DIGIT[(cksum >> 4) & 0xf];
231 buf[bytes++] = HEX_DIGIT[cksum & 0xf];
233 #ifdef DEBUG
234 std::cout << util::format("Send: \"%s\"") % buf << std::endl;
235 #endif
236 write( buf, bytes );
240 void GdbServer::setBlockingMode( bool blocking ) {
241 if( blocking == blockingOn )
242 return;
244 int flags = fcntl(conn, F_GETFL, 0);
245 if( blocking ) {
246 /* turn non-blocking mode off */
247 if( fcntl( conn, F_SETFL, flags & ~O_NONBLOCK) < 0 )
248 throw GdbException( "fcntl failed" );
249 } else {
250 /* turn non-blocking mode on */
251 if (fcntl( conn, F_SETFL, flags | O_NONBLOCK) < 0)
252 throw GdbException( "fcntl failed" );
255 blockingOn = blocking;
258 /* Convert a hexidecimal digit to a 4 bit nibble. */
259 static int hex2nib( char hex ) {
260 if( (hex >= 'A') && (hex <= 'F') )
261 return (10 + (hex - 'A'));
263 else if( (hex >= 'a') && (hex <= 'f') )
264 return (10 + (hex - 'a'));
266 else if( (hex >= '0') && (hex <= '9') )
267 return (hex - '0');
269 throw GdbException( "Invalid hexidecimal digit" );
272 static byte hex2byte( char **pkt ) {
273 char *p = *pkt;
274 byte val = hex2nib(*p++);
275 val = (val << 4) | hex2nib(*p++);
276 *pkt = p;
277 return val;
280 static void putHex( char **pkt, byte val ) {
281 char *p = *pkt;
282 *p++ = HEX_DIGIT[(val >> 4) & 0xf];
283 *p++ = HEX_DIGIT[val & 0xf];
284 *pkt = p;
287 static int extractHexNum( char **pkt, char stop = '\0' ) {
288 int num = 0;
289 char *p = *pkt;
290 int max_shifts = sizeof(int)*2-1; /* max number of nibbles to shift through */
292 int i = 0;
293 while ( (*p != stop) && (*p != '\0') ) {
294 if( i > max_shifts )
295 throw GdbException( "number too large" );
297 num = (num << 4) | hex2nib(*p);
298 i++;
299 p++;
302 *pkt = p;
303 return num;
306 static void getAddrLen( char **pkt, char a_end, char l_end,
307 unsigned int & addr, int & len ) {
308 char *p = *pkt;
310 addr = 0;
311 len = 0;
313 /* Get the addr from the packet */
314 while( *p != a_end )
315 addr = (addr << 4) + hex2nib(*p++);
316 p++; /* skip over a_end */
318 /* Get the length from the packet */
319 while( *p != l_end )
320 len = (len << 4) + hex2nib(*p++);
321 p++; /* skip over l_end */
323 *pkt = p;
326 void GdbServer::queryPacket( char *pkt ) {
327 char reply[MAX_BUF];
328 memset(reply, '\0', sizeof(reply));
330 if( strcmp(pkt, "C") == 0 ) {
332 * `qC'
333 * Return the current thread id.
334 * Reply:
335 * `QC pid'
337 snprintf( reply, sizeof(reply)-1, "%02x", current );
338 } else if( strcmp(pkt, "qfThreadInfo") == 0 ) {
340 * `qfThreadInfo'
341 * `qsThreadInfo'
342 * Obtain a list of all active thread ids from the target (OS).
343 * Since there may be too many active threads to fit into one
344 * reply packet, this query works iteratively: it may require more
345 * than one query/reply sequence to obtain the entire list of threads.
346 * The first query of the sequence will be the `qfThreadInfo' query;
347 * subsequent queries in the sequence will be the `qsThreadInfo' query.
350 int n;
351 n = snprintf( reply, sizeof(reply)-1, "m %02x", 0 );
352 for(size_t i = 1; i < devices.size(); ++i)
353 snprintf( reply + n, sizeof(reply)-n-1, ",%02x", 0 );
354 } else if( strcmp(pkt, "qsThreadInfo") == 0 ) {
355 reply[0] = 'l';
356 } else if( strcmp(pkt, "qSupported") == 0) {
357 sendReply( "PacketSize=800;qXfer:features:read+" );
358 } else if( strncmp(pkt, "qXfer:features:read:target.xml:", 31) == 0 ) {
359 // GDB XML target descriptions, since GDB 6.7 (2007-10-10)
360 // see http://sources.redhat.com/gdb/current/onlinedocs/gdb/Target-Descriptions.html
361 sendReply( "l"
362 "<?xml version=\"1.0\"?>\n"
363 "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">\n"
364 "<target version=\"1.0\">\n"
365 " <architecture>avr</architecture>\n"
366 "</target>\n" );
367 return;
370 sendReply( reply );
373 void GdbServer::readRegisters() {
374 /* (32 gpwr, SREG, SP, PC) * 2 hex bytes + terminator */
375 size_t buf_sz = (32 + 1 + 2 + 4)*2 + 1;
376 char buf[ buf_sz ];
378 char *p = buf;
379 /* 32 gen purpose working registers */
380 for( int i = 0; i<32; i++ ) {
381 byte val = devices[current]->reg(i);
382 putHex( &p, val );
386 /* GDB thinks SREG is register number 32 */
387 byte val = devices[current]->status();
388 putHex( &p, val );
392 /* GDB thinks SP is register number 33 */
393 word sp = devices[current]->stackPointer();
394 putHex( &p, sp & 0xff );
395 putHex( &p, (sp >> 8) & 0xff );
399 dword pc = devices[current]->programCounter();
400 /* GDB thinks PC is register number 34.
401 * GDB stores PC in a 32 bit value (only uses 23 bits though).
404 putHex( &p, pc & 0xff );
405 putHex( &p, (pc >> 8) & 0xff );
406 putHex( &p, (pc >> 16) & 0xff );
407 putHex( &p, (pc >> 24) & 0xff );
410 *p = '\0';
411 sendReply( buf );
414 void GdbServer::writeRegisters( char *pkt ) {
415 /* 32 gen purpose working registers */
416 for(int i = 0; i < 32; i++) {
417 byte val = hex2byte( &pkt );
418 devices[current]->setReg( i, val );
422 /* GDB thinks SREG is register number 32 */
423 byte val = hex2byte( &pkt );
424 devices[current]->setStatus( val );
428 /* GDB thinks SP is register number 33 */
429 word sp = hex2byte( &pkt ) | (hex2byte( &pkt ) << 8);
430 devices[current]->setStackPointer( sp );
435 * GDB thinks PC is register number 34.
436 * GDB stores PC in a 32 bit value (only uses 23 bits though).
438 dword pc = hex2byte( &pkt ) |
439 hex2byte( &pkt ) << 8 |
440 hex2byte( &pkt ) << 16 |
441 hex2byte( &pkt ) << 24;
442 devices[current]->setProgramCounter( pc );
445 sendReply( "OK" );
448 void GdbServer::readRegister( char *pkt ) {
449 char reply[MAX_BUF];
450 memset(reply, '\0', sizeof(reply));
452 int reg = extractHexNum(&pkt, '\0');
453 if( reg < 32 ) {
454 byte val = devices[current]->reg(reg);
455 snprintf( reply, sizeof(reply)-1, "%02x", val );
456 } else if( reg == 32 ) {
457 byte val = devices[current]->status();
458 snprintf( reply, sizeof(reply)-1, "%02x", val );
459 } else if( reg == 33 ) {
460 /* SP */
461 word sp = devices[current]->stackPointer();
462 snprintf( reply, sizeof(reply)-1, "%02x%02x",
463 sp & 0xff, (sp >> 8) & 0xff );
464 } else if (reg == 34) {
465 /* PC */
466 dword val = devices[current]->programCounter();
467 snprintf( reply, sizeof(reply)-1,
468 "%02x%02x" "%02x%02x",
469 val & 0xff, (val >> 8) & 0xff,
470 (val >> 16) & 0xff, (val >> 24) & 0xff );
471 } else {
472 sendReply( "E00" );
473 return;
476 sendReply( reply );
479 void GdbServer::writeRegister( char *pkt ) {
480 int reg = extractHexNum(&pkt, '=');
481 pkt++; /* skip over '=' character */
483 /* extract the low byte of value from pkt */
484 byte val = hex2byte( &pkt );
485 if( (reg >= 0) && (reg < 33) ) {
486 /* r0 to r31 */
487 devices[current]->setReg( reg, val );
488 } else if( reg == 32 ) {
489 /* SREG is register 32 */
490 devices[current]->setStatus( val );
491 } else if( reg == 33 ) {
492 /* SP is 2 bytes long so extract upper byte */
493 byte hval = hex2byte( &pkt );
494 word sp = (hval << 8) | val;
495 devices[current]->setStackPointer( sp );
496 } else if( reg == 34 ) {
497 /* GDB thinks PC is register number 34.
498 GDB stores PC in a 32 bit value (only uses 23 bits though).
499 GDB thinks PC is bytes into flash, not words like in simulavr.
501 Must cast to dword so as not to get mysterious truncation. */
503 dword pc = val |
504 hex2byte( &pkt ) << 8 |
505 hex2byte( &pkt ) << 16 |
506 hex2byte( &pkt ) << 24;
507 devices[current]->setProgramCounter( pc );
508 } else {
509 sendReply( "E00" );
510 return;
513 sendReply( "OK" );
516 void GdbServer::readMemory( char *pkt ) {
517 unsigned int addr;
518 int len;
519 getAddrLen( &pkt, ',', '\0', addr, len );
521 char *buf = 0;
522 try {
523 const unsigned char *data;
524 if( (addr & MEM_SPACE_MASK) == EEPROM_OFFSET ) {
525 /* addressing eeprom */
526 unsigned int eaddr = addr & ~MEM_SPACE_MASK; /* remove the offset bits */
527 data = devices[current]->readEeprom( eaddr, len );
528 } else if ( (addr & MEM_SPACE_MASK) == SRAM_OFFSET ) {
529 /* addressing sram */
530 unsigned int saddr = addr & ~MEM_SPACE_MASK; /* remove the offset bits */
531 data = devices[current]->readRam( saddr, len );
532 } else if ( (addr & MEM_SPACE_MASK) == FLASH_OFFSET ) {
533 /* addressing flash */
534 unsigned int faddr = addr & ~MEM_SPACE_MASK; /* remove the offset bits */
535 data = devices[current]->readFlash( faddr, len );
536 } else {
537 throw AccessViolation( "memory space does not exist " );
540 buf = new char[len*2+1];
541 int i;
542 for(i = 0; i < len; i++) {
543 byte bval = data[i];
544 buf[i*2] = HEX_DIGIT[bval >> 4];
545 buf[i*2+1] = HEX_DIGIT[bval & 0xf];
547 buf[i*2] = '\0';
548 } catch( util::Exception & ex ) {
549 std::ios_base::fmtflags f = std::cerr.flags();
550 std::cerr << ex.message() << " reading address "
551 << std::hex << addr << " length " << std::dec << len << std::endl;
552 std::cerr.flags(f);
555 * If gdb requested a read from invalid memory,
556 * always reply with 0's
557 * TODO find out why gdb requests these addresses
559 if ( (addr & MEM_SPACE_MASK) == SRAM_OFFSET ) {
560 buf = new char[len*2+1];
561 int i;
562 for(i = 0; i < 2*len; i++)
563 buf[i] = '0';
564 buf[i] = '\0';
565 } else {
566 char reply[10];
567 snprintf( reply, sizeof(reply), "E%02x", EIO );
568 sendReply( reply );
569 return;
571 } catch( std::exception & ex ) {
572 std::cerr << ex.what() << std::endl;
574 char reply[10];
575 snprintf( reply, sizeof(reply), "E%02x", EIO );
576 sendReply( reply );
577 return;
580 sendReply( buf );
582 if( buf != 0 )
583 delete [] buf;
586 void GdbServer::writeMemory( char *pkt ) {
587 unsigned int addr;
588 int len;
589 getAddrLen( &pkt, ',', ':', addr, len );
591 try {
592 unsigned char *data = new unsigned char[len];
593 for(int i = 0; i < len; ++i) {
594 byte val = hex2byte( &pkt );
595 data[i] = val;
598 if( (addr & MEM_SPACE_MASK) == EEPROM_OFFSET ) {
599 /* addressing eeprom */
600 addr = addr & ~MEM_SPACE_MASK; /* remove the offset bits */
601 devices[current]->writeEeprom(data, addr, len);
602 } else if ( (addr & MEM_SPACE_MASK) == SRAM_OFFSET ) {
603 /* addressing sram */
604 addr = addr & ~MEM_SPACE_MASK; /* remove the offset bits */
605 devices[current]->writeRam(data, addr, len);
606 } else if ( (addr & MEM_SPACE_MASK) == FLASH_OFFSET ) {
607 /* addressing flash */
608 addr = addr & ~MEM_SPACE_MASK; /* remove the offset bits */
609 devices[current]->writeFlash(data, addr, len);
610 } else {
611 throw AccessViolation( "memory space does not exist " );
613 } catch( util::Exception & ex ) {
614 std::cerr << ex.message() << std::endl;
616 char reply[10];
617 snprintf( reply, sizeof(reply), "E%02x", EIO );
618 sendReply( reply );
619 return;
620 } catch( std::exception & ex ) {
621 std::cerr << ex.what() << std::endl;
623 char reply[10];
624 snprintf( reply, sizeof(reply), "E%02x", EIO );
625 sendReply( reply );
626 return;
629 sendReply( "OK" );
632 int GdbServer::getSignal( char *pkt ) {
633 int signo = hex2byte( &pkt );
636 * Process signals send via remote protocol from gdb.
637 * Signals really don't make sense to the program running
638 * in the simulator, so we are using them sort of as
639 * an 'out of band' data.
642 switch (signo) {
643 case SIGHUP:
644 /* Gdb user issuing the 'signal SIGHUP' command tells sim to reset
645 itself. We reply with a SIGTRAP the same as we do when gdb
646 makes first connection with simulator. */
647 devices[current]->reset();
648 sendReply( "S05" );
651 return signo;
655 /* Format of breakpoint commands (both insert and remove):
657 "z<t>,<addr>,<length>" - remove break/watch point
658 "Z<t>,<add>r,<length>" - insert break/watch point
660 In both cases t can be the following:
661 t = '0' - software breakpoint
662 t = '1' - hardware breakpoint
663 t = '2' - write watch point
664 t = '3' - read watch point
665 t = '4' - access watch point
667 addr is address.
668 length is in bytes
670 For a software breakpoint, length specifies the size of the instruction to
671 be patched. For hardware breakpoints and watchpoints, length specifies the
672 memory region to be monitored. To avoid potential problems, the operations
673 should be implemented in an idempotent way. -- GDB 5.0 manual.
675 void GdbServer::breakPoint( char *pkt ) {
676 char z = *(pkt-1); /* get char parser already looked at */
677 char t = *pkt++;
678 pkt++; /* skip over first ',' */
680 unsigned int addr;
681 int len;
682 getAddrLen( &pkt, ',', '\0', addr, len );
684 try {
685 switch( t ) {
686 case '0': /* software breakpoint */
687 case '1': /* hardware breakpoint */
688 if( z == 'z' )
689 devices[current]->removeBreak( addr );
690 else
691 devices[current]->insertBreak( addr );
692 break;
694 case '2': /* write watchpoint */
695 sendReply( "" );
696 return;
698 case '3': /* read watchpoint */
699 sendReply( "" );
700 return;
702 case '4': /* access watchpoint */
703 sendReply( "" );
704 return; /* unsupported yet */
707 sendReply( "OK" );
708 } catch( util::Exception & ex ) {
709 std::cerr << ex.message() << std::endl;
710 sendReply( "E01" );
714 int GdbServer::parsePacket( char *pkt ) {
715 switch( *pkt++ ) {
716 case '?': /* last signal */
717 sendReply( "S05" ); /* signal # 5 is SIGTRAP */
718 break;
720 case 'g': /* read registers */
721 readRegisters( );
722 break;
724 case 'G': /* write registers */
725 writeRegisters( pkt );
726 break;
728 case 'p': /* read a single register */
729 readRegister( pkt );
730 break;
732 case 'P': /* write single register */
733 writeRegister( pkt );
734 break;
736 case 'm': /* read memory */
737 readMemory( pkt );
738 break;
740 case 'M': /* write memory */
741 writeMemory( pkt );
742 break;
744 case 'D': /* detach the debugger */
745 case 'k': /* kill request */
746 sendReply( "OK" );
747 return GDB_RET_KILL_REQUEST;
749 case 'c': /* continue */
750 return GDB_RET_CONTINUE;
752 case 'C': /* continue with signal */
753 return GDB_RET_CONTINUE;
755 case 's': /* step */
756 return GDB_RET_SINGLE_STEP;
758 case 'S': /* step with signal */
759 getSignal(pkt);
760 return GDB_RET_SINGLE_STEP;
762 case 'z': /* remove break/watch point */
763 case 'Z': /* insert break/watch point */
764 breakPoint( pkt );
765 break;
767 case 'H': /* Set thread for subsequent operations */
769 * `H c t'
770 * Set thread for subsequent operations (`m', `M', `g', `G', et.al.).
771 * c depends on the operation to be performed: it should be `c'
772 * for step and continue operations, `g' for other operations.
773 * The thread designator t may be `-1', meaning all the threads,
774 * a thread number, or `0' which means pick any thread.
776 pkt++;
777 current = strtoul(pkt, 0, 16);
778 sendReply("OK");
779 break;
781 case 'q': /* query requests */
782 queryPacket(pkt);
783 break;
785 default:
786 sendReply( "" );
789 return GDB_RET_OK;
792 int GdbServer::readPacket() {
793 char pkt_buf[MAX_BUF];
795 memset( pkt_buf, 0, sizeof(pkt_buf) );
796 setBlockingMode( true );
798 int pkt_cksum = 0, i = 0;
799 int c = readByte();
800 while ( (c != '#') && (i < MAX_BUF) ) {
801 pkt_buf[i++] = c;
802 pkt_cksum += (unsigned char)c;
803 c = readByte();
806 int cksum;
807 cksum = hex2nib( readByte() ) << 4;
808 cksum |= hex2nib( readByte() );
810 /* FIXME: Should send "-" (Nak) instead of aborting when we get
811 checksum errors. Leave this as an error until it is actually
812 seen (I've yet to see a bad checksum - TRoth). It's not a simple
813 matter of sending (Nak) since you don't want to get into an
814 infinite loop of (bad cksum, nak, resend, repeat).*/
816 if( (pkt_cksum & 0xff) != cksum )
817 throw GdbException(
818 util::format("Bad checksum: sent 0x%x <--> computed 0x%x") % cksum % pkt_cksum );
820 #ifdef DEBUG
821 std::cout << util::format("Recv: \"$%s#%02x\"") % pkt_buf % cksum << std::endl;
822 #endif
824 /* always acknowledge a well formed packet immediately */
825 sendAck();
827 return parsePacket( pkt_buf );
830 int GdbServer::preParsePacket(bool blocking) {
831 setBlockingMode(blocking);
833 int c = readByte( );
834 switch (c) {
835 case '$': /* read a packet */
836 return readPacket();
838 case '-': // Nack
839 sendReply( lastReply );
840 break;
842 case '+': // Ack
843 break;
845 case 0x03:
846 /* Gdb sends this when the user hits C-c. This is gdb's way of
847 telling the simulator to interrupt what it is doing and return
848 control back to gdb. */
849 return GDB_RET_CTRL_C;
851 case -1:
852 /* fd is non-blocking and no data to read */
853 return GDB_RET_NOTHING_RECEIVED;
855 default:
856 std::cout << "Unknown request from gdb: "
857 << std::hex << c << std::dec << std::endl;
860 return GDB_RET_OK;
863 void GdbServer::sendPosition(int signo) {
864 /* status */
865 byte status = devices[current]->status();
866 /* SP */
867 word sp = devices[current]->stackPointer();
868 /* PC */
869 dword val = devices[current]->programCounter();
871 char reply[MAX_BUF];
872 snprintf( reply, sizeof(reply),
873 "T%02x20:%02x;21:%02x%02x;22:%02x%02x%02x%02x;",
874 signo,
875 status,
876 sp & 0xff, (sp >> 8) & 0xff,
877 val & 0xff, (val >> 8) & 0xff,
878 (val >> 16) & 0xff, (val >> 24) & 0xff);
880 sendReply(reply);
883 void GdbServer::exec() {
884 while( true ) {
885 if( conn < 0 )
886 acceptClient();
888 try {
889 if( lastReply != 0 ) {
890 delete [] lastReply;
891 lastReply = 0;
894 handleClient();
895 } catch( GdbException & ex ) {
896 std::cerr << "GdbServer " << ex.message() << std::endl;
898 devices[current]->deleteAllBreakpoints();
899 devices[current]->reset();
901 if( conn != -1 ) {
902 closesocket(conn);
903 conn = -1;
909 void GdbServer::handleClient() {
910 do {
911 int gdbRet = preParsePacket( runMode != GDB_RET_CONTINUE );
912 switch( gdbRet ) {
913 case GDB_RET_NOTHING_RECEIVED:
914 break;
916 case GDB_RET_OK:
917 runMode = GDB_RET_OK;
918 break;
920 case GDB_RET_CONTINUE:
921 runMode = GDB_RET_CONTINUE;
922 break;
924 case GDB_RET_SINGLE_STEP:
925 runMode = GDB_RET_SINGLE_STEP;
926 break;
928 case GDB_RET_CTRL_C:
929 runMode = GDB_RET_CTRL_C;
930 sendPosition(SIGINT);
931 break;
933 case GDB_RET_KILL_REQUEST:
934 devices[current]->deleteAllBreakpoints();
935 devices[current]->reset();
937 if( conn != -1 ) {
938 closesocket(conn);
939 conn = -1;
941 return;
944 } while( (runMode != GDB_RET_SINGLE_STEP ) &&
945 ( runMode != GDB_RET_CONTINUE) );
947 try {
948 do {
949 devices[current]->step();
950 } while( (runMode == GDB_RET_SINGLE_STEP )
951 && ! devices[current]->stepDone() );
953 if( devices[current]->hasBreaked() ) {
954 runMode = GDB_RET_OK;
955 sendPosition(SIGTRAP);
957 } catch( IllegalInstruction & ex ) {
958 char reply[10];
959 snprintf( reply, sizeof(reply), "S%02x", SIGILL );
960 sendReply( reply );
961 runMode = GDB_RET_OK;
962 sendPosition(SIGILL);
965 if( runMode == GDB_RET_SINGLE_STEP ) {
966 runMode = GDB_RET_OK;
967 sendPosition(SIGTRAP);