c88ab8d4b22b9baa8eb5f60535b7963803d42bfa
[lunaix-os.git] / lunaix-os / kernel / debug / gdbstub.c
1 /**
2  * @file gdbstub.h
3  * @author Lunaixsky ()
4  * @brief GDB Stub implementation (https://github.com/mborgerson/gdbstub).
5  *          Ported for LunaixOS
6  * @version 0.1
7  * @date 2022-10-18
8  *
9  * @copyright Copyright (c) 2022 Lunaixsky & (See license below)
10  *
11  */
12
13 /*
14  * Copyright (c) 2016-2022 Matt Borgerson
15  *
16  * Permission is hereby granted, free of charge, to any person obtaining a copy
17  * of this software and associated documentation files (the "Software"), to deal
18  * in the Software without restriction, including without limitation the rights
19  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
20  * copies of the Software, and to permit persons to whom the Software is
21  * furnished to do so, subject to the following conditions:
22  *
23  * The above copyright notice and this permission notice shall be included in
24  * all copies or substantial portions of the Software.
25  *
26  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
29  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
31  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32  * SOFTWARE.
33  */
34
35 #include <hal/serial.h>
36 #include <klibc/string.h>
37 #include <sdbg/gdbstub.h>
38
39 #include <sys/port_io.h>
40 #include <sys/cpu.h>
41 #include <sys/gdbstub.h>
42
43 /*****************************************************************************
44  * Macros
45  ****************************************************************************/
46
47 #define GDB_PRINT(...)
48
49 #define GDB_EOF (-1)
50
51 #ifndef GDB_ASSERT
52 #define GDB_ASSERT(x)                                                          \
53     do {                                                                       \
54     } while (0)
55 #endif
56
57 /*****************************************************************************
58  * Prototypes
59  ****************************************************************************/
60
61 int
62 gdb_main(struct gdb_state* state);
63
64 /* System functions, supported by all stubs */
65 void
66 gdb_sys_init(void);
67 int
68 gdb_sys_getc(struct gdb_state* state);
69 int
70 gdb_sys_putchar(struct gdb_state* state, int ch);
71 int
72 gdb_sys_mem_readb(struct gdb_state* state, ptr_t addr, char* val);
73 int
74 gdb_sys_mem_writeb(struct gdb_state* state, ptr_t addr, char val);
75
76
77 /*****************************************************************************
78  * Types
79  ****************************************************************************/
80
81 typedef int (*gdb_enc_func)(char* buf,
82                             unsigned int buf_len,
83                             const char* data,
84                             unsigned int data_len);
85 typedef int (*gdb_dec_func)(const char* buf,
86                             unsigned int buf_len,
87                             char* data,
88                             unsigned int data_len);
89
90 /*****************************************************************************
91  * Const Data
92  ****************************************************************************/
93
94 static const char digits[] = "0123456789abcdef";
95
96 /*****************************************************************************
97  * Prototypes
98  ****************************************************************************/
99
100 /* Communication functions */
101 static int
102 gdb_write(struct gdb_state* state, const char* buf, unsigned int len);
103 static int
104 gdb_read(struct gdb_state* state,
105          char* buf,
106          unsigned int buf_len,
107          unsigned int len);
108
109
110 static char
111 gdb_get_digit(int val);
112 static int
113 gdb_get_val(char digit, int base);
114 static int
115 gdb_strtol(const char* str, unsigned int len, int base, const char** endptr);
116
117 /* Packet functions */
118 static int
119 gdb_send_packet(struct gdb_state* state, const char* pkt, unsigned int pkt_len);
120 static int
121 gdb_recv_packet(struct gdb_state* state,
122                 char* pkt_buf,
123                 unsigned int pkt_buf_len,
124                 unsigned int* pkt_len);
125 static int
126 gdb_checksum(const char* buf, unsigned int len);
127 static int
128 gdb_recv_ack(struct gdb_state* state);
129
130 /* Data encoding/decoding */
131 static int
132 gdb_enc_hex(char* buf,
133             unsigned int buf_len,
134             const char* data,
135             unsigned int data_len);
136 static int
137 gdb_dec_hex(const char* buf,
138             unsigned int buf_len,
139             char* data,
140             unsigned int data_len);
141 static int
142 gdb_enc_bin(char* buf,
143             unsigned int buf_len,
144             const char* data,
145             unsigned int data_len);
146 static int
147 gdb_dec_bin(const char* buf,
148             unsigned int buf_len,
149             char* data,
150             unsigned int data_len);
151
152 /* Packet creation helpers */
153 static int
154 gdb_send_ok_packet(struct gdb_state* state, char* buf, unsigned int buf_len);
155 static int
156 gdb_send_conmsg_packet(struct gdb_state* state,
157                        char* buf,
158                        unsigned int buf_len,
159                        const char* msg);
160 static int
161 gdb_send_signal_packet(struct gdb_state* state,
162                        char* buf,
163                        unsigned int buf_len,
164                        char signal);
165 static int
166 gdb_send_error_packet(struct gdb_state* state,
167                       char* buf,
168                       unsigned int buf_len,
169                       char error);
170
171 /* Command functions */
172 static int
173 gdb_mem_read(struct gdb_state* state,
174              char* buf,
175              unsigned int buf_len,
176              ptr_t addr,
177              unsigned int len,
178              gdb_enc_func enc);
179 static int
180 gdb_mem_write(struct gdb_state* state,
181               const char* buf,
182               unsigned int buf_len,
183               ptr_t addr,
184               unsigned int len,
185               gdb_dec_func dec);
186 static int
187 gdb_continue(struct gdb_state* state);
188 static int
189 gdb_step(struct gdb_state* state);
190
191 /*****************************************************************************
192  * String Processing Helper Functions
193  ****************************************************************************/
194
195 /*
196  * Get integer value for a string representation.
197  *
198  * If the string starts with + or -, it will be signed accordingly.
199  *
200  * If base == 0, the base will be determined:
201  *   base 16 if the string starts with 0x or 0X,
202  *   base 10 otherwise
203  *
204  * If endptr is specified, it will point to the last non-digit in the
205  * string. If there are no digits in the string, it will be set to NULL.
206  */
207 static int
208 gdb_strtol(const char* str, unsigned int len, int base, const char** endptr)
209 {
210     unsigned int pos;
211     int sign, tmp, value, valid;
212
213     value = 0;
214     pos = 0;
215     sign = 1;
216     valid = 0;
217
218     if (endptr) {
219         *(endptr) = 0;
220     }
221
222     if (len < 1) {
223         return 0;
224     }
225
226     /* Detect negative numbers */
227     if (str[pos] == '-') {
228         sign = -1;
229         pos += 1;
230     } else if (str[pos] == '+') {
231         sign = 1;
232         pos += 1;
233     }
234
235     /* Detect '0x' hex prefix */
236     if ((pos + 2 < len) && (str[pos] == '0') &&
237         ((str[pos + 1] == 'x') || (str[pos + 1] == 'X'))) {
238         base = 16;
239         pos += 2;
240     }
241
242     if (base == 0) {
243         base = 10;
244     }
245
246     for (; (pos < len) && (str[pos] != '\x00'); pos++) {
247         tmp = gdb_get_val(str[pos], base);
248         if (tmp == GDB_EOF) {
249             break;
250         }
251
252         value = value * base + tmp;
253         valid = 1; /* At least one digit is valid */
254     }
255
256     if (!valid) {
257         return 0;
258     }
259
260     if (endptr) {
261         *endptr = str + pos;
262     }
263
264     value *= sign;
265
266     return value;
267 }
268
269 /*
270  * Get the corresponding ASCII hex digit character for a value.
271  */
272 static char
273 gdb_get_digit(int val)
274 {
275     if ((val >= 0) && (val <= 0xf)) {
276         return digits[val];
277     } else {
278         return GDB_EOF;
279     }
280 }
281
282 /*
283  * Get the corresponding value for a ASCII digit character.
284  *
285  * Supports bases 2-16.
286  */
287 static int
288 gdb_get_val(char digit, int base)
289 {
290     int value;
291
292     if ((digit >= '0') && (digit <= '9')) {
293         value = digit - '0';
294     } else if ((digit >= 'a') && (digit <= 'f')) {
295         value = digit - 'a' + 0xa;
296     } else if ((digit >= 'A') && (digit <= 'F')) {
297         value = digit - 'A' + 0xa;
298     } else {
299         return GDB_EOF;
300     }
301
302     return (value < base) ? value : GDB_EOF;
303 }
304
305 /*****************************************************************************
306  * Packet Functions
307  ****************************************************************************/
308
309 /*
310  * Receive a packet acknowledgment
311  *
312  * Returns:
313  *    0   if an ACK (+) was received
314  *    1   if a NACK (-) was received
315  *    GDB_EOF otherwise
316  */
317 static int
318 gdb_recv_ack(struct gdb_state* state)
319 {
320     int response;
321
322     /* Wait for packet ack */
323     switch (response = gdb_sys_getc(state)) {
324         case '+':
325             /* Packet acknowledged */
326             return 0;
327         case '-':
328             /* Packet negative acknowledged */
329             return 1;
330         default:
331             /* Bad response! */
332             GDB_PRINT("received bad packet response: 0x%2x\n", response);
333             return GDB_EOF;
334     }
335 }
336
337 /*
338  * Calculate 8-bit checksum of a buffer.
339  *
340  * Returns:
341  *    8-bit checksum.
342  */
343 static int
344 gdb_checksum(const char* buf, unsigned int len)
345 {
346     unsigned char csum;
347
348     csum = 0;
349
350     while (len--) {
351         csum += *buf++;
352     }
353
354     return csum;
355 }
356
357 /*
358  * Transmits a packet of data.
359  * Packets are of the form: $<packet-data>#<checksum>
360  *
361  * Returns:
362  *    0   if the packet was transmitted and acknowledged
363  *    1   if the packet was transmitted but not acknowledged
364  *    GDB_EOF otherwise
365  */
366 static int
367 gdb_send_packet(struct gdb_state* state,
368                 const char* pkt_data,
369                 unsigned int pkt_len)
370 {
371     char buf[3];
372     char csum;
373
374     /* Send packet start */
375     if (gdb_sys_putchar(state, '$') == GDB_EOF) {
376         return GDB_EOF;
377     }
378
379     /* Send packet data */
380     if (gdb_write(state, pkt_data, pkt_len) == GDB_EOF) {
381         return GDB_EOF;
382     }
383
384     /* Send the checksum */
385     buf[0] = '#';
386     csum = gdb_checksum(pkt_data, pkt_len);
387     if ((gdb_enc_hex(buf + 1, sizeof(buf) - 1, &csum, 1) == GDB_EOF) ||
388         (gdb_write(state, buf, sizeof(buf)) == GDB_EOF)) {
389         return GDB_EOF;
390     }
391
392     return gdb_recv_ack(state);
393 }
394
395 /*
396  * Receives a packet of data, assuming a 7-bit clean connection.
397  *
398  * Returns:
399  *    0   if the packet was received
400  *    GDB_EOF otherwise
401  */
402 static int
403 gdb_recv_packet(struct gdb_state* state,
404                 char* pkt_buf,
405                 unsigned int pkt_buf_len,
406                 unsigned int* pkt_len)
407 {
408     int data;
409     char expected_csum, actual_csum;
410     char buf[2];
411
412     /* Wait for packet start */
413     actual_csum = 0;
414
415     while (1) {
416         data = gdb_sys_getc(state);
417         if (data == GDB_EOF) {
418             return GDB_EOF;
419         } else if (data == '$') {
420             /* Detected start of packet. */
421             break;
422         }
423     }
424
425     /* Read until checksum */
426     *pkt_len = 0;
427     while (1) {
428         data = gdb_sys_getc(state);
429
430         if (data == GDB_EOF) {
431             /* Error receiving character */
432             return GDB_EOF;
433         } else if (data == '#') {
434             /* End of packet */
435             break;
436         } else {
437             /* Check for space */
438             if (*pkt_len >= pkt_buf_len) {
439                 GDB_PRINT("packet buffer overflow\n");
440                 return GDB_EOF;
441             }
442
443             /* Store character and update checksum */
444             pkt_buf[(*pkt_len)++] = (char)data;
445         }
446     }
447
448     /* Receive the checksum */
449     if ((gdb_read(state, buf, sizeof(buf), 2) == GDB_EOF) ||
450         (gdb_dec_hex(buf, 2, &expected_csum, 1) == GDB_EOF)) {
451         return GDB_EOF;
452     }
453
454     /* Verify checksum */
455     actual_csum = gdb_checksum(pkt_buf, *pkt_len);
456     if (actual_csum != expected_csum) {
457         /* Send packet nack */
458         GDB_PRINT("received packet with bad checksum\n");
459         gdb_sys_putchar(state, '-');
460         return GDB_EOF;
461     }
462
463     /* Send packet ack */
464     gdb_sys_putchar(state, '+');
465     return 0;
466 }
467
468 /*****************************************************************************
469  * Data Encoding/Decoding
470  ****************************************************************************/
471
472 /*
473  * Encode data to its hex-value representation in a buffer.
474  *
475  * Returns:
476  *    0+  number of bytes written to buf
477  *    GDB_EOF if the buffer is too small
478  */
479 static int
480 gdb_enc_hex(char* buf,
481             unsigned int buf_len,
482             const char* data,
483             unsigned int data_len)
484 {
485     unsigned int pos;
486
487     if (buf_len < data_len * 2) {
488         /* Buffer too small */
489         return GDB_EOF;
490     }
491
492     for (pos = 0; pos < data_len; pos++) {
493         *buf++ = gdb_get_digit((data[pos] >> 4) & 0xf);
494         *buf++ = gdb_get_digit((data[pos]) & 0xf);
495     }
496
497     return data_len * 2;
498 }
499
500 /*
501  * Decode data from its hex-value representation to a buffer.
502  *
503  * Returns:
504  *    0   if successful
505  *    GDB_EOF if the buffer is too small
506  */
507 static int
508 gdb_dec_hex(const char* buf,
509             unsigned int buf_len,
510             char* data,
511             unsigned int data_len)
512 {
513     unsigned int pos;
514     int tmp;
515
516     if (buf_len != data_len * 2) {
517         /* Buffer too small */
518         return GDB_EOF;
519     }
520
521     for (pos = 0; pos < data_len; pos++) {
522         /* Decode high nibble */
523         tmp = gdb_get_val(*buf++, 16);
524         if (tmp == GDB_EOF) {
525             /* Buffer contained junk. */
526             GDB_ASSERT(0);
527             return GDB_EOF;
528         }
529
530         data[pos] = tmp << 4;
531
532         /* Decode low nibble */
533         tmp = gdb_get_val(*buf++, 16);
534         if (tmp == GDB_EOF) {
535             /* Buffer contained junk. */
536             GDB_ASSERT(0);
537             return GDB_EOF;
538         }
539         data[pos] |= tmp;
540     }
541
542     return 0;
543 }
544
545 /*
546  * Encode data to its binary representation in a buffer.
547  *
548  * Returns:
549  *    0+  number of bytes written to buf
550  *    GDB_EOF if the buffer is too small
551  */
552 static int
553 gdb_enc_bin(char* buf,
554             unsigned int buf_len,
555             const char* data,
556             unsigned int data_len)
557 {
558     unsigned int buf_pos, data_pos;
559
560     for (buf_pos = 0, data_pos = 0; data_pos < data_len; data_pos++) {
561         if (data[data_pos] == '$' || data[data_pos] == '#' ||
562             data[data_pos] == '}' || data[data_pos] == '*') {
563             if (buf_pos + 1 >= buf_len) {
564                 GDB_ASSERT(0);
565                 return GDB_EOF;
566             }
567             buf[buf_pos++] = '}';
568             buf[buf_pos++] = data[data_pos] ^ 0x20;
569         } else {
570             if (buf_pos >= buf_len) {
571                 GDB_ASSERT(0);
572                 return GDB_EOF;
573             }
574             buf[buf_pos++] = data[data_pos];
575         }
576     }
577
578     return buf_pos;
579 }
580
581 /*
582  * Decode data from its bin-value representation to a buffer.
583  *
584  * Returns:
585  *    0+  if successful, number of bytes decoded
586  *    GDB_EOF if the buffer is too small
587  */
588 static int
589 gdb_dec_bin(const char* buf,
590             unsigned int buf_len,
591             char* data,
592             unsigned int data_len)
593 {
594     unsigned int buf_pos, data_pos;
595
596     for (buf_pos = 0, data_pos = 0; buf_pos < buf_len; buf_pos++) {
597         if (data_pos >= data_len) {
598             /* Output buffer overflow */
599             GDB_ASSERT(0);
600             return GDB_EOF;
601         }
602         if (buf[buf_pos] == '}') {
603             /* The next byte is escaped! */
604             if (buf_pos + 1 >= buf_len) {
605                 /* There's an escape character, but no escaped character
606                  * following the escape character. */
607                 GDB_ASSERT(0);
608                 return GDB_EOF;
609             }
610             buf_pos += 1;
611             data[data_pos++] = buf[buf_pos] ^ 0x20;
612         } else {
613             data[data_pos++] = buf[buf_pos];
614         }
615     }
616
617     return data_pos;
618 }
619
620 /*****************************************************************************
621  * Command Functions
622  ****************************************************************************/
623
624 /*
625  * Read from memory and encode into buf.
626  *
627  * Returns:
628  *    0+  number of bytes written to buf
629  *    GDB_EOF if the buffer is too small
630  */
631 static int
632 gdb_mem_read(struct gdb_state* state,
633              char* buf,
634              unsigned int buf_len,
635              ptr_t addr,
636              unsigned int len,
637              gdb_enc_func enc)
638 {
639     char data[64];
640     unsigned int pos;
641
642     if (len > sizeof(data)) {
643         return GDB_EOF;
644     }
645
646     /* Read from system memory */
647     for (pos = 0; pos < len; pos++) {
648         if (gdb_sys_mem_readb(state, addr + pos, &data[pos])) {
649             /* Failed to read */
650             return GDB_EOF;
651         }
652     }
653
654     /* Encode data */
655     return enc(buf, buf_len, data, len);
656 }
657
658 /*
659  * Write to memory from encoded buf.
660  */
661 static int
662 gdb_mem_write(struct gdb_state* state,
663               const char* buf,
664               unsigned int buf_len,
665               ptr_t addr,
666               unsigned int len,
667               gdb_dec_func dec)
668 {
669     char data[64];
670     unsigned int pos;
671
672     if (len > sizeof(data)) {
673         return GDB_EOF;
674     }
675
676     /* Decode data */
677     if (dec(buf, buf_len, data, len) == GDB_EOF) {
678         return GDB_EOF;
679     }
680
681     /* Write to system memory */
682     for (pos = 0; pos < len; pos++) {
683         if (gdb_sys_mem_writeb(state, addr + pos, data[pos])) {
684             /* Failed to write */
685             return GDB_EOF;
686         }
687     }
688
689     return 0;
690 }
691
692 /*
693  * Continue program execution at PC.
694  */
695 int
696 gdb_continue(struct gdb_state* state)
697 {
698     gdb_sys_continue(state);
699     return 0;
700 }
701
702 /*
703  * Step one instruction.
704  */
705 int
706 gdb_step(struct gdb_state* state)
707 {
708     gdb_sys_step(state);
709     return 0;
710 }
711
712 /*****************************************************************************
713  * Packet Creation Helpers
714  ****************************************************************************/
715
716 /*
717  * Send OK packet
718  */
719 static int
720 gdb_send_ok_packet(struct gdb_state* state, char* buf, unsigned int buf_len)
721 {
722     return gdb_send_packet(state, "OK", 2);
723 }
724
725 /*
726  * Send a message to the debugging console (via O XX... packet)
727  */
728 static int
729 gdb_send_conmsg_packet(struct gdb_state* state,
730                        char* buf,
731                        unsigned int buf_len,
732                        const char* msg)
733 {
734     unsigned int size;
735     int status;
736
737     if (buf_len < 2) {
738         /* Buffer too small */
739         return GDB_EOF;
740     }
741
742     buf[0] = 'O';
743     status = gdb_enc_hex(&buf[1], buf_len - 1, msg, strlen(msg));
744     if (status == GDB_EOF) {
745         return GDB_EOF;
746     }
747     size = 1 + status;
748     return gdb_send_packet(state, buf, size);
749 }
750
751 /*
752  * Send a signal packet (S AA).
753  */
754 static int
755 gdb_send_signal_packet(struct gdb_state* state,
756                        char* buf,
757                        unsigned int buf_len,
758                        char signal)
759 {
760     unsigned int size;
761     int status;
762
763     if (buf_len < 4) {
764         /* Buffer too small */
765         return GDB_EOF;
766     }
767
768     buf[0] = 'S';
769     status = gdb_enc_hex(&buf[1], buf_len - 1, &signal, 1);
770     if (status == GDB_EOF) {
771         return GDB_EOF;
772     }
773     size = 1 + status;
774     return gdb_send_packet(state, buf, size);
775 }
776
777 /*
778  * Send a error packet (E AA).
779  */
780 static int
781 gdb_send_error_packet(struct gdb_state* state,
782                       char* buf,
783                       unsigned int buf_len,
784                       char error)
785 {
786     unsigned int size;
787     int status;
788
789     if (buf_len < 4) {
790         /* Buffer too small */
791         return GDB_EOF;
792     }
793
794     buf[0] = 'E';
795     status = gdb_enc_hex(&buf[1], buf_len - 1, &error, 1);
796     if (status == GDB_EOF) {
797         return GDB_EOF;
798     }
799     size = 1 + status;
800     return gdb_send_packet(state, buf, size);
801 }
802
803 /*****************************************************************************
804  * Communication Functions
805  ****************************************************************************/
806
807 /*
808  * Write a sequence of bytes.
809  *
810  * Returns:
811  *    0   if successful
812  *    GDB_EOF if failed to write all bytes
813  */
814 static int
815 gdb_write(struct gdb_state* state, const char* buf, unsigned int len)
816 {
817     int err = serial_rwbuf_sync(state->sdev, buf, len, SERIAL_RW_TX);
818
819     return err < 0 ? GDB_EOF : 0;
820 }
821
822 /*
823  * Read a sequence of bytes.
824  *
825  * Returns:
826  *    0   if successfully read len bytes
827  *    GDB_EOF if failed to read all bytes
828  */
829 static int
830 gdb_read(struct gdb_state* state,
831          char* buf,
832          unsigned int buf_len,
833          unsigned int len)
834 {
835     char c;
836
837     if (buf_len < len) {
838         /* Buffer too small */
839         return GDB_EOF;
840     }
841
842     int err = serial_rwbuf_sync(state->sdev, buf, buf_len, SERIAL_RW_RX);
843
844     return err < 0 ? GDB_EOF : 0;
845 }
846
847 /*****************************************************************************
848  * Main Loop
849  ****************************************************************************/
850
851 /*
852  * Main debug loop. Handles commands.
853  */
854 int
855 gdb_main(struct gdb_state* state)
856 {
857     ptr_t addr;
858     char pkt_buf[256];
859     int status;
860     unsigned int length;
861     unsigned int pkt_len;
862     const char* ptr_next;
863
864     gdb_send_signal_packet(state, pkt_buf, sizeof(pkt_buf), state->signum);
865
866     while (1) {
867         /* Receive the next packet */
868         status = gdb_recv_packet(state, pkt_buf, sizeof(pkt_buf), &pkt_len);
869         if (status == GDB_EOF) {
870             break;
871         }
872
873         if (pkt_len == 0) {
874             /* Received empty packet.. */
875             continue;
876         }
877
878         ptr_next = pkt_buf;
879
880         /*
881          * Handle one letter commands
882          */
883         switch (pkt_buf[0]) {
884
885 /* Calculate remaining space in packet from ptr_next position. */
886 #define token_remaining_buf (pkt_len - (ptr_next - pkt_buf))
887
888 /* Expecting a seperator. If not present, go to error */
889 #define token_expect_seperator(c)                                              \
890     {                                                                          \
891         if (!ptr_next || *ptr_next != c) {                                     \
892             goto error;                                                        \
893         } else {                                                               \
894             ptr_next += 1;                                                     \
895         }                                                                      \
896     }
897
898 /* Expecting an integer argument. If not present, go to error */
899 #define token_expect_integer_arg(arg)                                          \
900     {                                                                          \
901         arg = gdb_strtol(ptr_next, token_remaining_buf, 16, &ptr_next);        \
902         if (!ptr_next) {                                                       \
903             goto error;                                                        \
904         }                                                                      \
905     }
906
907             /*
908              * Read Registers
909              * Command Format: g
910              */
911             case 'g':
912                 /* Encode registers */
913                 status = gdb_enc_hex(pkt_buf,
914                                      sizeof(pkt_buf),
915                                      (char*)&(state->registers),
916                                      sizeof(state->registers));
917                 if (status == GDB_EOF) {
918                     goto error;
919                 }
920                 pkt_len = status;
921                 gdb_send_packet(state, pkt_buf, pkt_len);
922                 break;
923
924             /*
925              * Write Registers
926              * Command Format: G XX...
927              */
928             case 'G':
929                 status = gdb_dec_hex(pkt_buf + 1,
930                                      pkt_len - 1,
931                                      (char*)&(state->registers),
932                                      sizeof(state->registers));
933                 if (status == GDB_EOF) {
934                     goto error;
935                 }
936                 gdb_send_ok_packet(state, pkt_buf, sizeof(pkt_buf));
937                 break;
938
939             /*
940              * Read a Register
941              * Command Format: p n
942              */
943             case 'p':
944                 ptr_next += 1;
945                 token_expect_integer_arg(addr);
946
947                 if (addr >= GDB_CPU_NUM_REGISTERS) {
948                     goto error;
949                 }
950
951                 /* Read Register */
952                 status = gdb_enc_hex(pkt_buf,
953                                      sizeof(pkt_buf),
954                                      (char*)&(state->registers[addr]),
955                                      sizeof(state->registers[addr]));
956                 if (status == GDB_EOF) {
957                     goto error;
958                 }
959                 gdb_send_packet(state, pkt_buf, status);
960                 break;
961
962             /*
963              * Write a Register
964              * Command Format: P n...=r...
965              */
966             case 'P':
967                 ptr_next += 1;
968                 token_expect_integer_arg(addr);
969                 token_expect_seperator('=');
970
971                 if (addr < GDB_CPU_NUM_REGISTERS) {
972                     status = gdb_dec_hex(ptr_next,
973                                          token_remaining_buf,
974                                          (char*)&(state->registers[addr]),
975                                          sizeof(state->registers[addr]));
976                     if (status == GDB_EOF) {
977                         goto error;
978                     }
979                 }
980                 gdb_send_ok_packet(state, pkt_buf, sizeof(pkt_buf));
981                 break;
982
983             /*
984              * Read Memory
985              * Command Format: m addr,length
986              */
987             case 'm':
988                 ptr_next += 1;
989                 token_expect_integer_arg(addr);
990                 token_expect_seperator(',');
991                 token_expect_integer_arg(length);
992
993                 /* Read Memory */
994                 status = gdb_mem_read(
995                   state, pkt_buf, sizeof(pkt_buf), addr, length, gdb_enc_hex);
996                 if (status == GDB_EOF) {
997                     goto error;
998                 }
999                 gdb_send_packet(state, pkt_buf, status);
1000                 break;
1001
1002             /*
1003              * Write Memory
1004              * Command Format: M addr,length:XX..
1005              */
1006             case 'M':
1007                 ptr_next += 1;
1008                 token_expect_integer_arg(addr);
1009                 token_expect_seperator(',');
1010                 token_expect_integer_arg(length);
1011                 token_expect_seperator(':');
1012
1013                 /* Write Memory */
1014                 status = gdb_mem_write(state,
1015                                        ptr_next,
1016                                        token_remaining_buf,
1017                                        addr,
1018                                        length,
1019                                        gdb_dec_hex);
1020                 if (status == GDB_EOF) {
1021                     goto error;
1022                 }
1023                 gdb_send_ok_packet(state, pkt_buf, sizeof(pkt_buf));
1024                 break;
1025
1026             /*
1027              * Write Memory (Binary)
1028              * Command Format: X addr,length:XX..
1029              */
1030             case 'X':
1031                 ptr_next += 1;
1032                 token_expect_integer_arg(addr);
1033                 token_expect_seperator(',');
1034                 token_expect_integer_arg(length);
1035                 token_expect_seperator(':');
1036
1037                 /* Write Memory */
1038                 status = gdb_mem_write(state,
1039                                        ptr_next,
1040                                        token_remaining_buf,
1041                                        addr,
1042                                        length,
1043                                        gdb_dec_bin);
1044                 if (status == GDB_EOF) {
1045                     goto error;
1046                 }
1047                 gdb_send_ok_packet(state, pkt_buf, sizeof(pkt_buf));
1048                 break;
1049
1050             /*
1051              * Continue, Kill (also treated as continue!)
1052              * Command Format: c [addr]
1053              */
1054             case 'c':
1055             case 'C':
1056             case 'k':
1057                 gdb_continue(state);
1058                 return 0;
1059
1060             /*
1061              * Single-step
1062              * Command Format: s [addr]
1063              */
1064             case 's':
1065             case 'S':
1066                 gdb_step(state);
1067                 return 0;
1068
1069             case '?':
1070                 gdb_send_signal_packet(
1071                   state, pkt_buf, sizeof(pkt_buf), state->signum);
1072                 break;
1073
1074             /*
1075              * Unsupported Command
1076              */
1077             default:
1078                 gdb_send_packet(state, 0, 0);
1079         }
1080
1081         continue;
1082
1083     error:
1084         gdb_send_error_packet(state, pkt_buf, sizeof(pkt_buf), 0x00);
1085
1086 #undef token_remaining_buf
1087 #undef token_expect_seperator
1088 #undef token_expect_integer_arg
1089     }
1090
1091     return 0;
1092 }
1093
1094
1095 static struct gdb_state gdb_state;
1096 static volatile int start_debugging = 0;
1097
1098 /*
1099  * Debug interrupt handler.
1100  */
1101 void
1102 gdbstub_loop(struct hart_state* hstate)
1103 {
1104     arch_gdbstub_setup_state(&gdb_state, hstate);
1105     arch_gdbstub_save_regs(&gdb_state, hstate);
1106     
1107     gdb_main(&gdb_state);
1108
1109     arch_gdbstub_restore_regs(&gdb_state, hstate);
1110 }
1111
1112 /*****************************************************************************
1113  * Debugging System Functions
1114  ****************************************************************************/
1115
1116 /*
1117  * Write one character to the debugging stream.
1118  */
1119 int
1120 gdb_sys_putchar(struct gdb_state* state, int ch)
1121 {
1122     serial_rwbuf_sync(state->sdev, &ch, 1, SERIAL_RW_TX);
1123     return ch;
1124 }
1125
1126 /*
1127  * Read one character from the debugging stream.
1128  */
1129 int
1130 gdb_sys_getc(struct gdb_state* state)
1131 {
1132     char ch;
1133     serial_rwbuf_sync(state->sdev, &ch, 1, SERIAL_RW_RX);
1134     return ch & 0xff;
1135 }
1136
1137 /*
1138  * Read one byte from memory.
1139  */
1140 int
1141 gdb_sys_mem_readb(struct gdb_state* state, ptr_t addr, char* val)
1142 {
1143     *val = *(volatile char*)addr;
1144     return 0;
1145 }
1146
1147 /*
1148  * Write one byte to memory.
1149  */
1150 int
1151 gdb_sys_mem_writeb(struct gdb_state* state, ptr_t addr, char val)
1152 {
1153     *(volatile char*)addr = val;
1154     return 0;
1155 }