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>
42 /*****************************************************************************
44 ****************************************************************************/
46 #define GDB_PRINT(...)
51 #define GDB_ASSERT(x) \
56 /*****************************************************************************
58 ****************************************************************************/
61 gdb_main(struct gdb_state* state);
63 /* System functions, supported by all stubs */
67 gdb_sys_getc(struct gdb_state* state);
69 gdb_sys_putchar(struct gdb_state* state, int ch);
71 gdb_sys_mem_readb(struct gdb_state* state, ptr_t addr, char* val);
73 gdb_sys_mem_writeb(struct gdb_state* state, ptr_t addr, char val);
76 /*****************************************************************************
78 ****************************************************************************/
80 typedef int (*gdb_enc_func)(char* buf,
83 unsigned int data_len);
84 typedef int (*gdb_dec_func)(const char* buf,
87 unsigned int data_len);
89 /*****************************************************************************
91 ****************************************************************************/
93 static const char digits[] = "0123456789abcdef";
95 /*****************************************************************************
97 ****************************************************************************/
99 /* Communication functions */
101 gdb_write(struct gdb_state* state, const char* buf, unsigned int len);
103 gdb_read(struct gdb_state* state,
105 unsigned int buf_len,
110 gdb_get_digit(int val);
112 gdb_get_val(char digit, int base);
114 gdb_strtol(const char* str, unsigned int len, int base, const char** endptr);
116 /* Packet functions */
118 gdb_send_packet(struct gdb_state* state, const char* pkt, unsigned int pkt_len);
120 gdb_recv_packet(struct gdb_state* state,
122 unsigned int pkt_buf_len,
123 unsigned int* pkt_len);
125 gdb_checksum(const char* buf, unsigned int len);
127 gdb_recv_ack(struct gdb_state* state);
129 /* Data encoding/decoding */
131 gdb_enc_hex(char* buf,
132 unsigned int buf_len,
134 unsigned int data_len);
136 gdb_dec_hex(const char* buf,
137 unsigned int buf_len,
139 unsigned int data_len);
141 gdb_enc_bin(char* buf,
142 unsigned int buf_len,
144 unsigned int data_len);
146 gdb_dec_bin(const char* buf,
147 unsigned int buf_len,
149 unsigned int data_len);
151 /* Packet creation helpers */
153 gdb_send_ok_packet(struct gdb_state* state, char* buf, unsigned int buf_len);
155 gdb_send_conmsg_packet(struct gdb_state* state,
157 unsigned int buf_len,
160 gdb_send_signal_packet(struct gdb_state* state,
162 unsigned int buf_len,
165 gdb_send_error_packet(struct gdb_state* state,
167 unsigned int buf_len,
170 /* Command functions */
172 gdb_mem_read(struct gdb_state* state,
174 unsigned int buf_len,
179 gdb_mem_write(struct gdb_state* state,
181 unsigned int buf_len,
186 gdb_continue(struct gdb_state* state);
188 gdb_step(struct gdb_state* state);
190 /*****************************************************************************
191 * String Processing Helper Functions
192 ****************************************************************************/
195 * Get integer value for a string representation.
197 * If the string starts with + or -, it will be signed accordingly.
199 * If base == 0, the base will be determined:
200 * base 16 if the string starts with 0x or 0X,
203 * If endptr is specified, it will point to the last non-digit in the
204 * string. If there are no digits in the string, it will be set to NULL.
207 gdb_strtol(const char* str, unsigned int len, int base, const char** endptr)
210 int sign, tmp, value, valid;
225 /* Detect negative numbers */
226 if (str[pos] == '-') {
229 } else if (str[pos] == '+') {
234 /* Detect '0x' hex prefix */
235 if ((pos + 2 < len) && (str[pos] == '0') &&
236 ((str[pos + 1] == 'x') || (str[pos + 1] == 'X'))) {
245 for (; (pos < len) && (str[pos] != '\x00'); pos++) {
246 tmp = gdb_get_val(str[pos], base);
247 if (tmp == GDB_EOF) {
251 value = value * base + tmp;
252 valid = 1; /* At least one digit is valid */
269 * Get the corresponding ASCII hex digit character for a value.
272 gdb_get_digit(int val)
274 if ((val >= 0) && (val <= 0xf)) {
282 * Get the corresponding value for a ASCII digit character.
284 * Supports bases 2-16.
287 gdb_get_val(char digit, int base)
291 if ((digit >= '0') && (digit <= '9')) {
293 } else if ((digit >= 'a') && (digit <= 'f')) {
294 value = digit - 'a' + 0xa;
295 } else if ((digit >= 'A') && (digit <= 'F')) {
296 value = digit - 'A' + 0xa;
301 return (value < base) ? value : GDB_EOF;
304 /*****************************************************************************
306 ****************************************************************************/
309 * Receive a packet acknowledgment
312 * 0 if an ACK (+) was received
313 * 1 if a NACK (-) was received
317 gdb_recv_ack(struct gdb_state* state)
321 /* Wait for packet ack */
322 switch (response = gdb_sys_getc(state)) {
324 /* Packet acknowledged */
327 /* Packet negative acknowledged */
331 GDB_PRINT("received bad packet response: 0x%2x\n", response);
337 * Calculate 8-bit checksum of a buffer.
343 gdb_checksum(const char* buf, unsigned int len)
357 * Transmits a packet of data.
358 * Packets are of the form: $<packet-data>#<checksum>
361 * 0 if the packet was transmitted and acknowledged
362 * 1 if the packet was transmitted but not acknowledged
366 gdb_send_packet(struct gdb_state* state,
367 const char* pkt_data,
368 unsigned int pkt_len)
373 /* Send packet start */
374 if (gdb_sys_putchar(state, '$') == GDB_EOF) {
378 /* Send packet data */
379 if (gdb_write(state, pkt_data, pkt_len) == GDB_EOF) {
383 /* Send the checksum */
385 csum = gdb_checksum(pkt_data, pkt_len);
386 if ((gdb_enc_hex(buf + 1, sizeof(buf) - 1, &csum, 1) == GDB_EOF) ||
387 (gdb_write(state, buf, sizeof(buf)) == GDB_EOF)) {
391 return gdb_recv_ack(state);
395 * Receives a packet of data, assuming a 7-bit clean connection.
398 * 0 if the packet was received
402 gdb_recv_packet(struct gdb_state* state,
404 unsigned int pkt_buf_len,
405 unsigned int* pkt_len)
408 char expected_csum, actual_csum;
411 /* Wait for packet start */
415 data = gdb_sys_getc(state);
416 if (data == GDB_EOF) {
418 } else if (data == '$') {
419 /* Detected start of packet. */
424 /* Read until checksum */
427 data = gdb_sys_getc(state);
429 if (data == GDB_EOF) {
430 /* Error receiving character */
432 } else if (data == '#') {
436 /* Check for space */
437 if (*pkt_len >= pkt_buf_len) {
438 GDB_PRINT("packet buffer overflow\n");
442 /* Store character and update checksum */
443 pkt_buf[(*pkt_len)++] = (char)data;
447 /* Receive the checksum */
448 if ((gdb_read(state, buf, sizeof(buf), 2) == GDB_EOF) ||
449 (gdb_dec_hex(buf, 2, &expected_csum, 1) == GDB_EOF)) {
453 /* Verify checksum */
454 actual_csum = gdb_checksum(pkt_buf, *pkt_len);
455 if (actual_csum != expected_csum) {
456 /* Send packet nack */
457 GDB_PRINT("received packet with bad checksum\n");
458 gdb_sys_putchar(state, '-');
462 /* Send packet ack */
463 gdb_sys_putchar(state, '+');
467 /*****************************************************************************
468 * Data Encoding/Decoding
469 ****************************************************************************/
472 * Encode data to its hex-value representation in a buffer.
475 * 0+ number of bytes written to buf
476 * GDB_EOF if the buffer is too small
479 gdb_enc_hex(char* buf,
480 unsigned int buf_len,
482 unsigned int data_len)
486 if (buf_len < data_len * 2) {
487 /* Buffer too small */
491 for (pos = 0; pos < data_len; pos++) {
492 *buf++ = gdb_get_digit((data[pos] >> 4) & 0xf);
493 *buf++ = gdb_get_digit((data[pos]) & 0xf);
500 * Decode data from its hex-value representation to a buffer.
504 * GDB_EOF if the buffer is too small
507 gdb_dec_hex(const char* buf,
508 unsigned int buf_len,
510 unsigned int data_len)
515 if (buf_len != data_len * 2) {
516 /* Buffer too small */
520 for (pos = 0; pos < data_len; pos++) {
521 /* Decode high nibble */
522 tmp = gdb_get_val(*buf++, 16);
523 if (tmp == GDB_EOF) {
524 /* Buffer contained junk. */
529 data[pos] = tmp << 4;
531 /* Decode low nibble */
532 tmp = gdb_get_val(*buf++, 16);
533 if (tmp == GDB_EOF) {
534 /* Buffer contained junk. */
545 * Encode data to its binary representation in a buffer.
548 * 0+ number of bytes written to buf
549 * GDB_EOF if the buffer is too small
552 gdb_enc_bin(char* buf,
553 unsigned int buf_len,
555 unsigned int data_len)
557 unsigned int buf_pos, data_pos;
559 for (buf_pos = 0, data_pos = 0; data_pos < data_len; data_pos++) {
560 if (data[data_pos] == '$' || data[data_pos] == '#' ||
561 data[data_pos] == '}' || data[data_pos] == '*') {
562 if (buf_pos + 1 >= buf_len) {
566 buf[buf_pos++] = '}';
567 buf[buf_pos++] = data[data_pos] ^ 0x20;
569 if (buf_pos >= buf_len) {
573 buf[buf_pos++] = data[data_pos];
581 * Decode data from its bin-value representation to a buffer.
584 * 0+ if successful, number of bytes decoded
585 * GDB_EOF if the buffer is too small
588 gdb_dec_bin(const char* buf,
589 unsigned int buf_len,
591 unsigned int data_len)
593 unsigned int buf_pos, data_pos;
595 for (buf_pos = 0, data_pos = 0; buf_pos < buf_len; buf_pos++) {
596 if (data_pos >= data_len) {
597 /* Output buffer overflow */
601 if (buf[buf_pos] == '}') {
602 /* The next byte is escaped! */
603 if (buf_pos + 1 >= buf_len) {
604 /* There's an escape character, but no escaped character
605 * following the escape character. */
610 data[data_pos++] = buf[buf_pos] ^ 0x20;
612 data[data_pos++] = buf[buf_pos];
619 /*****************************************************************************
621 ****************************************************************************/
624 * Read from memory and encode into buf.
627 * 0+ number of bytes written to buf
628 * GDB_EOF if the buffer is too small
631 gdb_mem_read(struct gdb_state* state,
633 unsigned int buf_len,
641 if (len > sizeof(data)) {
645 /* Read from system memory */
646 for (pos = 0; pos < len; pos++) {
647 if (gdb_sys_mem_readb(state, addr + pos, &data[pos])) {
654 return enc(buf, buf_len, data, len);
658 * Write to memory from encoded buf.
661 gdb_mem_write(struct gdb_state* state,
663 unsigned int buf_len,
671 if (len > sizeof(data)) {
676 if (dec(buf, buf_len, data, len) == GDB_EOF) {
680 /* Write to system memory */
681 for (pos = 0; pos < len; pos++) {
682 if (gdb_sys_mem_writeb(state, addr + pos, data[pos])) {
683 /* Failed to write */
692 * Continue program execution at PC.
695 gdb_continue(struct gdb_state* state)
697 gdb_sys_continue(state);
702 * Step one instruction.
705 gdb_step(struct gdb_state* state)
711 /*****************************************************************************
712 * Packet Creation Helpers
713 ****************************************************************************/
719 gdb_send_ok_packet(struct gdb_state* state, char* buf, unsigned int buf_len)
721 return gdb_send_packet(state, "OK", 2);
725 * Send a message to the debugging console (via O XX... packet)
728 gdb_send_conmsg_packet(struct gdb_state* state,
730 unsigned int buf_len,
737 /* Buffer too small */
742 status = gdb_enc_hex(&buf[1], buf_len - 1, msg, strlen(msg));
743 if (status == GDB_EOF) {
747 return gdb_send_packet(state, buf, size);
751 * Send a signal packet (S AA).
754 gdb_send_signal_packet(struct gdb_state* state,
756 unsigned int buf_len,
763 /* Buffer too small */
768 status = gdb_enc_hex(&buf[1], buf_len - 1, &signal, 1);
769 if (status == GDB_EOF) {
773 return gdb_send_packet(state, buf, size);
777 * Send a error packet (E AA).
780 gdb_send_error_packet(struct gdb_state* state,
782 unsigned int buf_len,
789 /* Buffer too small */
794 status = gdb_enc_hex(&buf[1], buf_len - 1, &error, 1);
795 if (status == GDB_EOF) {
799 return gdb_send_packet(state, buf, size);
802 /*****************************************************************************
803 * Communication Functions
804 ****************************************************************************/
807 * Write a sequence of bytes.
811 * GDB_EOF if failed to write all bytes
814 gdb_write(struct gdb_state* state, const char* buf, unsigned int len)
816 int err = serial_rwbuf_sync(state->sdev, buf, len, SERIAL_RW_TX);
818 return err < 0 ? GDB_EOF : 0;
822 * Read a sequence of bytes.
825 * 0 if successfully read len bytes
826 * GDB_EOF if failed to read all bytes
829 gdb_read(struct gdb_state* state,
831 unsigned int buf_len,
837 /* Buffer too small */
841 int err = serial_rwbuf_sync(state->sdev, buf, buf_len, SERIAL_RW_RX);
843 return err < 0 ? GDB_EOF : 0;
846 /*****************************************************************************
848 ****************************************************************************/
851 * Main debug loop. Handles commands.
854 gdb_main(struct gdb_state* state)
860 unsigned int pkt_len;
861 const char* ptr_next;
863 gdb_send_signal_packet(state, pkt_buf, sizeof(pkt_buf), state->signum);
866 /* Receive the next packet */
867 status = gdb_recv_packet(state, pkt_buf, sizeof(pkt_buf), &pkt_len);
868 if (status == GDB_EOF) {
873 /* Received empty packet.. */
880 * Handle one letter commands
882 switch (pkt_buf[0]) {
884 /* Calculate remaining space in packet from ptr_next position. */
885 #define token_remaining_buf (pkt_len - (ptr_next - pkt_buf))
887 /* Expecting a seperator. If not present, go to error */
888 #define token_expect_seperator(c) \
890 if (!ptr_next || *ptr_next != c) { \
897 /* Expecting an integer argument. If not present, go to error */
898 #define token_expect_integer_arg(arg) \
900 arg = gdb_strtol(ptr_next, token_remaining_buf, 16, &ptr_next); \
911 /* Encode registers */
912 status = gdb_enc_hex(pkt_buf,
914 (char*)&(state->registers),
915 sizeof(state->registers));
916 if (status == GDB_EOF) {
920 gdb_send_packet(state, pkt_buf, pkt_len);
925 * Command Format: G XX...
928 status = gdb_dec_hex(pkt_buf + 1,
930 (char*)&(state->registers),
931 sizeof(state->registers));
932 if (status == GDB_EOF) {
935 gdb_send_ok_packet(state, pkt_buf, sizeof(pkt_buf));
940 * Command Format: p n
944 token_expect_integer_arg(addr);
946 if (addr >= GDB_CPU_NUM_REGISTERS) {
951 status = gdb_enc_hex(pkt_buf,
953 (char*)&(state->registers[addr]),
954 sizeof(state->registers[addr]));
955 if (status == GDB_EOF) {
958 gdb_send_packet(state, pkt_buf, status);
963 * Command Format: P n...=r...
967 token_expect_integer_arg(addr);
968 token_expect_seperator('=');
970 if (addr < GDB_CPU_NUM_REGISTERS) {
971 status = gdb_dec_hex(ptr_next,
973 (char*)&(state->registers[addr]),
974 sizeof(state->registers[addr]));
975 if (status == GDB_EOF) {
979 gdb_send_ok_packet(state, pkt_buf, sizeof(pkt_buf));
984 * Command Format: m addr,length
988 token_expect_integer_arg(addr);
989 token_expect_seperator(',');
990 token_expect_integer_arg(length);
993 status = gdb_mem_read(
994 state, pkt_buf, sizeof(pkt_buf), addr, length, gdb_enc_hex);
995 if (status == GDB_EOF) {
998 gdb_send_packet(state, pkt_buf, status);
1003 * Command Format: M addr,length:XX..
1007 token_expect_integer_arg(addr);
1008 token_expect_seperator(',');
1009 token_expect_integer_arg(length);
1010 token_expect_seperator(':');
1013 status = gdb_mem_write(state,
1015 token_remaining_buf,
1019 if (status == GDB_EOF) {
1022 gdb_send_ok_packet(state, pkt_buf, sizeof(pkt_buf));
1026 * Write Memory (Binary)
1027 * Command Format: X addr,length:XX..
1031 token_expect_integer_arg(addr);
1032 token_expect_seperator(',');
1033 token_expect_integer_arg(length);
1034 token_expect_seperator(':');
1037 status = gdb_mem_write(state,
1039 token_remaining_buf,
1043 if (status == GDB_EOF) {
1046 gdb_send_ok_packet(state, pkt_buf, sizeof(pkt_buf));
1050 * Continue, Kill (also treated as continue!)
1051 * Command Format: c [addr]
1056 gdb_continue(state);
1061 * Command Format: s [addr]
1069 gdb_send_signal_packet(
1070 state, pkt_buf, sizeof(pkt_buf), state->signum);
1074 * Unsupported Command
1077 gdb_send_packet(state, 0, 0);
1083 gdb_send_error_packet(state, pkt_buf, sizeof(pkt_buf), 0x00);
1085 #undef token_remaining_buf
1086 #undef token_expect_seperator
1087 #undef token_expect_integer_arg
1094 static struct gdb_state gdb_state;
1095 static volatile int start_debugging = 0;
1098 * Debug interrupt handler.
1101 gdbstub_loop(struct hart_state* hstate)
1103 arch_gdbstub_setup_state(&gdb_state, hstate);
1104 arch_gdbstub_save_regs(&gdb_state, hstate);
1106 gdb_main(&gdb_state);
1108 arch_gdbstub_restore_regs(&gdb_state, hstate);
1111 /*****************************************************************************
1112 * Debugging System Functions
1113 ****************************************************************************/
1116 * Write one character to the debugging stream.
1119 gdb_sys_putchar(struct gdb_state* state, int ch)
1121 serial_rwbuf_sync(state->sdev, &ch, 1, SERIAL_RW_TX);
1126 * Read one character from the debugging stream.
1129 gdb_sys_getc(struct gdb_state* state)
1132 serial_rwbuf_sync(state->sdev, &ch, 1, SERIAL_RW_RX);
1137 * Read one byte from memory.
1140 gdb_sys_mem_readb(struct gdb_state* state, ptr_t addr, char* val)
1142 *val = *(volatile char*)addr;
1147 * Write one byte to memory.
1150 gdb_sys_mem_writeb(struct gdb_state* state, ptr_t addr, char val)
1152 *(volatile char*)addr = val;