Main Page

- Main Page
- Related Pages
- Files

- File List
- Globals

gdbserver.c
Go to the documentation of this file.
1 /*
2 * $Id: gdbserver.c,v 1.53 2008/01/07 17:04:15 joerg_wunsch Exp $
3 *
4 ****************************************************************************
5 *
6 * gdbserver.c - Provide interface to a remote debugging target of gdb.
7 * Copyright (C) 2001, 2002, 2003 Theodore A. Roth
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 *
23 ****************************************************************************
24 */
25
26 /**
27 * \file gdbserver.c
28 * \brief Provide an interface to gdb's remote serial protocol.
29 *
30 * This module allows a program to be used by gdb as a remote target. The
31 * remote target and gdb communicate via gdb's remote serial protocol. The
32 * protocol is documented in the gdb manual and will not be repeated here.
33 *
34 * Hitting Ctrl-c in gdb can be used to interrupt the remote target while it
35 * is processing instructions and return control back to gdb.
36 *
37 * Issuing a 'signal SIGxxx' command from gdb will send the signal to the
38 * remote target via a "continue with signal" packet. The target will process
39 * and interpret the signal, but not pass it on to the AVR program running in
40 * the target since it really makes no sense to do so. In some circumstances,
41 * it may make sense to use the gdb signal mechanism as a way to initiate some
42 * sort of external stimulus to be passed on to the virtual hardware system.
43 *
44 * Signals from gdb which are processed have the following meanings:
45 *
46 * \li \c SIGHUP Initiate a reset of the target. (Simulates a hardware reset)
47 */
48
49 #include <config.h>
50
51 #include <sys/types.h>
52 #include <netinet/in.h>
53 #include <netinet/tcp.h>
54 #include <arpa/inet.h>
55 #include <sys/socket.h>
56 #include <stdio.h>
57 #include <string.h>
58 #include <errno.h>
59 #include <unistd.h>
60 #include <fcntl.h>
61 #include <signal.h>
62
63 #include "avrerror.h"
64 #include "avrmalloc.h"
65 #include "gdb.h"
66 #include "sig.h"
67
68 /* *INDENT-OFF* */
69 #ifndef DOXYGEN /* have doxygen system ignore this. */
70 enum
71 {
72 MAX_BUF = 100000, /* Maximum size of read/write buffers. */
73 MAX_READ_RETRY = 10, /* Maximum number of retries if a read is
74 incomplete. */
75
76 #if defined(USE_EEPROM_SPACE)
77 MEM_SPACE_MASK = 0x00ff0000, /* mask to get bits which determine memory
78 space */
79 FLASH_OFFSET = 0x00000000, /* Data in flash has this offset from gdb */
80 SRAM_OFFSET = 0x00800000, /* Data in sram has this offset from gdb */
81 EEPROM_OFFSET = 0x00810000, /* Data in eeprom has this offset from gdb */
82 #else
83 MEM_SPACE_MASK = 0x00f00000, /* mask to get bits which determine memory
84 space */
85 FLASH_OFFSET = 0x00000000, /* Data in flash has this offset from gdb */
86 SRAM_OFFSET = 0x00800000, /* Data in sram has this offset from gdb */
87 #endif
88
89 GDB_BLOCKING_OFF = 0, /* Signify that a read is non-blocking. */
90 GDB_BLOCKING_ON = 1, /* Signify that a read will block. */
91
92 GDB_RET_CTRL_C = -2, /* gdb has sent Ctrl-C to interrupt what is
93 doing */
94 GDB_RET_KILL_REQUEST = -1, /* gdb has requested that sim be killed */
95 GDB_RET_OK = 0, /* continue normal processing of gdb
96 requests */
97
98 SPL_ADDR = 0x5d,
99 SPH_ADDR = 0x5e,
100 };
101 #endif /* not DOXYGEN */
102 /* *INDENT-ON* */
103
104 /* Use HEX_DIGIT as a lookup table to convert a nibble to hex
105 digit. */
106 static char HEX_DIGIT[] = "0123456789abcdef";
107
108 /* There are a couple of nested infinite loops, this allows escaping them
109 all. */
110 static int global_server_quit = 0;
111
112 /* Flag if debug messages should be printed out. */
113 static int global_debug_on;
114
115 /* prototypes */
116
117 static int gdb_pre_parse_packet (GdbComm_T *comm, int fd, int blocking);
118
119 /* Wrap read(2) so we can read a byte without having
120 to do a shit load of error checking every time. */
121
122 static int
123 gdb_read_byte (int fd)
124 {
125 char c;
126 int res;
127 int cnt = MAX_READ_RETRY;
128
129 while (cnt--)
130 {
131 res = read (fd, &c, 1);
132 if (res < 0)
133 {
134 if (errno == EAGAIN)
135 /* fd was set to non-blocking and no data was available */
136 return -1;
137
138 avr_error ("read failed: %s", strerror (errno));
139 }
140
141 if (res == 0)
142 {
143 avr_warning ("incomplete read\n");
144 continue;
145 }
146
147 return c;
148 }
149 avr_error ("Maximum read reties reached");
150
151 return 0; /* make compiler happy */
152 }
153
154 /* Convert a hexidecimal digit to a 4 bit nibble. */
155
156 static uint8_t
157 hex2nib (char hex)
158 {
159 if ((hex >= 'A') && (hex <= 'F'))
160 return (10 + (hex - 'A'));
161
162 else if ((hex >= 'a') && (hex <= 'f'))
163 return (10 + (hex - 'a'));
164
165 else if ((hex >= '0') && (hex <= '9'))
166 return (hex - '0');
167
168 /* Shouldn't get here unless the developer screwed up ;) */
169 avr_error ("Invalid hexidecimal digit: 0x%02x", hex);
170
171 return 0; /* make compiler happy */
172 }
173
174 /* Wrapper for write(2) which hides all the repetitive error
175 checking crap. */
176
177 static void
178 gdb_write (int fd, const void *buf, size_t count)
179 {
180 int res;
181
182 res = write (fd, buf, count);
183
184 /* FIXME: should we try and catch interrupted system calls here? */
185
186 if (res < 0)
187 avr_error ("write failed: %s", strerror (errno));
188
189 /* FIXME: if this happens a lot, we could try to resend the
190 unsent bytes. */
191
192 if (res != count)
193 avr_error ("write only wrote %d of %d bytes", res, count);
194 }
195
196 /* Use a single function for storing/getting the last reply message.
197 If reply is NULL, return pointer to the last reply saved.
198 Otherwise, make a copy of the buffer pointed to by reply. */
199
200 static char *
201 gdb_last_reply (char *reply)
202 {
203 static char *last_reply = NULL;
204
205 if (reply == NULL)
206 {
207 if (last_reply == NULL)
208 return "";
209 else
210 return last_reply;
211 }
212
213 avr_free (last_reply);
214 last_reply = avr_strdup (reply);
215
216 return last_reply;
217 }
218
219 /* Acknowledge a packet from GDB */
220
221 static void
222 gdb_send_ack (int fd)
223 {
224 if (global_debug_on)
225 fprintf (stderr, " Ack -> gdb\n");
226
227 gdb_write (fd, "+", 1);
228 }
229
230 /* Send a reply to GDB. */
231
232 static void
233 gdb_send_reply (int fd, char *reply)
234 {
235 int cksum = 0;
236 int bytes;
237
238 static char buf[MAX_BUF];
239
240 /* Save the reply to last reply so we can resend if need be. */
241 gdb_last_reply (reply);
242
243 if (global_debug_on)
244 fprintf (stderr, "Sent: $%s#", reply);
245
246 if (*reply == '\0')
247 {
248 gdb_write (fd, "$#00", 4);
249
250 if (global_debug_on)
251 fprintf (stderr, "%02x\n", cksum & 0xff);
252 }
253 else
254 {
255 memset (buf, '\0', sizeof (buf));
256
257 buf[0] = '$';
258 bytes = 1;
259
260 while (*reply)
261 {
262 cksum += (unsigned char)*reply;
263 buf[bytes] = *reply;
264 bytes++;
265 reply++;
266
267 /* must account for "#cc" to be added */
268 if (bytes == (MAX_BUF - 3))
269 {
270 /* FIXME: TRoth 2002/02/18 - splitting reply would be better */
271 avr_error ("buffer overflow");
272 }
273 }
274
275 if (global_debug_on)
276 fprintf (stderr, "%02x\n", cksum & 0xff);
277
278 buf[bytes++] = '#';
279 buf[bytes++] = HEX_DIGIT[(cksum >> 4) & 0xf];
280 buf[bytes++] = HEX_DIGIT[cksum & 0xf];
281
282 gdb_write (fd, buf, bytes);
283 }
284 }
285
286 /* GDB needs the 32 8-bit, gpw registers (r00 - r31), the
287 8-bit SREG, the 16-bit SP (stack pointer) and the 32-bit PC
288 (program counter). Thus need to send a reply with
289 r00, r01, ..., r31, SREG, SPL, SPH, PCL, PCH
290 Low bytes before High since AVR is little endian. */
291
292 static void
293 gdb_read_registers (GdbComm_T *comm, int fd)
294 {
295 int i;
296 uint32_t val; /* ensure it's 32 bit value */
297
298 /* (32 gpwr, SREG, SP, PC) * 2 hex bytes + terminator */
299 size_t buf_sz = (32 + 1 + 2 + 4) * 2 + 1;
300 char *buf;
301
302 buf = avr_new0 (char, buf_sz);
303
304 /* 32 gen purpose working registers */
305 for (i = 0; i < 32; i++)
306 {
307 val = comm->read_reg (comm->user_data, i);
308 buf[i * 2] = HEX_DIGIT[(val >> 4) & 0xf];
309 buf[i * 2 + 1] = HEX_DIGIT[val & 0xf];
310 }
311
312 /* GDB thinks SREG is register number 32 */
313 val = comm->read_sreg (comm->user_data);
314 buf[i * 2] = HEX_DIGIT[(val >> 4) & 0xf];
315 buf[i * 2 + 1] = HEX_DIGIT[val & 0xf];
316 i++;
317
318 /* GDB thinks SP is register number 33 */
319 val = comm->read_sram (comm->user_data, SPL_ADDR);
320 buf[i * 2] = HEX_DIGIT[(val >> 4) & 0xf];
321 buf[i * 2 + 1] = HEX_DIGIT[val & 0xf];
322 i++;
323
324 val = comm->read_sram (comm->user_data, SPH_ADDR);
325 buf[i * 2] = HEX_DIGIT[(val >> 4) & 0xf];
326 buf[i * 2 + 1] = HEX_DIGIT[val & 0xf];
327 i++;
328
329 /* GDB thinks PC is register number 34.
330 GDB stores PC in a 32 bit value (only uses 23 bits though).
331 GDB thinks PC is bytes into flash, not words like in simulavr. */
332
333 val = comm->read_pc (comm->user_data) * 2;
334 buf[i * 2] = HEX_DIGIT[(val >> 4) & 0xf];
335 buf[i * 2 + 1] = HEX_DIGIT[val & 0xf];
336
337 val >>= 8;
338 buf[i * 2 + 2] = HEX_DIGIT[(val >> 4) & 0xf];
339 buf[i * 2 + 3] = HEX_DIGIT[val & 0xf];
340
341 val >>= 8;
342 buf[i * 2 + 4] = HEX_DIGIT[(val >> 4) & 0xf];
343 buf[i * 2 + 5] = HEX_DIGIT[val & 0xf];
344
345 val >>= 8;
346 buf[i * 2 + 6] = HEX_DIGIT[(val >> 4) & 0xf];
347 buf[i * 2 + 7] = HEX_DIGIT[val & 0xf];
348
349 gdb_send_reply (fd, buf);
350 avr_free (buf);
351 }
352
353 /* GDB is sending values to be written to the registers. Registers are the
354 same and in the same order as described in gdb_read_registers() above. */
355
356 static void
357 gdb_write_registers (GdbComm_T *comm, int fd, char *pkt)
358 {
359 int i;
360 uint8_t bval;
361 uint32_t val; /* ensure it's a 32 bit value */
362
363 /* 32 gen purpose working registers */
364 for (i = 0; i < 32; i++)
365 {
366 bval = hex2nib (*pkt++) << 4;
367 bval += hex2nib (*pkt++);
368 comm->write_reg (comm->user_data, i, bval);
369 }
370
371 /* GDB thinks SREG is register number 32 */
372 bval = hex2nib (*pkt++) << 4;
373 bval += hex2nib (*pkt++);
374 comm->write_sreg (comm->user_data, bval);
375
376 /* GDB thinks SP is register number 33 */
377 bval = hex2nib (*pkt++) << 4;
378 bval += hex2nib (*pkt++);
379 comm->write_sram (comm->user_data, SPL_ADDR, bval);
380
381 bval = hex2nib (*pkt++) << 4;
382 bval += hex2nib (*pkt++);
383 comm->write_sram (comm->user_data, SPH_ADDR, bval);
384
385 /* GDB thinks PC is register number 34.
386 GDB stores PC in a 32 bit value (only uses 23 bits though).
387 GDB thinks PC is bytes into flash, not words like in simulavr.
388
389 Must cast to uint32_t so as not to get mysterious truncation. */
390
391 val = ((uint32_t) hex2nib (*pkt++)) << 4;
392 val += ((uint32_t) hex2nib (*pkt++));
393
394 val += ((uint32_t) hex2nib (*pkt++)) << 12;
395 val += ((uint32_t) hex2nib (*pkt++)) << 8;
396
397 val += ((uint32_t) hex2nib (*pkt++)) << 20;
398 val += ((uint32_t) hex2nib (*pkt++)) << 16;
399
400 val += ((uint32_t) hex2nib (*pkt++)) << 28;
401 val += ((uint32_t) hex2nib (*pkt++)) << 24;
402 comm->write_pc (comm->user_data, val / 2);
403
404 gdb_send_reply (fd, "OK");
405 }
406
407 /* Extract a hexidecimal number from the pkt. Keep scanning pkt until stop
408 char is reached or size of int is exceeded or a NULL is reached. pkt is
409 modified to point to stop char when done.
410
411 Use this function to extract a num with an arbitrary num of hex
412 digits. This should _not_ be used to extract n digits from a m len string
413 of digits (n <= m). */
414
415 static int
416 gdb_extract_hex_num (char **pkt, char stop)
417 {
418 int i = 0;
419 int num = 0;
420 char *p = *pkt;
421 int max_shifts = sizeof (int) * 2 - 1; /* max number of nibbles to shift
422 through */
423
424 while ((*p != stop) && (*p != '\0'))
425 {
426 if (i > max_shifts)
427 avr_error ("number too large");
428
429 num = (num << 4) | hex2nib (*p);
430 i++;
431 p++;
432 }
433
434 *pkt = p;
435 return num;
436 }
437
438 /* Read a single register. Packet form: 'pn' where n is a hex number with no
439 zero padding. */
440
441 static void
442 gdb_read_register (GdbComm_T *comm, int fd, char *pkt)
443 {
444 int reg;
445
446 char reply[MAX_BUF];
447
448 memset (reply, '\0', sizeof (reply));
449
450 reg = gdb_extract_hex_num (&pkt, '\0');
451
452 if ((reg >= 0) && (reg < 32))
453 { /* general regs */
454 uint8_t val = comm->read_reg (comm->user_data, reg);
455 snprintf (reply, sizeof (reply) - 1, "%02x", val);
456 }
457 else if (reg == 32) /* sreg */
458 {
459 uint8_t val = comm->read_sreg (comm->user_data);
460 snprintf (reply, sizeof (reply) - 1, "%02x", val);
461 }
462 else if (reg == 33) /* SP */
463 {
464 uint8_t spl, sph;
465 spl = comm->read_sram (comm->user_data, SPL_ADDR);
466 sph = comm->read_sram (comm->user_data, SPH_ADDR);
467 snprintf (reply, sizeof (reply) - 1, "%02x%02x", spl, sph);
468 }
469 else if (reg == 34) /* PC */
470 {
471 int val = comm->read_pc (comm->user_data) * 2;
472 snprintf (reply, sizeof (reply) - 1, "%02x%02x" "%02x%02x",
473 val & 0xff, (val >> 8) & 0xff, (val >> 16) & 0xff,
474 (val >> 24) & 0xff);
475 }
476 else
477 {
478 avr_warning ("Bad register value: %d\n", reg);
479 gdb_send_reply (fd, "E00");
480 return;
481 }
482 gdb_send_reply (fd, reply);
483 }
484
485 /* Write a single register. Packet form: 'Pn=r' where n is a hex number with
486 no zero padding and r is two hex digits for each byte in register (target
487 byte order). */
488
489 static void
490 gdb_write_register (GdbComm_T *comm, int fd, char *pkt)
491 {
492 int reg;
493 uint32_t dval, hval;
494
495 reg = gdb_extract_hex_num (&pkt, '=');
496 pkt++; /* skip over '=' character */
497
498 /* extract the low byte of value from pkt */
499 dval = hex2nib (*pkt++) << 4;
500 dval += hex2nib (*pkt++);
501
502 if ((reg >= 0) && (reg < 33))
503 {
504 /* r0 to r31 and SREG */
505 if (reg == 32) /* gdb thinks SREG is register 32 */
506 {
507 comm->write_sreg (comm->user_data, dval & 0xff);
508 }
509 else
510 {
511 comm->write_reg (comm->user_data, reg, dval & 0xff);
512 }
513 }
514 else if (reg == 33)
515 {
516 /* SP is 2 bytes long so extract upper byte */
517 hval = hex2nib (*pkt++) << 4;
518 hval += hex2nib (*pkt++);
519
520 comm->write_sram (comm->user_data, SPL_ADDR, dval & 0xff);
521 comm->write_sram (comm->user_data, SPH_ADDR, hval & 0xff);
522 }
523 else if (reg == 34)
524 {
525 /* GDB thinks PC is register number 34.
526 GDB stores PC in a 32 bit value (only uses 23 bits though).
527 GDB thinks PC is bytes into flash, not words like in simulavr.
528
529 Must cast to uint32_t so as not to get mysterious truncation. */
530
531 /* we already read the first two nibbles */
532
533 dval += ((uint32_t) hex2nib (*pkt++)) << 12;
534 dval += ((uint32_t) hex2nib (*pkt++)) << 8;
535
536 dval += ((uint32_t) hex2nib (*pkt++)) << 20;
537 dval += ((uint32_t) hex2nib (*pkt++)) << 16;
538
539 dval += ((uint32_t) hex2nib (*pkt++)) << 28;
540 dval += ((uint32_t) hex2nib (*pkt++)) << 24;
541 comm->write_pc (comm->user_data, dval / 2);
542 }
543 else
544 {
545 avr_warning ("Bad register value: %d\n", reg);
546 gdb_send_reply (fd, "E00");
547 return;
548 }
549
550 gdb_send_reply (fd, "OK");
551 }
552
553 /* Parse the pkt string for the addr and length.
554 a_end is first char after addr.
555 l_end is first char after len.
556 Returns number of characters to advance pkt. */
557
558 static int
559 gdb_get_addr_len (char *pkt, char a_end, char l_end, int *addr, int *len)
560 {
561 char *orig_pkt = pkt;
562
563 *addr = 0;
564 *len = 0;
565
566 /* Get the addr from the packet */
567 while (*pkt != a_end)
568 *addr = (*addr << 4) + hex2nib (*pkt++);
569 pkt++; /* skip over a_end */
570
571 /* Get the length from the packet */
572 while (*pkt != l_end)
573 *len = (*len << 4) + hex2nib (*pkt++);
574 pkt++; /* skip over l_end */
575
576 /* fprintf( stderr, "+++++++++++++ addr = 0x%08x\n", *addr ); */
577 /* fprintf( stderr, "+++++++++++++ len = %d\n", *len ); */
578
579 return (pkt - orig_pkt);
580 }
581
582 static void
583 gdb_read_memory (GdbComm_T *comm, int fd, char *pkt)
584 {
585 int addr = 0;
586 int len = 0;
587 uint8_t *buf;
588 uint8_t bval;
589 uint16_t wval;
590 int i;
591 int is_odd_addr;
592
593 pkt += gdb_get_addr_len (pkt, ',', '\0', &addr, &len);
594
595 buf = avr_new0 (uint8_t, (len * 2) + 1);
596
597 if ((addr & MEM_SPACE_MASK) == SRAM_OFFSET)
598 {
599 /* addressing sram */
600
601 addr = addr & ~MEM_SPACE_MASK; /* remove the offset bits */
602
603 /* Return an error to gdb if it tries to read or write any of the 32
604 general purpse registers. This allows gdb to know when a zero
605 pointer has been dereferenced. */
606
607 /* FIXME: [TRoth 2002/03/31] This isn't working quite the way I
608 thought it would so I've removed it for now. */
609
610 /* if ( (addr >= 0) && (addr < 32) ) */
611 if (0)
612 {
613 snprintf ((char*)buf, len * 2, "E%02x", EIO);
614 }
615 else
616 {
617 for (i = 0; i < len; i++)
618 {
619 bval = comm->read_sram (comm->user_data, addr + i);
620 buf[i * 2] = HEX_DIGIT[bval >> 4];
621 buf[i * 2 + 1] = HEX_DIGIT[bval & 0xf];
622 }
623 }
624 }
625 else if ((addr & MEM_SPACE_MASK) == FLASH_OFFSET)
626 {
627 /* addressing flash */
628
629 addr = addr & ~MEM_SPACE_MASK; /* remove the offset bits */
630
631 is_odd_addr = addr % 2;
632 i = 0;
633
634 if (is_odd_addr)
635 {
636 bval = comm->read_flash (comm->user_data, addr / 2) >> 8;
637 buf[i++] = HEX_DIGIT[bval >> 4];
638 buf[i++] = HEX_DIGIT[bval & 0xf];
639 addr++;
640 len--;
641 }
642
643 while (len > 1)
644 {
645 wval = comm->read_flash (comm->user_data, addr / 2);
646
647 bval = wval & 0xff;
648 buf[i++] = HEX_DIGIT[bval >> 4];
649 buf[i++] = HEX_DIGIT[bval & 0xf];
650
651 bval = wval >> 8;
652 buf[i++] = HEX_DIGIT[bval >> 4];
653 buf[i++] = HEX_DIGIT[bval & 0xf];
654
655 len -= 2;
656 addr += 2;
657 }
658
659 if (len == 1)
660 {
661 bval = comm->read_flash (comm->user_data, addr / 2) & 0xff;
662 buf[i++] = HEX_DIGIT[bval >> 4];
663 buf[i++] = HEX_DIGIT[bval & 0xf];
664 }
665 }
666 #if defined(USE_EEPROM_SPACE)
667 else if ((addr & MEM_SPACE_MASK) == EEPROM_OFFSET)
668 {
669 /* addressing eeprom */
670
671 addr = addr & ~MEM_SPACE_MASK; /* remove the offset bits */
672
673 avr_warning ("reading of eeprom not yet implemented: 0x%x.\n", addr);
674 snprintf (buf, len * 2, "E%02x", EIO);
675 }
676 #endif
677 else
678 {
679 /* gdb asked for memory space which doesn't exist */
680 avr_warning ("Invalid memory address: 0x%x.\n", addr);
681 snprintf ((char*)buf, len * 2, "E%02x", EIO);
682 }
683
684 gdb_send_reply (fd, (char*)buf);
685
686 avr_free (buf);
687 }
688
689 static void
690 gdb_write_memory (GdbComm_T *comm, int fd, char *pkt)
691 {
692 int addr = 0;
693 int len = 0;
694 uint8_t bval;
695 uint16_t wval;
696 int is_odd_addr;
697 int i;
698 char reply[10];
699
700 /* Set the default reply. */
701 strncpy (reply, "OK", sizeof (reply));
702
703 pkt += gdb_get_addr_len (pkt, ',', ':', &addr, &len);
704
705 if ((addr & MEM_SPACE_MASK) == SRAM_OFFSET)
706 {
707 /* addressing sram */
708
709 addr = addr & ~MEM_SPACE_MASK; /* remove the offset bits */
710
711 /* Return error. See gdb_read_memory for reasoning. */
712 /* FIXME: [TRoth 2002/03/31] This isn't working quite the way I
713 thought it would so I've removed it for now. */
714 /* if ( (addr >= 0) && (addr < 32) ) */
715 if (0)
716 {
717 snprintf (reply, sizeof (reply), "E%02x", EIO);
718 }
719 else
720 {
721 for (i = addr; i < addr + len; i++)
722 {
723 bval = hex2nib (*pkt++) << 4;
724 bval += hex2nib (*pkt++);
725 comm->write_sram (comm->user_data, i, bval);
726 }
727 }
728 }
729 else if ((addr & MEM_SPACE_MASK) == FLASH_OFFSET)
730 {
731 /* addressing flash */
732
733 /* Some targets might not allow writing to flash */
734
735 if (comm->write_flash && comm->write_flash_lo8
736 && comm->write_flash_hi8)
737 {
738 addr = addr & ~MEM_SPACE_MASK; /* remove the offset bits */
739
740 is_odd_addr = addr % 2;
741
742 if (is_odd_addr)
743 {
744 bval = hex2nib (*pkt++) << 4;
745 bval += hex2nib (*pkt++);
746 comm->write_flash_hi8 (comm->user_data, addr / 2, bval);
747 len--;
748 addr++;
749 }
750
751 while (len > 1)
752 {
753 wval = hex2nib (*pkt++) << 4; /* low byte first */
754 wval += hex2nib (*pkt++);
755 wval += hex2nib (*pkt++) << 12; /* high byte last */
756 wval += hex2nib (*pkt++) << 8;
757 comm->write_flash (comm->user_data, addr / 2, wval);
758 len -= 2;
759 addr += 2;
760 }
761
762 if (len == 1)
763 {
764 /* one more byte to write */
765 bval = hex2nib (*pkt++) << 4;
766 bval += hex2nib (*pkt++);
767 comm->write_flash_lo8 (comm->user_data, addr / 2, bval);
768 }
769 }
770 else
771 {
772 /* target can't write to flash, so complain to gdb */
773 avr_warning ("Gdb asked to write to flash and target can't.\n");
774 snprintf (reply, sizeof (reply), "E%02x", EIO);
775 }
776 }
777 #if defined (USE_EEPROM_SPACE)
778 else if ((addr & MEM_SPACE_MASK) == EEPROM_OFFSET)
779 {
780 /* addressing eeprom */
781
782 addr = addr & ~MEM_SPACE_MASK; /* remove the offset bits */
783
784 avr_warning ("writing of eeprom not yet implemented: 0x%x.\n", addr);
785 snprintf (reply, sizeof (reply), "E%02x", EIO);
786 }
787 #endif
788 else
789 {
790 /* gdb asked for memory space which doesn't exist */
791 avr_warning ("Invalid memory address: 0x%x.\n", addr);
792 snprintf (reply, sizeof (reply), "E%02x", EIO);
793 }
794
795 gdb_send_reply (fd, reply);
796 }
797
798 /* Format of breakpoint commands (both insert and remove):
799
800 "z<t>,<addr>,<length>" - remove break/watch point
801 "Z<t>,<add>r,<length>" - insert break/watch point
802
803 In both cases t can be the following:
804 t = '0' - software breakpoint
805 t = '1' - hardware breakpoint
806 t = '2' - write watch point
807 t = '3' - read watch point
808 t = '4' - access watch point
809
810 addr is address.
811 length is in bytes
812
813 For a software breakpoint, length specifies the size of the instruction to
814 be patched. For hardware breakpoints and watchpoints, length specifies the
815 memory region to be monitored. To avoid potential problems, the operations
816 should be implemented in an idempotent way. -- GDB 5.0 manual. */
817
818 static void
819 gdb_break_point (GdbComm_T *comm, int fd, char *pkt)
820 {
821 int addr = 0;
822 int len = 0;
823
824 char z = *(pkt - 1); /* get char parser already looked at */
825 char t = *pkt++;
826 pkt++; /* skip over first ',' */
827
828 gdb_get_addr_len (pkt, ',', '\0', &addr, &len);
829
830 switch (t)
831 {
832 case '0': /* software breakpoint */
833 /* addr/2 since addr refers to PC */
834 if (comm->max_pc
835 && ((addr / 2) >= comm->max_pc (comm->user_data)))
836 {
837 avr_warning ("Attempt to set break at invalid addr\n");
838 gdb_send_reply (fd, "E01");
839 return;
840 }
841
842 if (z == 'z')
843 comm->remove_break (comm->user_data, addr / 2);
844 else
845 comm->insert_break (comm->user_data, addr / 2);
846 break;
847
848 case '1': /* hardware breakpoint */
849 case '2': /* write watchpoint */
850 case '3': /* read watchpoint */
851 case '4': /* access watchpoint */
852 gdb_send_reply (fd, "");
853 return; /* unsupported yet */
854 }
855
856 gdb_send_reply (fd, "OK");
857 }
858
859 /* Handle an io registers query. Query has two forms:
860 "avr.io_reg" and "avr.io_reg:addr,len".
861
862 The "avr.io_reg" has already been stripped off at this point.
863
864 The first form means, "return the number of io registers for this target
865 device." Second form means, "send data len io registers starting with
866 register addr." */
867
868 static void
869 gdb_fetch_io_registers (GdbComm_T *comm, int fd, char *pkt)
870 {
871 int addr, len;
872 int i;
873 uint8_t val;
874 char reply[400];
875 char reg_name[80];
876 int pos = 0;
877
878 if (comm->io_fetch)
879 {
880 if (pkt[0] == '\0')
881 {
882 /* gdb is asking how many io registers the device has. */
883 gdb_send_reply (fd, "40");
884 }
885
886 else if (pkt[0] == ':')
887 {
888 /* gdb is asking for io registers addr to (addr + len) */
889
890 gdb_get_addr_len (pkt + 1, ',', '\0', &addr, &len);
891
892 memset (reply, '\0', sizeof (reply));
893
894 for (i = 0; i < len; i++)
895 {
896 comm->io_fetch (comm->user_data, addr + i, &val, reg_name,
897 sizeof (reg_name));
898 pos +=
899 snprintf (reply + pos, sizeof (reply) - pos, "%s,%x;",
900 reg_name, val);
901 }
902
903 gdb_send_reply (fd, reply); /* do nothing for now */
904 }
905
906 else
907 gdb_send_reply (fd, "E01"); /* An error occurred */
908
909 }
910
911 else
912 gdb_send_reply (fd, ""); /* tell gdb we don't handle info io
913 command. */
914 }
915
916 /* Dispatch various query request to specific handler functions. If a query is
917 not handled, send an empry reply. */
918
919 static void
920 gdb_query_request (GdbComm_T *comm, int fd, char *pkt)
921 {
922 int len;
923
924 switch (*pkt++)
925 {
926 case 'R':
927 len = strlen ("avr.io_reg");
928 if (strncmp (pkt, "avr.io_reg", len) == 0)
929 {
930 gdb_fetch_io_registers (comm, fd, pkt + len);
931 return;
932 }
933 }
934
935 gdb_send_reply (fd, "");
936 }
937
938 /* Continue command format: "c<addr>" or "s<addr>"
939
940 If addr is given, resume at that address, otherwise, resume at current
941 address. */
942
943 static void
944 gdb_continue (GdbComm_T *comm, int fd, char *pkt)
945 {
946 char reply[MAX_BUF + 1];
947 int res;
948 int pc;
949 char step = *(pkt - 1); /* called from 'c' or 's'? */
950 int signo = SIGTRAP;
951
952 static int is_running = 0;
953
954 /* This allows gdb_continue to be reentrant while it's running. */
955 if (is_running == 1)
956 {
957 return;
958 }
959 is_running = 1;
960
961 memset (reply, 0, sizeof (reply));
962
963 if (*pkt != '\0')
964 {
965 /* NOTE: from what I've read on the gdb lists, gdb never uses the
966 "continue at address" functionality. That may change, so let's
967 catch that case. */
968
969 /* get addr to resume at */
970 avr_error ("attempt to resume at other than current");
971 }
972
973 while (1)
974 {
975 if (signal_has_occurred (SIGINT))
976 {
977 global_server_quit = 1;
978 break;
979 }
980
981 res = comm->step (comm->user_data);
982
983 if (res == BREAK_POINT)
984 {
985 if (comm->disable_breakpts)
986 comm->disable_breakpts (comm->user_data);
987 break;
988 }
989
990 /* check if gdb sent any messages */
991 res = gdb_pre_parse_packet (comm, fd, GDB_BLOCKING_OFF);
992 if (res < 0)
993 {
994 if (res == GDB_RET_CTRL_C)
995 {
996 signo = SIGINT;
997 }
998 break;
999 }
1000
1001 /* If called from 's' or 'S', only want to step once */
1002 if ((step == 's') || (step == 'S'))
1003 break;
1004 }
1005
1006 /* If reply hasn't been set, respond as if a breakpoint was hit. */
1007 if (reply[0] == '\0')
1008 {
1009 /* Send gdb SREG, SP, PC */
1010 int bytes = 0;
1011
1012 pc = comm->read_pc (comm->user_data) * 2;
1013
1014 bytes = snprintf (reply, MAX_BUF, "T%02x", signo);
1015
1016 /* SREG, SP & PC */
1017 snprintf (reply + bytes, MAX_BUF - bytes,
1018 "20:%02x;" "21:%02x%02x;" "22:%02x%02x%02x%02x;",
1019 comm->read_sreg (comm->user_data),
1020 comm->read_sram (comm->user_data, SPL_ADDR),
1021 comm->read_sram (comm->user_data, SPH_ADDR), pc & 0xff,
1022 (pc >> 8) & 0xff, (pc >> 16) & 0xff, (pc >> 24) & 0xff);
1023 }
1024
1025 gdb_send_reply (fd, reply);
1026
1027 is_running = 0;
1028 }
1029
1030 /* Continue with signal command format: "C<sig>;<addr>" or "S<sig>;<addr>"
1031 "<sig>" should always be 2 hex digits, possibly zero padded.
1032 ";<addr>" part is optional.
1033
1034 If addr is given, resume at that address, otherwise, resume at current
1035 address. */
1036
1037 static void
1038 gdb_continue_with_signal (GdbComm_T *comm, int fd, char *pkt)
1039 {
1040 int signo;
1041 char step = *(pkt - 1);
1042
1043 /* strip out the signal part of the packet */
1044
1045 signo = (hex2nib (*pkt++) << 4);
1046 signo += (hex2nib (*pkt++) & 0xf);
1047
1048 if (global_debug_on)
1049 fprintf (stderr, "GDB sent signal: %d\n", signo);
1050
1051 /* Process signals send via remote protocol from gdb. Signals really don't
1052 make sense to the program running in the simulator, so we are using
1053 them sort of as an 'out of band' data. */
1054
1055 switch (signo)
1056 {
1057 case SIGHUP:
1058 /* Gdb user issuing the 'signal SIGHUP' command tells sim to reset
1059 itself. We reply with a SIGTRAP the same as we do when gdb
1060 makes first connection with simulator. */
1061 comm->reset (comm->user_data);
1062 gdb_send_reply (fd, "S05");
1063 return;
1064 default:
1065 /* Gdb user issuing the 'signal <signum>' command where signum is
1066 >= 80 is interpreted as a request to trigger an interrupt
1067 vector. The vector to trigger is signo-80.
1068 (there's an offset of 14) */
1069 if (signo >= 94)
1070 {
1071 if (comm->irq_raise)
1072 {
1073 comm->irq_raise (comm->user_data, signo - 94);
1074 }
1075 }
1076 }
1077
1078 /* Modify pkt to look like what gdb_continue() expects and send it to
1079 gdb_continue(): *pkt should now be either '\0' or ';' */
1080
1081 if (*pkt == '\0')
1082 {
1083 *(pkt - 1) = step;
1084 }
1085 else if (*pkt == ';')
1086 {
1087 *pkt = step;
1088 }
1089 else
1090 {
1091 avr_warning ("Malformed packet: \"%s\"\n", pkt);
1092 gdb_send_reply (fd, "");
1093 return;
1094 }
1095
1096 gdb_continue (comm, fd, pkt);
1097 }
1098
1099 /* Parse the packet. Assumes that packet is null terminated.
1100 Return GDB_RET_KILL_REQUEST if packet is 'kill' command,
1101 GDB_RET_OK otherwise. */
1102
1103 static int
1104 gdb_parse_packet (GdbComm_T *comm, int fd, char *pkt)
1105 {
1106 switch (*pkt++)
1107 {
1108 case '?': /* last signal */
1109 gdb_send_reply (fd, "S05"); /* signal # 5 is SIGTRAP */
1110 break;
1111
1112 case 'g': /* read registers */
1113 gdb_read_registers (comm, fd);
1114 break;
1115
1116 case 'G': /* write registers */
1117 gdb_write_registers (comm, fd, pkt);
1118 break;
1119
1120 case 'p': /* read a single register */
1121 gdb_read_register (comm, fd, pkt);
1122 break;
1123
1124 case 'P': /* write single register */
1125 gdb_write_register (comm, fd, pkt);
1126 break;
1127
1128 case 'm': /* read memory */
1129 gdb_read_memory (comm, fd, pkt);
1130 break;
1131
1132 case 'M': /* write memory */
1133 gdb_write_memory (comm, fd, pkt);
1134 break;
1135
1136 case 'k': /* kill request */
1137 case 'D': /* Detach request */
1138 /* Reset the simulator since there may be another connection
1139 before the simulator stops running. */
1140
1141 comm->reset (comm->user_data);
1142 gdb_send_reply (fd, "OK");
1143 return GDB_RET_KILL_REQUEST;
1144
1145 case 'C': /* continue with signal */
1146 case 'S': /* step with signal */
1147 gdb_continue_with_signal (comm, fd, pkt);
1148 break;
1149
1150 case 'c': /* continue */
1151 case 's': /* step */
1152 gdb_continue (comm, fd, pkt);
1153 break;
1154
1155 case 'z': /* remove break/watch point */
1156 case 'Z': /* insert break/watch point */
1157 gdb_break_point (comm, fd, pkt);
1158 break;
1159
1160 case 'q': /* query requests */
1161 gdb_query_request (comm, fd, pkt);
1162 break;
1163
1164 default:
1165 gdb_send_reply (fd, "");
1166 }
1167
1168 return GDB_RET_OK;
1169 }
1170
1171 static void
1172 gdb_set_blocking_mode (int fd, int mode)
1173 {
1174 if (mode)
1175 {
1176 /* turn non-blocking mode off */
1177 if (fcntl (fd, F_SETFL, fcntl (fd, F_GETFL, 0) & ~O_NONBLOCK) < 0)
1178 avr_warning ("fcntl failed: %s\n", strerror (errno));
1179 }
1180 else
1181 {
1182 /* turn non-blocking mode on */
1183 if (fcntl (fd, F_SETFL, fcntl (fd, F_GETFL, 0) | O_NONBLOCK) < 0)
1184 avr_warning ("fcntl failed: %s\n", strerror (errno));
1185 }
1186 }
1187
1188 /* Perform pre-packet parsing. This will handle messages from gdb which are
1189 outside the realm of packets or prepare a packet for parsing.
1190
1191 Use the static block_on flag to reduce the over head of turning blocking on
1192 and off every time this function is called. */
1193
1194 static int
1195 gdb_pre_parse_packet (GdbComm_T *comm, int fd, int blocking)
1196 {
1197 int i, res;
1198 int c;
1199 char pkt_buf[MAX_BUF + 1];
1200 int cksum, pkt_cksum;
1201 static int block_on = 1; /* default is blocking mode */
1202
1203 if (block_on != blocking)
1204 {
1205 gdb_set_blocking_mode (fd, blocking);
1206 block_on = blocking;
1207 }
1208
1209 c = gdb_read_byte (fd);
1210
1211 switch (c)
1212 {
1213 case '$': /* read a packet */
1214 /* insure that packet is null terminated. */
1215 memset (pkt_buf, 0, sizeof (pkt_buf));
1216
1217 /* make sure we block on fd */
1218 gdb_set_blocking_mode (fd, GDB_BLOCKING_ON);
1219
1220 pkt_cksum = i = 0;
1221 c = gdb_read_byte (fd);
1222 while ((c != '#') && (i < MAX_BUF))
1223 {
1224 pkt_buf[i++] = c;
1225 pkt_cksum += (unsigned char)c;
1226 c = gdb_read_byte (fd);
1227 }
1228
1229 cksum = hex2nib (gdb_read_byte (fd)) << 4;
1230 cksum |= hex2nib (gdb_read_byte (fd));
1231
1232 /* FIXME: Should send "-" (Nak) instead of aborting when we get
1233 checksum errors. Leave this as an error until it is actually
1234 seen (I've yet to see a bad checksum - TRoth). It's not a
1235 simple matter of sending (Nak) since you don't want to get into
1236 an infinite loop of (bad cksum, nak, resend, repeat). */
1237
1238 if ((pkt_cksum & 0xff) != cksum)
1239 avr_error ("Bad checksum: sent 0x%x <--> computed 0x%x",
1240 cksum, pkt_cksum);
1241
1242 if (global_debug_on)
1243 fprintf (stderr, "Recv: \"$%s#%02x\"\n", pkt_buf, cksum);
1244
1245 /* always acknowledge a well formed packet immediately */
1246 gdb_send_ack (fd);
1247
1248 res = gdb_parse_packet (comm, fd, pkt_buf);
1249 if (res < 0)
1250 return res;
1251
1252 break;
1253
1254 case '-':
1255 if (global_debug_on)
1256 fprintf (stderr, " gdb -> Nak\n");
1257 gdb_send_reply (fd, gdb_last_reply (NULL));
1258 break;
1259
1260 case '+':
1261 if (global_debug_on)
1262 fprintf (stderr, " gdb -> Ack\n");
1263 break;
1264
1265 case 0x03:
1266 /* Gdb sends this when the user hits C-c. This is gdb's way of
1267 telling the simulator to interrupt what it is doing and return
1268 control back to gdb. */
1269 return GDB_RET_CTRL_C;
1270
1271 case -1:
1272 /* fd is non-blocking and no data to read */
1273 break;
1274
1275 default:
1276 avr_warning ("Unknown request from gdb: %c (0x%02x)\n", c, c);
1277 }
1278
1279 return GDB_RET_OK;
1280 }
1281
1282 static void
1283 gdb_main_loop (GdbComm_T *comm, int fd)
1284 {
1285 int res;
1286 char reply[MAX_BUF];
1287
1288 while (1)
1289 {
1290 res = gdb_pre_parse_packet (comm, fd, GDB_BLOCKING_ON);
1291 switch (res)
1292 {
1293 case GDB_RET_KILL_REQUEST:
1294 return;
1295
1296 case GDB_RET_CTRL_C:
1297 gdb_send_ack (fd);
1298 snprintf (reply, MAX_BUF, "S%02x", SIGINT);
1299 gdb_send_reply (fd, reply);
1300 break;
1301
1302 default:
1303 break;
1304 }
1305 }
1306 }
1307
1308 /**
1309 * \brief Start interacting with gdb.
1310 * \param comm A previously initialized simulator comm
1311 * \param port Port which server will listen for connections on.
1312 * \param debug_on Turn on gdb debug diagnostic messages.
1313 *
1314 * Start a tcp server socket on localhost listening for connections on the
1315 * given port. Once a connection is established, enter an infinite loop and
1316 * process command requests from gdb using the remote serial protocol. Only a
1317 * single connection is allowed at a time.
1318 */
1319 void
1320 gdb_interact (GdbComm_T *comm, int port, int debug_on)
1321 {
1322 struct sockaddr_in address[1];
1323 int sock, conn, i;
1324 socklen_t addrLength[1];
1325
1326 global_debug_on = debug_on;
1327
1328 if ((sock = socket (PF_INET, SOCK_STREAM, 0)) < 0)
1329 avr_error ("Can't create socket: %s", strerror (errno));
1330
1331 /* Let the kernel reuse the socket address. This lets us run
1332 twice in a row, without waiting for the (ip, port) tuple
1333 to time out. */
1334 i = 1;
1335 setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof (i));
1336
1337 address->sin_family = AF_INET;
1338 address->sin_port = htons (port);
1339 memset (&address->sin_addr, 0, sizeof (address->sin_addr));
1340
1341 if (bind (sock, (struct sockaddr *)address, sizeof (address)))
1342 avr_error ("Can not bind socket: %s", strerror (errno));
1343
1344 signal_watch_start (SIGINT);
1345
1346 while (global_server_quit == 0)
1347 {
1348 if (listen (sock, 1))
1349 {
1350 int saved_errno = errno;
1351
1352 if (signal_has_occurred (SIGINT))
1353 {
1354 break; /* SIGINT will cause listen to be
1355 interrupted */
1356 }
1357 avr_error ("Can not listen on socket: %s",
1358 strerror (saved_errno));
1359 }
1360
1361 fprintf (stderr, "Waiting on port %d for gdb client to connect...\n",
1362 port);
1363
1364 /* accept() needs this set, or it fails (sometimes) */
1365 addrLength[0] = sizeof (struct sockaddr);
1366
1367 /* We only want to accept a single connection, thus don't need a
1368 loop. */
1369 conn = accept (sock, (struct sockaddr *)address, addrLength);
1370 if (conn < 0)
1371 {
1372 int saved_errno = errno;
1373
1374 if (signal_has_occurred (SIGINT))
1375 {
1376 break; /* SIGINT will cause accept to be
1377 interrupted */
1378 }
1379 avr_error ("Accept connection failed: %s",
1380 strerror (saved_errno));
1381 }
1382
1383 /* Tell TCP not to delay small packets. This greatly speeds up
1384 interactive response. WARNING: If TCP_NODELAY is set on, then gdb
1385 may timeout in mid-packet if the (gdb)packet is not sent within a
1386 single (tcp)packet, thus all outgoing (gdb)packets _must_ be sent
1387 with a single call to write. (see Stevens "Unix Network
1388 Programming", Vol 1, 2nd Ed, page 202 for more info) */
1389
1390 i = 1;
1391 setsockopt (conn, IPPROTO_TCP, TCP_NODELAY, &i, sizeof (i));
1392
1393 /* If we got this far, we now have a client connected and can start
1394 processing. */
1395
1396 fprintf (stderr, "Connection opened by host %s, port %hd.\n",
1397 inet_ntoa (address->sin_addr), ntohs (address->sin_port));
1398
1399 gdb_main_loop (comm, conn);
1400
1401 comm->reset (comm->user_data);
1402
1403 close (conn);
1404
1405 /* FIXME: How do we correctly break out of this loop? This keeps the
1406 simulator server up so you don't have to restart it with every gdb
1407 session. To exit the server loop, you have to hit C-c or send some
1408 signal which causes the program to terminate, in which case, you
1409 won't get a dump of the simulator's state. This might actually be
1410 acceptable behavior. */
1411 if (signal_has_occurred (SIGINT))
1412 {
1413 break;
1414 }
1415 }
1416
1417 signal_watch_stop (SIGINT);
1418
1419 close (sock);
1420 }

Automatically generated by Doxygen 1.8.2 on Mon Aug 18 2014.