Debian Codegraph @

src/remote.cc

raw symbols SCIP
1 /*
2 * avarice - The "avarice" program.
3 * Copyright (C) 2001 Scott Finneran
4 * Copyright (C) 2002 Intel Corporation
5 * Copyright (C) 2005 Joerg Wunsch
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License Version 2
9 * as published by the Free Software Foundation.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
19 *
20 * This file contains functions for interfacing with the GDB remote protocol.
21 *
22 * $Id: remote.cc 346 2014-10-13 19:55:46Z joerg_wunsch $
23 */
24
25 #include <stdlib.h>
26 #include <string.h>
27 #include <termios.h>
28 #include <sys/time.h>
29 #include <unistd.h>
30 #include <ctype.h>
31 #include <errno.h>
32 #include <stdio.h>
33 #include <fcntl.h>
34 #include <signal.h>
35
36 #include "avarice.h"
37 #include "remote.h"
38 #include "jtag.h"
39
40 enum
41 {
42 /** BUFMAX defines the maximum number of characters in
43 * inbound/outbound buffers at least NUMREGBYTES*2 are needed for
44 * register packets
45 */
46 BUFMAX = 400,
47 NUMREGS = 32/* + 1 + 1 + 1*/, /* SREG, FP, PC */
48 SREG = 32,
49 SP = 33,
50 PC = 34,
51
52 // Number of bytes of registers. See GDB gdb/avr-tdep.c
53 NUMREGBYTES = (NUMREGS + 1 + 2 + 4),
54
55 // max number of bytes in a "monitor" command request
56 MONMAX = 100,
57 };
58
59 static char remcomInBuffer[BUFMAX];
60 static char remcomOutBuffer[BUFMAX];
61
62 static void ok();
63 static void error(int n);
64
65 int gdbFileDescriptor = -1;
66
67 void setGdbFile(int fd)
68 {
69 gdbFileDescriptor = fd;
70 int ret = fcntl(gdbFileDescriptor, F_SETFL, O_NONBLOCK);
71 if (ret < 0)
72 throw jtag_exception();
73 }
74
75 static void waitForGdbOutput(void)
76 {
77 int numfds;
78 fd_set writefds;
79
80 FD_ZERO (&writefds);
81 FD_SET (gdbFileDescriptor, &writefds);
82
83 numfds = select (gdbFileDescriptor + 1, 0, &writefds, 0, 0);
84 if (numfds < 0)
85 throw jtag_exception();
86 }
87
88 /** Send single char to gdb. Abort in case of problem. **/
89 static void putDebugChar(char c)
90 {
91 // This loop busy waits when it cannot write to gdb.
92 // But that shouldn't happen
93 for (;;)
94 {
95 int ret = write(gdbFileDescriptor, &c, 1);
96
97 if (ret == 1)
98 return;
99
100 if (ret == 0) // this shouldn't happen?
101 throw jtag_exception();
102
103 if (errno != EAGAIN && ret < 0)
104 throw jtag_exception();
105
106 waitForGdbOutput();
107 }
108 }
109
110 static void waitForGdbInput(void)
111 {
112 int numfds;
113 fd_set readfds;
114
115 FD_ZERO (&readfds);
116 FD_SET (gdbFileDescriptor, &readfds);
117
118 numfds = select (gdbFileDescriptor + 1, &readfds, 0, 0, 0);
119 if (numfds < 0)
120 throw jtag_exception();
121 }
122
123 /** Return single char read from gdb. Abort in case of problem,
124 exit cleanly if EOF detected on gdbFileDescriptor. **/
125 int getDebugChar(void)
126 {
127 uchar c = 0;
128 int result;
129
130 do
131 {
132 waitForGdbInput();
133 result = read(gdbFileDescriptor, &c, 1);
134 }
135 while (result < 0 && errno == EAGAIN);
136
137 if (result < 0)
138 throw jtag_exception();
139
140 if (result == 0) // gdb exited
141 {
142 statusOut("gdb exited.\n");
143 theJtagICE->resumeProgram();
144 throw jtag_exception("gdb exited");
145 }
146
147 return (int)c;
148 }
149
150 int checkForDebugChar(void)
151 {
152 uchar c = 0;
153 int result;
154
155 result = read(gdbFileDescriptor, &c, 1);
156
157 if (result < 0 && errno == EAGAIN)
158 return -1;
159
160 if (result < 0)
161 throw jtag_exception();
162
163 if (result == 0) // gdb exited
164 {
165 statusOut("gdb exited.\n");
166 theJtagICE->resumeProgram();
167 throw jtag_exception("gdb exited");
168 }
169
170 return (int)c;
171 }
172
173 static const unsigned char hexchars[] = "0123456789abcdef";
174
175 static char *byteToHex(uchar x, char *buf)
176 {
177 *buf++ = hexchars[x >> 4];
178 *buf++ = hexchars[x & 0xf];
179
180 return buf;
181 }
182
183 static int hex(unsigned char ch)
184 {
185 if((ch >= 'a') && (ch <= 'f'))
186 {
187 return (ch - 'a' + 10);
188 }
189 if((ch >= '0') && (ch <= '9'))
190 {
191 return (ch - '0');
192 }
193 if((ch >= 'A') && (ch <= 'F'))
194 {
195 return (ch - 'A' + 10);
196 }
197 return (-1);
198 }
199
200
201 /** Convert hex string at '*ptr' to an integer.
202 Advances '*ptr' to 1st non-hex character found.
203 Returns number of characters used in conversion.
204 **/
205 static int hexToInt(char **ptr, int *intValue, int nMax = 0)
206 {
207 int numChars = 0;
208 int hexValue;
209
210 *intValue = 0;
211 while (**ptr)
212 {
213 hexValue = hex(**ptr);
214 if(hexValue >= 0)
215 {
216 *intValue = (*intValue << 4) | hexValue;
217 numChars++;
218 }
219 else
220 {
221 break;
222 }
223 (*ptr)++;
224 if (nMax != 0 && numChars >= nMax)
225 return numChars;
226 }
227 return (numChars);
228 }
229
230 /** Convert the memory pointed to by mem into hex, placing result in buf.
231 Return a pointer to the last char put in buf (null).
232 **/
233 static char *mem2hex(uchar *mem, char *buf, int count)
234 {
235 for (int i = 0; i < count; i++)
236 buf = byteToHex(*mem++, buf);
237 *buf = 0;
238
239 return (buf);
240 }
241
242 /** Convert the hex array pointed to by buf into binary to be placed in mem.
243 Return a pointer to the character AFTER the last byte written.
244 **/
245 static uchar *hex2mem(char *buf, uchar *mem, int count)
246 {
247 int i;
248 unsigned char ch;
249
250 for(i = 0; i < count; i++)
251 {
252 ch = hex(*buf++) << 4;
253 ch = ch + hex(*buf++);
254 *mem++ = ch;
255 }
256
257 return (mem);
258 }
259
260 static void putpacket(char *buffer);
261
262 void vgdbOut(const char *fmt, va_list args)
263 {
264 // We protect against reentry because putpacket could try and report
265 // an error which would lead to a call back to vgdbOut
266 static bool reentered = false;
267
268 if (gdbFileDescriptor >= 0 && !reentered)
269 {
270 char textbuf[BUFMAX], hexbuf[2 * BUFMAX], *textscan, *hexscan;
271
272 reentered = true;
273
274 vsnprintf(textbuf, BUFMAX, fmt, args);
275
276 hexscan = hexbuf;
277 *hexscan++ = 'O';
278 for (textscan = textbuf; *textscan; textscan++)
279 hexscan = byteToHex(*textscan, hexscan);
280 *hexscan = '\0';
281 putpacket(hexbuf);
282
283 reentered = false;
284 }
285 }
286
287 void gdbOut(const char *fmt, ...)
288 {
289 va_list args;
290 va_start(args, fmt);
291 vgdbOut(fmt, args);
292 va_end(args);
293 }
294
295 /** Fill 'remcomOutBuffer' with a status report for signal 'sigval'
296
297 Reply with a packet of the form:
298
299 "Tss20:rr;21:llhh;22:aabbccdd;"
300
301 where (all values in hex):
302 ss = signal number (usually SIGTRAP)
303 rr = SREG value
304 llhh = SPL:SPH (stack pointer)
305 aabbccdd = PC (program counter)
306
307 This actually saves having to read the 32 general registers when stepping
308 over code since gdb won't send a 'g' packet until the PC it is hunting for
309 is found. */
310
311 static void reportStatusExtended(int sigval)
312 {
313 uchar *jtagBuffer;
314 unsigned int pc = theJtagICE->getProgramCounter();
315
316 // Read in SPL SPH SREG
317 jtagBuffer = theJtagICE->jtagRead(theJtagICE->statusAreaAddress(), 0x03);
318
319 if (jtagBuffer)
320 {
321 // We have SPL SPH SREG and need SREG SPL SPH
322
323 snprintf (remcomOutBuffer, sizeof(remcomOutBuffer),
324 "T%02x" "20:%02x;" "21:%02x%02x;" "22:%02x%02x%02x%02x;",
325 sigval & 0xff,
326 jtagBuffer[2], // SREG
327 jtagBuffer[0], // SPL
328 jtagBuffer[1], // SPH
329 pc & 0xff, (pc >> 8) & 0xff,
330 (pc >> 16) & 0xff, (pc >> 24) & 0xff);
331
332 delete [] jtagBuffer;
333 jtagBuffer = 0;
334 }
335 else
336 {
337 error(1);
338 return;
339 }
340 }
341
342 /** Fill 'remcomOutBuffer' with a status report for signal 'sigval' **/
343 static void reportStatus(int sigval)
344 {
345 char *ptr = remcomOutBuffer;
346
347 // We could use 'T'. But this requires reading SREG, SP, PC at least, so
348 // won't be significantly faster than the 'g' operation that gdb will
349 // request if we use 'S' here. [TRoth/2003-06-12: this is not necessarily
350 // true. See above comment for reportStatusExtended().]
351
352 *ptr++ = 'S'; // notify gdb with signo
353 ptr = byteToHex(sigval, ptr);
354 *ptr++ = 0;
355 }
356
357 // little-endian word read
358 unsigned int readLWord(unsigned int address)
359 {
360 unsigned char *mem = theJtagICE->jtagRead(DATA_SPACE_ADDR_OFFSET + address, 2);
361
362 if (!mem)
363 return 0; // hmm
364
365 unsigned int val = mem[0] | mem[1] << 8;
366 delete[] mem;
367 return val;
368 }
369
370 // big-endian word read
371 unsigned int readBWord(unsigned int address)
372 {
373 unsigned char *mem = theJtagICE->jtagRead(DATA_SPACE_ADDR_OFFSET + address, 2);
374
375 if (!mem)
376 return 0; // hmm
377
378 unsigned int val = mem[0] << 8 | mem[1];
379 delete[] mem;
380 return val;
381 }
382
383 unsigned int readSP(void)
384 {
385 return readLWord(0x5d);
386 }
387
388 bool handleInterrupt(void)
389 {
390 bool result;
391
392 // Set a breakpoint at return address
393 debugOut("INTERRUPT\n");
394 unsigned int intrSP = readSP();
395 unsigned int retPC = readBWord(intrSP + 1) << 1;
396 debugOut("INT SP = %x, retPC = %x\n", intrSP, retPC);
397
398 bool needBP = !theJtagICE->codeBreakpointAt(retPC);
399
400 for (;;)
401 {
402 if (needBP)
403 {
404 // If no breakpoint at return address (normal case),
405 // add one.
406 // Normally, this breakpoint add should succeed as gdb shouldn't
407 // be using a momentary breakpoint when doing a step-through-range,
408 // thus leaving is a free hw breakpoint. But if for some reason it
409 // the add fails, interrupt the program at the interrupt handler
410 // entry point
411 if (!theJtagICE->addBreakpoint(retPC, CODE, 0))
412 return false;
413 }
414 result = theJtagICE->jtagContinue();
415 if (needBP)
416 theJtagICE->deleteBreakpoint(retPC, CODE, 0);
417
418 if (!result || !needBP) // user interrupt or hit user BP at retPC
419 break;
420
421 // We check that SP is > intrSP. If SP <= intrSP, this is just
422 // an unrelated excursion to retPC
423 if (readSP() > intrSP)
424 break;
425 }
426 return result;
427 }
428
429 static bool singleStep()
430 {
431 try
432 {
433 theJtagICE->jtagSingleStep();
434 }
435 catch (jtag_exception& e)
436 {
437 gdbOut("Failed to single-step");
438 }
439
440 unsigned int newPC = theJtagICE->getProgramCounter();
441 if (theJtagICE->codeBreakpointAt(newPC))
442 return true;
443 // assume interrupt when PC goes into interrupt table
444 if (ignoreInterrupts && newPC < theJtagICE->deviceDef->vectors_end)
445 return handleInterrupt();
446
447 return true;
448 }
449
450 /** Read packet from gdb into remcomInBuffer, check checksum and confirm
451 reception to gdb.
452 Return pointer to null-terminated, actual packet data (without $, #,
453 the checksum)
454 **/
455 static char *getpacket(int &len)
456 {
457 char *buffer = &remcomInBuffer[0];
458 unsigned char checksum;
459 unsigned char xmitcsum;
460 int count;
461 char ch;
462 bool is_escaped;
463
464 // scan for the sequence $<data>#<checksum>
465 while(1)
466 {
467 // wait around for the start character, ignore all other characters
468 while((ch = getDebugChar()) != '$')
469 ;
470
471 retry:
472 checksum = 0;
473 count = 0;
474 is_escaped = false;
475
476 // now, read until a # or end of buffer is found
477 while(count < BUFMAX - 1)
478 {
479 ch = getDebugChar();
480 if(is_escaped)
481 {
482 checksum = checksum + ch;
483 ch ^= 0x20;
484 is_escaped = false;
485 goto have_char;
486 }
487 if(ch == '$')
488 {
489 goto retry;
490 }
491 if(ch == '#')
492 {
493 break;
494 }
495 checksum = checksum + ch;
496 if(ch == '}')
497 {
498 is_escaped = true;
499 continue;
500 }
501 have_char:
502 buffer[count] = ch;
503 count = count + 1;
504 }
505 buffer[count] = 0;
506
507 if(ch == '#')
508 {
509 ch = getDebugChar();
510 xmitcsum = hex(ch) << 4;
511 ch = getDebugChar();
512 xmitcsum += hex(ch);
513
514 if(checksum != xmitcsum)
515 {
516 char buf[16];
517
518 mem2hex(&checksum, buf, 4);
519 gdbOut("Bad checksum: my count = %s, ", buf);
520 mem2hex(&xmitcsum, buf, 4);
521 gdbOut("sent count = %s\n", buf);
522 gdbOut(" -- Bad buffer: \"%s\"\n", buffer);
523
524 putDebugChar('-'); // failed checksum
525 }
526 else
527 {
528 putDebugChar('+'); // successful transfer
529
530 // if a sequence char is present, reply the sequence ID
531 if(buffer[2] == ':')
532 {
533 putDebugChar(buffer[0]);
534 putDebugChar(buffer[1]);
535
536 len = count - 3;
537
538 return &buffer[3];
539 }
540
541 len = count;
542 return &buffer[0];
543 }
544 }
545 }
546 }
547
548 /** Send packet 'buffer' to gdb. Adds $, # and checksum wrappers. **/
549 static void putpacket(char *buffer)
550 {
551 unsigned char checksum;
552 int count;
553 char ch;
554
555 // $<packet info>#<checksum>.
556 do
557 {
558 putDebugChar('$');
559 checksum = 0;
560 count = 0;
561
562 while((ch = buffer[count]))
563 {
564 putDebugChar(ch);
565 checksum += ch;
566 count += 1;
567 }
568 putDebugChar('#');
569 putDebugChar(hexchars[checksum >> 4]);
570 putDebugChar(hexchars[checksum % 16]);
571 } while(getDebugChar() != '+'); // wait for the ACK
572 }
573
574 /** Set remcomOutBuffer to "ok" response */
575 static void ok()
576 {
577 strcpy(remcomOutBuffer, "OK");
578 }
579
580 /** Set remcomOutBuffer to error 'n' response */
581 static void error(int n)
582 {
583 char *ptr = remcomOutBuffer;
584
585 *ptr++ = 'E';
586 ptr = byteToHex(n, ptr);
587 *ptr = '\0';
588 }
589
590 // put "s" into remcomOutBuffer, obeying the packet size limit
591 static void replyString(const char *s)
592 {
593 unsigned int i = 0;
594 char c, *ptr;
595
596 ptr = remcomOutBuffer;
597 while ((c = *s++) != 0 && i < BUFMAX - 1)
598 {
599 ptr = byteToHex((int)c, ptr);
600 i += 2;
601 }
602 *ptr = '\0';
603 }
604
605 /** reply to a "monitor" command */
606 static bool monitor(const char *cmd)
607 {
608 unsigned int ln = strlen(cmd);
609 if (strncmp(cmd, "help", ln) == 0 ||
610 strcmp(cmd, "?") == 0)
611 {
612 replyString("AVaRICE commands:\n"
613 "help, ?: get help\n"
614 "version: ask AVaRICE version\n"
615 "reset: reset target\n");
616 return true;
617 }
618
619 if (strncmp(cmd, "version", ln) == 0)
620 {
621 char reply[80];
622 sprintf(reply, "AVaRICE version %s, %s %s\n",
623 PACKAGE_VERSION, __DATE__, __TIME__);
624 replyString(reply);
625 return true;
626 }
627
628 if (strncmp(cmd, "reset", ln) == 0)
629 {
630 try
631 {
632 theJtagICE->resetProgram(false);
633 replyString("Resetting MCU...\n");
634 }
635 catch (jtag_exception& e)
636 {
637 char reply[80];
638 sprintf(reply, "Failed to reset MCU: %s\n",
639 e.what());
640 replyString(reply);
641 }
642 return true;
643 }
644
645 return false;
646 }
647
648
649 static void repStatus(bool breaktime)
650 {
651 if (breaktime)
652 reportStatusExtended(SIGTRAP);
653 else
654 {
655 // A breakpoint did not occur. Assume that GDB sent a break.
656 // Halt the target.
657 theJtagICE->interruptProgram();
658 // Report this as a user interrupt
659 reportStatusExtended(SIGINT);
660 }
661 }
662
663 static char *makeSafeString(const char *s, int inLength)
664 {
665 int l = 4 * inLength + 1;
666 char *r = new char[l];
667 char c;
668
669 int i = 0;
670 int j = 0;
671 while (j++ < inLength)
672 {
673 c = *s++;
674 if (isprint(c))
675 {
676 r[i++] = c;
677 }
678 else
679 {
680 i += sprintf(r + i, "\\x%02x", (unsigned)c & 0xff);
681 }
682 }
683 r[i] = '\0';
684 return r;
685 }
686
687
688 void talkToGdb(void)
689 {
690 int addr;
691 int length, plen;
692 int i;
693 unsigned int newPC;
694 int regno;
695 char *ptr;
696 bool adding = false;
697 bool dontSendReply = false;
698 char cmd;
699 static char last_cmd = 0;
700 static unsigned char *flashbuf;
701 static int maxaddr;
702
703 ptr = getpacket(plen);
704
705 if (debugMode)
706 {
707 char *s = makeSafeString(ptr, plen);
708 debugOut("GDB: <%s>\n", s);
709 delete [] s;
710 }
711
712 // default empty response
713 remcomOutBuffer[0] = 0;
714
715 cmd = *ptr++;
716 switch (cmd)
717 {
718 default: // Unknown code. Return an empty reply message.
719 break;
720
721 case 'k': // kill the program
722 dontSendReply = true;
723 break;
724
725 case 'R':
726 try
727 {
728 theJtagICE->resetProgram(false);
729 }
730 catch (jtag_exception& e)
731 {
732 gdbOut("reset failed\n");
733 }
734 dontSendReply = true;
735 break;
736
737 case '!':
738 ok();
739 break;
740
741 case 'M':
742 {
743 uchar *jtagBuffer;
744 int lead = 0;
745 static bool last_orphan_pending = false;
746 static uchar last_orphan = 0xff;
747
748 // MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK
749 // TRY TO READ '%x,%x:'. IF SUCCEED, SET PTR = 0
750
751 error(1); // default is error
752 if((hexToInt(&ptr, &addr)) &&
753 (*(ptr++) == ',') &&
754 (hexToInt(&ptr, &length)) &&
755 (*(ptr++) == ':') &&
756 (length > 0))
757 {
758 debugOut("\nGDB: Write %d bytes to 0x%X\n",
759 length, addr);
760
761 // There is no gaurantee that gdb will send a word aligned stream
762 // of bytes, so we need to try and catch that here. This ugly, but
763 // it would more difficult to change in gdb and probably affect
764 // more than avarice users. This hack will make the gdb 'load'
765 // command less prone to failure.
766
767 if (addr & 1)
768 {
769 // odd addr means there may be a byte from last 'M' to write
770 if ((last_cmd == 'M') && (last_orphan_pending))
771 {
772 length++;
773 addr--;
774 lead = 1;
775 }
776 }
777
778 last_orphan_pending = false;
779
780 jtagBuffer = new uchar[length];
781 hex2mem(ptr, jtagBuffer+lead, length);
782 if (lead)
783 jtagBuffer[0] = last_orphan;
784
785 if ((addr < DATA_SPACE_ADDR_OFFSET) && (length & 1))
786 {
787 // An odd length means we will have an orphan this round but
788 // only if we are writing to PROG space.
789 last_orphan_pending = true;
790 last_orphan = jtagBuffer[length];
791 length--;
792 }
793
794 try
795 {
796 theJtagICE->jtagWrite(addr, length, jtagBuffer);
797 }
798 catch (jtag_exception&)
799 {
800 delete [] jtagBuffer;
801 break;
802 }
803 ok();
804 delete [] jtagBuffer;
805
806 }
807
808 break;
809 }
810 case 'm': // mAA..AA,LLLL Read LLLL bytes at address AA..AA
811 {
812 uchar *jtagBuffer;
813
814 if((hexToInt(&ptr, &addr)) &&
815 (*(ptr++) == ',') &&
816 (hexToInt(&ptr, &length)))
817 {
818 debugOut("\nGDB: Read %d bytes from 0x%X\n", length, addr);
819 try
820 {
821 jtagBuffer = theJtagICE->jtagRead(addr, length);
822 mem2hex(jtagBuffer, remcomOutBuffer, length);
823 delete [] jtagBuffer;
824 }
825 catch (jtag_exception&)
826 {
827 error(1);
828 }
829 }
830 break;
831 }
832 case '?':
833 // Report status. We don't actually know, so always report breakpoint
834 reportStatus(SIGTRAP);
835 break;
836
837 case 'g': // return the value of the CPU registers
838 {
839 uchar *jtagBuffer;
840 uchar regBuffer[40];
841
842 memset(regBuffer, 0, sizeof(regBuffer));
843
844 // Read the registers directly from memory
845 // R0..R31 are at locations 0..31
846 // SP is at 0x5D & 0x5E
847 // SREG is at 0x5F
848 debugOut("\nGDB: (Registers)Read %d bytes from 0x%X\n",
849 0x20, theJtagICE->cpuRegisterAreaAddress());
850 jtagBuffer = theJtagICE->jtagRead(theJtagICE->cpuRegisterAreaAddress(), 0x20);
851
852 if (jtagBuffer)
853 {
854 // Put GPRs into the first 32 locations
855 memcpy(regBuffer, jtagBuffer, 0x20);
856
857 delete [] jtagBuffer;
858 jtagBuffer = 0;
859 }
860 else
861 {
862 error (1);
863 break;
864 }
865
866 // Read in SPL SPH SREG
867 jtagBuffer = theJtagICE->jtagRead(theJtagICE->statusAreaAddress(), 0x03);
868
869 if (jtagBuffer)
870 {
871 // We have SPL SPH SREG and need SREG SPL SPH
872
873 // SREG
874 regBuffer[0x20] = jtagBuffer[0x02];
875
876 // NOTE: Little endian, so SPL comes first.
877
878 // SPL
879 regBuffer[0x21] = jtagBuffer[0x00];
880
881 // SPH
882 regBuffer[0x22] = jtagBuffer[0x01];
883
884 delete [] jtagBuffer;
885 jtagBuffer = 0;
886 }
887 else
888 {
889 error (1);
890 break;
891 }
892
893 // PC
894 newPC = theJtagICE->getProgramCounter();
895 regBuffer[35] = (unsigned char)(newPC & 0xff);
896 regBuffer[36] = (unsigned char)((newPC & 0xff00) >> 8);
897 regBuffer[37] = (unsigned char)((newPC & 0xff0000) >> 16);
898 regBuffer[38] = (unsigned char)((newPC & 0xff000000) >> 24);
899 debugOut("PC = %x\n", newPC);
900
901 if (newPC == PC_INVALID)
902 error(1);
903 else
904 mem2hex(regBuffer, remcomOutBuffer, 32 + 1 + 2 + 4);
905
906 break;
907 }
908
909 case 'q': // general query
910 {
911 uchar* jtagBuffer;
912
913 length = strlen("Ravr.io_reg");
914 if ( strncmp(ptr, "Ravr.io_reg", length) == 0 )
915 {
916 int i, j, regcount;
917 gdb_io_reg_def_type *io_reg_defs;
918
919 debugOut("\nGDB: (io registers) Read %d bytes from 0x%X\n",
920 0x40, 0x20);
921
922 /* If there is an io_reg_defs for this device then respond */
923
924 io_reg_defs = theJtagICE->deviceDef->io_reg_defs;
925 if (io_reg_defs)
926 {
927 // count the number of defined registers
928 regcount = 0;
929 while (io_reg_defs[regcount].name)
930 {
931 regcount++;
932 }
933
934 ptr += length;
935 if (*ptr == '\0')
936 {
937 sprintf(remcomOutBuffer, "%02x", regcount);
938 }
939 else if (*ptr == ':')
940 {
941 // Request for a sequence of io registers
942 int offset;
943 i = 0;
944 j = 0;
945 int count;
946 unsigned int addr;
947
948 // Find the first register
949 ptr++;
950 hexToInt(&ptr,&i);
951
952 // Confirm presence of ','
953 if (*ptr++ == ',')
954 {
955 hexToInt(&ptr,&j);
956 }
957
958 // i is the first register to read
959 // j is the number of registers to read
960 while ((j > 0) && (i < regcount))
961 {
962 count = 0;
963
964 if ((io_reg_defs[i].name != 0x00)
965 && (io_reg_defs[i].flags != 0x00))
966 {
967 // Register with special flags set
968 offset = strlen(remcomOutBuffer);
969 sprintf(&remcomOutBuffer[offset],
970 "[-- %s --],00;", io_reg_defs[i].name);
971 i++;
972 j--;
973 }
974 else
975 {
976 // Get the address of the first io_register to be
977 // read
978 addr = io_reg_defs[i].reg_addr;
979
980 // Count the number of consecutive address,
981 // no-side effects, valid registers
982
983 for (count = 0; count < j; count++)
984 {
985 if ((io_reg_defs[i+count].name == 0x00)
986 || (io_reg_defs[i+count].flags != 0x00)
987 || (io_reg_defs[i+count].reg_addr != addr))
988 {
989 break;
990 }
991 addr++;
992 }
993
994 if (count)
995 {
996 // Read consecutive address io_registers
997 jtagBuffer = theJtagICE->jtagRead(DATA_SPACE_ADDR_OFFSET +
998 io_reg_defs[i].reg_addr,
999 count);
1000
1001 if (jtagBuffer)
1002 {
1003 int k = 0;
1004 // successfully read
1005 while(count--)
1006 {
1007 offset = strlen(remcomOutBuffer);
1008 sprintf(&remcomOutBuffer[offset],
1009 "%s,%02x;",
1010 io_reg_defs[i].name,
1011 jtagBuffer[k++]);
1012 i++;
1013 j--;
1014 }
1015
1016 delete [] jtagBuffer;
1017 jtagBuffer = 0;
1018 }
1019 }
1020 }
1021 }
1022 }
1023 }
1024 }
1025 else if (strncmp(ptr, "Supported:", 10) == 0)
1026 {
1027 strcpy(remcomOutBuffer, "qXfer:memory-map:read+");
1028 }
1029 else if (strncmp(ptr, "Xfer:memory-map:read::", 22) == 0)
1030 {
1031 sprintf(remcomOutBuffer,
1032 "l<memory-map>\n"
1033 /* The RAM size indicated includes the possible
1034 * EEPROM range, so GDB will treat EEPROM uploads
1035 * just like simple SRAM load operations. AVaRICE
1036 * will disambiguate them based on their virtual
1037 * offset. */
1038 " <memory type=\"ram\" start=\"0x800000\" length=\"0x20000\" />\n"
1039 " <memory type=\"flash\" start=\"0\" length=\"0x%x\">\n"
1040 " <property name=\"blocksize\">0x%0x</property>\n"
1041 " </memory>\n"
1042 "</memory-map>\n",
1043 theJtagICE->deviceDef->flash_page_size *
1044 theJtagICE->deviceDef->flash_page_count,
1045 theJtagICE->deviceDef->flash_page_size);
1046 }
1047 else if (length > 5 && strncmp(ptr, "Rcmd,", 4) == 0)
1048 {
1049 char cmdbuf[MONMAX];
1050 int i;
1051 ptr += 5;
1052 length -= 5;
1053 memset(cmdbuf, 0, sizeof cmdbuf);
1054 for (i = 0; i < MONMAX && length >= 0; i++)
1055 {
1056 int c;
1057 length -= hexToInt(&ptr, &c, 2);
1058 cmdbuf[i] = (char)c;
1059 }
1060 debugOut("\nGDB: (monitor) %s\n", cmdbuf);
1061
1062 // when creating a response, minde the BUFMAX bytes per
1063 // packet limit above
1064 if (!monitor(cmdbuf))
1065 remcomOutBuffer[0] = '\0'; // not recognized
1066 }
1067
1068 break;
1069 }
1070
1071 case 'P': // set the value of a single CPU register - return OK
1072 error(1); // error by default
1073 if (hexToInt(&ptr, &regno) && *ptr++ == '=')
1074 {
1075 uchar reg[4];
1076
1077 try
1078 {
1079 if (regno >= 0 && regno < NUMREGS)
1080 {
1081 hex2mem(ptr, reg, 1);
1082 theJtagICE->jtagWrite(theJtagICE->cpuRegisterAreaAddress() + regno,
1083 1, reg);
1084 ok();
1085 break;
1086 }
1087 else if (regno == SREG)
1088 {
1089 hex2mem(ptr, reg, 1);
1090 theJtagICE->jtagWrite(theJtagICE->statusAreaAddress() + 2,
1091 1, reg);
1092 }
1093 else if (regno == SP)
1094 {
1095 hex2mem(ptr, reg, 2);
1096 theJtagICE->jtagWrite(theJtagICE->statusAreaAddress(),
1097 2, reg);
1098 ok();
1099 }
1100 else if (regno == PC)
1101 {
1102 hex2mem(ptr, reg, 4);
1103 theJtagICE->setProgramCounter(reg[0] | reg[1] << 8 |
1104 reg[2] << 16 | reg[3] << 24);
1105 ok();
1106 }
1107 }
1108 catch (jtag_exception& e)
1109 {
1110 // ignore, error state already set above
1111 }
1112 }
1113 break;
1114
1115 case 'G': // set the value of the CPU registers
1116 // It would appear that we don't need to support this as
1117 // we have 'P'. Report an error (rather than fail silently,
1118 // this will make errors in this comment more apparent...)
1119 error(1);
1120 break;
1121
1122 case 's': // sAA..AA Step one instruction from AA..AA(optional)
1123 // try to read optional parameter, pc unchanged if no parm
1124 if (hexToInt(&ptr, &addr))
1125 {
1126 try
1127 {
1128 theJtagICE->setProgramCounter(addr);
1129 }
1130 catch (jtag_exception&)
1131 {
1132 gdbOut("Failed to set PC");
1133 }
1134 }
1135 repStatus(singleStep());
1136 break;
1137
1138 case 'C':
1139 {
1140 /* Continue with signal command format:
1141 "C<sig>;<addr>" or "S<sig>;<addr>"
1142
1143 "<sig>" should always be 2 hex digits, possibly zero padded.
1144 ";<addr>" part is optional.
1145
1146 If addr is given, resume at that address, otherwise, resume at
1147 current address. */
1148
1149 int sig;
1150
1151 if (hexToInt(&ptr, &sig))
1152 {
1153 if (sig == SIGHUP)
1154 {
1155 try
1156 {
1157 theJtagICE->resetProgram(false);
1158 reportStatusExtended(SIGTRAP);
1159 }
1160 catch (jtag_exception& e)
1161 {
1162 fprintf(stderr, "Failed to reset MCU: %s\n",
1163 e.what());
1164 }
1165 }
1166 }
1167 break;
1168 }
1169
1170 case 'c': // cAA..AA Continue from address AA..AA(optional)
1171 // try to read optional parameter, pc unchanged if no parm
1172 if (hexToInt(&ptr, &addr))
1173 {
1174 try
1175 {
1176 theJtagICE->setProgramCounter(addr);
1177 }
1178 catch (jtag_exception&)
1179 {
1180 gdbOut("Failed to set PC");
1181 }
1182 }
1183 repStatus(theJtagICE->jtagContinue());
1184 break;
1185
1186 case 'D':
1187 // Detach, resumes target. Can get control back with step
1188 // or continue
1189 try
1190 {
1191 theJtagICE->resumeProgram();
1192 }
1193 catch (jtag_exception&)
1194 {
1195 error(1);
1196 break;
1197 }
1198 ok();
1199 break;
1200
1201 case 'v':
1202 if (strncmp(ptr, "FlashErase:", 11) == 0)
1203 {
1204 ptr += 11;
1205 int offset, length;
1206 hexToInt(&ptr, &offset);
1207 ptr++;
1208 hexToInt(&ptr, &length);
1209 statusOut("erasing %d bytes @ 0x%0x\n", length, offset);
1210 theJtagICE->enableProgramming();
1211 theJtagICE->eraseProgramMemory();
1212 flashbuf = new unsigned char[theJtagICE->deviceDef->flash_page_size *
1213 theJtagICE->deviceDef->flash_page_count];
1214 maxaddr = 0;
1215 memset(flashbuf, 0xff, theJtagICE->deviceDef->flash_page_size *
1216 theJtagICE->deviceDef->flash_page_count);
1217 ok();
1218 }
1219 else if (strncmp(ptr, "FlashWrite:", 11) == 0)
1220 {
1221 char *optr = ptr;
1222 ptr += 11;
1223 int offset;
1224 hexToInt(&ptr, &offset);
1225 ptr++; // past ":"
1226 int amount = plen - 1 - (ptr - optr);
1227 statusOut("buffering data, %d bytes @ 0x%x\n", amount, offset);
1228 if (offset + amount > maxaddr)
1229 maxaddr = offset + amount;
1230 memcpy(flashbuf + offset, ptr, amount);
1231 ok();
1232 }
1233 else if (strncmp(ptr, "FlashDone", 9) == 0)
1234 {
1235 statusOut("committing to flash\n");
1236 int pagesize = theJtagICE->deviceDef->flash_page_size;
1237 for (int offset = 0; offset < maxaddr; offset += pagesize)
1238 {
1239 theJtagICE->jtagWrite(offset, pagesize, flashbuf + offset);
1240 }
1241 theJtagICE->disableProgramming();
1242 delete [] flashbuf;
1243 ok();
1244 }
1245 break;
1246
1247 case 'Z':
1248 adding = true;
1249 case 'z':
1250 error(1); // assume the worst.
1251
1252 // Add a Breakpoint. note: length specifier is ignored for now.
1253 if (hexToInt(&ptr, &i) && *ptr++ == ',' &&
1254 hexToInt(&ptr, &addr) && *ptr++ == ',' &&
1255 hexToInt(&ptr, &length))
1256 {
1257 bpType mode = NONE;
1258
1259 switch(i)
1260 {
1261 case 0:
1262 case 1:
1263 mode = CODE;
1264 break;
1265 case 2:
1266 mode = WRITE_DATA;
1267 break;
1268 case 3:
1269 mode = READ_DATA;
1270 break;
1271 case 4:
1272 mode = ACCESS_DATA;
1273 break;
1274 default:
1275 debugOut("Unknown breakpoint type from GDB.\n");
1276 throw jtag_exception();
1277 }
1278
1279 if (adding)
1280 {
1281 try
1282 {
1283 theJtagICE->addBreakpoint(addr, mode, length);
1284 }
1285 catch (jtag_exception&)
1286 {
1287 break;
1288 }
1289 }
1290 else
1291 {
1292 try
1293 {
1294 theJtagICE->deleteBreakpoint(addr, mode, length);
1295 }
1296 catch (jtag_exception&)
1297 {
1298 break;
1299 }
1300 }
1301 ok();
1302 }
1303 break;
1304
1305 } // switch
1306
1307 last_cmd = cmd;
1308
1309 // reply to the request
1310 if (!dontSendReply)
1311 {
1312 debugOut("->GDB: %s\n", remcomOutBuffer);
1313 putpacket(remcomOutBuffer);
1314 }
1315 }
1316
1317