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