1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2007 Robert N. M. Watson
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  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 /*
30  * DDB capture support: capture kernel debugger output into a fixed-size
31  * buffer for later dumping to disk or extraction from user space.
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD: stable/12/sys/ddb/db_capture.c 373241 2023-10-12 05:11:39Z zlei $");
36 
37 #include "opt_ddb.h"
38 
39 #include <sys/param.h>
40 #include <sys/conf.h>
41 #include <sys/kernel.h>
42 #include <sys/kerneldump.h>
43 #include <sys/malloc.h>
44 #include <sys/msgbuf.h>
45 #include <sys/priv.h>
46 #include <sys/sx.h>
47 #include <sys/sysctl.h>
48 #include <sys/systm.h>
49 
50 #include <ddb/ddb.h>
51 #include <ddb/db_lex.h>
52 
53 /*
54  * While it would be desirable to use a small block-sized buffer and dump
55  * incrementally to disk in fixed-size blocks, it's not possible to enter
56  * kernel dumper routines without restarting the kernel, which is undesirable
57  * in the midst of debugging.  Instead, we maintain a large static global
58  * buffer that we fill from DDB's output routines.
59  *
60  * We enforce an invariant at runtime that buffer sizes are even multiples of
61  * the textdump block size, which is a design choice that we might want to
62  * reconsider.
63  */
64 static MALLOC_DEFINE(M_DDB_CAPTURE, "ddb_capture", "DDB capture buffer");
65 
66 #ifndef DDB_CAPTURE_DEFAULTBUFSIZE
67 #define	DDB_CAPTURE_DEFAULTBUFSIZE	48*1024
68 #endif
69 #ifndef DDB_CAPTURE_MAXBUFSIZE
70 #define	DDB_CAPTURE_MAXBUFSIZE	5*1024*1024
71 #endif
72 #define	DDB_CAPTURE_FILENAME	"ddb.txt"	/* Captured DDB output. */
73 
74 static char *db_capture_buf;
75 static u_int db_capture_bufsize = DDB_CAPTURE_DEFAULTBUFSIZE;
76 static u_int db_capture_maxbufsize = DDB_CAPTURE_MAXBUFSIZE; /* Read-only. */
77 static u_int db_capture_bufoff;		/* Next location to write in buffer. */
78 static u_int db_capture_bufpadding;	/* Amount of zero padding. */
79 static int db_capture_inpager;		/* Suspend capture in pager. */
80 static int db_capture_inprogress;	/* DDB capture currently in progress. */
81 
82 struct sx db_capture_sx;		/* Lock against user thread races. */
83 SX_SYSINIT(db_capture_sx, &db_capture_sx, "db_capture_sx");
84 
85 static SYSCTL_NODE(_debug_ddb, OID_AUTO, capture, CTLFLAG_RW, 0,
86     "DDB capture options");
87 
88 SYSCTL_UINT(_debug_ddb_capture, OID_AUTO, bufoff, CTLFLAG_RD,
89     &db_capture_bufoff, 0, "Bytes of data in DDB capture buffer");
90 
91 SYSCTL_UINT(_debug_ddb_capture, OID_AUTO, maxbufsize, CTLFLAG_RD,
92     &db_capture_maxbufsize, 0,
93     "Maximum value for debug.ddb.capture.bufsize");
94 
95 SYSCTL_INT(_debug_ddb_capture, OID_AUTO, inprogress, CTLFLAG_RD,
96     &db_capture_inprogress, 0, "DDB output capture in progress");
97 
98 /*
99  * Boot-time allocation of the DDB capture buffer, if any.  Force all buffer
100  * sizes, including the maximum size, to be rounded to block sizes.
101  */
102 static void
db_capture_sysinit(__unused void * dummy)103 db_capture_sysinit(__unused void *dummy)
104 {
105 
106 	TUNABLE_INT_FETCH("debug.ddb.capture.bufsize", &db_capture_bufsize);
107 	db_capture_maxbufsize = roundup(db_capture_maxbufsize,
108 	    TEXTDUMP_BLOCKSIZE);
109 	db_capture_bufsize = roundup(db_capture_bufsize, TEXTDUMP_BLOCKSIZE);
110 	if (db_capture_bufsize > db_capture_maxbufsize)
111 		db_capture_bufsize = db_capture_maxbufsize;
112 	if (db_capture_bufsize != 0)
113 		db_capture_buf = malloc(db_capture_bufsize, M_DDB_CAPTURE,
114 		    M_WAITOK);
115 }
116 SYSINIT(db_capture, SI_SUB_DDB_SERVICES, SI_ORDER_ANY, db_capture_sysinit,
117     NULL);
118 
119 /*
120  * Run-time adjustment of the capture buffer.
121  */
122 static int
sysctl_debug_ddb_capture_bufsize(SYSCTL_HANDLER_ARGS)123 sysctl_debug_ddb_capture_bufsize(SYSCTL_HANDLER_ARGS)
124 {
125 	u_int len, size;
126 	char *buf;
127 	int error;
128 
129 	size = db_capture_bufsize;
130 	error = sysctl_handle_int(oidp, &size, 0, req);
131 	if (error || req->newptr == NULL)
132 		return (error);
133 	size = roundup(size, TEXTDUMP_BLOCKSIZE);
134 	if (size > db_capture_maxbufsize)
135 		return (EINVAL);
136 	sx_xlock(&db_capture_sx);
137 	if (size != 0) {
138 		/*
139 		 * Potentially the buffer is quite large, so if we can't
140 		 * allocate it, fail rather than waiting.
141 		 */
142 		buf = malloc(size, M_DDB_CAPTURE, M_NOWAIT);
143 		if (buf == NULL) {
144 			sx_xunlock(&db_capture_sx);
145 			return (ENOMEM);
146 		}
147 		len = min(db_capture_bufoff, size);
148 	} else {
149 		buf = NULL;
150 		len = 0;
151 	}
152 	if (db_capture_buf != NULL && buf != NULL)
153 		bcopy(db_capture_buf, buf, len);
154 	if (db_capture_buf != NULL)
155 		free(db_capture_buf, M_DDB_CAPTURE);
156 	db_capture_bufoff = len;
157 	db_capture_buf = buf;
158 	db_capture_bufsize = size;
159 	sx_xunlock(&db_capture_sx);
160 
161 	KASSERT(db_capture_bufoff <= db_capture_bufsize,
162 	    ("sysctl_debug_ddb_capture_bufsize: bufoff > bufsize"));
163 	KASSERT(db_capture_bufsize <= db_capture_maxbufsize,
164 	    ("sysctl_debug_ddb_capture_maxbufsize: bufsize > maxbufsize"));
165 
166 	return (0);
167 }
168 SYSCTL_PROC(_debug_ddb_capture, OID_AUTO, bufsize,
169     CTLTYPE_UINT | CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
170     0, 0, sysctl_debug_ddb_capture_bufsize, "IU",
171     "Size of DDB capture buffer");
172 
173 /*
174  * Sysctl to read out the capture buffer from userspace.  We require
175  * privilege as sensitive process/memory information may be accessed.
176  */
177 static int
sysctl_debug_ddb_capture_data(SYSCTL_HANDLER_ARGS)178 sysctl_debug_ddb_capture_data(SYSCTL_HANDLER_ARGS)
179 {
180 	int error;
181 	char ch;
182 
183 	error = priv_check(req->td, PRIV_DDB_CAPTURE);
184 	if (error)
185 		return (error);
186 
187 	sx_slock(&db_capture_sx);
188 	error = SYSCTL_OUT(req, db_capture_buf, db_capture_bufoff);
189 	sx_sunlock(&db_capture_sx);
190 	if (error)
191 		return (error);
192 	ch = '\0';
193 	return (SYSCTL_OUT(req, &ch, sizeof(ch)));
194 }
195 SYSCTL_PROC(_debug_ddb_capture, OID_AUTO, data, CTLTYPE_STRING | CTLFLAG_RD,
196     NULL, 0, sysctl_debug_ddb_capture_data, "A", "DDB capture data");
197 
198 /*
199  * Routines for capturing DDB output into a fixed-size buffer.  These are
200  * invoked from DDB's input and output routines.  If we hit the limit on the
201  * buffer, we simply drop further data.
202  */
203 void
db_capture_write(char * buffer,u_int buflen)204 db_capture_write(char *buffer, u_int buflen)
205 {
206 	u_int len;
207 
208 	if (db_capture_inprogress == 0 || db_capture_inpager)
209 		return;
210 	len = min(buflen, db_capture_bufsize - db_capture_bufoff);
211 	bcopy(buffer, db_capture_buf + db_capture_bufoff, len);
212 	db_capture_bufoff += len;
213 
214 	KASSERT(db_capture_bufoff <= db_capture_bufsize,
215 	    ("db_capture_write: bufoff > bufsize"));
216 }
217 
218 void
db_capture_writech(char ch)219 db_capture_writech(char ch)
220 {
221 
222 	return (db_capture_write(&ch, sizeof(ch)));
223 }
224 
225 void
db_capture_enterpager(void)226 db_capture_enterpager(void)
227 {
228 
229 	db_capture_inpager = 1;
230 }
231 
232 void
db_capture_exitpager(void)233 db_capture_exitpager(void)
234 {
235 
236 	db_capture_inpager = 0;
237 }
238 
239 /*
240  * Zero out any bytes left in the last block of the DDB capture buffer.  This
241  * is run shortly before writing the blocks to disk, rather than when output
242  * capture is stopped, in order to avoid injecting nul's into the middle of
243  * output.
244  */
245 static void
db_capture_zeropad(void)246 db_capture_zeropad(void)
247 {
248 	u_int len;
249 
250 	len = min(TEXTDUMP_BLOCKSIZE, (db_capture_bufsize -
251 	    db_capture_bufoff) % TEXTDUMP_BLOCKSIZE);
252 	bzero(db_capture_buf + db_capture_bufoff, len);
253 	db_capture_bufpadding = len;
254 }
255 
256 /*
257  * Reset capture state, which flushes buffers.
258  */
259 static void
db_capture_reset(void)260 db_capture_reset(void)
261 {
262 
263 	db_capture_inprogress = 0;
264 	db_capture_bufoff = 0;
265 	db_capture_bufpadding = 0;
266 }
267 
268 /*
269  * Start capture.  Only one session is allowed at any time, but we may
270  * continue a previous session, so the buffer isn't reset.
271  */
272 static void
db_capture_start(void)273 db_capture_start(void)
274 {
275 
276 	if (db_capture_inprogress) {
277 		db_printf("Capture already started\n");
278 		return;
279 	}
280 	db_capture_inprogress = 1;
281 }
282 
283 /*
284  * Terminate DDB output capture--real work is deferred to db_capture_dump,
285  * which executes outside of the DDB context.  We don't zero pad here because
286  * capture may be started again before the dump takes place.
287  */
288 static void
db_capture_stop(void)289 db_capture_stop(void)
290 {
291 
292 	if (db_capture_inprogress == 0) {
293 		db_printf("Capture not started\n");
294 		return;
295 	}
296 	db_capture_inprogress = 0;
297 }
298 
299 /*
300  * Dump DDB(4) captured output (and resets capture buffers).
301  */
302 void
db_capture_dump(struct dumperinfo * di)303 db_capture_dump(struct dumperinfo *di)
304 {
305 	u_int offset;
306 
307 	if (db_capture_bufoff == 0)
308 		return;
309 
310 	db_capture_zeropad();
311 	textdump_mkustar(textdump_block_buffer, DDB_CAPTURE_FILENAME,
312 	    db_capture_bufoff);
313 	(void)textdump_writenextblock(di, textdump_block_buffer);
314 	for (offset = 0; offset < db_capture_bufoff + db_capture_bufpadding;
315 	    offset += TEXTDUMP_BLOCKSIZE)
316 		(void)textdump_writenextblock(di, db_capture_buf + offset);
317 	db_capture_bufoff = 0;
318 	db_capture_bufpadding = 0;
319 }
320 
321 /*-
322  * DDB(4) command to manage capture:
323  *
324  * capture on          - start DDB output capture
325  * capture off         - stop DDB output capture
326  * capture reset       - reset DDB capture buffer (also stops capture)
327  * capture status      - print DDB output capture status
328  */
329 static void
db_capture_usage(void)330 db_capture_usage(void)
331 {
332 
333 	db_error("capture [on|off|reset|status]\n");
334 }
335 
336 void
db_capture_cmd(db_expr_t addr,bool have_addr,db_expr_t count,char * modif)337 db_capture_cmd(db_expr_t addr, bool have_addr, db_expr_t count, char *modif)
338 {
339 	int t;
340 
341 	t = db_read_token();
342 	if (t != tIDENT) {
343 		db_capture_usage();
344 		return;
345 	}
346 	if (db_read_token() != tEOL)
347 		db_error("?\n");
348 	if (strcmp(db_tok_string, "on") == 0)
349 		db_capture_start();
350 	else if (strcmp(db_tok_string, "off") == 0)
351 		db_capture_stop();
352 	else if (strcmp(db_tok_string, "reset") == 0)
353 		db_capture_reset();
354 	else if (strcmp(db_tok_string, "status") == 0) {
355 		db_printf("%u/%u bytes used\n", db_capture_bufoff,
356 		    db_capture_bufsize);
357 		if (db_capture_inprogress)
358 			db_printf("capture is on\n");
359 		else
360 			db_printf("capture is off\n");
361 	} else
362 		db_capture_usage();
363 }
364