2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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 __FBSDID("$FreeBSD$");
32 #include <sys/param.h>
33 #include <sys/systm.h>
35 #include <sys/kernel.h>
38 #include <sys/reboot.h>
41 #include <machine/gdb_machdep.h>
42 #include <machine/kdb.h>
45 #include <gdb/gdb_int.h>
47 SYSCTL_NODE(_debug, OID_AUTO, gdb, CTLFLAG_RW, 0, "GDB settings");
49 static dbbe_init_f gdb_init;
50 static dbbe_trap_f gdb_trap;
52 KDB_BACKEND(gdb, gdb_init, NULL, NULL, gdb_trap);
54 static struct gdb_dbgport null_gdb_dbgport;
55 DATA_SET(gdb_dbgport_set, null_gdb_dbgport);
56 SET_DECLARE(gdb_dbgport_set, struct gdb_dbgport);
58 struct gdb_dbgport *gdb_cur = NULL;
59 int gdb_listening = 0;
61 static unsigned char gdb_bindata[64];
66 struct gdb_dbgport *dp, **iter;
71 SET_FOREACH(iter, gdb_dbgport_set) {
73 pri = (dp->gdb_probe != NULL) ? dp->gdb_probe() : -1;
74 dp->gdb_active = (pri >= 0) ? 0 : -1;
80 if (gdb_cur != NULL) {
81 printf("GDB: debug ports:");
82 SET_FOREACH(iter, gdb_dbgport_set) {
84 if (dp->gdb_active == 0)
85 printf(" %s", dp->gdb_name);
89 printf("GDB: no debug ports present\n");
90 if (gdb_cur != NULL) {
92 printf("GDB: current port: %s\n", gdb_cur->gdb_name);
94 if (gdb_cur != NULL) {
95 cur_pri = (boothowto & RB_GDB) ? 2 : 0;
103 gdb_do_mem_search(void)
107 const unsigned char *found;
109 if (gdb_rx_varhex(&addr) || gdb_rx_char() != ';' ||
110 gdb_rx_varhex(&size) || gdb_rx_char() != ';' ||
111 gdb_rx_bindata(gdb_bindata, sizeof(gdb_bindata), &patlen)) {
115 if (gdb_search_mem((char *)(uintptr_t)addr, size, gdb_bindata,
122 gdb_tx_hex((intmax_t)(uintptr_t)found, 8);
130 gdb_do_threadinfo(struct thread **thr_iter)
132 static struct thread * const done_sentinel = (void *)(uintptr_t)1;
133 static const size_t tidsz_hex = sizeof(lwpid_t) * 2;
136 if (*thr_iter == NULL) {
141 if (*thr_iter == done_sentinel) {
150 *thr_iter != NULL && gdb_txbuf_has_capacity(tidsz_hex + 1);
151 *thr_iter = kdb_thr_next(*thr_iter), tds_sent++) {
154 gdb_tx_varhex((*thr_iter)->td_tid);
158 * Can't send EOF and "some" in same packet, so set a sentinel to send
159 * EOF when GDB asks us next.
161 if (*thr_iter == NULL && tds_sent > 0)
162 *thr_iter = done_sentinel;
168 #define BIT(n) (1ull << (n))
181 static const char * const gdb_feature_names[] = {
182 [GDB_MULTIPROCESS] = "multiprocess",
183 [GDB_SWBREAK] = "swbreak",
184 [GDB_HWBREAK] = "hwbreak",
185 [GDB_QRELOCINSN] = "qRelocInsn",
186 [GDB_FORK_EVENTS] = "fork-events",
187 [GDB_VFORK_EVENTS] = "vfork-events",
188 [GDB_EXEC_EVENTS] = "exec-events",
189 [GDB_VCONT_SUPPORTED] = "vContSupported",
190 [GDB_QTHREADEVENTS] = "QThreadEvents",
191 [GDB_NO_RESUMED] = "no-resumed",
194 gdb_do_qsupported(uint32_t *feat)
196 char *tok, *delim, ok;
199 /* Parse supported host features */
201 if (gdb_rx_char() != ':')
204 while (gdb_rxsz > 0) {
206 delim = strchrnul(gdb_rxp, ';');
207 toklen = (delim - tok);
211 if (*delim != '\0') {
220 ok = tok[toklen - 1];
221 if (ok != '-' && ok != '+') {
223 * GDB only has one KV-pair feature, and we don't
224 * support it, so ignore and move on.
226 if (strchr(tok, '=') != NULL)
228 /* Not a KV-pair, and not a +/- flag? Malformed. */
233 tok[toklen - 1] = '\0';
235 for (i = 0; i < nitems(gdb_feature_names); i++)
236 if (strcmp(gdb_feature_names[i], tok) == 0)
239 if (i == nitems(gdb_feature_names)) {
240 /* Unknown GDB feature. */
247 /* Send a supported feature list back */
250 gdb_tx_str("PacketSize");
253 * We don't buffer framing bytes, but we do need to retain a byte for a
256 gdb_tx_varhex(GDB_BUFSZ + strlen("$#nn") - 1);
258 gdb_tx_str(";qXfer:threads:read+");
261 * Future consideration:
274 * A qXfer_context provides a vaguely generic way to generate a multi-packet
275 * response on the fly, making some assumptions about the size of sbuf writes
276 * vs actual packet length constraints. A non-byzantine gdb host should allow
277 * hundreds of bytes per packet or more.
279 * Upper layers are considered responsible for escaping the four forbidden
280 * characters '# $ } *'.
282 struct qXfer_context {
287 char xfer_buf[GDB_BUFSZ];
291 qXfer_drain(void *v, const char *buf, int len)
293 struct qXfer_context *qx;
301 * Overflow. We lost some message. Maybe the packet size is
302 * ridiculously small.
304 printf("%s: Overflow in qXfer detected.\n", __func__);
308 qx->last_offset += len;
316 memcpy(gdb_txp, buf, len);
324 init_qXfer_ctx(struct qXfer_context *qx, uintmax_t len)
327 /* Protocol (max) length field includes framing overhead. */
328 if (len < sizeof("$m#nn"))
332 len = ummin(len, GDB_BUFSZ - 1);
336 qx->lastmessage = false;
337 sbuf_new(&qx->sb, qx->xfer_buf, len, SBUF_FIXEDLEN);
338 sbuf_set_drain(&qx->sb, qXfer_drain, qx);
343 * dst must be 2x strlen(max_src) + 1.
345 * Squashes invalid XML characters down to _. Sorry. Then escapes for GDB.
348 qXfer_escape_xmlattr_str(char *dst, size_t dstlen, const char *src)
350 static const char *forbidden = "#$}*";
355 for (i = 0; i < dstlen - 1 && *src != 0; src++, i++) {
357 /* XML attr filter */
360 /* We assume attributes will be "" quoted. */
361 if (c == '<' || c == '&' || c == '"')
365 if (strchr(forbidden, c) != NULL) {
372 printf("XXX%s: overflow; API misuse\n", __func__);
378 * Dynamically generate qXfer:threads document, one packet at a time.
380 * The format is loosely described[0], although it does not seem that the
381 * <?xml?> mentioned on that page is required.
383 * [0]: https://sourceware.org/gdb/current/onlinedocs/gdb/Thread-List-Format.html
386 do_qXfer_threads_read(void)
390 struct qXfer_context qXfer;
391 /* Kludgy state machine */
394 XML_START_THREAD, /* '<thread' */
395 XML_THREAD_ID, /* ' id="xxx"' */
396 XML_THREAD_CORE, /* ' core="yyy"' */
397 XML_THREAD_NAME, /* ' name="zzz"' */
398 XML_THREAD_EXTRA, /* '> ...' */
399 XML_END_THREAD, /* '</thread>' */
400 XML_SENT_END_THREADS, /* '</threads>' */
403 static char td_name_escape[MAXCOMLEN * 2 + 1];
405 const char *name_src;
406 uintmax_t offset, len;
409 /* Annex part must be empty. */
410 if (gdb_rx_char() != ':')
411 goto misformed_request;
413 if (gdb_rx_varhex(&offset) != 0 ||
414 gdb_rx_char() != ',' ||
415 gdb_rx_varhex(&len) != 0)
416 goto misformed_request;
419 * Validate resume xfers.
422 if (offset != ctx.qXfer.last_offset) {
423 printf("%s: Resumed offset %ju != expected %zu\n",
424 __func__, offset, ctx.qXfer.last_offset);
428 ctx.qXfer.flushed = false;
432 ctx.iter = kdb_thr_first();
433 ctx.next_step = XML_START_THREAD;
434 error = init_qXfer_ctx(&ctx.qXfer, len);
438 sbuf_cat(&ctx.qXfer.sb, "<threads>");
441 while (!ctx.qXfer.flushed && ctx.iter != NULL) {
442 switch (ctx.next_step) {
443 case XML_START_THREAD:
444 ctx.next_step = XML_THREAD_ID;
445 sbuf_cat(&ctx.qXfer.sb, "<thread");
449 ctx.next_step = XML_THREAD_CORE;
450 sbuf_printf(&ctx.qXfer.sb, " id=\"%jx\"",
451 (uintmax_t)ctx.iter->td_tid);
454 case XML_THREAD_CORE:
455 ctx.next_step = XML_THREAD_NAME;
456 if (ctx.iter->td_oncpu != NOCPU) {
457 sbuf_printf(&ctx.qXfer.sb, " core=\"%d\"",
462 case XML_THREAD_NAME:
463 ctx.next_step = XML_THREAD_EXTRA;
465 if (ctx.iter->td_name[0] != 0)
466 name_src = ctx.iter->td_name;
467 else if (ctx.iter->td_proc != NULL &&
468 ctx.iter->td_proc->p_comm[0] != 0)
469 name_src = ctx.iter->td_proc->p_comm;
473 qXfer_escape_xmlattr_str(td_name_escape,
474 sizeof(td_name_escape), name_src);
475 sbuf_printf(&ctx.qXfer.sb, " name=\"%s\"",
479 case XML_THREAD_EXTRA:
480 ctx.next_step = XML_END_THREAD;
482 sbuf_putc(&ctx.qXfer.sb, '>');
484 if (ctx.iter->td_state == TDS_RUNNING)
485 sbuf_cat(&ctx.qXfer.sb, "Running");
486 else if (ctx.iter->td_state == TDS_RUNQ)
487 sbuf_cat(&ctx.qXfer.sb, "RunQ");
488 else if (ctx.iter->td_state == TDS_CAN_RUN)
489 sbuf_cat(&ctx.qXfer.sb, "CanRun");
490 else if (TD_ON_LOCK(ctx.iter))
491 sbuf_cat(&ctx.qXfer.sb, "Blocked");
492 else if (TD_IS_SLEEPING(ctx.iter))
493 sbuf_cat(&ctx.qXfer.sb, "Sleeping");
494 else if (TD_IS_SWAPPED(ctx.iter))
495 sbuf_cat(&ctx.qXfer.sb, "Swapped");
496 else if (TD_AWAITING_INTR(ctx.iter))
497 sbuf_cat(&ctx.qXfer.sb, "IthreadWait");
498 else if (TD_IS_SUSPENDED(ctx.iter))
499 sbuf_cat(&ctx.qXfer.sb, "Suspended");
501 sbuf_cat(&ctx.qXfer.sb, "???");
505 ctx.next_step = XML_START_THREAD;
506 sbuf_cat(&ctx.qXfer.sb, "</thread>");
507 ctx.iter = kdb_thr_next(ctx.iter);
511 * This one isn't part of the looping state machine,
512 * but GCC complains if you leave an enum value out of the
515 case XML_SENT_END_THREADS:
520 if (ctx.qXfer.flushed)
523 if (ctx.next_step != XML_SENT_END_THREADS) {
524 ctx.next_step = XML_SENT_END_THREADS;
525 sbuf_cat(&ctx.qXfer.sb, "</threads>");
527 if (ctx.qXfer.flushed)
530 ctx.qXfer.lastmessage = true;
531 sbuf_finish(&ctx.qXfer.sb);
532 sbuf_delete(&ctx.qXfer.sb);
533 ctx.qXfer.last_offset = 0;
538 * GDB "General-Query-Packets.html" qXfer-read anchor specifically
539 * documents an E00 code for malformed requests or invalid annex.
540 * Non-zero codes indicate invalid offset or "error reading the data."
549 * A set of standardized transfers from "special data areas."
551 * We've already matched on "qXfer:" and advanced the rx packet buffer past
552 * that bit. Parse out the rest of the packet and generate an appropriate
558 if (!gdb_rx_equal("threads:"))
561 if (!gdb_rx_equal("read:"))
564 do_qXfer_threads_read();
573 gdb_trap(int type, int code)
576 struct thread *thr_iter;
578 uint32_t host_features;
580 prev_jb = kdb_jmpbuf(jb);
581 if (setjmp(jb) != 0) {
582 printf("%s bailing, hopefully back to ddb!\n", __func__);
584 (void)kdb_jmpbuf(prev_jb);
590 * Send a T packet. We currently do not support watchpoints (the
591 * awatch, rwatch or watch elements).
594 gdb_tx_hex(gdb_cpu_signal(type, code), 2);
595 gdb_tx_varhex(GDB_REG_PC);
597 gdb_tx_reg(GDB_REG_PC);
599 gdb_tx_str("thread:");
600 gdb_tx_varhex((long)kdb_thread->td_tid);
602 gdb_tx_end(); /* XXX check error condition. */
605 while (gdb_rx_begin() == 0) {
606 /* printf("GDB: got '%s'\n", gdb_rxp); */
607 switch (gdb_rx_char()) {
608 case '?': /* Last signal. */
610 gdb_tx_hex(gdb_cpu_signal(type, code), 2);
611 gdb_tx_str("thread:");
612 gdb_tx_varhex((long)kdb_thread->td_tid);
616 case 'c': { /* Continue. */
619 if (!gdb_rx_varhex(&addr)) {
621 gdb_cpu_setreg(GDB_REG_PC, &pc);
623 kdb_cpu_clear_singlestep();
627 case 'C': { /* Continue with signal. */
630 if (!gdb_rx_varhex(&sig) && gdb_rx_char() == ';' &&
631 !gdb_rx_varhex(&addr)) {
633 gdb_cpu_setreg(GDB_REG_PC, &pc);
635 kdb_cpu_clear_singlestep();
639 case 'D': { /* Detach */
641 kdb_cpu_clear_singlestep();
644 case 'g': { /* Read registers. */
647 for (r = 0; r < GDB_NREGS; r++)
652 case 'G': /* Write registers. */
655 case 'H': { /* Set thread. */
659 /* Ignore 'g' (general) or 'c' (continue) flag. */
660 (void) gdb_rx_char();
662 if (gdb_rx_varhex(&tid)) {
667 thr = kdb_thr_lookup(tid);
677 case 'k': /* Kill request. */
678 kdb_cpu_clear_singlestep();
681 case 'm': { /* Read memory. */
682 uintmax_t addr, size;
683 if (gdb_rx_varhex(&addr) || gdb_rx_char() != ',' ||
684 gdb_rx_varhex(&size)) {
689 if (gdb_tx_mem((char *)(uintptr_t)addr, size))
695 case 'M': { /* Write memory. */
696 uintmax_t addr, size;
697 if (gdb_rx_varhex(&addr) || gdb_rx_char() != ',' ||
698 gdb_rx_varhex(&size) || gdb_rx_char() != ':') {
702 if (gdb_rx_mem((char *)(uintptr_t)addr, size) == 0)
708 case 'P': { /* Write register. */
712 if (gdb_rx_varhex(®) || gdb_rx_char() != '=' ||
713 !gdb_rx_mem(val, gdb_cpu_regsz(reg))) {
717 gdb_cpu_setreg(reg, val);
721 case 'q': /* General query. */
722 if (gdb_rx_equal("C")) {
725 gdb_tx_varhex((long)kdb_thread->td_tid);
727 } else if (gdb_rx_equal("Supported")) {
728 gdb_do_qsupported(&host_features);
729 } else if (gdb_rx_equal("fThreadInfo")) {
730 thr_iter = kdb_thr_first();
731 gdb_do_threadinfo(&thr_iter);
732 } else if (gdb_rx_equal("sThreadInfo")) {
733 gdb_do_threadinfo(&thr_iter);
734 } else if (gdb_rx_equal("Xfer:")) {
736 } else if (gdb_rx_equal("Search:memory:")) {
738 } else if (!gdb_cpu_query())
741 case 's': { /* Step. */
744 if (!gdb_rx_varhex(&addr)) {
746 gdb_cpu_setreg(GDB_REG_PC, &pc);
748 kdb_cpu_set_singlestep();
752 case 'S': { /* Step with signal. */
755 if (!gdb_rx_varhex(&sig) && gdb_rx_char() == ';' &&
756 !gdb_rx_varhex(&addr)) {
758 gdb_cpu_setreg(GDB_REG_PC, &pc);
760 kdb_cpu_set_singlestep();
764 case 'T': { /* Thread alive. */
766 if (gdb_rx_varhex(&tid)) {
770 if (kdb_thr_lookup(tid) != NULL)
777 /* Empty command. Treat as unknown command. */
780 /* Unknown command. Send empty response. */
785 (void)kdb_jmpbuf(prev_jb);