xref: /freebsd/usr.bin/ktrdump/ktrdump.c (revision 7815283df299be63807225a9fe9b6e54406eae28)
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 	{ "_ktr_version" },
60 	{ "_ktr_entries" },
61 	{ "_ktr_idx" },
62 	{ "_ktr_buf" },
63 	{ 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 (cap_rights_limit(in, &rights) < 0 &&
136 			    errno != ENOSYS)
137 				err(1, "unable to limit rights for %s",
138 				    optarg);
139 			break;
140 		case 'l':
141 			lflag = 1;
142 			break;
143 		case 'M':
144 		case 'm':
145 			if (strlcpy(corefile, optarg, sizeof(corefile))
146 			    >= sizeof(corefile))
147 				errx(1, "%s: File name too long", optarg);
148 			Mflag = 1;
149 			break;
150 		case 'o':
151 			if ((out = fopen(optarg, "w")) == NULL)
152 				err(1, "%s", optarg);
153 			strlcpy(outfile, optarg, sizeof(outfile));
154 			break;
155 		case 'q':
156 			qflag++;
157 			break;
158 		case 'r':
159 			rflag = 1;
160 			break;
161 		case 't':
162 			tflag = 1;
163 			break;
164 		case 'H':
165 			hflag = 1;
166 			break;
167 		case '?':
168 		default:
169 			usage();
170 		}
171 	ac -= optind;
172 	av += optind;
173 	if (ac != 0)
174 		usage();
175 
176 	if (caph_limit_stream(fileno(out), CAPH_WRITE) < 0)
177 		err(1, "unable to limit rights for %s", outfile);
178 	if (caph_limit_stderr() < 0)
179 		err(1, "unable to limit rights for stderr");
180 
181 	/*
182 	 * Open our execfile and corefile, resolve needed symbols and read in
183 	 * the trace buffer.
184 	 */
185 	if ((kd = kvm_openfiles(Nflag ? execfile : NULL,
186 	    Mflag ? corefile : NULL, NULL, O_RDONLY, errbuf)) == NULL)
187 		errx(1, "%s", errbuf);
188 
189 	/*
190 	 * Cache NLS data, for strerror, for err(3), before entering capability
191 	 * mode.
192 	 */
193 	caph_cache_catpages();
194 
195 	count = kvm_nlist(kd, nl);
196 	if (count == -1)
197 		errx(1, "%s", kvm_geterr(kd));
198 	if (count > 0)
199 		errx(1, "failed to resolve ktr symbols");
200 	if (kvm_read(kd, nl[0].n_value, &version, sizeof(version)) == -1)
201 		errx(1, "%s", kvm_geterr(kd));
202 	if (version != KTR_VERSION)
203 		errx(1, "ktr version mismatch");
204 
205 	/*
206 	 * Enter Capsicum sandbox.
207 	 *
208 	 * kvm_nlist() above uses kldsym(2) for native kernels, and that isn't
209 	 * allowed in the sandbox.
210 	 */
211 	if (caph_enter() < 0)
212 		err(1, "unable to enter capability mode");
213 
214 	if (iflag) {
215 		if (fstat(in, &sb) == -1)
216 			errx(1, "stat");
217 		entries = sb.st_size / sizeof(*buf);
218 		index = 0;
219 		buf = mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, in, 0);
220 		if (buf == MAP_FAILED)
221 			errx(1, "mmap");
222 	} else {
223 		if (kvm_read(kd, nl[1].n_value, &entries, sizeof(entries))
224 		    == -1)
225 			errx(1, "%s", kvm_geterr(kd));
226 		if ((buf = malloc(sizeof(*buf) * entries)) == NULL)
227 			err(1, NULL);
228 		if (kvm_read(kd, nl[2].n_value, &index, sizeof(index)) == -1 ||
229 		    kvm_read(kd, nl[3].n_value, &bufptr,
230 		    sizeof(bufptr)) == -1 ||
231 		    kvm_read(kd, bufptr, buf, sizeof(*buf) * entries) == -1 ||
232 		    kvm_read(kd, nl[2].n_value, &index2, sizeof(index2)) == -1)
233 			errx(1, "%s", kvm_geterr(kd));
234 	}
235 
236 	/*
237 	 * Print a nice header.
238 	 */
239 	if (!qflag) {
240 		fprintf(out, "%-6s ", "index");
241 		if (cflag)
242 			fprintf(out, "%-3s ", "cpu");
243 		if (tflag)
244 			fprintf(out, "%-16s ", "timestamp");
245 		if (fflag)
246 			fprintf(out, "%-40s ", "file and line");
247 		if (hflag)
248 			fprintf(out, "%-18s ", "tid");
249 		fprintf(out, "%s", "trace");
250 		fprintf(out, "\n");
251 
252 		fprintf(out, "------ ");
253 		if (cflag)
254 			fprintf(out, "--- ");
255 		if (tflag)
256 			fprintf(out, "---------------- ");
257 		if (fflag)
258 			fprintf(out,
259 			    "---------------------------------------- ");
260 		if (hflag)
261 			fprintf(out, "------------------ ");
262 		fprintf(out, "----- ");
263 		fprintf(out, "\n");
264 	}
265 
266 	tlast = -1;
267 	/*
268 	 * Now tear through the trace buffer.
269 	 *
270 	 * In "live" mode, find the oldest entry (first non-NULL entry
271 	 * after index2) and walk forward.  Otherwise, start with the
272 	 * most recent entry and walk backwards.
273 	 */
274 	if (!iflag) {
275 		if (lflag) {
276 			i = index2 + 1 % entries;
277 			while (buf[i].ktr_desc == NULL && i != index) {
278 				i++;
279 				if (i == entries)
280 					i = 0;
281 			}
282 		} else {
283 			i = index - 1;
284 			if (i < 0)
285 				i = entries - 1;
286 		}
287 	}
288 dump_entries:
289 	for (;;) {
290 		if (buf[i].ktr_desc == NULL)
291 			break;
292 		if (kvm_read(kd, (u_long)buf[i].ktr_desc, desc,
293 		    sizeof(desc)) == -1)
294 			errx(1, "%s", kvm_geterr(kd));
295 		desc[sizeof(desc) - 1] = '\0';
296 		parm = 0;
297 		for (p = desc; (c = *p++) != '\0';) {
298 			if (c != '%')
299 				continue;
300 next:			if ((c = *p++) == '\0')
301 				break;
302 			if (parm == KTR_PARMS)
303 				errx(1, "too many parameters in \"%s\"", desc);
304 			switch (c) {
305 			case '0': case '1': case '2': case '3': case '4':
306 			case '5': case '6': case '7': case '8': case '9':
307 			case '#': case '-': case ' ': case '+': case '\'':
308 			case 'h': case 'l': case 'j': case 't': case 'z':
309 			case 'q': case 'L': case '.':
310 				goto next;
311 			case 's':
312 				if (kvm_read(kd, (u_long)buf[i].ktr_parms[parm],
313 				    sbuf[parm], sizeof(sbuf[parm])) == -1)
314 					strcpy(sbuf[parm], "(null)");
315 				sbuf[parm][sizeof(sbuf[0]) - 1] = '\0';
316 				parms[parm] = (u_long)sbuf[parm];
317 				parm++;
318 				break;
319 			default:
320 				parms[parm] = buf[i].ktr_parms[parm];
321 				parm++;
322 				break;
323 			}
324 		}
325 		fprintf(out, "%6d ", i);
326 		if (cflag)
327 			fprintf(out, "%3d ", buf[i].ktr_cpu);
328 		if (tflag) {
329 			tnow = (uintmax_t)buf[i].ktr_timestamp;
330 			if (rflag) {
331 				if (tlast == -1)
332 					tlast = tnow;
333 				fprintf(out, "%16ju ", !iflag ? tlast - tnow :
334 				    tnow - tlast);
335 				tlast = tnow;
336 			} else
337 				fprintf(out, "%16ju ", tnow);
338 		}
339 		if (fflag) {
340 			if (kvm_read(kd, (u_long)buf[i].ktr_file, fbuf,
341 			    sizeof(fbuf)) == -1)
342 				strcpy(fbuf, "(null)");
343 			snprintf(obuf, sizeof(obuf), "%s:%d", fbuf,
344 			    buf[i].ktr_line);
345 			fprintf(out, "%-40s ", obuf);
346 		}
347 		if (hflag)
348 			fprintf(out, "%p ", buf[i].ktr_thread);
349 		fprintf(out, desc, parms[0], parms[1], parms[2], parms[3],
350 		    parms[4], parms[5]);
351 		fprintf(out, "\n");
352 		if (!iflag) {
353 			/*
354 			 * 'index' and 'index2' are the values of 'ktr_idx'
355 			 * before and after the KTR buffer was copied into
356 			 * 'buf'. Since the KTR entries between 'index' and
357 			 * 'index2' were in flux while the KTR buffer was
358 			 * being copied to userspace we don't dump them.
359 			 */
360 			if (lflag) {
361 				if (++i == entries)
362 					i = 0;
363 				if (i == index)
364 					break;
365 			} else {
366 				if (i == index2)
367 					break;
368 				if (--i < 0)
369 					i = entries - 1;
370 			}
371 		} else {
372 			if (++i == entries)
373 				break;
374 		}
375 	}
376 
377 	/*
378 	 * In "live" mode, poll 'ktr_idx' periodically and dump any
379 	 * new entries since our last pass through the ring.
380 	 */
381 	if (lflag && !iflag) {
382 		while (index == index2) {
383 			usleep(50 * 1000);
384 			if (kvm_read(kd, nl[2].n_value, &index2,
385 			    sizeof(index2)) == -1)
386 				errx(1, "%s", kvm_geterr(kd));
387 		}
388 		i = index;
389 		index = index2;
390 		if (kvm_read(kd, bufptr, buf, sizeof(*buf) * entries) == -1 ||
391 		    kvm_read(kd, nl[2].n_value, &index2, sizeof(index2)) == -1)
392 			errx(1, "%s", kvm_geterr(kd));
393 		goto dump_entries;
394 	}
395 
396 	return (0);
397 }
398 
399 static void
400 usage(void)
401 {
402 
403 	fprintf(stderr, USAGE);
404 	exit(1);
405 }
406