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];
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 if (gdb_rx_char() != ':')
208 while (gdb_rxsz > 0) {
210 delim = strchrnul(gdb_rxp, ';');
211 toklen = (delim - tok);
215 if (*delim != '\0') {
224 ok = tok[toklen - 1];
225 if (ok != '-' && ok != '+') {
227 * GDB only has one KV-pair feature, and we don't
228 * support it, so ignore and move on.
230 if (strchr(tok, '=') != NULL)
232 /* Not a KV-pair, and not a +/- flag? Malformed. */
237 tok[toklen - 1] = '\0';
239 for (i = 0; i < nitems(gdb_feature_names); i++)
240 if (strcmp(gdb_feature_names[i], tok) == 0)
243 if (i == nitems(gdb_feature_names)) {
244 /* Unknown GDB feature. */
251 /* Send a supported feature list back */
254 gdb_tx_str("PacketSize");
257 * We don't buffer framing bytes, but we do need to retain a byte for a
260 gdb_tx_varhex(GDB_BUFSZ + strlen("$#nn") - 1);
262 gdb_tx_str(";qXfer:threads:read+");
265 * Future consideration:
278 * A qXfer_context provides a vaguely generic way to generate a multi-packet
279 * response on the fly, making some assumptions about the size of sbuf writes
280 * vs actual packet length constraints. A non-byzantine gdb host should allow
281 * hundreds of bytes per packet or more.
283 * Upper layers are considered responsible for escaping the four forbidden
284 * characters '# $ } *'.
286 struct qXfer_context {
291 char xfer_buf[GDB_BUFSZ];
295 qXfer_drain(void *v, const char *buf, int len)
297 struct qXfer_context *qx;
305 * Overflow. We lost some message. Maybe the packet size is
306 * ridiculously small.
308 printf("%s: Overflow in qXfer detected.\n", __func__);
312 qx->last_offset += len;
320 memcpy(gdb_txp, buf, len);
328 init_qXfer_ctx(struct qXfer_context *qx, uintmax_t len)
331 /* Protocol (max) length field includes framing overhead. */
332 if (len < sizeof("$m#nn"))
336 len = ummin(len, GDB_BUFSZ - 1);
340 qx->lastmessage = false;
341 sbuf_new(&qx->sb, qx->xfer_buf, len, SBUF_FIXEDLEN);
342 sbuf_set_drain(&qx->sb, qXfer_drain, qx);
347 * dst must be 2x strlen(max_src) + 1.
349 * Squashes invalid XML characters down to _. Sorry. Then escapes for GDB.
352 qXfer_escape_xmlattr_str(char *dst, size_t dstlen, const char *src)
354 static const char *forbidden = "#$}*";
359 for (i = 0; i < dstlen - 1 && *src != 0; src++, i++) {
361 /* XML attr filter */
364 /* We assume attributes will be "" quoted. */
365 if (c == '<' || c == '&' || c == '"')
369 if (strchr(forbidden, c) != NULL) {
376 printf("XXX%s: overflow; API misuse\n", __func__);
382 * Dynamically generate qXfer:threads document, one packet at a time.
384 * The format is loosely described[0], although it does not seem that the
385 * <?xml?> mentioned on that page is required.
387 * [0]: https://sourceware.org/gdb/current/onlinedocs/gdb/Thread-List-Format.html
390 do_qXfer_threads_read(void)
394 struct qXfer_context qXfer;
395 /* Kludgy state machine */
398 XML_START_THREAD, /* '<thread' */
399 XML_THREAD_ID, /* ' id="xxx"' */
400 XML_THREAD_CORE, /* ' core="yyy"' */
401 XML_THREAD_NAME, /* ' name="zzz"' */
402 XML_THREAD_EXTRA, /* '> ...' */
403 XML_END_THREAD, /* '</thread>' */
404 XML_SENT_END_THREADS, /* '</threads>' */
407 static char td_name_escape[MAXCOMLEN * 2 + 1];
409 const char *name_src;
410 uintmax_t offset, len;
413 /* Annex part must be empty. */
414 if (gdb_rx_char() != ':')
415 goto misformed_request;
417 if (gdb_rx_varhex(&offset) != 0 ||
418 gdb_rx_char() != ',' ||
419 gdb_rx_varhex(&len) != 0)
420 goto misformed_request;
423 * Validate resume xfers.
426 if (offset != ctx.qXfer.last_offset) {
427 printf("%s: Resumed offset %ju != expected %zu\n",
428 __func__, offset, ctx.qXfer.last_offset);
432 ctx.qXfer.flushed = false;
436 ctx.iter = kdb_thr_first();
437 ctx.next_step = XML_START_THREAD;
438 error = init_qXfer_ctx(&ctx.qXfer, len);
442 sbuf_cat(&ctx.qXfer.sb, "<threads>");
445 while (!ctx.qXfer.flushed && ctx.iter != NULL) {
446 switch (ctx.next_step) {
447 case XML_START_THREAD:
448 ctx.next_step = XML_THREAD_ID;
449 sbuf_cat(&ctx.qXfer.sb, "<thread");
453 ctx.next_step = XML_THREAD_CORE;
454 sbuf_printf(&ctx.qXfer.sb, " id=\"%jx\"",
455 (uintmax_t)ctx.iter->td_tid);
458 case XML_THREAD_CORE:
459 ctx.next_step = XML_THREAD_NAME;
460 if (ctx.iter->td_oncpu != NOCPU) {
461 sbuf_printf(&ctx.qXfer.sb, " core=\"%d\"",
466 case XML_THREAD_NAME:
467 ctx.next_step = XML_THREAD_EXTRA;
469 if (ctx.iter->td_name[0] != 0)
470 name_src = ctx.iter->td_name;
471 else if (ctx.iter->td_proc != NULL &&
472 ctx.iter->td_proc->p_comm[0] != 0)
473 name_src = ctx.iter->td_proc->p_comm;
477 qXfer_escape_xmlattr_str(td_name_escape,
478 sizeof(td_name_escape), name_src);
479 sbuf_printf(&ctx.qXfer.sb, " name=\"%s\"",
483 case XML_THREAD_EXTRA:
484 ctx.next_step = XML_END_THREAD;
486 sbuf_putc(&ctx.qXfer.sb, '>');
488 if (ctx.iter->td_state == TDS_RUNNING)
489 sbuf_cat(&ctx.qXfer.sb, "Running");
490 else if (ctx.iter->td_state == TDS_RUNQ)
491 sbuf_cat(&ctx.qXfer.sb, "RunQ");
492 else if (ctx.iter->td_state == TDS_CAN_RUN)
493 sbuf_cat(&ctx.qXfer.sb, "CanRun");
494 else if (TD_ON_LOCK(ctx.iter))
495 sbuf_cat(&ctx.qXfer.sb, "Blocked");
496 else if (TD_IS_SLEEPING(ctx.iter))
497 sbuf_cat(&ctx.qXfer.sb, "Sleeping");
498 else if (TD_IS_SWAPPED(ctx.iter))
499 sbuf_cat(&ctx.qXfer.sb, "Swapped");
500 else if (TD_AWAITING_INTR(ctx.iter))
501 sbuf_cat(&ctx.qXfer.sb, "IthreadWait");
502 else if (TD_IS_SUSPENDED(ctx.iter))
503 sbuf_cat(&ctx.qXfer.sb, "Suspended");
505 sbuf_cat(&ctx.qXfer.sb, "???");
509 ctx.next_step = XML_START_THREAD;
510 sbuf_cat(&ctx.qXfer.sb, "</thread>");
511 ctx.iter = kdb_thr_next(ctx.iter);
515 * This one isn't part of the looping state machine,
516 * but GCC complains if you leave an enum value out of the
519 case XML_SENT_END_THREADS:
524 if (ctx.qXfer.flushed)
527 if (ctx.next_step != XML_SENT_END_THREADS) {
528 ctx.next_step = XML_SENT_END_THREADS;
529 sbuf_cat(&ctx.qXfer.sb, "</threads>");
531 if (ctx.qXfer.flushed)
534 ctx.qXfer.lastmessage = true;
535 sbuf_finish(&ctx.qXfer.sb);
536 sbuf_delete(&ctx.qXfer.sb);
537 ctx.qXfer.last_offset = 0;
542 * GDB "General-Query-Packets.html" qXfer-read anchor specifically
543 * documents an E00 code for malformed requests or invalid annex.
544 * Non-zero codes indicate invalid offset or "error reading the data."
553 * A set of standardized transfers from "special data areas."
555 * We've already matched on "qXfer:" and advanced the rx packet buffer past
556 * that bit. Parse out the rest of the packet and generate an appropriate
562 if (!gdb_rx_equal("threads:"))
565 if (!gdb_rx_equal("read:"))
568 do_qXfer_threads_read();
577 gdb_handle_detach(void)
579 kdb_cpu_clear_singlestep();
582 if (gdb_cur->gdb_dbfeatures & GDB_DBGP_FEAT_WANTTERM)
586 if (!gdb_return_to_ddb)
589 gdb_return_to_ddb = false;
591 if (kdb_dbbe_select("ddb") != 0)
592 printf("The ddb backend could not be selected.\n");
597 gdb_trap(int type, int code)
600 struct thread *thr_iter;
602 uint32_t host_features;
604 prev_jb = kdb_jmpbuf(jb);
605 if (setjmp(jb) != 0) {
606 printf("%s bailing, hopefully back to ddb!\n", __func__);
608 (void)kdb_jmpbuf(prev_jb);
614 * Send a T packet. We currently do not support watchpoints (the
615 * awatch, rwatch or watch elements).
618 gdb_tx_hex(gdb_cpu_signal(type, code), 2);
619 gdb_tx_varhex(GDB_REG_PC);
621 gdb_tx_reg(GDB_REG_PC);
623 gdb_tx_str("thread:");
624 gdb_tx_varhex((long)kdb_thread->td_tid);
626 gdb_tx_end(); /* XXX check error condition. */
629 while (gdb_rx_begin() == 0) {
630 /* printf("GDB: got '%s'\n", gdb_rxp); */
631 switch (gdb_rx_char()) {
632 case '?': /* Last signal. */
634 gdb_tx_hex(gdb_cpu_signal(type, code), 2);
635 gdb_tx_str("thread:");
636 gdb_tx_varhex((long)kdb_thread->td_tid);
640 case 'c': { /* Continue. */
643 if (!gdb_rx_varhex(&addr)) {
645 gdb_cpu_setreg(GDB_REG_PC, &pc);
647 kdb_cpu_clear_singlestep();
651 case 'C': { /* Continue with signal. */
654 if (!gdb_rx_varhex(&sig) && gdb_rx_char() == ';' &&
655 !gdb_rx_varhex(&addr)) {
657 gdb_cpu_setreg(GDB_REG_PC, &pc);
659 kdb_cpu_clear_singlestep();
663 case 'D': { /* Detach */
668 case 'g': { /* Read registers. */
671 for (r = 0; r < GDB_NREGS; r++)
676 case 'G': /* Write registers. */
679 case 'H': { /* Set thread. */
683 /* Ignore 'g' (general) or 'c' (continue) flag. */
684 (void) gdb_rx_char();
686 if (gdb_rx_varhex(&tid)) {
691 thr = kdb_thr_lookup(tid);
701 case 'k': /* Kill request. */
704 case 'm': { /* Read memory. */
705 uintmax_t addr, size;
706 if (gdb_rx_varhex(&addr) || gdb_rx_char() != ',' ||
707 gdb_rx_varhex(&size)) {
712 if (gdb_tx_mem((char *)(uintptr_t)addr, size))
718 case 'M': { /* Write memory. */
719 uintmax_t addr, size;
720 if (gdb_rx_varhex(&addr) || gdb_rx_char() != ',' ||
721 gdb_rx_varhex(&size) || gdb_rx_char() != ':') {
725 if (gdb_rx_mem((char *)(uintptr_t)addr, size) == 0)
731 case 'P': { /* Write register. */
735 if (gdb_rx_varhex(®) || gdb_rx_char() != '=' ||
736 !gdb_rx_mem(val, gdb_cpu_regsz(reg))) {
740 gdb_cpu_setreg(reg, val);
744 case 'q': /* General query. */
745 if (gdb_rx_equal("C")) {
748 gdb_tx_varhex((long)kdb_thread->td_tid);
750 } else if (gdb_rx_equal("Supported")) {
751 gdb_do_qsupported(&host_features);
752 } else if (gdb_rx_equal("fThreadInfo")) {
753 thr_iter = kdb_thr_first();
754 gdb_do_threadinfo(&thr_iter);
755 } else if (gdb_rx_equal("sThreadInfo")) {
756 gdb_do_threadinfo(&thr_iter);
757 } else if (gdb_rx_equal("Xfer:")) {
759 } else if (gdb_rx_equal("Search:memory:")) {
761 } else if (!gdb_cpu_query())
764 case 's': { /* Step. */
767 if (!gdb_rx_varhex(&addr)) {
769 gdb_cpu_setreg(GDB_REG_PC, &pc);
771 kdb_cpu_set_singlestep();
775 case 'S': { /* Step with signal. */
778 if (!gdb_rx_varhex(&sig) && gdb_rx_char() == ';' &&
779 !gdb_rx_varhex(&addr)) {
781 gdb_cpu_setreg(GDB_REG_PC, &pc);
783 kdb_cpu_set_singlestep();
787 case 'T': { /* Thread alive. */
789 if (gdb_rx_varhex(&tid)) {
793 if (kdb_thr_lookup(tid) != NULL)
800 /* Empty command. Treat as unknown command. */
803 /* Unknown command. Send empty response. */
808 (void)kdb_jmpbuf(prev_jb);