xref: /freebsd/sys/gdb/gdb_main.c (revision d0b2dbfa)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
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 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/kdb.h>
33 #include <sys/kernel.h>
34 #include <sys/pcpu.h>
35 #include <sys/proc.h>
36 #include <sys/reboot.h>
37 #include <sys/sbuf.h>
38 
39 #include <machine/gdb_machdep.h>
40 #include <machine/kdb.h>
41 
42 #include <gdb/gdb.h>
43 #include <gdb/gdb_int.h>
44 
45 SYSCTL_NODE(_debug, OID_AUTO, gdb, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
46     "GDB settings");
47 
48 static dbbe_init_f gdb_init;
49 static dbbe_trap_f gdb_trap;
50 
51 KDB_BACKEND(gdb, gdb_init, NULL, NULL, gdb_trap);
52 
53 static struct gdb_dbgport null_gdb_dbgport;
54 DATA_SET(gdb_dbgport_set, null_gdb_dbgport);
55 SET_DECLARE(gdb_dbgport_set, struct gdb_dbgport);
56 
57 struct gdb_dbgport *gdb_cur = NULL;
58 int gdb_listening = 0;
59 bool gdb_ackmode = true;
60 
61 static unsigned char gdb_bindata[64];
62 
63 #ifdef DDB
64 bool gdb_return_to_ddb = false;
65 #endif
66 
67 static int
68 gdb_init(void)
69 {
70 	struct gdb_dbgport *dp, **iter;
71 	int cur_pri, pri;
72 
73 	gdb_cur = NULL;
74 	cur_pri = -1;
75 	SET_FOREACH(iter, gdb_dbgport_set) {
76 		dp = *iter;
77 		pri = (dp->gdb_probe != NULL) ? dp->gdb_probe() : -1;
78 		dp->gdb_active = (pri >= 0) ? 0 : -1;
79 		if (pri > cur_pri) {
80 			cur_pri = pri;
81 			gdb_cur = dp;
82 		}
83 	}
84 	if (gdb_cur != NULL) {
85 		printf("GDB: debug ports:");
86 		SET_FOREACH(iter, gdb_dbgport_set) {
87 			dp = *iter;
88 			if (dp->gdb_active == 0)
89 				printf(" %s", dp->gdb_name);
90 		}
91 		printf("\n");
92 	} else
93 		printf("GDB: no debug ports present\n");
94 	if (gdb_cur != NULL) {
95 		gdb_cur->gdb_init();
96 		printf("GDB: current port: %s\n", gdb_cur->gdb_name);
97 	}
98 	if (gdb_cur != NULL) {
99 		cur_pri = (boothowto & RB_GDB) ? 2 : 0;
100 		gdb_consinit();
101 	} else
102 		cur_pri = -1;
103 	return (cur_pri);
104 }
105 
106 static void
107 gdb_do_mem_search(void)
108 {
109 	size_t patlen;
110 	intmax_t addr, size;
111 	const unsigned char *found;
112 
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)) {
116 		gdb_tx_err(EINVAL);
117 		return;
118 	}
119 	if (gdb_search_mem((char *)(uintptr_t)addr, size, gdb_bindata,
120 	    patlen, &found)) {
121 		if (found == 0ULL)
122 			gdb_tx_begin('0');
123 		else {
124 			gdb_tx_begin('1');
125 			gdb_tx_char(',');
126 			gdb_tx_hex((intmax_t)(uintptr_t)found, 8);
127 		}
128 		gdb_tx_end();
129 	} else
130 		gdb_tx_err(EIO);
131 }
132 
133 static void
134 gdb_do_threadinfo(struct thread **thr_iter)
135 {
136 	static struct thread * const done_sentinel = (void *)(uintptr_t)1;
137 	static const size_t tidsz_hex = sizeof(lwpid_t) * 2;
138 	size_t tds_sent;
139 
140 	if (*thr_iter == NULL) {
141 		gdb_tx_err(ENXIO);
142 		return;
143 	}
144 
145 	if (*thr_iter == done_sentinel) {
146 		gdb_tx_begin('l');
147 		*thr_iter = NULL;
148 		goto sendit;
149 	}
150 
151 	gdb_tx_begin('m');
152 
153 	for (tds_sent = 0;
154 	    *thr_iter != NULL && gdb_txbuf_has_capacity(tidsz_hex + 1);
155 	    *thr_iter = kdb_thr_next(*thr_iter), tds_sent++) {
156 		if (tds_sent > 0)
157 			gdb_tx_char(',');
158 		gdb_tx_varhex((*thr_iter)->td_tid);
159 	}
160 
161 	/*
162 	 * Can't send EOF and "some" in same packet, so set a sentinel to send
163 	 * EOF when GDB asks us next.
164 	 */
165 	if (*thr_iter == NULL && tds_sent > 0)
166 		*thr_iter = done_sentinel;
167 
168 sendit:
169 	gdb_tx_end();
170 }
171 
172 #define	BIT(n)	(1ull << (n))
173 enum {
174 	GDB_MULTIPROCESS,
175 	GDB_SWBREAK,
176 	GDB_HWBREAK,
177 	GDB_QRELOCINSN,
178 	GDB_FORK_EVENTS,
179 	GDB_VFORK_EVENTS,
180 	GDB_EXEC_EVENTS,
181 	GDB_VCONT_SUPPORTED,
182 	GDB_QTHREADEVENTS,
183 	GDB_NO_RESUMED,
184 };
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",
196 };
197 static void
198 gdb_do_qsupported(uint32_t *feat)
199 {
200 	char *tok, *delim, ok;
201 	size_t i, toklen;
202 
203 	/* Parse supported host features */
204 	*feat = 0;
205 	switch (gdb_rx_char()) {
206 	case ':':
207 		break;
208 	case EOF:
209 		goto nofeatures;
210 	default:
211 		goto error;
212 	}
213 
214 	while (gdb_rxsz > 0) {
215 		tok = gdb_rxp;
216 		delim = strchrnul(gdb_rxp, ';');
217 		toklen = (delim - tok);
218 
219 		gdb_rxp += toklen;
220 		gdb_rxsz -= toklen;
221 		if (*delim != '\0') {
222 			*delim = '\0';
223 			gdb_rxp += 1;
224 			gdb_rxsz -= 1;
225 		}
226 
227 		if (toklen < 2)
228 			goto error;
229 
230 		ok = tok[toklen - 1];
231 		if (ok != '-' && ok != '+') {
232 			/*
233 			 * GDB only has one KV-pair feature, and we don't
234 			 * support it, so ignore and move on.
235 			 */
236 			if (strchr(tok, '=') != NULL)
237 				continue;
238 			/* Not a KV-pair, and not a +/- flag?  Malformed. */
239 			goto error;
240 		}
241 		if (ok != '+')
242 			continue;
243 		tok[toklen - 1] = '\0';
244 
245 		for (i = 0; i < nitems(gdb_feature_names); i++)
246 			if (strcmp(gdb_feature_names[i], tok) == 0)
247 				break;
248 
249 		if (i == nitems(gdb_feature_names)) {
250 			/* Unknown GDB feature. */
251 			continue;
252 		}
253 
254 		*feat |= BIT(i);
255 	}
256 
257 nofeatures:
258 	/* Send a supported feature list back */
259 	gdb_tx_begin(0);
260 
261 	gdb_tx_str("PacketSize");
262 	gdb_tx_char('=');
263 	/*
264 	 * We don't buffer framing bytes, but we do need to retain a byte for a
265 	 * trailing nul.
266 	 */
267 	gdb_tx_varhex(GDB_BUFSZ + strlen("$#nn") - 1);
268 
269 	gdb_tx_str(";qXfer:threads:read+");
270 
271 	/*
272 	 * If the debugport is a reliable transport, request No Ack mode from
273 	 * the server.  The server may or may not choose to enter No Ack mode.
274 	 * https://sourceware.org/gdb/onlinedocs/gdb/Packet-Acknowledgment.html
275 	 */
276 	if (gdb_cur->gdb_dbfeatures & GDB_DBGP_FEAT_RELIABLE)
277 		gdb_tx_str(";QStartNoAckMode+");
278 
279 	/*
280 	 * Future consideration:
281 	 *   - vCont
282 	 *   - multiprocess
283 	 */
284 	gdb_tx_end();
285 	return;
286 
287 error:
288 	*feat = 0;
289 	gdb_tx_err(EINVAL);
290 }
291 
292 /*
293  * A qXfer_context provides a vaguely generic way to generate a multi-packet
294  * response on the fly, making some assumptions about the size of sbuf writes
295  * vs actual packet length constraints.  A non-byzantine gdb host should allow
296  * hundreds of bytes per packet or more.
297  *
298  * Upper layers are considered responsible for escaping the four forbidden
299  * characters '# $ } *'.
300  */
301 struct qXfer_context {
302 	struct sbuf sb;
303 	size_t last_offset;
304 	bool flushed;
305 	bool lastmessage;
306 	char xfer_buf[GDB_BUFSZ];
307 };
308 
309 static int
310 qXfer_drain(void *v, const char *buf, int len)
311 {
312 	struct qXfer_context *qx;
313 
314 	if (len < 0)
315 		return (-EINVAL);
316 
317 	qx = v;
318 	if (qx->flushed) {
319 		/*
320 		 * Overflow.  We lost some message.  Maybe the packet size is
321 		 * ridiculously small.
322 		 */
323 		printf("%s: Overflow in qXfer detected.\n", __func__);
324 		return (-ENOBUFS);
325 	}
326 
327 	qx->last_offset += len;
328 	qx->flushed = true;
329 
330 	if (qx->lastmessage)
331 		gdb_tx_begin('l');
332 	else
333 		gdb_tx_begin('m');
334 
335 	memcpy(gdb_txp, buf, len);
336 	gdb_txp += len;
337 
338 	gdb_tx_end();
339 	return (len);
340 }
341 
342 static int
343 init_qXfer_ctx(struct qXfer_context *qx, uintmax_t len)
344 {
345 
346 	/* Protocol (max) length field includes framing overhead. */
347 	if (len < sizeof("$m#nn"))
348 		return (ENOSPC);
349 
350 	len -= 4;
351 	len = ummin(len, GDB_BUFSZ - 1);
352 
353 	qx->last_offset = 0;
354 	qx->flushed = false;
355 	qx->lastmessage = false;
356 	sbuf_new(&qx->sb, qx->xfer_buf, len, SBUF_FIXEDLEN);
357 	sbuf_set_drain(&qx->sb, qXfer_drain, qx);
358 	return (0);
359 }
360 
361 /*
362  * Squashes special XML and GDB characters down to _.  Sorry.
363  */
364 static void
365 qXfer_escape_xmlattr_str(char *dst, size_t dstlen, const char *src)
366 {
367 	static const char *forbidden = "#$}*";
368 
369 	size_t i;
370 	char c;
371 
372 	for (i = 0; i < dstlen - 1 && *src != 0; src++, i++) {
373 		c = *src;
374 		/* XML attr filter */
375 		if (c < 32)
376 			c = '_';
377 		/* We assume attributes will be "" quoted. */
378 		if (c == '<' || c == '&' || c == '"')
379 			c = '_';
380 
381 		/* GDB escape. */
382 		if (strchr(forbidden, c) != NULL) {
383 			/*
384 			 * It would be nice to escape these properly, but to do
385 			 * it correctly we need to escape them in the transmit
386 			 * layer, potentially doubling our buffer requirements.
387 			 * For now, avoid breaking the protocol by squashing
388 			 * them to underscore.
389 			 */
390 #if 0
391 			*dst++ = '}';
392 			c ^= 0x20;
393 #endif
394 			c = '_';
395 		}
396 		*dst++ = c;
397 	}
398 	if (*src != 0)
399 		printf("XXX%s: overflow; API misuse\n", __func__);
400 
401 	*dst = 0;
402 }
403 
404 /*
405  * Dynamically generate qXfer:threads document, one packet at a time.
406  *
407  * The format is loosely described[0], although it does not seem that the
408  * <?xml?> mentioned on that page is required.
409  *
410  * [0]: https://sourceware.org/gdb/current/onlinedocs/gdb/Thread-List-Format.html
411  */
412 static void
413 do_qXfer_threads_read(void)
414 {
415 	/* Kludgy context */
416 	static struct {
417 		struct qXfer_context qXfer;
418 		/* Kludgy state machine */
419 		struct thread *iter;
420 		enum {
421 			XML_START_THREAD,	/* '<thread' */
422 			XML_THREAD_ID,		/* ' id="xxx"' */
423 			XML_THREAD_CORE,	/* ' core="yyy"' */
424 			XML_THREAD_NAME,	/* ' name="zzz"' */
425 			XML_THREAD_EXTRA,	/* '> ...' */
426 			XML_END_THREAD,		/* '</thread>' */
427 			XML_SENT_END_THREADS,	/* '</threads>' */
428 		} next_step;
429 	} ctx;
430 	static char td_name_escape[MAXCOMLEN * 2 + 1];
431 
432 	const char *name_src;
433 	uintmax_t offset, len;
434 	int error;
435 
436 	/* Annex part must be empty. */
437 	if (gdb_rx_char() != ':')
438 		goto misformed_request;
439 
440 	if (gdb_rx_varhex(&offset) != 0 ||
441 	    gdb_rx_char() != ',' ||
442 	    gdb_rx_varhex(&len) != 0)
443 		goto misformed_request;
444 
445 	/*
446 	 * Validate resume xfers.
447 	 */
448 	if (offset != 0) {
449 		if (offset != ctx.qXfer.last_offset) {
450 			printf("%s: Resumed offset %ju != expected %zu\n",
451 			    __func__, offset, ctx.qXfer.last_offset);
452 			error = ESPIPE;
453 			goto request_error;
454 		}
455 		ctx.qXfer.flushed = false;
456 	}
457 
458 	if (offset == 0) {
459 		ctx.iter = kdb_thr_first();
460 		ctx.next_step = XML_START_THREAD;
461 		error = init_qXfer_ctx(&ctx.qXfer, len);
462 		if (error != 0)
463 			goto request_error;
464 
465 		sbuf_cat(&ctx.qXfer.sb, "<threads>");
466 	}
467 
468 	while (!ctx.qXfer.flushed && ctx.iter != NULL) {
469 		switch (ctx.next_step) {
470 		case XML_START_THREAD:
471 			ctx.next_step = XML_THREAD_ID;
472 			sbuf_cat(&ctx.qXfer.sb, "<thread");
473 			continue;
474 
475 		case XML_THREAD_ID:
476 			ctx.next_step = XML_THREAD_CORE;
477 			sbuf_printf(&ctx.qXfer.sb, " id=\"%jx\"",
478 			    (uintmax_t)ctx.iter->td_tid);
479 			continue;
480 
481 		case XML_THREAD_CORE:
482 			ctx.next_step = XML_THREAD_NAME;
483 			if (ctx.iter->td_oncpu != NOCPU) {
484 				sbuf_printf(&ctx.qXfer.sb, " core=\"%d\"",
485 				    ctx.iter->td_oncpu);
486 			}
487 			continue;
488 
489 		case XML_THREAD_NAME:
490 			ctx.next_step = XML_THREAD_EXTRA;
491 
492 			if (ctx.iter->td_name[0] != 0)
493 				name_src = ctx.iter->td_name;
494 			else if (ctx.iter->td_proc != NULL &&
495 			    ctx.iter->td_proc->p_comm[0] != 0)
496 				name_src = ctx.iter->td_proc->p_comm;
497 			else
498 				continue;
499 
500 			qXfer_escape_xmlattr_str(td_name_escape,
501 			    sizeof(td_name_escape), name_src);
502 			sbuf_printf(&ctx.qXfer.sb, " name=\"%s\"",
503 			    td_name_escape);
504 			continue;
505 
506 		case XML_THREAD_EXTRA:
507 			ctx.next_step = XML_END_THREAD;
508 
509 			sbuf_putc(&ctx.qXfer.sb, '>');
510 
511 			if (TD_GET_STATE(ctx.iter) == TDS_RUNNING)
512 				sbuf_cat(&ctx.qXfer.sb, "Running");
513 			else if (TD_GET_STATE(ctx.iter) == TDS_RUNQ)
514 				sbuf_cat(&ctx.qXfer.sb, "RunQ");
515 			else if (TD_GET_STATE(ctx.iter) == TDS_CAN_RUN)
516 				sbuf_cat(&ctx.qXfer.sb, "CanRun");
517 			else if (TD_ON_LOCK(ctx.iter))
518 				sbuf_cat(&ctx.qXfer.sb, "Blocked");
519 			else if (TD_IS_SLEEPING(ctx.iter))
520 				sbuf_cat(&ctx.qXfer.sb, "Sleeping");
521 			else if (TD_IS_SWAPPED(ctx.iter))
522 				sbuf_cat(&ctx.qXfer.sb, "Swapped");
523 			else if (TD_AWAITING_INTR(ctx.iter))
524 				sbuf_cat(&ctx.qXfer.sb, "IthreadWait");
525 			else if (TD_IS_SUSPENDED(ctx.iter))
526 				sbuf_cat(&ctx.qXfer.sb, "Suspended");
527 			else
528 				sbuf_cat(&ctx.qXfer.sb, "???");
529 			continue;
530 
531 		case XML_END_THREAD:
532 			ctx.next_step = XML_START_THREAD;
533 			sbuf_cat(&ctx.qXfer.sb, "</thread>");
534 			ctx.iter = kdb_thr_next(ctx.iter);
535 			continue;
536 
537 		/*
538 		 * This one isn't part of the looping state machine,
539 		 * but GCC complains if you leave an enum value out of the
540 		 * select.
541 		 */
542 		case XML_SENT_END_THREADS:
543 			/* NOTREACHED */
544 			break;
545 		}
546 	}
547 	if (ctx.qXfer.flushed)
548 		return;
549 
550 	if (ctx.next_step != XML_SENT_END_THREADS) {
551 		ctx.next_step = XML_SENT_END_THREADS;
552 		sbuf_cat(&ctx.qXfer.sb, "</threads>");
553 	}
554 	if (ctx.qXfer.flushed)
555 		return;
556 
557 	ctx.qXfer.lastmessage = true;
558 	sbuf_finish(&ctx.qXfer.sb);
559 	sbuf_delete(&ctx.qXfer.sb);
560 	ctx.qXfer.last_offset = 0;
561 	return;
562 
563 misformed_request:
564 	/*
565 	 * GDB "General-Query-Packets.html" qXfer-read anchor specifically
566 	 * documents an E00 code for malformed requests or invalid annex.
567 	 * Non-zero codes indicate invalid offset or "error reading the data."
568 	 */
569 	error = 0;
570 request_error:
571 	gdb_tx_err(error);
572 	return;
573 }
574 
575 /*
576  * A set of standardized transfers from "special data areas."
577  *
578  * We've already matched on "qXfer:" and advanced the rx packet buffer past
579  * that bit.  Parse out the rest of the packet and generate an appropriate
580  * response.
581  */
582 static void
583 do_qXfer(void)
584 {
585 	if (!gdb_rx_equal("threads:"))
586 		goto unrecognized;
587 
588 	if (!gdb_rx_equal("read:"))
589 		goto unrecognized;
590 
591 	do_qXfer_threads_read();
592 	return;
593 
594 unrecognized:
595 	gdb_tx_empty();
596 	return;
597 }
598 
599 static void
600 gdb_handle_detach(void)
601 {
602 	kdb_cpu_clear_singlestep();
603 	gdb_listening = 0;
604 
605 	if (gdb_cur->gdb_dbfeatures & GDB_DBGP_FEAT_WANTTERM)
606 		gdb_cur->gdb_term();
607 
608 #ifdef DDB
609 	if (!gdb_return_to_ddb)
610 		return;
611 
612 	gdb_return_to_ddb = false;
613 
614 	if (kdb_dbbe_select("ddb") != 0)
615 		printf("The ddb backend could not be selected.\n");
616 #endif
617 }
618 
619 /*
620  * Handle a 'Z' packet: set a breakpoint or watchpoint.
621  *
622  * Currently, only watchpoints are supported.
623  */
624 static void
625 gdb_z_insert(void)
626 {
627 	intmax_t addr, length;
628 	char ztype;
629 	int error;
630 
631 	ztype = gdb_rx_char();
632 	if (gdb_rx_char() != ',' || gdb_rx_varhex(&addr) ||
633 	    gdb_rx_char() != ',' || gdb_rx_varhex(&length)) {
634 		error = EINVAL;
635 		goto fail;
636 	}
637 
638 	switch (ztype) {
639 	case '2': /* write watchpoint */
640 		error = kdb_cpu_set_watchpoint((vm_offset_t)addr,
641 		    (vm_size_t)length, KDB_DBG_ACCESS_W);
642 		break;
643 	case '3': /* read watchpoint */
644 		error = kdb_cpu_set_watchpoint((vm_offset_t)addr,
645 		    (vm_size_t)length, KDB_DBG_ACCESS_R);
646 		break;
647 	case '4': /* access (RW) watchpoint */
648 		error = kdb_cpu_set_watchpoint((vm_offset_t)addr,
649 		    (vm_size_t)length, KDB_DBG_ACCESS_RW);
650 		break;
651 	case '1': /* hardware breakpoint */
652 	case '0': /* software breakpoint */
653 		/* Not implemented. */
654 		gdb_tx_empty();
655 		return;
656 	default:
657 		error = EINVAL;
658 		break;
659 	}
660 	if (error != 0)
661 		goto fail;
662 	gdb_tx_ok();
663 	return;
664 fail:
665 	gdb_tx_err(error);
666 	return;
667 }
668 
669 /*
670  * Handle a 'z' packet; clear a breakpoint or watchpoint.
671  *
672  * Currently, only watchpoints are supported.
673  */
674 static void
675 gdb_z_remove(void)
676 {
677 	intmax_t addr, length;
678 	char ztype;
679 	int error;
680 
681 	ztype = gdb_rx_char();
682 	if (gdb_rx_char() != ',' || gdb_rx_varhex(&addr) ||
683 	    gdb_rx_char() != ',' || gdb_rx_varhex(&length)) {
684 		error = EINVAL;
685 		goto fail;
686 	}
687 
688 	switch (ztype) {
689 	case '2': /* write watchpoint */
690 	case '3': /* read watchpoint */
691 	case '4': /* access (RW) watchpoint */
692 		error = kdb_cpu_clr_watchpoint((vm_offset_t)addr,
693 		    (vm_size_t)length);
694 		break;
695 	case '1': /* hardware breakpoint */
696 	case '0': /* software breakpoint */
697 		/* Not implemented. */
698 		gdb_tx_empty();
699 		return;
700 	default:
701 		error = EINVAL;
702 		break;
703 	}
704 	if (error != 0)
705 		goto fail;
706 	gdb_tx_ok();
707 	return;
708 fail:
709 	gdb_tx_err(error);
710 	return;
711 }
712 
713 static int
714 gdb_trap(int type, int code)
715 {
716 	jmp_buf jb;
717 	struct thread *thr_iter;
718 	void *prev_jb;
719 	uint32_t host_features;
720 
721 	prev_jb = kdb_jmpbuf(jb);
722 	if (setjmp(jb) != 0) {
723 		printf("%s bailing, hopefully back to ddb!\n", __func__);
724 		gdb_listening = 0;
725 		(void)kdb_jmpbuf(prev_jb);
726 		return (1);
727 	}
728 
729 	gdb_listening = 0;
730 	gdb_ackmode = true;
731 
732 	/*
733 	 * Send a T packet. We currently do not support watchpoints (the
734 	 * awatch, rwatch or watch elements).
735 	 */
736 	gdb_tx_begin('T');
737 	gdb_tx_hex(gdb_cpu_signal(type, code), 2);
738 	gdb_tx_varhex(GDB_REG_PC);
739 	gdb_tx_char(':');
740 	gdb_tx_reg(GDB_REG_PC);
741 	gdb_tx_char(';');
742 	gdb_cpu_stop_reason(type, code);
743 	gdb_tx_str("thread:");
744 	gdb_tx_varhex((uintmax_t)kdb_thread->td_tid);
745 	gdb_tx_char(';');
746 	gdb_tx_end();			/* XXX check error condition. */
747 
748 	thr_iter = NULL;
749 	while (gdb_rx_begin() == 0) {
750 		/* printf("GDB: got '%s'\n", gdb_rxp); */
751 		switch (gdb_rx_char()) {
752 		case '?':	/* Last signal. */
753 			gdb_tx_begin('T');
754 			gdb_tx_hex(gdb_cpu_signal(type, code), 2);
755 			gdb_tx_str("thread:");
756 			gdb_tx_varhex((long)kdb_thread->td_tid);
757 			gdb_tx_char(';');
758 			gdb_tx_end();
759 			break;
760 		case 'c': {	/* Continue. */
761 			uintmax_t addr;
762 			register_t pc;
763 			if (!gdb_rx_varhex(&addr)) {
764 				pc = addr;
765 				gdb_cpu_setreg(GDB_REG_PC, &pc);
766 			}
767 			kdb_cpu_clear_singlestep();
768 			gdb_listening = 1;
769 			return (1);
770 		}
771 		case 'C': {	/* Continue with signal. */
772 			uintmax_t addr, sig;
773 			register_t pc;
774 			if (!gdb_rx_varhex(&sig) && gdb_rx_char() == ';' &&
775 			    !gdb_rx_varhex(&addr)) {
776 				pc = addr;
777 				gdb_cpu_setreg(GDB_REG_PC, &pc);
778 			}
779 			kdb_cpu_clear_singlestep();
780 			gdb_listening = 1;
781 			return (1);
782 		}
783 		case 'D': {     /* Detach */
784 			gdb_tx_ok();
785 			gdb_handle_detach();
786 			return (1);
787 		}
788 		case 'g': {	/* Read registers. */
789 			size_t r;
790 			gdb_tx_begin(0);
791 			for (r = 0; r < GDB_NREGS; r++)
792 				gdb_tx_reg(r);
793 			gdb_tx_end();
794 			break;
795 		}
796 		case 'G': {	/* Write registers. */
797 			char *val;
798 			bool success;
799 			size_t r;
800 			for (success = true, r = 0; r < GDB_NREGS; r++) {
801 				val = gdb_rxp;
802 				if (!gdb_rx_mem(val, gdb_cpu_regsz(r))) {
803 					gdb_tx_err(EINVAL);
804 					success = false;
805 					break;
806 				}
807 				gdb_cpu_setreg(r, val);
808 			}
809 			if (success)
810 				gdb_tx_ok();
811 			break;
812 		}
813 		case 'H': {	/* Set thread. */
814 			intmax_t tid;
815 			struct thread *thr;
816 
817 			/* Ignore 'g' (general) or 'c' (continue) flag. */
818 			(void) gdb_rx_char();
819 
820 			if (gdb_rx_varhex(&tid)) {
821 				gdb_tx_err(EINVAL);
822 				break;
823 			}
824 			if (tid > 0) {
825 				thr = kdb_thr_lookup(tid);
826 				if (thr == NULL) {
827 					gdb_tx_err(ENOENT);
828 					break;
829 				}
830 				kdb_thr_select(thr);
831 			}
832 			gdb_tx_ok();
833 			break;
834 		}
835 		case 'k':	/* Kill request. */
836 			gdb_handle_detach();
837 			return (1);
838 		case 'm': {	/* Read memory. */
839 			uintmax_t addr, size;
840 			if (gdb_rx_varhex(&addr) || gdb_rx_char() != ',' ||
841 			    gdb_rx_varhex(&size)) {
842 				gdb_tx_err(EINVAL);
843 				break;
844 			}
845 			gdb_tx_begin(0);
846 			if (gdb_tx_mem((char *)(uintptr_t)addr, size))
847 				gdb_tx_end();
848 			else
849 				gdb_tx_err(EIO);
850 			break;
851 		}
852 		case 'M': {	/* Write memory. */
853 			uintmax_t addr, size;
854 			if (gdb_rx_varhex(&addr) || gdb_rx_char() != ',' ||
855 			    gdb_rx_varhex(&size) || gdb_rx_char() != ':') {
856 				gdb_tx_err(EINVAL);
857 				break;
858 			}
859 			if (gdb_rx_mem((char *)(uintptr_t)addr, size) == 0)
860 				gdb_tx_err(EIO);
861 			else
862 				gdb_tx_ok();
863 			break;
864 		}
865 		case 'p': {     /* Read register. */
866 			uintmax_t reg;
867 			if (gdb_rx_varhex(&reg)) {
868 				gdb_tx_err(EINVAL);
869 				break;
870 			}
871 			gdb_tx_begin(0);
872 			gdb_tx_reg(reg);
873 			gdb_tx_end();
874 			break;
875 		}
876 		case 'P': {	/* Write register. */
877 			char *val;
878 			uintmax_t reg;
879 			val = gdb_rxp;
880 			if (gdb_rx_varhex(&reg) || gdb_rx_char() != '=' ||
881 			    !gdb_rx_mem(val, gdb_cpu_regsz(reg))) {
882 				gdb_tx_err(EINVAL);
883 				break;
884 			}
885 			gdb_cpu_setreg(reg, val);
886 			gdb_tx_ok();
887 			break;
888 		}
889 		case 'q':	/* General query. */
890 			if (gdb_rx_equal("C")) {
891 				gdb_tx_begin('Q');
892 				gdb_tx_char('C');
893 				gdb_tx_varhex((long)kdb_thread->td_tid);
894 				gdb_tx_end();
895 			} else if (gdb_rx_equal("Supported")) {
896 				gdb_do_qsupported(&host_features);
897 			} else if (gdb_rx_equal("fThreadInfo")) {
898 				thr_iter = kdb_thr_first();
899 				gdb_do_threadinfo(&thr_iter);
900 			} else if (gdb_rx_equal("sThreadInfo")) {
901 				gdb_do_threadinfo(&thr_iter);
902 			} else if (gdb_rx_equal("Xfer:")) {
903 				do_qXfer();
904 			} else if (gdb_rx_equal("Search:memory:")) {
905 				gdb_do_mem_search();
906 #ifdef __powerpc__
907 			} else if (gdb_rx_equal("Offsets")) {
908 				gdb_cpu_do_offsets();
909 #endif
910 			} else if (!gdb_cpu_query())
911 				gdb_tx_empty();
912 			break;
913 		case 'Q':
914 			if (gdb_rx_equal("StartNoAckMode")) {
915 				if ((gdb_cur->gdb_dbfeatures &
916 				    GDB_DBGP_FEAT_RELIABLE) == 0) {
917 					/*
918 					 * Shouldn't happen if we didn't
919 					 * advertise support.  Reject.
920 					 */
921 					gdb_tx_empty();
922 					break;
923 				}
924 				gdb_ackmode = false;
925 				gdb_tx_ok();
926 			} else
927 				gdb_tx_empty();
928 			break;
929 		case 's': {	/* Step. */
930 			uintmax_t addr;
931 			register_t pc;
932 			if (!gdb_rx_varhex(&addr)) {
933 				pc = addr;
934 				gdb_cpu_setreg(GDB_REG_PC, &pc);
935 			}
936 			kdb_cpu_set_singlestep();
937 			gdb_listening = 1;
938 			return (1);
939 		}
940 		case 'S': {	/* Step with signal. */
941 			uintmax_t addr, sig;
942 			register_t pc;
943 			if (!gdb_rx_varhex(&sig) && gdb_rx_char() == ';' &&
944 			    !gdb_rx_varhex(&addr)) {
945 				pc = addr;
946 				gdb_cpu_setreg(GDB_REG_PC, &pc);
947 			}
948 			kdb_cpu_set_singlestep();
949 			gdb_listening = 1;
950 			return (1);
951 		}
952 		case 'T': {	/* Thread alive. */
953 			intmax_t tid;
954 			if (gdb_rx_varhex(&tid)) {
955 				gdb_tx_err(EINVAL);
956 				break;
957 			}
958 			if (kdb_thr_lookup(tid) != NULL)
959 				gdb_tx_ok();
960 			else
961 				gdb_tx_err(ENOENT);
962 			break;
963 		}
964 		case 'z': {	/* Remove watchpoint. */
965 			gdb_z_remove();
966 			break;
967 		}
968 		case 'Z': {	/* Set watchpoint. */
969 			gdb_z_insert();
970 			break;
971 		}
972 		case EOF:
973 			/* Empty command. Treat as unknown command. */
974 			/* FALLTHROUGH */
975 		default:
976 			/* Unknown command. Send empty response. */
977 			gdb_tx_empty();
978 			break;
979 		}
980 	}
981 	(void)kdb_jmpbuf(prev_jb);
982 	return (0);
983 }
984