xref: /freebsd/usr.bin/ktrdump/ktrdump.c (revision 90aac0d83bc9645f51ef0c2aeae6f9c0540bb031)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2002 Jake Burkholder
5  * Copyright (c) 2004 Robert Watson
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
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 AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 #include <sys/types.h>
32 #include <sys/capsicum.h>
33 #include <sys/ktr.h>
34 #include <sys/mman.h>
35 #include <sys/stat.h>
36 
37 #include <capsicum_helpers.h>
38 #include <err.h>
39 #include <errno.h>
40 #include <fcntl.h>
41 #include <kvm.h>
42 #include <limits.h>
43 #include <nlist.h>
44 #include <stdint.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <unistd.h>
49 
50 #define	SBUFLEN	128
51 #define	USAGE \
52 	"usage: ktrdump [-cflqrtH] [-i ktrfile] [-M core] [-N system] [-o outfile]\n"
53 
54 static void usage(void) __dead2;
55 
56 static struct nlist nl[] = {
57 	{ .n_name = "_ktr_version" },
58 	{ .n_name = "_ktr_entries" },
59 	{ .n_name = "_ktr_idx" },
60 	{ .n_name = "_ktr_buf" },
61 	{ .n_name = NULL }
62 };
63 
64 static int cflag;
65 static int fflag;
66 static int lflag;
67 static int Mflag;
68 static int Nflag;
69 static int qflag;
70 static int rflag;
71 static int tflag;
72 static int iflag;
73 static int hflag;
74 
75 static char corefile[PATH_MAX];
76 static char execfile[PATH_MAX];
77 static char outfile[PATH_MAX] = "stdout";
78 
79 static char desc[SBUFLEN];
80 static char errbuf[_POSIX2_LINE_MAX];
81 static char fbuf[PATH_MAX];
82 static char obuf[PATH_MAX];
83 static char sbuf[KTR_PARMS][SBUFLEN];
84 
85 /*
86  * Reads the ktr trace buffer from kernel memory and prints the trace entries.
87  */
88 int
89 main(int ac, char **av)
90 {
91 	u_long parms[KTR_PARMS];
92 	struct ktr_entry *buf;
93 	uintmax_t tlast, tnow;
94 	unsigned long bufptr;
95 	cap_rights_t rights;
96 	struct stat sb;
97 	kvm_t *kd;
98 	FILE *out;
99 	char *p;
100 	int version;
101 	int entries;
102 	int count;
103 	int index, index2;
104 	int parm;
105 	int in;
106 	int c;
107 	int i = 0;
108 
109 	/*
110 	 * Parse commandline arguments.
111 	 */
112 	out = stdout;
113 	while ((c = getopt(ac, av, "cflqrtHe:i:m:M:N:o:")) != -1)
114 		switch (c) {
115 		case 'c':
116 			cflag = 1;
117 			break;
118 		case 'N':
119 		case 'e':
120 			if (strlcpy(execfile, optarg, sizeof(execfile))
121 			    >= sizeof(execfile))
122 				errx(1, "%s: File name too long", optarg);
123 			Nflag = 1;
124 			break;
125 		case 'f':
126 			fflag = 1;
127 			break;
128 		case 'i':
129 			iflag = 1;
130 			if ((in = open(optarg, O_RDONLY)) == -1)
131 				err(1, "%s", optarg);
132 			cap_rights_init(&rights, CAP_FSTAT, CAP_MMAP_R);
133 			if (caph_rights_limit(in, &rights) < 0)
134 				err(1, "unable to limit rights for %s",
135 				    optarg);
136 			break;
137 		case 'l':
138 			lflag = 1;
139 			break;
140 		case 'M':
141 		case 'm':
142 			if (strlcpy(corefile, optarg, sizeof(corefile))
143 			    >= sizeof(corefile))
144 				errx(1, "%s: File name too long", optarg);
145 			Mflag = 1;
146 			break;
147 		case 'o':
148 			if ((out = fopen(optarg, "w")) == NULL)
149 				err(1, "%s", optarg);
150 			strlcpy(outfile, optarg, sizeof(outfile));
151 			break;
152 		case 'q':
153 			qflag++;
154 			break;
155 		case 'r':
156 			rflag = 1;
157 			break;
158 		case 't':
159 			tflag = 1;
160 			break;
161 		case 'H':
162 			hflag = 1;
163 			break;
164 		case '?':
165 		default:
166 			usage();
167 		}
168 	ac -= optind;
169 	av += optind;
170 	if (ac != 0)
171 		usage();
172 
173 	if (caph_limit_stream(fileno(out), CAPH_WRITE) < 0)
174 		err(1, "unable to limit rights for %s", outfile);
175 	if (caph_limit_stderr() < 0)
176 		err(1, "unable to limit rights for stderr");
177 
178 	/*
179 	 * Open our execfile and corefile, resolve needed symbols and read in
180 	 * the trace buffer.
181 	 */
182 	if ((kd = kvm_openfiles(Nflag ? execfile : NULL,
183 	    Mflag ? corefile : NULL, NULL, O_RDONLY, errbuf)) == NULL)
184 		errx(1, "%s", errbuf);
185 
186 	/*
187 	 * Cache NLS data, for strerror, for err(3), before entering capability
188 	 * mode.
189 	 */
190 	caph_cache_catpages();
191 
192 	count = kvm_nlist(kd, nl);
193 	if (count == -1)
194 		errx(1, "%s", kvm_geterr(kd));
195 	if (count > 0)
196 		errx(1, "failed to resolve ktr symbols");
197 	if (kvm_read(kd, nl[0].n_value, &version, sizeof(version)) == -1)
198 		errx(1, "%s", kvm_geterr(kd));
199 	if (version != KTR_VERSION)
200 		errx(1, "ktr version mismatch");
201 
202 	/*
203 	 * Enter Capsicum sandbox.
204 	 *
205 	 * kvm_nlist() above uses kldsym(2) for native kernels, and that isn't
206 	 * allowed in the sandbox.
207 	 */
208 	if (caph_enter() < 0)
209 		err(1, "unable to enter capability mode");
210 
211 	if (iflag) {
212 		if (fstat(in, &sb) == -1)
213 			errx(1, "stat");
214 		entries = sb.st_size / sizeof(*buf);
215 		index = 0;
216 		buf = mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, in, 0);
217 		if (buf == MAP_FAILED)
218 			errx(1, "mmap");
219 	} else {
220 		if (kvm_read(kd, nl[1].n_value, &entries, sizeof(entries))
221 		    == -1)
222 			errx(1, "%s", kvm_geterr(kd));
223 		if ((buf = malloc(sizeof(*buf) * entries)) == NULL)
224 			err(1, NULL);
225 		if (kvm_read(kd, nl[2].n_value, &index, sizeof(index)) == -1 ||
226 		    kvm_read(kd, nl[3].n_value, &bufptr,
227 		    sizeof(bufptr)) == -1 ||
228 		    kvm_read(kd, bufptr, buf, sizeof(*buf) * entries) == -1 ||
229 		    kvm_read(kd, nl[2].n_value, &index2, sizeof(index2)) == -1)
230 			errx(1, "%s", kvm_geterr(kd));
231 	}
232 
233 	/*
234 	 * Print a nice header.
235 	 */
236 	if (!qflag) {
237 		fprintf(out, "%-6s ", "index");
238 		if (cflag)
239 			fprintf(out, "%-3s ", "cpu");
240 		if (tflag)
241 			fprintf(out, "%-16s ", "timestamp");
242 		if (fflag)
243 			fprintf(out, "%-40s ", "file and line");
244 		if (hflag)
245 			fprintf(out, "%-18s ", "tid");
246 		fprintf(out, "%s", "trace");
247 		fprintf(out, "\n");
248 
249 		fprintf(out, "------ ");
250 		if (cflag)
251 			fprintf(out, "--- ");
252 		if (tflag)
253 			fprintf(out, "---------------- ");
254 		if (fflag)
255 			fprintf(out,
256 			    "---------------------------------------- ");
257 		if (hflag)
258 			fprintf(out, "------------------ ");
259 		fprintf(out, "----- ");
260 		fprintf(out, "\n");
261 	}
262 
263 	tlast = UINTPTR_MAX;
264 	/*
265 	 * Now tear through the trace buffer.
266 	 *
267 	 * In "live" mode, find the oldest entry (first non-NULL entry
268 	 * after index2) and walk forward.  Otherwise, start with the
269 	 * most recent entry and walk backwards.
270 	 */
271 	if (!iflag) {
272 		if (lflag) {
273 			i = index2 + 1 % entries;
274 			while (buf[i].ktr_desc == NULL && i != index) {
275 				i++;
276 				if (i == entries)
277 					i = 0;
278 			}
279 		} else {
280 			i = index - 1;
281 			if (i < 0)
282 				i = entries - 1;
283 		}
284 	}
285 dump_entries:
286 	for (;;) {
287 		if (buf[i].ktr_desc == NULL)
288 			break;
289 		if (kvm_read(kd, (u_long)buf[i].ktr_desc, desc,
290 		    sizeof(desc)) == -1)
291 			errx(1, "%s", kvm_geterr(kd));
292 		desc[sizeof(desc) - 1] = '\0';
293 		parm = 0;
294 		for (p = desc; (c = *p++) != '\0';) {
295 			if (c != '%')
296 				continue;
297 next:			if ((c = *p++) == '\0')
298 				break;
299 			if (c == '%')
300 				continue;
301 			if (parm == KTR_PARMS)
302 				errx(1, "too many parameters in \"%s\"", desc);
303 			switch (c) {
304 			case '0': case '1': case '2': case '3': case '4':
305 			case '5': case '6': case '7': case '8': case '9':
306 			case '#': case '-': case ' ': case '+': case '\'':
307 			case 'h': case 'l': case 'j': case 't': case 'z':
308 			case 'q': case 'L': case '.':
309 				goto next;
310 			case 's':
311 				if (kvm_read(kd, (u_long)buf[i].ktr_parms[parm],
312 				    sbuf[parm], sizeof(sbuf[parm])) == -1)
313 					strcpy(sbuf[parm], "(null)");
314 				sbuf[parm][sizeof(sbuf[0]) - 1] = '\0';
315 				parms[parm] = (u_long)sbuf[parm];
316 				parm++;
317 				break;
318 			default:
319 				parms[parm] = buf[i].ktr_parms[parm];
320 				parm++;
321 				break;
322 			}
323 		}
324 		fprintf(out, "%6d ", i);
325 		if (cflag)
326 			fprintf(out, "%3d ", buf[i].ktr_cpu);
327 		if (tflag) {
328 			tnow = (uintmax_t)buf[i].ktr_timestamp;
329 			if (rflag) {
330 				if (tlast == UINTPTR_MAX)
331 					tlast = tnow;
332 				fprintf(out, "%16ju ", !iflag ? tlast - tnow :
333 				    tnow - tlast);
334 				tlast = tnow;
335 			} else
336 				fprintf(out, "%16ju ", tnow);
337 		}
338 		if (fflag) {
339 			if (kvm_read(kd, (u_long)buf[i].ktr_file, fbuf,
340 			    sizeof(fbuf)) == -1)
341 				strcpy(fbuf, "(null)");
342 			snprintf(obuf, sizeof(obuf), "%s:%d", fbuf,
343 			    buf[i].ktr_line);
344 			fprintf(out, "%-40s ", obuf);
345 		}
346 		if (hflag)
347 			fprintf(out, "%p ", buf[i].ktr_thread);
348 		fprintf(out, desc, parms[0], parms[1], parms[2], parms[3],
349 		    parms[4], parms[5]);
350 		fprintf(out, "\n");
351 		if (!iflag) {
352 			/*
353 			 * 'index' and 'index2' are the values of 'ktr_idx'
354 			 * before and after the KTR buffer was copied into
355 			 * 'buf'. Since the KTR entries between 'index' and
356 			 * 'index2' were in flux while the KTR buffer was
357 			 * being copied to userspace we don't dump them.
358 			 */
359 			if (lflag) {
360 				if (++i == entries)
361 					i = 0;
362 				if (i == index)
363 					break;
364 			} else {
365 				if (i == index2)
366 					break;
367 				if (--i < 0)
368 					i = entries - 1;
369 			}
370 		} else {
371 			if (++i == entries)
372 				break;
373 		}
374 	}
375 
376 	/*
377 	 * In "live" mode, poll 'ktr_idx' periodically and dump any
378 	 * new entries since our last pass through the ring.
379 	 */
380 	if (lflag && !iflag) {
381 		while (index == index2) {
382 			usleep(50 * 1000);
383 			if (kvm_read(kd, nl[2].n_value, &index2,
384 			    sizeof(index2)) == -1)
385 				errx(1, "%s", kvm_geterr(kd));
386 		}
387 		i = index;
388 		index = index2;
389 		if (kvm_read(kd, bufptr, buf, sizeof(*buf) * entries) == -1 ||
390 		    kvm_read(kd, nl[2].n_value, &index2, sizeof(index2)) == -1)
391 			errx(1, "%s", kvm_geterr(kd));
392 		goto dump_entries;
393 	}
394 
395 	return (0);
396 }
397 
398 static void
399 usage(void)
400 {
401 
402 	fprintf(stderr, USAGE);
403 	exit(1);
404 }
405