4 * @brief GDB Stub implementation (https://github.com/mborgerson/gdbstub).
9 * @copyright Copyright (c) 2022 Lunaixsky & (See license below)
14 * Copyright (c) 2016-2022 Matt Borgerson
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:
23 * The above copyright notice and this permission notice shall be included in
24 * all copies or substantial portions of the Software.
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
35 #include <hal/serial.h>
36 #include <klibc/string.h>
37 #include <sdbg/gdbstub.h>
39 #include <sys/port_io.h>
41 #include <sys/gdbstub.h>
43 /*****************************************************************************
45 ****************************************************************************/
47 #define GDB_PRINT(...)
52 #define GDB_ASSERT(x) \
57 /*****************************************************************************
59 ****************************************************************************/
62 gdb_main(struct gdb_state* state);
64 /* System functions, supported by all stubs */
68 gdb_sys_getc(struct gdb_state* state);
70 gdb_sys_putchar(struct gdb_state* state, int ch);
72 gdb_sys_mem_readb(struct gdb_state* state, ptr_t addr, char* val);
74 gdb_sys_mem_writeb(struct gdb_state* state, ptr_t addr, char val);
77 /*****************************************************************************
79 ****************************************************************************/
81 typedef int (*gdb_enc_func)(char* buf,
84 unsigned int data_len);
85 typedef int (*gdb_dec_func)(const char* buf,
88 unsigned int data_len);
90 /*****************************************************************************
92 ****************************************************************************/
94 static const char digits[] = "0123456789abcdef";
96 /*****************************************************************************
98 ****************************************************************************/
100 /* Communication functions */
102 gdb_write(struct gdb_state* state, const char* buf, unsigned int len);
104 gdb_read(struct gdb_state* state,
106 unsigned int buf_len,
111 gdb_get_digit(int val);
113 gdb_get_val(char digit, int base);
115 gdb_strtol(const char* str, unsigned int len, int base, const char** endptr);
117 /* Packet functions */
119 gdb_send_packet(struct gdb_state* state, const char* pkt, unsigned int pkt_len);
121 gdb_recv_packet(struct gdb_state* state,
123 unsigned int pkt_buf_len,
124 unsigned int* pkt_len);
126 gdb_checksum(const char* buf, unsigned int len);
128 gdb_recv_ack(struct gdb_state* state);
130 /* Data encoding/decoding */
132 gdb_enc_hex(char* buf,
133 unsigned int buf_len,
135 unsigned int data_len);
137 gdb_dec_hex(const char* buf,
138 unsigned int buf_len,
140 unsigned int data_len);
142 gdb_enc_bin(char* buf,
143 unsigned int buf_len,
145 unsigned int data_len);
147 gdb_dec_bin(const char* buf,
148 unsigned int buf_len,
150 unsigned int data_len);
152 /* Packet creation helpers */
154 gdb_send_ok_packet(struct gdb_state* state, char* buf, unsigned int buf_len);
156 gdb_send_conmsg_packet(struct gdb_state* state,
158 unsigned int buf_len,
161 gdb_send_signal_packet(struct gdb_state* state,
163 unsigned int buf_len,
166 gdb_send_error_packet(struct gdb_state* state,
168 unsigned int buf_len,
171 /* Command functions */
173 gdb_mem_read(struct gdb_state* state,
175 unsigned int buf_len,
180 gdb_mem_write(struct gdb_state* state,
182 unsigned int buf_len,
187 gdb_continue(struct gdb_state* state);
189 gdb_step(struct gdb_state* state);
191 /*****************************************************************************
192 * String Processing Helper Functions
193 ****************************************************************************/
196 * Get integer value for a string representation.
198 * If the string starts with + or -, it will be signed accordingly.
200 * If base == 0, the base will be determined:
201 * base 16 if the string starts with 0x or 0X,
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.
208 gdb_strtol(const char* str, unsigned int len, int base, const char** endptr)
211 int sign, tmp, value, valid;
226 /* Detect negative numbers */
227 if (str[pos] == '-') {
230 } else if (str[pos] == '+') {
235 /* Detect '0x' hex prefix */
236 if ((pos + 2 < len) && (str[pos] == '0') &&
237 ((str[pos + 1] == 'x') || (str[pos + 1] == 'X'))) {
246 for (; (pos < len) && (str[pos] != '\x00'); pos++) {
247 tmp = gdb_get_val(str[pos], base);
248 if (tmp == GDB_EOF) {
252 value = value * base + tmp;
253 valid = 1; /* At least one digit is valid */
270 * Get the corresponding ASCII hex digit character for a value.
273 gdb_get_digit(int val)
275 if ((val >= 0) && (val <= 0xf)) {
283 * Get the corresponding value for a ASCII digit character.
285 * Supports bases 2-16.
288 gdb_get_val(char digit, int base)
292 if ((digit >= '0') && (digit <= '9')) {
294 } else if ((digit >= 'a') && (digit <= 'f')) {
295 value = digit - 'a' + 0xa;
296 } else if ((digit >= 'A') && (digit <= 'F')) {
297 value = digit - 'A' + 0xa;
302 return (value < base) ? value : GDB_EOF;
305 /*****************************************************************************
307 ****************************************************************************/
310 * Receive a packet acknowledgment
313 * 0 if an ACK (+) was received
314 * 1 if a NACK (-) was received
318 gdb_recv_ack(struct gdb_state* state)
322 /* Wait for packet ack */
323 switch (response = gdb_sys_getc(state)) {
325 /* Packet acknowledged */
328 /* Packet negative acknowledged */
332 GDB_PRINT("received bad packet response: 0x%2x\n", response);
338 * Calculate 8-bit checksum of a buffer.
344 gdb_checksum(const char* buf, unsigned int len)
358 * Transmits a packet of data.
359 * Packets are of the form: $<packet-data>#<checksum>
362 * 0 if the packet was transmitted and acknowledged
363 * 1 if the packet was transmitted but not acknowledged
367 gdb_send_packet(struct gdb_state* state,
368 const char* pkt_data,
369 unsigned int pkt_len)
374 /* Send packet start */
375 if (gdb_sys_putchar(state, '$') == GDB_EOF) {
379 /* Send packet data */
380 if (gdb_write(state, pkt_data, pkt_len) == GDB_EOF) {
384 /* Send the checksum */
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)) {
392 return gdb_recv_ack(state);
396 * Receives a packet of data, assuming a 7-bit clean connection.
399 * 0 if the packet was received
403 gdb_recv_packet(struct gdb_state* state,
405 unsigned int pkt_buf_len,
406 unsigned int* pkt_len)
409 char expected_csum, actual_csum;
412 /* Wait for packet start */
416 data = gdb_sys_getc(state);
417 if (data == GDB_EOF) {
419 } else if (data == '$') {
420 /* Detected start of packet. */
425 /* Read until checksum */
428 data = gdb_sys_getc(state);
430 if (data == GDB_EOF) {
431 /* Error receiving character */
433 } else if (data == '#') {
437 /* Check for space */
438 if (*pkt_len >= pkt_buf_len) {
439 GDB_PRINT("packet buffer overflow\n");
443 /* Store character and update checksum */
444 pkt_buf[(*pkt_len)++] = (char)data;
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)) {
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, '-');
463 /* Send packet ack */
464 gdb_sys_putchar(state, '+');
468 /*****************************************************************************
469 * Data Encoding/Decoding
470 ****************************************************************************/
473 * Encode data to its hex-value representation in a buffer.
476 * 0+ number of bytes written to buf
477 * GDB_EOF if the buffer is too small
480 gdb_enc_hex(char* buf,
481 unsigned int buf_len,
483 unsigned int data_len)
487 if (buf_len < data_len * 2) {
488 /* Buffer too small */
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);
501 * Decode data from its hex-value representation to a buffer.
505 * GDB_EOF if the buffer is too small
508 gdb_dec_hex(const char* buf,
509 unsigned int buf_len,
511 unsigned int data_len)
516 if (buf_len != data_len * 2) {
517 /* Buffer too small */
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. */
530 data[pos] = tmp << 4;
532 /* Decode low nibble */
533 tmp = gdb_get_val(*buf++, 16);
534 if (tmp == GDB_EOF) {
535 /* Buffer contained junk. */
546 * Encode data to its binary representation in a buffer.
549 * 0+ number of bytes written to buf
550 * GDB_EOF if the buffer is too small
553 gdb_enc_bin(char* buf,
554 unsigned int buf_len,
556 unsigned int data_len)
558 unsigned int buf_pos, data_pos;
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) {
567 buf[buf_pos++] = '}';
568 buf[buf_pos++] = data[data_pos] ^ 0x20;
570 if (buf_pos >= buf_len) {
574 buf[buf_pos++] = data[data_pos];
582 * Decode data from its bin-value representation to a buffer.
585 * 0+ if successful, number of bytes decoded
586 * GDB_EOF if the buffer is too small
589 gdb_dec_bin(const char* buf,
590 unsigned int buf_len,
592 unsigned int data_len)
594 unsigned int buf_pos, data_pos;
596 for (buf_pos = 0, data_pos = 0; buf_pos < buf_len; buf_pos++) {
597 if (data_pos >= data_len) {
598 /* Output buffer overflow */
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. */
611 data[data_pos++] = buf[buf_pos] ^ 0x20;
613 data[data_pos++] = buf[buf_pos];
620 /*****************************************************************************
622 ****************************************************************************/
625 * Read from memory and encode into buf.
628 * 0+ number of bytes written to buf
629 * GDB_EOF if the buffer is too small
632 gdb_mem_read(struct gdb_state* state,
634 unsigned int buf_len,
642 if (len > sizeof(data)) {
646 /* Read from system memory */
647 for (pos = 0; pos < len; pos++) {
648 if (gdb_sys_mem_readb(state, addr + pos, &data[pos])) {
655 return enc(buf, buf_len, data, len);
659 * Write to memory from encoded buf.
662 gdb_mem_write(struct gdb_state* state,
664 unsigned int buf_len,
672 if (len > sizeof(data)) {
677 if (dec(buf, buf_len, data, len) == GDB_EOF) {
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 */
693 * Continue program execution at PC.
696 gdb_continue(struct gdb_state* state)
698 gdb_sys_continue(state);
703 * Step one instruction.
706 gdb_step(struct gdb_state* state)
712 /*****************************************************************************
713 * Packet Creation Helpers
714 ****************************************************************************/
720 gdb_send_ok_packet(struct gdb_state* state, char* buf, unsigned int buf_len)
722 return gdb_send_packet(state, "OK", 2);
726 * Send a message to the debugging console (via O XX... packet)
729 gdb_send_conmsg_packet(struct gdb_state* state,
731 unsigned int buf_len,
738 /* Buffer too small */
743 status = gdb_enc_hex(&buf[1], buf_len - 1, msg, strlen(msg));
744 if (status == GDB_EOF) {
748 return gdb_send_packet(state, buf, size);
752 * Send a signal packet (S AA).
755 gdb_send_signal_packet(struct gdb_state* state,
757 unsigned int buf_len,
764 /* Buffer too small */
769 status = gdb_enc_hex(&buf[1], buf_len - 1, &signal, 1);
770 if (status == GDB_EOF) {
774 return gdb_send_packet(state, buf, size);
778 * Send a error packet (E AA).
781 gdb_send_error_packet(struct gdb_state* state,
783 unsigned int buf_len,
790 /* Buffer too small */
795 status = gdb_enc_hex(&buf[1], buf_len - 1, &error, 1);
796 if (status == GDB_EOF) {
800 return gdb_send_packet(state, buf, size);
803 /*****************************************************************************
804 * Communication Functions
805 ****************************************************************************/
808 * Write a sequence of bytes.
812 * GDB_EOF if failed to write all bytes
815 gdb_write(struct gdb_state* state, const char* buf, unsigned int len)
817 int err = serial_rwbuf_sync(state->sdev, buf, len, SERIAL_RW_TX);
819 return err < 0 ? GDB_EOF : 0;
823 * Read a sequence of bytes.
826 * 0 if successfully read len bytes
827 * GDB_EOF if failed to read all bytes
830 gdb_read(struct gdb_state* state,
832 unsigned int buf_len,
838 /* Buffer too small */
842 int err = serial_rwbuf_sync(state->sdev, buf, buf_len, SERIAL_RW_RX);
844 return err < 0 ? GDB_EOF : 0;
847 /*****************************************************************************
849 ****************************************************************************/
852 * Main debug loop. Handles commands.
855 gdb_main(struct gdb_state* state)
861 unsigned int pkt_len;
862 const char* ptr_next;
864 gdb_send_signal_packet(state, pkt_buf, sizeof(pkt_buf), state->signum);
867 /* Receive the next packet */
868 status = gdb_recv_packet(state, pkt_buf, sizeof(pkt_buf), &pkt_len);
869 if (status == GDB_EOF) {
874 /* Received empty packet.. */
881 * Handle one letter commands
883 switch (pkt_buf[0]) {
885 /* Calculate remaining space in packet from ptr_next position. */
886 #define token_remaining_buf (pkt_len - (ptr_next - pkt_buf))
888 /* Expecting a seperator. If not present, go to error */
889 #define token_expect_seperator(c) \
891 if (!ptr_next || *ptr_next != c) { \
898 /* Expecting an integer argument. If not present, go to error */
899 #define token_expect_integer_arg(arg) \
901 arg = gdb_strtol(ptr_next, token_remaining_buf, 16, &ptr_next); \
912 /* Encode registers */
913 status = gdb_enc_hex(pkt_buf,
915 (char*)&(state->registers),
916 sizeof(state->registers));
917 if (status == GDB_EOF) {
921 gdb_send_packet(state, pkt_buf, pkt_len);
926 * Command Format: G XX...
929 status = gdb_dec_hex(pkt_buf + 1,
931 (char*)&(state->registers),
932 sizeof(state->registers));
933 if (status == GDB_EOF) {
936 gdb_send_ok_packet(state, pkt_buf, sizeof(pkt_buf));
941 * Command Format: p n
945 token_expect_integer_arg(addr);
947 if (addr >= GDB_CPU_NUM_REGISTERS) {
952 status = gdb_enc_hex(pkt_buf,
954 (char*)&(state->registers[addr]),
955 sizeof(state->registers[addr]));
956 if (status == GDB_EOF) {
959 gdb_send_packet(state, pkt_buf, status);
964 * Command Format: P n...=r...
968 token_expect_integer_arg(addr);
969 token_expect_seperator('=');
971 if (addr < GDB_CPU_NUM_REGISTERS) {
972 status = gdb_dec_hex(ptr_next,
974 (char*)&(state->registers[addr]),
975 sizeof(state->registers[addr]));
976 if (status == GDB_EOF) {
980 gdb_send_ok_packet(state, pkt_buf, sizeof(pkt_buf));
985 * Command Format: m addr,length
989 token_expect_integer_arg(addr);
990 token_expect_seperator(',');
991 token_expect_integer_arg(length);
994 status = gdb_mem_read(
995 state, pkt_buf, sizeof(pkt_buf), addr, length, gdb_enc_hex);
996 if (status == GDB_EOF) {
999 gdb_send_packet(state, pkt_buf, status);
1004 * Command Format: M addr,length:XX..
1008 token_expect_integer_arg(addr);
1009 token_expect_seperator(',');
1010 token_expect_integer_arg(length);
1011 token_expect_seperator(':');
1014 status = gdb_mem_write(state,
1016 token_remaining_buf,
1020 if (status == GDB_EOF) {
1023 gdb_send_ok_packet(state, pkt_buf, sizeof(pkt_buf));
1027 * Write Memory (Binary)
1028 * Command Format: X addr,length:XX..
1032 token_expect_integer_arg(addr);
1033 token_expect_seperator(',');
1034 token_expect_integer_arg(length);
1035 token_expect_seperator(':');
1038 status = gdb_mem_write(state,
1040 token_remaining_buf,
1044 if (status == GDB_EOF) {
1047 gdb_send_ok_packet(state, pkt_buf, sizeof(pkt_buf));
1051 * Continue, Kill (also treated as continue!)
1052 * Command Format: c [addr]
1057 gdb_continue(state);
1062 * Command Format: s [addr]
1070 gdb_send_signal_packet(
1071 state, pkt_buf, sizeof(pkt_buf), state->signum);
1075 * Unsupported Command
1078 gdb_send_packet(state, 0, 0);
1084 gdb_send_error_packet(state, pkt_buf, sizeof(pkt_buf), 0x00);
1086 #undef token_remaining_buf
1087 #undef token_expect_seperator
1088 #undef token_expect_integer_arg
1095 static struct gdb_state gdb_state;
1096 static volatile int start_debugging = 0;
1099 * Debug interrupt handler.
1102 gdbstub_loop(struct hart_state* hstate)
1104 arch_gdbstub_setup_state(&gdb_state, hstate);
1105 arch_gdbstub_save_regs(&gdb_state, hstate);
1107 gdb_main(&gdb_state);
1109 arch_gdbstub_restore_regs(&gdb_state, hstate);
1112 /*****************************************************************************
1113 * Debugging System Functions
1114 ****************************************************************************/
1117 * Write one character to the debugging stream.
1120 gdb_sys_putchar(struct gdb_state* state, int ch)
1122 serial_rwbuf_sync(state->sdev, &ch, 1, SERIAL_RW_TX);
1127 * Read one character from the debugging stream.
1130 gdb_sys_getc(struct gdb_state* state)
1133 serial_rwbuf_sync(state->sdev, &ch, 1, SERIAL_RW_RX);
1138 * Read one byte from memory.
1141 gdb_sys_mem_readb(struct gdb_state* state, ptr_t addr, char* val)
1143 *val = *(volatile char*)addr;
1148 * Write one byte to memory.
1151 gdb_sys_mem_writeb(struct gdb_state* state, ptr_t addr, char val)
1153 *(volatile char*)addr = val;