xref: /freebsd/usr.bin/ktrdump/ktrdump.c (revision 63a938566d524836885917d95bd491aa4400b181)
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 [-cfqrtH] [-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 Mflag;
69 static int Nflag;
70 static int qflag;
71 static int rflag;
72 static int tflag;
73 static int iflag;
74 static int hflag;
75 
76 static char corefile[PATH_MAX];
77 static char execfile[PATH_MAX];
78 static char outfile[PATH_MAX] = "stdout";
79 
80 static char desc[SBUFLEN];
81 static char errbuf[_POSIX2_LINE_MAX];
82 static char fbuf[PATH_MAX];
83 static char obuf[PATH_MAX];
84 static char sbuf[KTR_PARMS][SBUFLEN];
85 
86 /*
87  * Reads the ktr trace buffer from kernel memory and prints the trace entries.
88  */
89 int
90 main(int ac, char **av)
91 {
92 	u_long parms[KTR_PARMS];
93 	struct ktr_entry *buf;
94 	uintmax_t tlast, tnow;
95 	unsigned long bufptr;
96 	cap_rights_t rights;
97 	struct stat sb;
98 	kvm_t *kd;
99 	FILE *out;
100 	char *p;
101 	int version;
102 	int entries;
103 	int count;
104 	int index, index2;
105 	int parm;
106 	int in;
107 	int c;
108 	int i = 0;
109 
110 	/*
111 	 * Parse commandline arguments.
112 	 */
113 	out = stdout;
114 	while ((c = getopt(ac, av, "cfqrtHe:i:m:M:N:o:")) != -1)
115 		switch (c) {
116 		case 'c':
117 			cflag = 1;
118 			break;
119 		case 'N':
120 		case 'e':
121 			if (strlcpy(execfile, optarg, sizeof(execfile))
122 			    >= sizeof(execfile))
123 				errx(1, "%s: File name too long", optarg);
124 			Nflag = 1;
125 			break;
126 		case 'f':
127 			fflag = 1;
128 			break;
129 		case 'i':
130 			iflag = 1;
131 			if ((in = open(optarg, O_RDONLY)) == -1)
132 				err(1, "%s", optarg);
133 			cap_rights_init(&rights, CAP_FSTAT, CAP_MMAP_R);
134 			if (cap_rights_limit(in, &rights) < 0 &&
135 			    errno != ENOSYS)
136 				err(1, "unable to limit rights for %s",
137 				    optarg);
138 			break;
139 		case 'M':
140 		case 'm':
141 			if (strlcpy(corefile, optarg, sizeof(corefile))
142 			    >= sizeof(corefile))
143 				errx(1, "%s: File name too long", optarg);
144 			Mflag = 1;
145 			break;
146 		case 'o':
147 			if ((out = fopen(optarg, "w")) == NULL)
148 				err(1, "%s", optarg);
149 			strlcpy(outfile, optarg, sizeof(outfile));
150 			break;
151 		case 'q':
152 			qflag++;
153 			break;
154 		case 'r':
155 			rflag = 1;
156 			break;
157 		case 't':
158 			tflag = 1;
159 			break;
160 		case 'H':
161 			hflag = 1;
162 			break;
163 		case '?':
164 		default:
165 			usage();
166 		}
167 	ac -= optind;
168 	av += optind;
169 	if (ac != 0)
170 		usage();
171 
172 	cap_rights_init(&rights, CAP_FSTAT, CAP_WRITE);
173 	if (cap_rights_limit(fileno(out), &rights) < 0 && errno != ENOSYS)
174 		err(1, "unable to limit rights for %s", outfile);
175 
176 	/*
177 	 * Open our execfile and corefile, resolve needed symbols and read in
178 	 * the trace buffer.
179 	 */
180 	if ((kd = kvm_openfiles(Nflag ? execfile : NULL,
181 	    Mflag ? corefile : NULL, NULL, O_RDONLY, errbuf)) == NULL)
182 		errx(1, "%s", errbuf);
183 
184 	/*
185 	 * Cache NLS data, for strerror, for err(3), before entering capability
186 	 * mode.
187 	 */
188 	caph_cache_catpages();
189 
190 	count = kvm_nlist(kd, nl);
191 	if (count == -1)
192 		errx(1, "%s", kvm_geterr(kd));
193 	if (count > 0)
194 		errx(1, "failed to resolve ktr symbols");
195 	if (kvm_read(kd, nl[0].n_value, &version, sizeof(version)) == -1)
196 		errx(1, "%s", kvm_geterr(kd));
197 	if (version != KTR_VERSION)
198 		errx(1, "ktr version mismatch");
199 
200 	/*
201 	 * Enter Capsicum sandbox.
202 	 *
203 	 * kvm_nlist() above uses kldsym(2) for native kernels, and that isn't
204 	 * allowed in the sandbox.
205 	 */
206 	if (cap_enter() < 0 && errno != ENOSYS)
207 		err(1, "unable to enter capability mode");
208 
209 	if (iflag) {
210 		if (fstat(in, &sb) == -1)
211 			errx(1, "stat");
212 		entries = sb.st_size / sizeof(*buf);
213 		index = 0;
214 		buf = mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, in, 0);
215 		if (buf == MAP_FAILED)
216 			errx(1, "mmap");
217 	} else {
218 		if (kvm_read(kd, nl[1].n_value, &entries, sizeof(entries))
219 		    == -1)
220 			errx(1, "%s", kvm_geterr(kd));
221 		if ((buf = malloc(sizeof(*buf) * entries)) == NULL)
222 			err(1, NULL);
223 		if (kvm_read(kd, nl[2].n_value, &index, sizeof(index)) == -1 ||
224 		    kvm_read(kd, nl[3].n_value, &bufptr,
225 		    sizeof(bufptr)) == -1 ||
226 		    kvm_read(kd, bufptr, buf, sizeof(*buf) * entries) == -1 ||
227 		    kvm_read(kd, nl[2].n_value, &index2, sizeof(index2)) == -1)
228 			errx(1, "%s", kvm_geterr(kd));
229 	}
230 
231 	/*
232 	 * Print a nice header.
233 	 */
234 	if (!qflag) {
235 		fprintf(out, "%-6s ", "index");
236 		if (cflag)
237 			fprintf(out, "%-3s ", "cpu");
238 		if (tflag)
239 			fprintf(out, "%-16s ", "timestamp");
240 		if (fflag)
241 			fprintf(out, "%-40s ", "file and line");
242 		if (hflag)
243 			fprintf(out, "%-18s ", "tid");
244 		fprintf(out, "%s", "trace");
245 		fprintf(out, "\n");
246 
247 		fprintf(out, "------ ");
248 		if (cflag)
249 			fprintf(out, "--- ");
250 		if (tflag)
251 			fprintf(out, "---------------- ");
252 		if (fflag)
253 			fprintf(out,
254 			    "---------------------------------------- ");
255 		if (hflag)
256 			fprintf(out, "------------------ ");
257 		fprintf(out, "----- ");
258 		fprintf(out, "\n");
259 	}
260 
261 	/*
262 	 * Now tear through the trace buffer.
263 	 */
264 	if (!iflag) {
265 		i = index - 1;
266 		if (i < 0)
267 			i = entries - 1;
268 	}
269 	tlast = -1;
270 	for (;;) {
271 		if (buf[i].ktr_desc == NULL)
272 			break;
273 		if (kvm_read(kd, (u_long)buf[i].ktr_desc, desc,
274 		    sizeof(desc)) == -1)
275 			errx(1, "%s", kvm_geterr(kd));
276 		desc[sizeof(desc) - 1] = '\0';
277 		parm = 0;
278 		for (p = desc; (c = *p++) != '\0';) {
279 			if (c != '%')
280 				continue;
281 next:			if ((c = *p++) == '\0')
282 				break;
283 			if (parm == KTR_PARMS)
284 				errx(1, "too many parameters in \"%s\"", desc);
285 			switch (c) {
286 			case '0': case '1': case '2': case '3': case '4':
287 			case '5': case '6': case '7': case '8': case '9':
288 			case '#': case '-': case ' ': case '+': case '\'':
289 			case 'h': case 'l': case 'j': case 't': case 'z':
290 			case 'q': case 'L': case '.':
291 				goto next;
292 			case 's':
293 				if (kvm_read(kd, (u_long)buf[i].ktr_parms[parm],
294 				    sbuf[parm], sizeof(sbuf[parm])) == -1)
295 					strcpy(sbuf[parm], "(null)");
296 				sbuf[parm][sizeof(sbuf[0]) - 1] = '\0';
297 				parms[parm] = (u_long)sbuf[parm];
298 				parm++;
299 				break;
300 			default:
301 				parms[parm] = buf[i].ktr_parms[parm];
302 				parm++;
303 				break;
304 			}
305 		}
306 		fprintf(out, "%6d ", i);
307 		if (cflag)
308 			fprintf(out, "%3d ", buf[i].ktr_cpu);
309 		if (tflag) {
310 			tnow = (uintmax_t)buf[i].ktr_timestamp;
311 			if (rflag) {
312 				if (tlast == -1)
313 					tlast = tnow;
314 				fprintf(out, "%16ju ", !iflag ? tlast - tnow :
315 				    tnow - tlast);
316 				tlast = tnow;
317 			} else
318 				fprintf(out, "%16ju ", tnow);
319 		}
320 		if (fflag) {
321 			if (kvm_read(kd, (u_long)buf[i].ktr_file, fbuf,
322 			    sizeof(fbuf)) == -1)
323 				strcpy(fbuf, "(null)");
324 			snprintf(obuf, sizeof(obuf), "%s:%d", fbuf,
325 			    buf[i].ktr_line);
326 			fprintf(out, "%-40s ", obuf);
327 		}
328 		if (hflag)
329 			fprintf(out, "%p ", buf[i].ktr_thread);
330 		fprintf(out, desc, parms[0], parms[1], parms[2], parms[3],
331 		    parms[4], parms[5]);
332 		fprintf(out, "\n");
333 		if (!iflag) {
334 			/*
335 			 * 'index' and 'index2' are the values of 'ktr_idx'
336 			 * before and after the KTR buffer was copied into
337 			 * 'buf'. Since the KTR entries between 'index' and
338 			 * 'index2' were in flux while the KTR buffer was
339 			 * being copied to userspace we don't dump them.
340 			 */
341 			if (i == index2)
342 				break;
343 			if (--i < 0)
344 				i = entries - 1;
345 		} else {
346 			if (++i == entries)
347 				break;
348 		}
349 	}
350 
351 	return (0);
352 }
353 
354 static void
355 usage(void)
356 {
357 
358 	fprintf(stderr, USAGE);
359 	exit(1);
360 }
361