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 | CTLFLAG_MPSAFE, 0,
50 static dbbe_init_f gdb_init;
51 static dbbe_trap_f gdb_trap;
53 KDB_BACKEND(gdb, gdb_init, NULL, NULL, gdb_trap);
55 static struct gdb_dbgport null_gdb_dbgport;
56 DATA_SET(gdb_dbgport_set, null_gdb_dbgport);
57 SET_DECLARE(gdb_dbgport_set, struct gdb_dbgport);
59 struct gdb_dbgport *gdb_cur = NULL;
60 int gdb_listening = 0;
61 bool gdb_ackmode = true;
63 static unsigned char gdb_bindata[64];
66 bool gdb_return_to_ddb = false;
72 struct gdb_dbgport *dp, **iter;
77 SET_FOREACH(iter, gdb_dbgport_set) {
79 pri = (dp->gdb_probe != NULL) ? dp->gdb_probe() : -1;
80 dp->gdb_active = (pri >= 0) ? 0 : -1;
86 if (gdb_cur != NULL) {
87 printf("GDB: debug ports:");
88 SET_FOREACH(iter, gdb_dbgport_set) {
90 if (dp->gdb_active == 0)
91 printf(" %s", dp->gdb_name);
95 printf("GDB: no debug ports present\n");
96 if (gdb_cur != NULL) {
98 printf("GDB: current port: %s\n", gdb_cur->gdb_name);
100 if (gdb_cur != NULL) {
101 cur_pri = (boothowto & RB_GDB) ? 2 : 0;
109 gdb_do_mem_search(void)
113 const unsigned char *found;
115 if (gdb_rx_varhex(&addr) || gdb_rx_char() != ';' ||
116 gdb_rx_varhex(&size) || gdb_rx_char() != ';' ||
117 gdb_rx_bindata(gdb_bindata, sizeof(gdb_bindata), &patlen)) {
121 if (gdb_search_mem((char *)(uintptr_t)addr, size, gdb_bindata,
128 gdb_tx_hex((intmax_t)(uintptr_t)found, 8);
136 gdb_do_threadinfo(struct thread **thr_iter)
138 static struct thread * const done_sentinel = (void *)(uintptr_t)1;
139 static const size_t tidsz_hex = sizeof(lwpid_t) * 2;
142 if (*thr_iter == NULL) {
147 if (*thr_iter == done_sentinel) {
156 *thr_iter != NULL && gdb_txbuf_has_capacity(tidsz_hex + 1);
157 *thr_iter = kdb_thr_next(*thr_iter), tds_sent++) {
160 gdb_tx_varhex((*thr_iter)->td_tid);
164 * Can't send EOF and "some" in same packet, so set a sentinel to send
165 * EOF when GDB asks us next.
167 if (*thr_iter == NULL && tds_sent > 0)
168 *thr_iter = done_sentinel;
174 #define BIT(n) (1ull << (n))
187 static const char * const gdb_feature_names[] = {
188 [GDB_MULTIPROCESS] = "multiprocess",
189 [GDB_SWBREAK] = "swbreak",
190 [GDB_HWBREAK] = "hwbreak",
191 [GDB_QRELOCINSN] = "qRelocInsn",
192 [GDB_FORK_EVENTS] = "fork-events",
193 [GDB_VFORK_EVENTS] = "vfork-events",
194 [GDB_EXEC_EVENTS] = "exec-events",
195 [GDB_VCONT_SUPPORTED] = "vContSupported",
196 [GDB_QTHREADEVENTS] = "QThreadEvents",
197 [GDB_NO_RESUMED] = "no-resumed",
200 gdb_do_qsupported(uint32_t *feat)
202 char *tok, *delim, ok;
205 /* Parse supported host features */
207 if (gdb_rx_char() != ':')
210 while (gdb_rxsz > 0) {
212 delim = strchrnul(gdb_rxp, ';');
213 toklen = (delim - tok);
217 if (*delim != '\0') {
226 ok = tok[toklen - 1];
227 if (ok != '-' && ok != '+') {
229 * GDB only has one KV-pair feature, and we don't
230 * support it, so ignore and move on.
232 if (strchr(tok, '=') != NULL)
234 /* Not a KV-pair, and not a +/- flag? Malformed. */
239 tok[toklen - 1] = '\0';
241 for (i = 0; i < nitems(gdb_feature_names); i++)
242 if (strcmp(gdb_feature_names[i], tok) == 0)
245 if (i == nitems(gdb_feature_names)) {
246 /* Unknown GDB feature. */
253 /* Send a supported feature list back */
256 gdb_tx_str("PacketSize");
259 * We don't buffer framing bytes, but we do need to retain a byte for a
262 gdb_tx_varhex(GDB_BUFSZ + strlen("$#nn") - 1);
264 gdb_tx_str(";qXfer:threads:read+");
267 * If the debugport is a reliable transport, request No Ack mode from
268 * the server. The server may or may not choose to enter No Ack mode.
269 * https://sourceware.org/gdb/onlinedocs/gdb/Packet-Acknowledgment.html
271 if (gdb_cur->gdb_dbfeatures & GDB_DBGP_FEAT_RELIABLE)
272 gdb_tx_str(";QStartNoAckMode+");
275 * Future consideration:
288 * A qXfer_context provides a vaguely generic way to generate a multi-packet
289 * response on the fly, making some assumptions about the size of sbuf writes
290 * vs actual packet length constraints. A non-byzantine gdb host should allow
291 * hundreds of bytes per packet or more.
293 * Upper layers are considered responsible for escaping the four forbidden
294 * characters '# $ } *'.
296 struct qXfer_context {
301 char xfer_buf[GDB_BUFSZ];
305 qXfer_drain(void *v, const char *buf, int len)
307 struct qXfer_context *qx;
315 * Overflow. We lost some message. Maybe the packet size is
316 * ridiculously small.
318 printf("%s: Overflow in qXfer detected.\n", __func__);
322 qx->last_offset += len;
330 memcpy(gdb_txp, buf, len);
338 init_qXfer_ctx(struct qXfer_context *qx, uintmax_t len)
341 /* Protocol (max) length field includes framing overhead. */
342 if (len < sizeof("$m#nn"))
346 len = ummin(len, GDB_BUFSZ - 1);
350 qx->lastmessage = false;
351 sbuf_new(&qx->sb, qx->xfer_buf, len, SBUF_FIXEDLEN);
352 sbuf_set_drain(&qx->sb, qXfer_drain, qx);
357 * dst must be 2x strlen(max_src) + 1.
359 * Squashes invalid XML characters down to _. Sorry. Then escapes for GDB.
362 qXfer_escape_xmlattr_str(char *dst, size_t dstlen, const char *src)
364 static const char *forbidden = "#$}*";
369 for (i = 0; i < dstlen - 1 && *src != 0; src++, i++) {
371 /* XML attr filter */
374 /* We assume attributes will be "" quoted. */
375 if (c == '<' || c == '&' || c == '"')
379 if (strchr(forbidden, c) != NULL) {
386 printf("XXX%s: overflow; API misuse\n", __func__);
392 * Dynamically generate qXfer:threads document, one packet at a time.
394 * The format is loosely described[0], although it does not seem that the
395 * <?xml?> mentioned on that page is required.
397 * [0]: https://sourceware.org/gdb/current/onlinedocs/gdb/Thread-List-Format.html
400 do_qXfer_threads_read(void)
404 struct qXfer_context qXfer;
405 /* Kludgy state machine */
408 XML_START_THREAD, /* '<thread' */
409 XML_THREAD_ID, /* ' id="xxx"' */
410 XML_THREAD_CORE, /* ' core="yyy"' */
411 XML_THREAD_NAME, /* ' name="zzz"' */
412 XML_THREAD_EXTRA, /* '> ...' */
413 XML_END_THREAD, /* '</thread>' */
414 XML_SENT_END_THREADS, /* '</threads>' */
417 static char td_name_escape[MAXCOMLEN * 2 + 1];
419 const char *name_src;
420 uintmax_t offset, len;
423 /* Annex part must be empty. */
424 if (gdb_rx_char() != ':')
425 goto misformed_request;
427 if (gdb_rx_varhex(&offset) != 0 ||
428 gdb_rx_char() != ',' ||
429 gdb_rx_varhex(&len) != 0)
430 goto misformed_request;
433 * Validate resume xfers.
436 if (offset != ctx.qXfer.last_offset) {
437 printf("%s: Resumed offset %ju != expected %zu\n",
438 __func__, offset, ctx.qXfer.last_offset);
442 ctx.qXfer.flushed = false;
446 ctx.iter = kdb_thr_first();
447 ctx.next_step = XML_START_THREAD;
448 error = init_qXfer_ctx(&ctx.qXfer, len);
452 sbuf_cat(&ctx.qXfer.sb, "<threads>");
455 while (!ctx.qXfer.flushed && ctx.iter != NULL) {
456 switch (ctx.next_step) {
457 case XML_START_THREAD:
458 ctx.next_step = XML_THREAD_ID;
459 sbuf_cat(&ctx.qXfer.sb, "<thread");
463 ctx.next_step = XML_THREAD_CORE;
464 sbuf_printf(&ctx.qXfer.sb, " id=\"%jx\"",
465 (uintmax_t)ctx.iter->td_tid);
468 case XML_THREAD_CORE:
469 ctx.next_step = XML_THREAD_NAME;
470 if (ctx.iter->td_oncpu != NOCPU) {
471 sbuf_printf(&ctx.qXfer.sb, " core=\"%d\"",
476 case XML_THREAD_NAME:
477 ctx.next_step = XML_THREAD_EXTRA;
479 if (ctx.iter->td_name[0] != 0)
480 name_src = ctx.iter->td_name;
481 else if (ctx.iter->td_proc != NULL &&
482 ctx.iter->td_proc->p_comm[0] != 0)
483 name_src = ctx.iter->td_proc->p_comm;
487 qXfer_escape_xmlattr_str(td_name_escape,
488 sizeof(td_name_escape), name_src);
489 sbuf_printf(&ctx.qXfer.sb, " name=\"%s\"",
493 case XML_THREAD_EXTRA:
494 ctx.next_step = XML_END_THREAD;
496 sbuf_putc(&ctx.qXfer.sb, '>');
498 if (ctx.iter->td_state == TDS_RUNNING)
499 sbuf_cat(&ctx.qXfer.sb, "Running");
500 else if (ctx.iter->td_state == TDS_RUNQ)
501 sbuf_cat(&ctx.qXfer.sb, "RunQ");
502 else if (ctx.iter->td_state == TDS_CAN_RUN)
503 sbuf_cat(&ctx.qXfer.sb, "CanRun");
504 else if (TD_ON_LOCK(ctx.iter))
505 sbuf_cat(&ctx.qXfer.sb, "Blocked");
506 else if (TD_IS_SLEEPING(ctx.iter))
507 sbuf_cat(&ctx.qXfer.sb, "Sleeping");
508 else if (TD_IS_SWAPPED(ctx.iter))
509 sbuf_cat(&ctx.qXfer.sb, "Swapped");
510 else if (TD_AWAITING_INTR(ctx.iter))
511 sbuf_cat(&ctx.qXfer.sb, "IthreadWait");
512 else if (TD_IS_SUSPENDED(ctx.iter))
513 sbuf_cat(&ctx.qXfer.sb, "Suspended");
515 sbuf_cat(&ctx.qXfer.sb, "???");
519 ctx.next_step = XML_START_THREAD;
520 sbuf_cat(&ctx.qXfer.sb, "</thread>");
521 ctx.iter = kdb_thr_next(ctx.iter);
525 * This one isn't part of the looping state machine,
526 * but GCC complains if you leave an enum value out of the
529 case XML_SENT_END_THREADS:
534 if (ctx.qXfer.flushed)
537 if (ctx.next_step != XML_SENT_END_THREADS) {
538 ctx.next_step = XML_SENT_END_THREADS;
539 sbuf_cat(&ctx.qXfer.sb, "</threads>");
541 if (ctx.qXfer.flushed)
544 ctx.qXfer.lastmessage = true;
545 sbuf_finish(&ctx.qXfer.sb);
546 sbuf_delete(&ctx.qXfer.sb);
547 ctx.qXfer.last_offset = 0;
552 * GDB "General-Query-Packets.html" qXfer-read anchor specifically
553 * documents an E00 code for malformed requests or invalid annex.
554 * Non-zero codes indicate invalid offset or "error reading the data."
563 * A set of standardized transfers from "special data areas."
565 * We've already matched on "qXfer:" and advanced the rx packet buffer past
566 * that bit. Parse out the rest of the packet and generate an appropriate
572 if (!gdb_rx_equal("threads:"))
575 if (!gdb_rx_equal("read:"))
578 do_qXfer_threads_read();
587 gdb_handle_detach(void)
589 kdb_cpu_clear_singlestep();
592 if (gdb_cur->gdb_dbfeatures & GDB_DBGP_FEAT_WANTTERM)
596 if (!gdb_return_to_ddb)
599 gdb_return_to_ddb = false;
601 if (kdb_dbbe_select("ddb") != 0)
602 printf("The ddb backend could not be selected.\n");
607 gdb_trap(int type, int code)
610 struct thread *thr_iter;
612 uint32_t host_features;
614 prev_jb = kdb_jmpbuf(jb);
615 if (setjmp(jb) != 0) {
616 printf("%s bailing, hopefully back to ddb!\n", __func__);
618 (void)kdb_jmpbuf(prev_jb);
626 * Send a T packet. We currently do not support watchpoints (the
627 * awatch, rwatch or watch elements).
630 gdb_tx_hex(gdb_cpu_signal(type, code), 2);
631 gdb_tx_varhex(GDB_REG_PC);
633 gdb_tx_reg(GDB_REG_PC);
635 gdb_tx_str("thread:");
636 gdb_tx_varhex((long)kdb_thread->td_tid);
638 gdb_tx_end(); /* XXX check error condition. */
641 while (gdb_rx_begin() == 0) {
642 /* printf("GDB: got '%s'\n", gdb_rxp); */
643 switch (gdb_rx_char()) {
644 case '?': /* Last signal. */
646 gdb_tx_hex(gdb_cpu_signal(type, code), 2);
647 gdb_tx_str("thread:");
648 gdb_tx_varhex((long)kdb_thread->td_tid);
652 case 'c': { /* Continue. */
655 if (!gdb_rx_varhex(&addr)) {
657 gdb_cpu_setreg(GDB_REG_PC, &pc);
659 kdb_cpu_clear_singlestep();
663 case 'C': { /* Continue with signal. */
666 if (!gdb_rx_varhex(&sig) && gdb_rx_char() == ';' &&
667 !gdb_rx_varhex(&addr)) {
669 gdb_cpu_setreg(GDB_REG_PC, &pc);
671 kdb_cpu_clear_singlestep();
675 case 'D': { /* Detach */
680 case 'g': { /* Read registers. */
683 for (r = 0; r < GDB_NREGS; r++)
688 case 'G': /* Write registers. */
691 case 'H': { /* Set thread. */
695 /* Ignore 'g' (general) or 'c' (continue) flag. */
696 (void) gdb_rx_char();
698 if (gdb_rx_varhex(&tid)) {
703 thr = kdb_thr_lookup(tid);
713 case 'k': /* Kill request. */
716 case 'm': { /* Read memory. */
717 uintmax_t addr, size;
718 if (gdb_rx_varhex(&addr) || gdb_rx_char() != ',' ||
719 gdb_rx_varhex(&size)) {
724 if (gdb_tx_mem((char *)(uintptr_t)addr, size))
730 case 'M': { /* Write memory. */
731 uintmax_t addr, size;
732 if (gdb_rx_varhex(&addr) || gdb_rx_char() != ',' ||
733 gdb_rx_varhex(&size) || gdb_rx_char() != ':') {
737 if (gdb_rx_mem((char *)(uintptr_t)addr, size) == 0)
743 case 'P': { /* Write register. */
747 if (gdb_rx_varhex(®) || gdb_rx_char() != '=' ||
748 !gdb_rx_mem(val, gdb_cpu_regsz(reg))) {
752 gdb_cpu_setreg(reg, val);
756 case 'q': /* General query. */
757 if (gdb_rx_equal("C")) {
760 gdb_tx_varhex((long)kdb_thread->td_tid);
762 } else if (gdb_rx_equal("Supported")) {
763 gdb_do_qsupported(&host_features);
764 } else if (gdb_rx_equal("fThreadInfo")) {
765 thr_iter = kdb_thr_first();
766 gdb_do_threadinfo(&thr_iter);
767 } else if (gdb_rx_equal("sThreadInfo")) {
768 gdb_do_threadinfo(&thr_iter);
769 } else if (gdb_rx_equal("Xfer:")) {
771 } else if (gdb_rx_equal("Search:memory:")) {
774 } else if (gdb_rx_equal("Offsets")) {
775 gdb_cpu_do_offsets();
777 } else if (!gdb_cpu_query())
781 if (gdb_rx_equal("StartNoAckMode")) {
782 if ((gdb_cur->gdb_dbfeatures &
783 GDB_DBGP_FEAT_RELIABLE) == 0) {
785 * Shouldn't happen if we didn't
786 * advertise support. Reject.
796 case 's': { /* Step. */
799 if (!gdb_rx_varhex(&addr)) {
801 gdb_cpu_setreg(GDB_REG_PC, &pc);
803 kdb_cpu_set_singlestep();
807 case 'S': { /* Step with signal. */
810 if (!gdb_rx_varhex(&sig) && gdb_rx_char() == ';' &&
811 !gdb_rx_varhex(&addr)) {
813 gdb_cpu_setreg(GDB_REG_PC, &pc);
815 kdb_cpu_set_singlestep();
819 case 'T': { /* Thread alive. */
821 if (gdb_rx_varhex(&tid)) {
825 if (kdb_thr_lookup(tid) != NULL)
832 /* Empty command. Treat as unknown command. */
835 /* Unknown command. Send empty response. */
840 (void)kdb_jmpbuf(prev_jb);