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