xref: /freebsd/sys/gdb/gdb_main.c (revision ec4deee4e4f2aef1b97d9424f25d04e91fd7dc10)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2004 Marcel Moolenaar
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
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.
16  *
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.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/kdb.h>
35 #include <sys/kernel.h>
36 #include <sys/pcpu.h>
37 #include <sys/proc.h>
38 #include <sys/reboot.h>
39 #include <sys/sbuf.h>
40 
41 #include <machine/gdb_machdep.h>
42 #include <machine/kdb.h>
43 
44 #include <gdb/gdb.h>
45 #include <gdb/gdb_int.h>
46 
47 SYSCTL_NODE(_debug, OID_AUTO, gdb, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
48     "GDB settings");
49 
50 static dbbe_init_f gdb_init;
51 static dbbe_trap_f gdb_trap;
52 
53 KDB_BACKEND(gdb, gdb_init, NULL, NULL, gdb_trap);
54 
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);
58 
59 struct gdb_dbgport *gdb_cur = NULL;
60 int gdb_listening = 0;
61 bool gdb_ackmode = true;
62 
63 static unsigned char gdb_bindata[64];
64 
65 #ifdef DDB
66 bool gdb_return_to_ddb = false;
67 #endif
68 
69 static int
70 gdb_init(void)
71 {
72 	struct gdb_dbgport *dp, **iter;
73 	int cur_pri, pri;
74 
75 	gdb_cur = NULL;
76 	cur_pri = -1;
77 	SET_FOREACH(iter, gdb_dbgport_set) {
78 		dp = *iter;
79 		pri = (dp->gdb_probe != NULL) ? dp->gdb_probe() : -1;
80 		dp->gdb_active = (pri >= 0) ? 0 : -1;
81 		if (pri > cur_pri) {
82 			cur_pri = pri;
83 			gdb_cur = dp;
84 		}
85 	}
86 	if (gdb_cur != NULL) {
87 		printf("GDB: debug ports:");
88 		SET_FOREACH(iter, gdb_dbgport_set) {
89 			dp = *iter;
90 			if (dp->gdb_active == 0)
91 				printf(" %s", dp->gdb_name);
92 		}
93 		printf("\n");
94 	} else
95 		printf("GDB: no debug ports present\n");
96 	if (gdb_cur != NULL) {
97 		gdb_cur->gdb_init();
98 		printf("GDB: current port: %s\n", gdb_cur->gdb_name);
99 	}
100 	if (gdb_cur != NULL) {
101 		cur_pri = (boothowto & RB_GDB) ? 2 : 0;
102 		gdb_consinit();
103 	} else
104 		cur_pri = -1;
105 	return (cur_pri);
106 }
107 
108 static void
109 gdb_do_mem_search(void)
110 {
111 	size_t patlen;
112 	intmax_t addr, size;
113 	const unsigned char *found;
114 
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)) {
118 		gdb_tx_err(EINVAL);
119 		return;
120 	}
121 	if (gdb_search_mem((char *)(uintptr_t)addr, size, gdb_bindata,
122 	    patlen, &found)) {
123 		if (found == 0ULL)
124 			gdb_tx_begin('0');
125 		else {
126 			gdb_tx_begin('1');
127 			gdb_tx_char(',');
128 			gdb_tx_hex((intmax_t)(uintptr_t)found, 8);
129 		}
130 		gdb_tx_end();
131 	} else
132 		gdb_tx_err(EIO);
133 }
134 
135 static void
136 gdb_do_threadinfo(struct thread **thr_iter)
137 {
138 	static struct thread * const done_sentinel = (void *)(uintptr_t)1;
139 	static const size_t tidsz_hex = sizeof(lwpid_t) * 2;
140 	size_t tds_sent;
141 
142 	if (*thr_iter == NULL) {
143 		gdb_tx_err(ENXIO);
144 		return;
145 	}
146 
147 	if (*thr_iter == done_sentinel) {
148 		gdb_tx_begin('l');
149 		*thr_iter = NULL;
150 		goto sendit;
151 	}
152 
153 	gdb_tx_begin('m');
154 
155 	for (tds_sent = 0;
156 	    *thr_iter != NULL && gdb_txbuf_has_capacity(tidsz_hex + 1);
157 	    *thr_iter = kdb_thr_next(*thr_iter), tds_sent++) {
158 		if (tds_sent > 0)
159 			gdb_tx_char(',');
160 		gdb_tx_varhex((*thr_iter)->td_tid);
161 	}
162 
163 	/*
164 	 * Can't send EOF and "some" in same packet, so set a sentinel to send
165 	 * EOF when GDB asks us next.
166 	 */
167 	if (*thr_iter == NULL && tds_sent > 0)
168 		*thr_iter = done_sentinel;
169 
170 sendit:
171 	gdb_tx_end();
172 }
173 
174 #define	BIT(n)	(1ull << (n))
175 enum {
176 	GDB_MULTIPROCESS,
177 	GDB_SWBREAK,
178 	GDB_HWBREAK,
179 	GDB_QRELOCINSN,
180 	GDB_FORK_EVENTS,
181 	GDB_VFORK_EVENTS,
182 	GDB_EXEC_EVENTS,
183 	GDB_VCONT_SUPPORTED,
184 	GDB_QTHREADEVENTS,
185 	GDB_NO_RESUMED,
186 };
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",
198 };
199 static void
200 gdb_do_qsupported(uint32_t *feat)
201 {
202 	char *tok, *delim, ok;
203 	size_t i, toklen;
204 
205 	/* Parse supported host features */
206 	*feat = 0;
207 	if (gdb_rx_char() != ':')
208 		goto error;
209 
210 	while (gdb_rxsz > 0) {
211 		tok = gdb_rxp;
212 		delim = strchrnul(gdb_rxp, ';');
213 		toklen = (delim - tok);
214 
215 		gdb_rxp += toklen;
216 		gdb_rxsz -= toklen;
217 		if (*delim != '\0') {
218 			*delim = '\0';
219 			gdb_rxp += 1;
220 			gdb_rxsz -= 1;
221 		}
222 
223 		if (toklen < 2)
224 			goto error;
225 
226 		ok = tok[toklen - 1];
227 		if (ok != '-' && ok != '+') {
228 			/*
229 			 * GDB only has one KV-pair feature, and we don't
230 			 * support it, so ignore and move on.
231 			 */
232 			if (strchr(tok, '=') != NULL)
233 				continue;
234 			/* Not a KV-pair, and not a +/- flag?  Malformed. */
235 			goto error;
236 		}
237 		if (ok != '+')
238 			continue;
239 		tok[toklen - 1] = '\0';
240 
241 		for (i = 0; i < nitems(gdb_feature_names); i++)
242 			if (strcmp(gdb_feature_names[i], tok) == 0)
243 				break;
244 
245 		if (i == nitems(gdb_feature_names)) {
246 			/* Unknown GDB feature. */
247 			continue;
248 		}
249 
250 		*feat |= BIT(i);
251 	}
252 
253 	/* Send a supported feature list back */
254 	gdb_tx_begin(0);
255 
256 	gdb_tx_str("PacketSize");
257 	gdb_tx_char('=');
258 	/*
259 	 * We don't buffer framing bytes, but we do need to retain a byte for a
260 	 * trailing nul.
261 	 */
262 	gdb_tx_varhex(GDB_BUFSZ + strlen("$#nn") - 1);
263 
264 	gdb_tx_str(";qXfer:threads:read+");
265 
266 	/*
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
270 	 */
271 	if (gdb_cur->gdb_dbfeatures & GDB_DBGP_FEAT_RELIABLE)
272 		gdb_tx_str(";QStartNoAckMode+");
273 
274 	/*
275 	 * Future consideration:
276 	 *   - vCont
277 	 *   - multiprocess
278 	 */
279 	gdb_tx_end();
280 	return;
281 
282 error:
283 	*feat = 0;
284 	gdb_tx_err(EINVAL);
285 }
286 
287 /*
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.
292  *
293  * Upper layers are considered responsible for escaping the four forbidden
294  * characters '# $ } *'.
295  */
296 struct qXfer_context {
297 	struct sbuf sb;
298 	size_t last_offset;
299 	bool flushed;
300 	bool lastmessage;
301 	char xfer_buf[GDB_BUFSZ];
302 };
303 
304 static int
305 qXfer_drain(void *v, const char *buf, int len)
306 {
307 	struct qXfer_context *qx;
308 
309 	if (len < 0)
310 		return (-EINVAL);
311 
312 	qx = v;
313 	if (qx->flushed) {
314 		/*
315 		 * Overflow.  We lost some message.  Maybe the packet size is
316 		 * ridiculously small.
317 		 */
318 		printf("%s: Overflow in qXfer detected.\n", __func__);
319 		return (-ENOBUFS);
320 	}
321 
322 	qx->last_offset += len;
323 	qx->flushed = true;
324 
325 	if (qx->lastmessage)
326 		gdb_tx_begin('l');
327 	else
328 		gdb_tx_begin('m');
329 
330 	memcpy(gdb_txp, buf, len);
331 	gdb_txp += len;
332 
333 	gdb_tx_end();
334 	return (len);
335 }
336 
337 static int
338 init_qXfer_ctx(struct qXfer_context *qx, uintmax_t len)
339 {
340 
341 	/* Protocol (max) length field includes framing overhead. */
342 	if (len < sizeof("$m#nn"))
343 		return (ENOSPC);
344 
345 	len -= 4;
346 	len = ummin(len, GDB_BUFSZ - 1);
347 
348 	qx->last_offset = 0;
349 	qx->flushed = false;
350 	qx->lastmessage = false;
351 	sbuf_new(&qx->sb, qx->xfer_buf, len, SBUF_FIXEDLEN);
352 	sbuf_set_drain(&qx->sb, qXfer_drain, qx);
353 	return (0);
354 }
355 
356 /*
357  * dst must be 2x strlen(max_src) + 1.
358  *
359  * Squashes invalid XML characters down to _.  Sorry.  Then escapes for GDB.
360  */
361 static void
362 qXfer_escape_xmlattr_str(char *dst, size_t dstlen, const char *src)
363 {
364 	static const char *forbidden = "#$}*";
365 
366 	size_t i;
367 	char c;
368 
369 	for (i = 0; i < dstlen - 1 && *src != 0; src++, i++) {
370 		c = *src;
371 		/* XML attr filter */
372 		if (c < 32)
373 			c = '_';
374 		/* We assume attributes will be "" quoted. */
375 		if (c == '<' || c == '&' || c == '"')
376 			c = '_';
377 
378 		/* GDB escape. */
379 		if (strchr(forbidden, c) != NULL) {
380 			*dst++ = '}';
381 			c ^= 0x20;
382 		}
383 		*dst++ = c;
384 	}
385 	if (*src != 0)
386 		printf("XXX%s: overflow; API misuse\n", __func__);
387 
388 	*dst = 0;
389 }
390 
391 /*
392  * Dynamically generate qXfer:threads document, one packet at a time.
393  *
394  * The format is loosely described[0], although it does not seem that the
395  * <?xml?> mentioned on that page is required.
396  *
397  * [0]: https://sourceware.org/gdb/current/onlinedocs/gdb/Thread-List-Format.html
398  */
399 static void
400 do_qXfer_threads_read(void)
401 {
402 	/* Kludgy context */
403 	static struct {
404 		struct qXfer_context qXfer;
405 		/* Kludgy state machine */
406 		struct thread *iter;
407 		enum {
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>' */
415 		} next_step;
416 	} ctx;
417 	static char td_name_escape[MAXCOMLEN * 2 + 1];
418 
419 	const char *name_src;
420 	uintmax_t offset, len;
421 	int error;
422 
423 	/* Annex part must be empty. */
424 	if (gdb_rx_char() != ':')
425 		goto misformed_request;
426 
427 	if (gdb_rx_varhex(&offset) != 0 ||
428 	    gdb_rx_char() != ',' ||
429 	    gdb_rx_varhex(&len) != 0)
430 		goto misformed_request;
431 
432 	/*
433 	 * Validate resume xfers.
434 	 */
435 	if (offset != 0) {
436 		if (offset != ctx.qXfer.last_offset) {
437 			printf("%s: Resumed offset %ju != expected %zu\n",
438 			    __func__, offset, ctx.qXfer.last_offset);
439 			error = ESPIPE;
440 			goto request_error;
441 		}
442 		ctx.qXfer.flushed = false;
443 	}
444 
445 	if (offset == 0) {
446 		ctx.iter = kdb_thr_first();
447 		ctx.next_step = XML_START_THREAD;
448 		error = init_qXfer_ctx(&ctx.qXfer, len);
449 		if (error != 0)
450 			goto request_error;
451 
452 		sbuf_cat(&ctx.qXfer.sb, "<threads>");
453 	}
454 
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");
460 			continue;
461 
462 		case XML_THREAD_ID:
463 			ctx.next_step = XML_THREAD_CORE;
464 			sbuf_printf(&ctx.qXfer.sb, " id=\"%jx\"",
465 			    (uintmax_t)ctx.iter->td_tid);
466 			continue;
467 
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\"",
472 				    ctx.iter->td_oncpu);
473 			}
474 			continue;
475 
476 		case XML_THREAD_NAME:
477 			ctx.next_step = XML_THREAD_EXTRA;
478 
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;
484 			else
485 				continue;
486 
487 			qXfer_escape_xmlattr_str(td_name_escape,
488 			    sizeof(td_name_escape), name_src);
489 			sbuf_printf(&ctx.qXfer.sb, " name=\"%s\"",
490 			    td_name_escape);
491 			continue;
492 
493 		case XML_THREAD_EXTRA:
494 			ctx.next_step = XML_END_THREAD;
495 
496 			sbuf_putc(&ctx.qXfer.sb, '>');
497 
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");
514 			else
515 				sbuf_cat(&ctx.qXfer.sb, "???");
516 			continue;
517 
518 		case XML_END_THREAD:
519 			ctx.next_step = XML_START_THREAD;
520 			sbuf_cat(&ctx.qXfer.sb, "</thread>");
521 			ctx.iter = kdb_thr_next(ctx.iter);
522 			continue;
523 
524 		/*
525 		 * This one isn't part of the looping state machine,
526 		 * but GCC complains if you leave an enum value out of the
527 		 * select.
528 		 */
529 		case XML_SENT_END_THREADS:
530 			/* NOTREACHED */
531 			break;
532 		}
533 	}
534 	if (ctx.qXfer.flushed)
535 		return;
536 
537 	if (ctx.next_step != XML_SENT_END_THREADS) {
538 		ctx.next_step = XML_SENT_END_THREADS;
539 		sbuf_cat(&ctx.qXfer.sb, "</threads>");
540 	}
541 	if (ctx.qXfer.flushed)
542 		return;
543 
544 	ctx.qXfer.lastmessage = true;
545 	sbuf_finish(&ctx.qXfer.sb);
546 	sbuf_delete(&ctx.qXfer.sb);
547 	ctx.qXfer.last_offset = 0;
548 	return;
549 
550 misformed_request:
551 	/*
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."
555 	 */
556 	error = 0;
557 request_error:
558 	gdb_tx_err(error);
559 	return;
560 }
561 
562 /*
563  * A set of standardized transfers from "special data areas."
564  *
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
567  * response.
568  */
569 static void
570 do_qXfer(void)
571 {
572 	if (!gdb_rx_equal("threads:"))
573 		goto unrecognized;
574 
575 	if (!gdb_rx_equal("read:"))
576 		goto unrecognized;
577 
578 	do_qXfer_threads_read();
579 	return;
580 
581 unrecognized:
582 	gdb_tx_empty();
583 	return;
584 }
585 
586 static void
587 gdb_handle_detach(void)
588 {
589 	kdb_cpu_clear_singlestep();
590 	gdb_listening = 0;
591 
592 	if (gdb_cur->gdb_dbfeatures & GDB_DBGP_FEAT_WANTTERM)
593 		gdb_cur->gdb_term();
594 
595 #ifdef DDB
596 	if (!gdb_return_to_ddb)
597 		return;
598 
599 	gdb_return_to_ddb = false;
600 
601 	if (kdb_dbbe_select("ddb") != 0)
602 		printf("The ddb backend could not be selected.\n");
603 #endif
604 }
605 
606 static int
607 gdb_trap(int type, int code)
608 {
609 	jmp_buf jb;
610 	struct thread *thr_iter;
611 	void *prev_jb;
612 	uint32_t host_features;
613 
614 	prev_jb = kdb_jmpbuf(jb);
615 	if (setjmp(jb) != 0) {
616 		printf("%s bailing, hopefully back to ddb!\n", __func__);
617 		gdb_listening = 0;
618 		(void)kdb_jmpbuf(prev_jb);
619 		return (1);
620 	}
621 
622 	gdb_listening = 0;
623 	gdb_ackmode = true;
624 
625 	/*
626 	 * Send a T packet. We currently do not support watchpoints (the
627 	 * awatch, rwatch or watch elements).
628 	 */
629 	gdb_tx_begin('T');
630 	gdb_tx_hex(gdb_cpu_signal(type, code), 2);
631 	gdb_tx_varhex(GDB_REG_PC);
632 	gdb_tx_char(':');
633 	gdb_tx_reg(GDB_REG_PC);
634 	gdb_tx_char(';');
635 	gdb_tx_str("thread:");
636 	gdb_tx_varhex((long)kdb_thread->td_tid);
637 	gdb_tx_char(';');
638 	gdb_tx_end();			/* XXX check error condition. */
639 
640 	thr_iter = NULL;
641 	while (gdb_rx_begin() == 0) {
642 		/* printf("GDB: got '%s'\n", gdb_rxp); */
643 		switch (gdb_rx_char()) {
644 		case '?':	/* Last signal. */
645 			gdb_tx_begin('T');
646 			gdb_tx_hex(gdb_cpu_signal(type, code), 2);
647 			gdb_tx_str("thread:");
648 			gdb_tx_varhex((long)kdb_thread->td_tid);
649 			gdb_tx_char(';');
650 			gdb_tx_end();
651 			break;
652 		case 'c': {	/* Continue. */
653 			uintmax_t addr;
654 			register_t pc;
655 			if (!gdb_rx_varhex(&addr)) {
656 				pc = addr;
657 				gdb_cpu_setreg(GDB_REG_PC, &pc);
658 			}
659 			kdb_cpu_clear_singlestep();
660 			gdb_listening = 1;
661 			return (1);
662 		}
663 		case 'C': {	/* Continue with signal. */
664 			uintmax_t addr, sig;
665 			register_t pc;
666 			if (!gdb_rx_varhex(&sig) && gdb_rx_char() == ';' &&
667 			    !gdb_rx_varhex(&addr)) {
668 				pc = addr;
669 				gdb_cpu_setreg(GDB_REG_PC, &pc);
670 			}
671 			kdb_cpu_clear_singlestep();
672 			gdb_listening = 1;
673 			return (1);
674 		}
675 		case 'D': {     /* Detach */
676 			gdb_tx_ok();
677 			gdb_handle_detach();
678 			return (1);
679 		}
680 		case 'g': {	/* Read registers. */
681 			size_t r;
682 			gdb_tx_begin(0);
683 			for (r = 0; r < GDB_NREGS; r++)
684 				gdb_tx_reg(r);
685 			gdb_tx_end();
686 			break;
687 		}
688 		case 'G':	/* Write registers. */
689 			gdb_tx_err(0);
690 			break;
691 		case 'H': {	/* Set thread. */
692 			intmax_t tid;
693 			struct thread *thr;
694 
695 			/* Ignore 'g' (general) or 'c' (continue) flag. */
696 			(void) gdb_rx_char();
697 
698 			if (gdb_rx_varhex(&tid)) {
699 				gdb_tx_err(EINVAL);
700 				break;
701 			}
702 			if (tid > 0) {
703 				thr = kdb_thr_lookup(tid);
704 				if (thr == NULL) {
705 					gdb_tx_err(ENOENT);
706 					break;
707 				}
708 				kdb_thr_select(thr);
709 			}
710 			gdb_tx_ok();
711 			break;
712 		}
713 		case 'k':	/* Kill request. */
714 			gdb_handle_detach();
715 			return (1);
716 		case 'm': {	/* Read memory. */
717 			uintmax_t addr, size;
718 			if (gdb_rx_varhex(&addr) || gdb_rx_char() != ',' ||
719 			    gdb_rx_varhex(&size)) {
720 				gdb_tx_err(EINVAL);
721 				break;
722 			}
723 			gdb_tx_begin(0);
724 			if (gdb_tx_mem((char *)(uintptr_t)addr, size))
725 				gdb_tx_end();
726 			else
727 				gdb_tx_err(EIO);
728 			break;
729 		}
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() != ':') {
734 				gdb_tx_err(EINVAL);
735 				break;
736 			}
737 			if (gdb_rx_mem((char *)(uintptr_t)addr, size) == 0)
738 				gdb_tx_err(EIO);
739 			else
740 				gdb_tx_ok();
741 			break;
742 		}
743 		case 'P': {	/* Write register. */
744 			char *val;
745 			uintmax_t reg;
746 			val = gdb_rxp;
747 			if (gdb_rx_varhex(&reg) || gdb_rx_char() != '=' ||
748 			    !gdb_rx_mem(val, gdb_cpu_regsz(reg))) {
749 				gdb_tx_err(EINVAL);
750 				break;
751 			}
752 			gdb_cpu_setreg(reg, val);
753 			gdb_tx_ok();
754 			break;
755 		}
756 		case 'q':	/* General query. */
757 			if (gdb_rx_equal("C")) {
758 				gdb_tx_begin('Q');
759 				gdb_tx_char('C');
760 				gdb_tx_varhex((long)kdb_thread->td_tid);
761 				gdb_tx_end();
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:")) {
770 				do_qXfer();
771 			} else if (gdb_rx_equal("Search:memory:")) {
772 				gdb_do_mem_search();
773 #ifdef __powerpc__
774 			} else if (gdb_rx_equal("Offsets")) {
775 				gdb_cpu_do_offsets();
776 #endif
777 			} else if (!gdb_cpu_query())
778 				gdb_tx_empty();
779 			break;
780 		case 'Q':
781 			if (gdb_rx_equal("StartNoAckMode")) {
782 				if ((gdb_cur->gdb_dbfeatures &
783 				    GDB_DBGP_FEAT_RELIABLE) == 0) {
784 					/*
785 					 * Shouldn't happen if we didn't
786 					 * advertise support.  Reject.
787 					 */
788 					gdb_tx_empty();
789 					break;
790 				}
791 				gdb_ackmode = false;
792 				gdb_tx_ok();
793 			} else
794 				gdb_tx_empty();
795 			break;
796 		case 's': {	/* Step. */
797 			uintmax_t addr;
798 			register_t pc;
799 			if (!gdb_rx_varhex(&addr)) {
800 				pc = addr;
801 				gdb_cpu_setreg(GDB_REG_PC, &pc);
802 			}
803 			kdb_cpu_set_singlestep();
804 			gdb_listening = 1;
805 			return (1);
806 		}
807 		case 'S': {	/* Step with signal. */
808 			uintmax_t addr, sig;
809 			register_t pc;
810 			if (!gdb_rx_varhex(&sig) && gdb_rx_char() == ';' &&
811 			    !gdb_rx_varhex(&addr)) {
812 				pc = addr;
813 				gdb_cpu_setreg(GDB_REG_PC, &pc);
814 			}
815 			kdb_cpu_set_singlestep();
816 			gdb_listening = 1;
817 			return (1);
818 		}
819 		case 'T': {	/* Thread alive. */
820 			intmax_t tid;
821 			if (gdb_rx_varhex(&tid)) {
822 				gdb_tx_err(EINVAL);
823 				break;
824 			}
825 			if (kdb_thr_lookup(tid) != NULL)
826 				gdb_tx_ok();
827 			else
828 				gdb_tx_err(ENOENT);
829 			break;
830 		}
831 		case EOF:
832 			/* Empty command. Treat as unknown command. */
833 			/* FALLTHROUGH */
834 		default:
835 			/* Unknown command. Send empty response. */
836 			gdb_tx_empty();
837 			break;
838 		}
839 	}
840 	(void)kdb_jmpbuf(prev_jb);
841 	return (0);
842 }
843