xref: /freebsd/sbin/dmesg/dmesg.c (revision a7233085558db6d2ee0251891a85a7e74dddcb7e)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/types.h>
33 #include <sys/msgbuf.h>
34 #include <sys/sysctl.h>
35 #include <sys/syslog.h>
36 #include <sys/time.h>
37 
38 #include <ctype.h>
39 #include <err.h>
40 #include <errno.h>
41 #include <fcntl.h>
42 #include <kvm.h>
43 #include <limits.h>
44 #include <locale.h>
45 #include <nlist.h>
46 #include <stdio.h>
47 #include <stdbool.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <unistd.h>
51 #include <vis.h>
52 
53 static struct nlist nl[] = {
54 #define	X_MSGBUF	0
55 	{ "_msgbufp", 0, 0, 0, 0 },
56 	{ NULL, 0, 0, 0, 0 },
57 };
58 
59 void usage(void) __dead2;
60 
61 #define	KREAD(addr, var) \
62 	kvm_read(kd, addr, &var, sizeof(var)) != sizeof(var)
63 
64 int
main(int argc,char * argv[])65 main(int argc, char *argv[])
66 {
67 	struct msgbuf *bufp, cur;
68 	struct timeval boottime, reltime, abstime;
69 	char timebuf[1024];
70 	char *bp, *ep, *memf, *nextp, *nlistf, *p, *q, *visbp;
71 	const char *timefmt = "%d %b %T";
72 	kvm_t *kd;
73 	size_t buflen, bufpos;
74 	long pri;
75 	int ch, clear;
76 	bool all, timeconv;
77 
78 	all = false;
79 	clear = false;
80 	timeconv = false;
81 	(void) setlocale(LC_CTYPE, "");
82 	memf = nlistf = NULL;
83 	while ((ch = getopt(argc, argv, "actM:N:f:")) != -1)
84 		switch(ch) {
85 		case 'a':
86 			all = true;
87 			break;
88 		case 'c':
89 			clear = true;
90 			break;
91 		case 't':
92 			timeconv = true;
93 			break;
94 		case 'M':
95 			memf = optarg;
96 			break;
97 		case 'N':
98 			nlistf = optarg;
99 			break;
100 		case 'f':
101 			timefmt = optarg;
102 			break;
103 		case '?':
104 		default:
105 			usage();
106 		}
107 	argc -= optind;
108 	if (argc != 0)
109 		usage();
110 
111 	if (timeconv) {
112 		int mib[2] = {CTL_KERN, KERN_BOOTTIME};
113 
114 		size_t l = sizeof(boottime);
115 		if (sysctl(mib, 2, &boottime, &l, 0, 0) < 0)
116 			err(1, "sysctl kern.boottime");
117         }
118 
119 	if (memf == NULL) {
120 		/*
121 		 * Running kernel.  Use sysctl.  This gives an unwrapped buffer
122 		 * as a side effect.  Remove nulterm (if present) so the value
123 		 * returned by sysctl is formatted as the rest of the code
124 		 * expects (the same as the value read from a core file below).
125 		 */
126 		if (sysctlbyname("kern.msgbuf", NULL, &buflen, NULL, 0) == -1)
127 			err(1, "sysctl kern.msgbuf");
128 		/* Allocate extra room for growth between the sysctl calls. */
129 		buflen += buflen/8;
130 		/* Allocate more than sysctl sees, for room to append \n\0. */
131 		if ((bp = malloc(buflen + 2)) == NULL)
132 			errx(1, "malloc failed");
133 		if (sysctlbyname("kern.msgbuf", bp, &buflen, NULL, 0) == -1)
134 			err(1, "sysctl kern.msgbuf");
135 		if (buflen > 0 && bp[buflen - 1] == '\0')
136 			buflen--;
137 		if (clear)
138 			if (sysctlbyname("kern.msgbuf_clear", NULL, NULL, &clear, sizeof(int)))
139 				err(1, "sysctl kern.msgbuf_clear");
140 	} else {
141 		/* Read in kernel message buffer and do sanity checks. */
142 		kd = kvm_open(nlistf, memf, NULL, O_RDONLY, "dmesg");
143 		if (kd == NULL)
144 			exit (1);
145 		if (kvm_nlist(kd, nl) == -1)
146 			errx(1, "kvm_nlist: %s", kvm_geterr(kd));
147 		if (nl[X_MSGBUF].n_type == 0)
148 			errx(1, "%s: msgbufp not found",
149 			    nlistf ? nlistf : "namelist");
150 		if (KREAD(nl[X_MSGBUF].n_value, bufp) || KREAD((long)bufp, cur))
151 			errx(1, "kvm_read: %s", kvm_geterr(kd));
152 		if (cur.msg_magic != MSG_MAGIC)
153 			errx(1, "kernel message buffer has different magic "
154 			    "number");
155 		if ((bp = malloc(cur.msg_size + 2)) == NULL)
156 			errx(1, "malloc failed");
157 
158 		/* Unwrap the circular buffer to start from the oldest data. */
159 		bufpos = MSGBUF_SEQ_TO_POS(&cur, cur.msg_wseq);
160 		if (kvm_read(kd, (long)&cur.msg_ptr[bufpos], bp,
161 		    cur.msg_size - bufpos) != (ssize_t)(cur.msg_size - bufpos))
162 			errx(1, "kvm_read: %s", kvm_geterr(kd));
163 		if (bufpos != 0 && kvm_read(kd, (long)cur.msg_ptr,
164 		    &bp[cur.msg_size - bufpos], bufpos) != (ssize_t)bufpos)
165 			errx(1, "kvm_read: %s", kvm_geterr(kd));
166 		kvm_close(kd);
167 		buflen = cur.msg_size;
168 	}
169 
170 	/*
171 	 * Ensure that the buffer ends with a newline and a \0 to avoid
172 	 * complications below.  We left space above.
173 	 */
174 	if (buflen == 0 || bp[buflen - 1] != '\n')
175 		bp[buflen++] = '\n';
176 	bp[buflen] = '\0';
177 
178 	if ((visbp = malloc(4 * buflen + 1)) == NULL)
179 		errx(1, "malloc failed");
180 
181 	/*
182 	 * The message buffer is circular, but has been unwrapped so that
183 	 * the oldest data comes first.  The data will be preceded by \0's
184 	 * if the message buffer was not full.
185 	 */
186 	p = bp;
187 	ep = &bp[buflen];
188 	if (*p == '\0') {
189 		/* Strip leading \0's */
190 		while (*p == '\0')
191 			p++;
192 	}
193 	for (; p < ep; p = nextp) {
194 		nextp = memchr(p, '\n', ep - p);
195 		nextp++;
196 
197 		/* Skip ^<[0-9]+> syslog sequences. */
198 		if (*p == '<' && isdigit(*(p+1))) {
199 			errno = 0;
200 			pri = strtol(p + 1, &q, 10);
201 			if (*q == '>' && pri >= 0 && pri < INT_MAX &&
202 			    errno == 0) {
203 				if (LOG_FAC(pri) != LOG_KERN && !all)
204 					continue;
205 				p = q + 1;
206 			}
207 		}
208 
209 		(void)strvisx(visbp, p, nextp - p, 0);
210 		if (!timeconv) {
211 			printf("%s", visbp);
212 			continue;
213 		}
214 
215 		if (visbp[0] != '[') {
216 			printf("%s", visbp);
217 			continue;
218 		}
219 
220 		reltime.tv_usec = 0;
221 		errno = 0;
222 		reltime.tv_sec = strtoul(visbp + 1, &q, 10);
223 		if (errno != 0) {
224 			printf("%s", visbp);
225 			continue;
226 		}
227 
228 		if (*q == '.') {
229 			errno = 0;
230 			reltime.tv_usec = strtof(q, &q) * 1000000.0;
231 			if (errno != 0) {
232 				printf("%s", visbp);
233 				continue;
234 			}
235 		}
236 
237 		if (*q != ']' || q[1] != ' ') {
238 			printf("%s", visbp);
239 			continue;
240 		}
241 		q++;
242 
243 		timeradd(&boottime, &reltime, &abstime);
244 
245 		if (strftime(timebuf, sizeof timebuf, timefmt,
246 		    localtime(&abstime.tv_sec)) != 0) {
247 			printf("[%s]%s", timebuf, q);
248 		} else {
249 			printf("%s", visbp);
250 			continue;
251 		}
252 	}
253 	exit(0);
254 }
255 
256 void
usage(void)257 usage(void)
258 {
259 	fprintf(stderr, "usage: dmesg [-ac] [-t [-f output_fmt]] [-M core [-N system]]\n");
260 	exit(1);
261 }
262