2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (c) 2004 Marcel Moolenaar
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #include <sys/cdefs.h>
30 #include <sys/param.h>
31 #include <sys/systm.h>
33 #include <sys/kernel.h>
36 #include <sys/reboot.h>
39 #include <machine/gdb_machdep.h>
40 #include <machine/kdb.h>
43 #include <gdb/gdb_int.h>
45 SYSCTL_NODE(_debug, OID_AUTO, gdb, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
48 static dbbe_init_f gdb_init;
49 static dbbe_trap_f gdb_trap;
51 KDB_BACKEND(gdb, gdb_init, NULL, NULL, gdb_trap);
53 static struct gdb_dbgport null_gdb_dbgport;
54 DATA_SET(gdb_dbgport_set, null_gdb_dbgport);
55 SET_DECLARE(gdb_dbgport_set, struct gdb_dbgport);
57 struct gdb_dbgport *gdb_cur = NULL;
58 int gdb_listening = 0;
59 bool gdb_ackmode = true;
61 static unsigned char gdb_bindata[64];
64 bool gdb_return_to_ddb = false;
70 struct gdb_dbgport *dp, **iter;
75 SET_FOREACH(iter, gdb_dbgport_set) {
77 pri = (dp->gdb_probe != NULL) ? dp->gdb_probe() : -1;
78 dp->gdb_active = (pri >= 0) ? 0 : -1;
84 if (gdb_cur != NULL) {
85 printf("GDB: debug ports:");
86 SET_FOREACH(iter, gdb_dbgport_set) {
88 if (dp->gdb_active == 0)
89 printf(" %s", dp->gdb_name);
93 printf("GDB: no debug ports present\n");
94 if (gdb_cur != NULL) {
96 printf("GDB: current port: %s\n", gdb_cur->gdb_name);
98 if (gdb_cur != NULL) {
99 cur_pri = (boothowto & RB_GDB) ? 2 : 0;
107 gdb_do_mem_search(void)
111 const unsigned char *found;
113 if (gdb_rx_varhex(&addr) || gdb_rx_char() != ';' ||
114 gdb_rx_varhex(&size) || gdb_rx_char() != ';' ||
115 gdb_rx_bindata(gdb_bindata, sizeof(gdb_bindata), &patlen)) {
119 if (gdb_search_mem((char *)(uintptr_t)addr, size, gdb_bindata,
126 gdb_tx_hex((intmax_t)(uintptr_t)found, 8);
134 gdb_do_threadinfo(struct thread **thr_iter)
136 static struct thread * const done_sentinel = (void *)(uintptr_t)1;
137 static const size_t tidsz_hex = sizeof(lwpid_t) * 2;
140 if (*thr_iter == NULL) {
145 if (*thr_iter == done_sentinel) {
154 *thr_iter != NULL && gdb_txbuf_has_capacity(tidsz_hex + 1);
155 *thr_iter = kdb_thr_next(*thr_iter), tds_sent++) {
158 gdb_tx_varhex((*thr_iter)->td_tid);
162 * Can't send EOF and "some" in same packet, so set a sentinel to send
163 * EOF when GDB asks us next.
165 if (*thr_iter == NULL && tds_sent > 0)
166 *thr_iter = done_sentinel;
172 #define BIT(n) (1ull << (n))
185 static const char * const gdb_feature_names[] = {
186 [GDB_MULTIPROCESS] = "multiprocess",
187 [GDB_SWBREAK] = "swbreak",
188 [GDB_HWBREAK] = "hwbreak",
189 [GDB_QRELOCINSN] = "qRelocInsn",
190 [GDB_FORK_EVENTS] = "fork-events",
191 [GDB_VFORK_EVENTS] = "vfork-events",
192 [GDB_EXEC_EVENTS] = "exec-events",
193 [GDB_VCONT_SUPPORTED] = "vContSupported",
194 [GDB_QTHREADEVENTS] = "QThreadEvents",
195 [GDB_NO_RESUMED] = "no-resumed",
198 gdb_do_qsupported(uint32_t *feat)
200 char *tok, *delim, ok;
203 /* Parse supported host features */
205 switch (gdb_rx_char()) {
214 while (gdb_rxsz > 0) {
216 delim = strchrnul(gdb_rxp, ';');
217 toklen = (delim - tok);
221 if (*delim != '\0') {
230 ok = tok[toklen - 1];
231 if (ok != '-' && ok != '+') {
233 * GDB only has one KV-pair feature, and we don't
234 * support it, so ignore and move on.
236 if (strchr(tok, '=') != NULL)
238 /* Not a KV-pair, and not a +/- flag? Malformed. */
243 tok[toklen - 1] = '\0';
245 for (i = 0; i < nitems(gdb_feature_names); i++)
246 if (strcmp(gdb_feature_names[i], tok) == 0)
249 if (i == nitems(gdb_feature_names)) {
250 /* Unknown GDB feature. */
258 /* Send a supported feature list back */
261 gdb_tx_str("PacketSize");
264 * We don't buffer framing bytes, but we do need to retain a byte for a
267 gdb_tx_varhex(GDB_BUFSZ + strlen("$#nn") - 1);
269 gdb_tx_str(";qXfer:threads:read+");
272 * If the debugport is a reliable transport, request No Ack mode from
273 * the server. The server may or may not choose to enter No Ack mode.
274 * https://sourceware.org/gdb/onlinedocs/gdb/Packet-Acknowledgment.html
276 if (gdb_cur->gdb_dbfeatures & GDB_DBGP_FEAT_RELIABLE)
277 gdb_tx_str(";QStartNoAckMode+");
280 * Future consideration:
293 * A qXfer_context provides a vaguely generic way to generate a multi-packet
294 * response on the fly, making some assumptions about the size of sbuf writes
295 * vs actual packet length constraints. A non-byzantine gdb host should allow
296 * hundreds of bytes per packet or more.
298 * Upper layers are considered responsible for escaping the four forbidden
299 * characters '# $ } *'.
301 struct qXfer_context {
306 char xfer_buf[GDB_BUFSZ];
310 qXfer_drain(void *v, const char *buf, int len)
312 struct qXfer_context *qx;
320 * Overflow. We lost some message. Maybe the packet size is
321 * ridiculously small.
323 printf("%s: Overflow in qXfer detected.\n", __func__);
327 qx->last_offset += len;
335 memcpy(gdb_txp, buf, len);
343 init_qXfer_ctx(struct qXfer_context *qx, uintmax_t len)
346 /* Protocol (max) length field includes framing overhead. */
347 if (len < sizeof("$m#nn"))
351 len = ummin(len, GDB_BUFSZ - 1);
355 qx->lastmessage = false;
356 sbuf_new(&qx->sb, qx->xfer_buf, len, SBUF_FIXEDLEN);
357 sbuf_set_drain(&qx->sb, qXfer_drain, qx);
362 * Squashes special XML and GDB characters down to _. Sorry.
365 qXfer_escape_xmlattr_str(char *dst, size_t dstlen, const char *src)
367 static const char *forbidden = "#$}*";
372 for (i = 0; i < dstlen - 1 && *src != 0; src++, i++) {
374 /* XML attr filter */
377 /* We assume attributes will be "" quoted. */
378 if (c == '<' || c == '&' || c == '"')
382 if (strchr(forbidden, c) != NULL) {
384 * It would be nice to escape these properly, but to do
385 * it correctly we need to escape them in the transmit
386 * layer, potentially doubling our buffer requirements.
387 * For now, avoid breaking the protocol by squashing
388 * them to underscore.
399 printf("XXX%s: overflow; API misuse\n", __func__);
405 * Dynamically generate qXfer:threads document, one packet at a time.
407 * The format is loosely described[0], although it does not seem that the
408 * <?xml?> mentioned on that page is required.
410 * [0]: https://sourceware.org/gdb/current/onlinedocs/gdb/Thread-List-Format.html
413 do_qXfer_threads_read(void)
417 struct qXfer_context qXfer;
418 /* Kludgy state machine */
421 XML_START_THREAD, /* '<thread' */
422 XML_THREAD_ID, /* ' id="xxx"' */
423 XML_THREAD_CORE, /* ' core="yyy"' */
424 XML_THREAD_NAME, /* ' name="zzz"' */
425 XML_THREAD_EXTRA, /* '> ...' */
426 XML_END_THREAD, /* '</thread>' */
427 XML_SENT_END_THREADS, /* '</threads>' */
430 static char td_name_escape[MAXCOMLEN * 2 + 1];
432 const char *name_src;
433 uintmax_t offset, len;
436 /* Annex part must be empty. */
437 if (gdb_rx_char() != ':')
438 goto misformed_request;
440 if (gdb_rx_varhex(&offset) != 0 ||
441 gdb_rx_char() != ',' ||
442 gdb_rx_varhex(&len) != 0)
443 goto misformed_request;
446 * Validate resume xfers.
449 if (offset != ctx.qXfer.last_offset) {
450 printf("%s: Resumed offset %ju != expected %zu\n",
451 __func__, offset, ctx.qXfer.last_offset);
455 ctx.qXfer.flushed = false;
459 ctx.iter = kdb_thr_first();
460 ctx.next_step = XML_START_THREAD;
461 error = init_qXfer_ctx(&ctx.qXfer, len);
465 sbuf_cat(&ctx.qXfer.sb, "<threads>");
468 while (!ctx.qXfer.flushed && ctx.iter != NULL) {
469 switch (ctx.next_step) {
470 case XML_START_THREAD:
471 ctx.next_step = XML_THREAD_ID;
472 sbuf_cat(&ctx.qXfer.sb, "<thread");
476 ctx.next_step = XML_THREAD_CORE;
477 sbuf_printf(&ctx.qXfer.sb, " id=\"%jx\"",
478 (uintmax_t)ctx.iter->td_tid);
481 case XML_THREAD_CORE:
482 ctx.next_step = XML_THREAD_NAME;
483 if (ctx.iter->td_oncpu != NOCPU) {
484 sbuf_printf(&ctx.qXfer.sb, " core=\"%d\"",
489 case XML_THREAD_NAME:
490 ctx.next_step = XML_THREAD_EXTRA;
492 if (ctx.iter->td_name[0] != 0)
493 name_src = ctx.iter->td_name;
494 else if (ctx.iter->td_proc != NULL &&
495 ctx.iter->td_proc->p_comm[0] != 0)
496 name_src = ctx.iter->td_proc->p_comm;
500 qXfer_escape_xmlattr_str(td_name_escape,
501 sizeof(td_name_escape), name_src);
502 sbuf_printf(&ctx.qXfer.sb, " name=\"%s\"",
506 case XML_THREAD_EXTRA:
507 ctx.next_step = XML_END_THREAD;
509 sbuf_putc(&ctx.qXfer.sb, '>');
511 if (TD_GET_STATE(ctx.iter) == TDS_RUNNING)
512 sbuf_cat(&ctx.qXfer.sb, "Running");
513 else if (TD_GET_STATE(ctx.iter) == TDS_RUNQ)
514 sbuf_cat(&ctx.qXfer.sb, "RunQ");
515 else if (TD_GET_STATE(ctx.iter) == TDS_CAN_RUN)
516 sbuf_cat(&ctx.qXfer.sb, "CanRun");
517 else if (TD_ON_LOCK(ctx.iter))
518 sbuf_cat(&ctx.qXfer.sb, "Blocked");
519 else if (TD_IS_SLEEPING(ctx.iter))
520 sbuf_cat(&ctx.qXfer.sb, "Sleeping");
521 else if (TD_IS_SWAPPED(ctx.iter))
522 sbuf_cat(&ctx.qXfer.sb, "Swapped");
523 else if (TD_AWAITING_INTR(ctx.iter))
524 sbuf_cat(&ctx.qXfer.sb, "IthreadWait");
525 else if (TD_IS_SUSPENDED(ctx.iter))
526 sbuf_cat(&ctx.qXfer.sb, "Suspended");
528 sbuf_cat(&ctx.qXfer.sb, "???");
532 ctx.next_step = XML_START_THREAD;
533 sbuf_cat(&ctx.qXfer.sb, "</thread>");
534 ctx.iter = kdb_thr_next(ctx.iter);
538 * This one isn't part of the looping state machine,
539 * but GCC complains if you leave an enum value out of the
542 case XML_SENT_END_THREADS:
547 if (ctx.qXfer.flushed)
550 if (ctx.next_step != XML_SENT_END_THREADS) {
551 ctx.next_step = XML_SENT_END_THREADS;
552 sbuf_cat(&ctx.qXfer.sb, "</threads>");
554 if (ctx.qXfer.flushed)
557 ctx.qXfer.lastmessage = true;
558 sbuf_finish(&ctx.qXfer.sb);
559 sbuf_delete(&ctx.qXfer.sb);
560 ctx.qXfer.last_offset = 0;
565 * GDB "General-Query-Packets.html" qXfer-read anchor specifically
566 * documents an E00 code for malformed requests or invalid annex.
567 * Non-zero codes indicate invalid offset or "error reading the data."
576 * A set of standardized transfers from "special data areas."
578 * We've already matched on "qXfer:" and advanced the rx packet buffer past
579 * that bit. Parse out the rest of the packet and generate an appropriate
585 if (!gdb_rx_equal("threads:"))
588 if (!gdb_rx_equal("read:"))
591 do_qXfer_threads_read();
600 gdb_handle_detach(void)
602 kdb_cpu_clear_singlestep();
605 if (gdb_cur->gdb_dbfeatures & GDB_DBGP_FEAT_WANTTERM)
609 if (!gdb_return_to_ddb)
612 gdb_return_to_ddb = false;
614 if (kdb_dbbe_select("ddb") != 0)
615 printf("The ddb backend could not be selected.\n");
620 * Handle a 'Z' packet: set a breakpoint or watchpoint.
622 * Currently, only watchpoints are supported.
627 intmax_t addr, length;
631 ztype = gdb_rx_char();
632 if (gdb_rx_char() != ',' || gdb_rx_varhex(&addr) ||
633 gdb_rx_char() != ',' || gdb_rx_varhex(&length)) {
639 case '2': /* write watchpoint */
640 error = kdb_cpu_set_watchpoint((vm_offset_t)addr,
641 (vm_size_t)length, KDB_DBG_ACCESS_W);
643 case '3': /* read watchpoint */
644 error = kdb_cpu_set_watchpoint((vm_offset_t)addr,
645 (vm_size_t)length, KDB_DBG_ACCESS_R);
647 case '4': /* access (RW) watchpoint */
648 error = kdb_cpu_set_watchpoint((vm_offset_t)addr,
649 (vm_size_t)length, KDB_DBG_ACCESS_RW);
651 case '1': /* hardware breakpoint */
652 case '0': /* software breakpoint */
653 /* Not implemented. */
670 * Handle a 'z' packet; clear a breakpoint or watchpoint.
672 * Currently, only watchpoints are supported.
677 intmax_t addr, length;
681 ztype = gdb_rx_char();
682 if (gdb_rx_char() != ',' || gdb_rx_varhex(&addr) ||
683 gdb_rx_char() != ',' || gdb_rx_varhex(&length)) {
689 case '2': /* write watchpoint */
690 case '3': /* read watchpoint */
691 case '4': /* access (RW) watchpoint */
692 error = kdb_cpu_clr_watchpoint((vm_offset_t)addr,
695 case '1': /* hardware breakpoint */
696 case '0': /* software breakpoint */
697 /* Not implemented. */
714 gdb_trap(int type, int code)
717 struct thread *thr_iter;
719 uint32_t host_features;
721 prev_jb = kdb_jmpbuf(jb);
722 if (setjmp(jb) != 0) {
723 printf("%s bailing, hopefully back to ddb!\n", __func__);
725 (void)kdb_jmpbuf(prev_jb);
733 * Send a T packet. We currently do not support watchpoints (the
734 * awatch, rwatch or watch elements).
737 gdb_tx_hex(gdb_cpu_signal(type, code), 2);
738 gdb_tx_varhex(GDB_REG_PC);
740 gdb_tx_reg(GDB_REG_PC);
742 gdb_cpu_stop_reason(type, code);
743 gdb_tx_str("thread:");
744 gdb_tx_varhex((uintmax_t)kdb_thread->td_tid);
746 gdb_tx_end(); /* XXX check error condition. */
749 while (gdb_rx_begin() == 0) {
750 /* printf("GDB: got '%s'\n", gdb_rxp); */
751 switch (gdb_rx_char()) {
752 case '?': /* Last signal. */
754 gdb_tx_hex(gdb_cpu_signal(type, code), 2);
755 gdb_tx_str("thread:");
756 gdb_tx_varhex((long)kdb_thread->td_tid);
760 case 'c': { /* Continue. */
763 if (!gdb_rx_varhex(&addr)) {
765 gdb_cpu_setreg(GDB_REG_PC, &pc);
767 kdb_cpu_clear_singlestep();
771 case 'C': { /* Continue with signal. */
774 if (!gdb_rx_varhex(&sig) && gdb_rx_char() == ';' &&
775 !gdb_rx_varhex(&addr)) {
777 gdb_cpu_setreg(GDB_REG_PC, &pc);
779 kdb_cpu_clear_singlestep();
783 case 'D': { /* Detach */
788 case 'g': { /* Read registers. */
791 for (r = 0; r < GDB_NREGS; r++)
796 case 'G': { /* Write registers. */
800 for (success = true, r = 0; r < GDB_NREGS; r++) {
802 if (!gdb_rx_mem(val, gdb_cpu_regsz(r))) {
807 gdb_cpu_setreg(r, val);
813 case 'H': { /* Set thread. */
817 /* Ignore 'g' (general) or 'c' (continue) flag. */
818 (void) gdb_rx_char();
820 if (gdb_rx_varhex(&tid)) {
825 thr = kdb_thr_lookup(tid);
835 case 'k': /* Kill request. */
838 case 'm': { /* Read memory. */
839 uintmax_t addr, size;
840 if (gdb_rx_varhex(&addr) || gdb_rx_char() != ',' ||
841 gdb_rx_varhex(&size)) {
846 if (gdb_tx_mem((char *)(uintptr_t)addr, size))
852 case 'M': { /* Write memory. */
853 uintmax_t addr, size;
854 if (gdb_rx_varhex(&addr) || gdb_rx_char() != ',' ||
855 gdb_rx_varhex(&size) || gdb_rx_char() != ':') {
859 if (gdb_rx_mem((char *)(uintptr_t)addr, size) == 0)
865 case 'p': { /* Read register. */
867 if (gdb_rx_varhex(®)) {
876 case 'P': { /* Write register. */
880 if (gdb_rx_varhex(®) || gdb_rx_char() != '=' ||
881 !gdb_rx_mem(val, gdb_cpu_regsz(reg))) {
885 gdb_cpu_setreg(reg, val);
889 case 'q': /* General query. */
890 if (gdb_rx_equal("C")) {
893 gdb_tx_varhex((long)kdb_thread->td_tid);
895 } else if (gdb_rx_equal("Supported")) {
896 gdb_do_qsupported(&host_features);
897 } else if (gdb_rx_equal("fThreadInfo")) {
898 thr_iter = kdb_thr_first();
899 gdb_do_threadinfo(&thr_iter);
900 } else if (gdb_rx_equal("sThreadInfo")) {
901 gdb_do_threadinfo(&thr_iter);
902 } else if (gdb_rx_equal("Xfer:")) {
904 } else if (gdb_rx_equal("Search:memory:")) {
907 } else if (gdb_rx_equal("Offsets")) {
908 gdb_cpu_do_offsets();
910 } else if (!gdb_cpu_query())
914 if (gdb_rx_equal("StartNoAckMode")) {
915 if ((gdb_cur->gdb_dbfeatures &
916 GDB_DBGP_FEAT_RELIABLE) == 0) {
918 * Shouldn't happen if we didn't
919 * advertise support. Reject.
929 case 's': { /* Step. */
932 if (!gdb_rx_varhex(&addr)) {
934 gdb_cpu_setreg(GDB_REG_PC, &pc);
936 kdb_cpu_set_singlestep();
940 case 'S': { /* Step with signal. */
943 if (!gdb_rx_varhex(&sig) && gdb_rx_char() == ';' &&
944 !gdb_rx_varhex(&addr)) {
946 gdb_cpu_setreg(GDB_REG_PC, &pc);
948 kdb_cpu_set_singlestep();
952 case 'T': { /* Thread alive. */
954 if (gdb_rx_varhex(&tid)) {
958 if (kdb_thr_lookup(tid) != NULL)
964 case 'z': { /* Remove watchpoint. */
968 case 'Z': { /* Set watchpoint. */
973 /* Empty command. Treat as unknown command. */
976 /* Unknown command. Send empty response. */
981 (void)kdb_jmpbuf(prev_jb);