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