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;
60 bool gdb_ackmode = true;
62 static unsigned char gdb_bindata[64];
65 bool gdb_return_to_ddb = false;
71 struct gdb_dbgport *dp, **iter;
76 SET_FOREACH(iter, gdb_dbgport_set) {
78 pri = (dp->gdb_probe != NULL) ? dp->gdb_probe() : -1;
79 dp->gdb_active = (pri >= 0) ? 0 : -1;
85 if (gdb_cur != NULL) {
86 printf("GDB: debug ports:");
87 SET_FOREACH(iter, gdb_dbgport_set) {
89 if (dp->gdb_active == 0)
90 printf(" %s", dp->gdb_name);
94 printf("GDB: no debug ports present\n");
95 if (gdb_cur != NULL) {
97 printf("GDB: current port: %s\n", gdb_cur->gdb_name);
99 if (gdb_cur != NULL) {
100 cur_pri = (boothowto & RB_GDB) ? 2 : 0;
108 gdb_do_mem_search(void)
112 const unsigned char *found;
114 if (gdb_rx_varhex(&addr) || gdb_rx_char() != ';' ||
115 gdb_rx_varhex(&size) || gdb_rx_char() != ';' ||
116 gdb_rx_bindata(gdb_bindata, sizeof(gdb_bindata), &patlen)) {
120 if (gdb_search_mem((char *)(uintptr_t)addr, size, gdb_bindata,
127 gdb_tx_hex((intmax_t)(uintptr_t)found, 8);
135 gdb_do_threadinfo(struct thread **thr_iter)
137 static struct thread * const done_sentinel = (void *)(uintptr_t)1;
138 static const size_t tidsz_hex = sizeof(lwpid_t) * 2;
141 if (*thr_iter == NULL) {
146 if (*thr_iter == done_sentinel) {
155 *thr_iter != NULL && gdb_txbuf_has_capacity(tidsz_hex + 1);
156 *thr_iter = kdb_thr_next(*thr_iter), tds_sent++) {
159 gdb_tx_varhex((*thr_iter)->td_tid);
163 * Can't send EOF and "some" in same packet, so set a sentinel to send
164 * EOF when GDB asks us next.
166 if (*thr_iter == NULL && tds_sent > 0)
167 *thr_iter = done_sentinel;
173 #define BIT(n) (1ull << (n))
186 static const char * const gdb_feature_names[] = {
187 [GDB_MULTIPROCESS] = "multiprocess",
188 [GDB_SWBREAK] = "swbreak",
189 [GDB_HWBREAK] = "hwbreak",
190 [GDB_QRELOCINSN] = "qRelocInsn",
191 [GDB_FORK_EVENTS] = "fork-events",
192 [GDB_VFORK_EVENTS] = "vfork-events",
193 [GDB_EXEC_EVENTS] = "exec-events",
194 [GDB_VCONT_SUPPORTED] = "vContSupported",
195 [GDB_QTHREADEVENTS] = "QThreadEvents",
196 [GDB_NO_RESUMED] = "no-resumed",
199 gdb_do_qsupported(uint32_t *feat)
201 char *tok, *delim, ok;
204 /* Parse supported host features */
206 if (gdb_rx_char() != ':')
209 while (gdb_rxsz > 0) {
211 delim = strchrnul(gdb_rxp, ';');
212 toklen = (delim - tok);
216 if (*delim != '\0') {
225 ok = tok[toklen - 1];
226 if (ok != '-' && ok != '+') {
228 * GDB only has one KV-pair feature, and we don't
229 * support it, so ignore and move on.
231 if (strchr(tok, '=') != NULL)
233 /* Not a KV-pair, and not a +/- flag? Malformed. */
238 tok[toklen - 1] = '\0';
240 for (i = 0; i < nitems(gdb_feature_names); i++)
241 if (strcmp(gdb_feature_names[i], tok) == 0)
244 if (i == nitems(gdb_feature_names)) {
245 /* Unknown GDB feature. */
252 /* Send a supported feature list back */
255 gdb_tx_str("PacketSize");
258 * We don't buffer framing bytes, but we do need to retain a byte for a
261 gdb_tx_varhex(GDB_BUFSZ + strlen("$#nn") - 1);
263 gdb_tx_str(";qXfer:threads:read+");
266 * If the debugport is a reliable transport, request No Ack mode from
267 * the server. The server may or may not choose to enter No Ack mode.
268 * https://sourceware.org/gdb/onlinedocs/gdb/Packet-Acknowledgment.html
270 if (gdb_cur->gdb_dbfeatures & GDB_DBGP_FEAT_RELIABLE)
271 gdb_tx_str(";QStartNoAckMode+");
274 * Future consideration:
287 * A qXfer_context provides a vaguely generic way to generate a multi-packet
288 * response on the fly, making some assumptions about the size of sbuf writes
289 * vs actual packet length constraints. A non-byzantine gdb host should allow
290 * hundreds of bytes per packet or more.
292 * Upper layers are considered responsible for escaping the four forbidden
293 * characters '# $ } *'.
295 struct qXfer_context {
300 char xfer_buf[GDB_BUFSZ];
304 qXfer_drain(void *v, const char *buf, int len)
306 struct qXfer_context *qx;
314 * Overflow. We lost some message. Maybe the packet size is
315 * ridiculously small.
317 printf("%s: Overflow in qXfer detected.\n", __func__);
321 qx->last_offset += len;
329 memcpy(gdb_txp, buf, len);
337 init_qXfer_ctx(struct qXfer_context *qx, uintmax_t len)
340 /* Protocol (max) length field includes framing overhead. */
341 if (len < sizeof("$m#nn"))
345 len = ummin(len, GDB_BUFSZ - 1);
349 qx->lastmessage = false;
350 sbuf_new(&qx->sb, qx->xfer_buf, len, SBUF_FIXEDLEN);
351 sbuf_set_drain(&qx->sb, qXfer_drain, qx);
356 * dst must be 2x strlen(max_src) + 1.
358 * Squashes invalid XML characters down to _. Sorry. Then escapes for GDB.
361 qXfer_escape_xmlattr_str(char *dst, size_t dstlen, const char *src)
363 static const char *forbidden = "#$}*";
368 for (i = 0; i < dstlen - 1 && *src != 0; src++, i++) {
370 /* XML attr filter */
373 /* We assume attributes will be "" quoted. */
374 if (c == '<' || c == '&' || c == '"')
378 if (strchr(forbidden, c) != NULL) {
385 printf("XXX%s: overflow; API misuse\n", __func__);
391 * Dynamically generate qXfer:threads document, one packet at a time.
393 * The format is loosely described[0], although it does not seem that the
394 * <?xml?> mentioned on that page is required.
396 * [0]: https://sourceware.org/gdb/current/onlinedocs/gdb/Thread-List-Format.html
399 do_qXfer_threads_read(void)
403 struct qXfer_context qXfer;
404 /* Kludgy state machine */
407 XML_START_THREAD, /* '<thread' */
408 XML_THREAD_ID, /* ' id="xxx"' */
409 XML_THREAD_CORE, /* ' core="yyy"' */
410 XML_THREAD_NAME, /* ' name="zzz"' */
411 XML_THREAD_EXTRA, /* '> ...' */
412 XML_END_THREAD, /* '</thread>' */
413 XML_SENT_END_THREADS, /* '</threads>' */
416 static char td_name_escape[MAXCOMLEN * 2 + 1];
418 const char *name_src;
419 uintmax_t offset, len;
422 /* Annex part must be empty. */
423 if (gdb_rx_char() != ':')
424 goto misformed_request;
426 if (gdb_rx_varhex(&offset) != 0 ||
427 gdb_rx_char() != ',' ||
428 gdb_rx_varhex(&len) != 0)
429 goto misformed_request;
432 * Validate resume xfers.
435 if (offset != ctx.qXfer.last_offset) {
436 printf("%s: Resumed offset %ju != expected %zu\n",
437 __func__, offset, ctx.qXfer.last_offset);
441 ctx.qXfer.flushed = false;
445 ctx.iter = kdb_thr_first();
446 ctx.next_step = XML_START_THREAD;
447 error = init_qXfer_ctx(&ctx.qXfer, len);
451 sbuf_cat(&ctx.qXfer.sb, "<threads>");
454 while (!ctx.qXfer.flushed && ctx.iter != NULL) {
455 switch (ctx.next_step) {
456 case XML_START_THREAD:
457 ctx.next_step = XML_THREAD_ID;
458 sbuf_cat(&ctx.qXfer.sb, "<thread");
462 ctx.next_step = XML_THREAD_CORE;
463 sbuf_printf(&ctx.qXfer.sb, " id=\"%jx\"",
464 (uintmax_t)ctx.iter->td_tid);
467 case XML_THREAD_CORE:
468 ctx.next_step = XML_THREAD_NAME;
469 if (ctx.iter->td_oncpu != NOCPU) {
470 sbuf_printf(&ctx.qXfer.sb, " core=\"%d\"",
475 case XML_THREAD_NAME:
476 ctx.next_step = XML_THREAD_EXTRA;
478 if (ctx.iter->td_name[0] != 0)
479 name_src = ctx.iter->td_name;
480 else if (ctx.iter->td_proc != NULL &&
481 ctx.iter->td_proc->p_comm[0] != 0)
482 name_src = ctx.iter->td_proc->p_comm;
486 qXfer_escape_xmlattr_str(td_name_escape,
487 sizeof(td_name_escape), name_src);
488 sbuf_printf(&ctx.qXfer.sb, " name=\"%s\"",
492 case XML_THREAD_EXTRA:
493 ctx.next_step = XML_END_THREAD;
495 sbuf_putc(&ctx.qXfer.sb, '>');
497 if (ctx.iter->td_state == TDS_RUNNING)
498 sbuf_cat(&ctx.qXfer.sb, "Running");
499 else if (ctx.iter->td_state == TDS_RUNQ)
500 sbuf_cat(&ctx.qXfer.sb, "RunQ");
501 else if (ctx.iter->td_state == TDS_CAN_RUN)
502 sbuf_cat(&ctx.qXfer.sb, "CanRun");
503 else if (TD_ON_LOCK(ctx.iter))
504 sbuf_cat(&ctx.qXfer.sb, "Blocked");
505 else if (TD_IS_SLEEPING(ctx.iter))
506 sbuf_cat(&ctx.qXfer.sb, "Sleeping");
507 else if (TD_IS_SWAPPED(ctx.iter))
508 sbuf_cat(&ctx.qXfer.sb, "Swapped");
509 else if (TD_AWAITING_INTR(ctx.iter))
510 sbuf_cat(&ctx.qXfer.sb, "IthreadWait");
511 else if (TD_IS_SUSPENDED(ctx.iter))
512 sbuf_cat(&ctx.qXfer.sb, "Suspended");
514 sbuf_cat(&ctx.qXfer.sb, "???");
518 ctx.next_step = XML_START_THREAD;
519 sbuf_cat(&ctx.qXfer.sb, "</thread>");
520 ctx.iter = kdb_thr_next(ctx.iter);
524 * This one isn't part of the looping state machine,
525 * but GCC complains if you leave an enum value out of the
528 case XML_SENT_END_THREADS:
533 if (ctx.qXfer.flushed)
536 if (ctx.next_step != XML_SENT_END_THREADS) {
537 ctx.next_step = XML_SENT_END_THREADS;
538 sbuf_cat(&ctx.qXfer.sb, "</threads>");
540 if (ctx.qXfer.flushed)
543 ctx.qXfer.lastmessage = true;
544 sbuf_finish(&ctx.qXfer.sb);
545 sbuf_delete(&ctx.qXfer.sb);
546 ctx.qXfer.last_offset = 0;
551 * GDB "General-Query-Packets.html" qXfer-read anchor specifically
552 * documents an E00 code for malformed requests or invalid annex.
553 * Non-zero codes indicate invalid offset or "error reading the data."
562 * A set of standardized transfers from "special data areas."
564 * We've already matched on "qXfer:" and advanced the rx packet buffer past
565 * that bit. Parse out the rest of the packet and generate an appropriate
571 if (!gdb_rx_equal("threads:"))
574 if (!gdb_rx_equal("read:"))
577 do_qXfer_threads_read();
586 gdb_handle_detach(void)
588 kdb_cpu_clear_singlestep();
591 if (gdb_cur->gdb_dbfeatures & GDB_DBGP_FEAT_WANTTERM)
595 if (!gdb_return_to_ddb)
598 gdb_return_to_ddb = false;
600 if (kdb_dbbe_select("ddb") != 0)
601 printf("The ddb backend could not be selected.\n");
606 gdb_trap(int type, int code)
609 struct thread *thr_iter;
611 uint32_t host_features;
613 prev_jb = kdb_jmpbuf(jb);
614 if (setjmp(jb) != 0) {
615 printf("%s bailing, hopefully back to ddb!\n", __func__);
617 (void)kdb_jmpbuf(prev_jb);
625 * Send a T packet. We currently do not support watchpoints (the
626 * awatch, rwatch or watch elements).
629 gdb_tx_hex(gdb_cpu_signal(type, code), 2);
630 gdb_tx_varhex(GDB_REG_PC);
632 gdb_tx_reg(GDB_REG_PC);
634 gdb_tx_str("thread:");
635 gdb_tx_varhex((long)kdb_thread->td_tid);
637 gdb_tx_end(); /* XXX check error condition. */
640 while (gdb_rx_begin() == 0) {
641 /* printf("GDB: got '%s'\n", gdb_rxp); */
642 switch (gdb_rx_char()) {
643 case '?': /* Last signal. */
645 gdb_tx_hex(gdb_cpu_signal(type, code), 2);
646 gdb_tx_str("thread:");
647 gdb_tx_varhex((long)kdb_thread->td_tid);
651 case 'c': { /* Continue. */
654 if (!gdb_rx_varhex(&addr)) {
656 gdb_cpu_setreg(GDB_REG_PC, &pc);
658 kdb_cpu_clear_singlestep();
662 case 'C': { /* Continue with signal. */
665 if (!gdb_rx_varhex(&sig) && gdb_rx_char() == ';' &&
666 !gdb_rx_varhex(&addr)) {
668 gdb_cpu_setreg(GDB_REG_PC, &pc);
670 kdb_cpu_clear_singlestep();
674 case 'D': { /* Detach */
679 case 'g': { /* Read registers. */
682 for (r = 0; r < GDB_NREGS; r++)
687 case 'G': /* Write registers. */
690 case 'H': { /* Set thread. */
694 /* Ignore 'g' (general) or 'c' (continue) flag. */
695 (void) gdb_rx_char();
697 if (gdb_rx_varhex(&tid)) {
702 thr = kdb_thr_lookup(tid);
712 case 'k': /* Kill request. */
715 case 'm': { /* Read memory. */
716 uintmax_t addr, size;
717 if (gdb_rx_varhex(&addr) || gdb_rx_char() != ',' ||
718 gdb_rx_varhex(&size)) {
723 if (gdb_tx_mem((char *)(uintptr_t)addr, size))
729 case 'M': { /* Write memory. */
730 uintmax_t addr, size;
731 if (gdb_rx_varhex(&addr) || gdb_rx_char() != ',' ||
732 gdb_rx_varhex(&size) || gdb_rx_char() != ':') {
736 if (gdb_rx_mem((char *)(uintptr_t)addr, size) == 0)
742 case 'P': { /* Write register. */
746 if (gdb_rx_varhex(®) || gdb_rx_char() != '=' ||
747 !gdb_rx_mem(val, gdb_cpu_regsz(reg))) {
751 gdb_cpu_setreg(reg, val);
755 case 'q': /* General query. */
756 if (gdb_rx_equal("C")) {
759 gdb_tx_varhex((long)kdb_thread->td_tid);
761 } else if (gdb_rx_equal("Supported")) {
762 gdb_do_qsupported(&host_features);
763 } else if (gdb_rx_equal("fThreadInfo")) {
764 thr_iter = kdb_thr_first();
765 gdb_do_threadinfo(&thr_iter);
766 } else if (gdb_rx_equal("sThreadInfo")) {
767 gdb_do_threadinfo(&thr_iter);
768 } else if (gdb_rx_equal("Xfer:")) {
770 } else if (gdb_rx_equal("Search:memory:")) {
773 } else if (gdb_rx_equal("Offsets")) {
774 gdb_cpu_do_offsets();
776 } else if (!gdb_cpu_query())
780 if (gdb_rx_equal("StartNoAckMode")) {
781 if ((gdb_cur->gdb_dbfeatures &
782 GDB_DBGP_FEAT_RELIABLE) == 0) {
784 * Shouldn't happen if we didn't
785 * advertise support. Reject.
795 case 's': { /* Step. */
798 if (!gdb_rx_varhex(&addr)) {
800 gdb_cpu_setreg(GDB_REG_PC, &pc);
802 kdb_cpu_set_singlestep();
806 case 'S': { /* Step with signal. */
809 if (!gdb_rx_varhex(&sig) && gdb_rx_char() == ';' &&
810 !gdb_rx_varhex(&addr)) {
812 gdb_cpu_setreg(GDB_REG_PC, &pc);
814 kdb_cpu_set_singlestep();
818 case 'T': { /* Thread alive. */
820 if (gdb_rx_varhex(&tid)) {
824 if (kdb_thr_lookup(tid) != NULL)
831 /* Empty command. Treat as unknown command. */
834 /* Unknown command. Send empty response. */
839 (void)kdb_jmpbuf(prev_jb);