xref: /freebsd/sys/kern/subr_prf.c (revision 3fc9e2c36555140de248a0b4def91bbfa44d7c2c)
1 /*-
2  * Copyright (c) 1986, 1988, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	@(#)subr_prf.c	8.3 (Berkeley) 1/21/94
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include "opt_ddb.h"
41 #include "opt_printf.h"
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/lock.h>
46 #include <sys/kdb.h>
47 #include <sys/mutex.h>
48 #include <sys/sx.h>
49 #include <sys/kernel.h>
50 #include <sys/msgbuf.h>
51 #include <sys/malloc.h>
52 #include <sys/priv.h>
53 #include <sys/proc.h>
54 #include <sys/stddef.h>
55 #include <sys/sysctl.h>
56 #include <sys/tty.h>
57 #include <sys/syslog.h>
58 #include <sys/cons.h>
59 #include <sys/uio.h>
60 #include <sys/ctype.h>
61 
62 #ifdef DDB
63 #include <ddb/ddb.h>
64 #endif
65 
66 /*
67  * Note that stdarg.h and the ANSI style va_start macro is used for both
68  * ANSI and traditional C compilers.
69  */
70 #include <machine/stdarg.h>
71 
72 #define TOCONS	0x01
73 #define TOTTY	0x02
74 #define TOLOG	0x04
75 
76 /* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
77 #define MAXNBUF	(sizeof(intmax_t) * NBBY + 1)
78 
79 struct putchar_arg {
80 	int	flags;
81 	int	pri;
82 	struct	tty *tty;
83 	char	*p_bufr;
84 	size_t	n_bufr;
85 	char	*p_next;
86 	size_t	remain;
87 };
88 
89 struct snprintf_arg {
90 	char	*str;
91 	size_t	remain;
92 };
93 
94 extern	int log_open;
95 
96 static void  msglogchar(int c, int pri);
97 static void  msglogstr(char *str, int pri, int filter_cr);
98 static void  putchar(int ch, void *arg);
99 static char *ksprintn(char *nbuf, uintmax_t num, int base, int *len, int upper);
100 static void  snprintf_func(int ch, void *arg);
101 
102 static int msgbufmapped;		/* Set when safe to use msgbuf */
103 int msgbuftrigger;
104 
105 static int      log_console_output = 1;
106 TUNABLE_INT("kern.log_console_output", &log_console_output);
107 SYSCTL_INT(_kern, OID_AUTO, log_console_output, CTLFLAG_RW,
108     &log_console_output, 0, "Duplicate console output to the syslog.");
109 
110 /*
111  * See the comment in log_console() below for more explanation of this.
112  */
113 static int log_console_add_linefeed = 0;
114 TUNABLE_INT("kern.log_console_add_linefeed", &log_console_add_linefeed);
115 SYSCTL_INT(_kern, OID_AUTO, log_console_add_linefeed, CTLFLAG_RW,
116     &log_console_add_linefeed, 0, "log_console() adds extra newlines.");
117 
118 static int	always_console_output = 0;
119 TUNABLE_INT("kern.always_console_output", &always_console_output);
120 SYSCTL_INT(_kern, OID_AUTO, always_console_output, CTLFLAG_RW,
121     &always_console_output, 0, "Always output to console despite TIOCCONS.");
122 
123 /*
124  * Warn that a system table is full.
125  */
126 void
127 tablefull(const char *tab)
128 {
129 
130 	log(LOG_ERR, "%s: table is full\n", tab);
131 }
132 
133 /*
134  * Uprintf prints to the controlling terminal for the current process.
135  */
136 int
137 uprintf(const char *fmt, ...)
138 {
139 	va_list ap;
140 	struct putchar_arg pca;
141 	struct proc *p;
142 	struct thread *td;
143 	int retval;
144 
145 	td = curthread;
146 	if (TD_IS_IDLETHREAD(td))
147 		return (0);
148 
149 	sx_slock(&proctree_lock);
150 	p = td->td_proc;
151 	PROC_LOCK(p);
152 	if ((p->p_flag & P_CONTROLT) == 0) {
153 		PROC_UNLOCK(p);
154 		retval = 0;
155 		goto out;
156 	}
157 	SESS_LOCK(p->p_session);
158 	pca.tty = p->p_session->s_ttyp;
159 	SESS_UNLOCK(p->p_session);
160 	PROC_UNLOCK(p);
161 	if (pca.tty == NULL) {
162 		retval = 0;
163 		goto out;
164 	}
165 	pca.flags = TOTTY;
166 	pca.p_bufr = NULL;
167 	va_start(ap, fmt);
168 	tty_lock(pca.tty);
169 	retval = kvprintf(fmt, putchar, &pca, 10, ap);
170 	tty_unlock(pca.tty);
171 	va_end(ap);
172 out:
173 	sx_sunlock(&proctree_lock);
174 	return (retval);
175 }
176 
177 /*
178  * tprintf and vtprintf print on the controlling terminal associated with the
179  * given session, possibly to the log as well.
180  */
181 void
182 tprintf(struct proc *p, int pri, const char *fmt, ...)
183 {
184 	va_list ap;
185 
186 	va_start(ap, fmt);
187 	vtprintf(p, pri, fmt, ap);
188 	va_end(ap);
189 }
190 
191 void
192 vtprintf(struct proc *p, int pri, const char *fmt, va_list ap)
193 {
194 	struct tty *tp = NULL;
195 	int flags = 0;
196 	struct putchar_arg pca;
197 	struct session *sess = NULL;
198 
199 	sx_slock(&proctree_lock);
200 	if (pri != -1)
201 		flags |= TOLOG;
202 	if (p != NULL) {
203 		PROC_LOCK(p);
204 		if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
205 			sess = p->p_session;
206 			sess_hold(sess);
207 			PROC_UNLOCK(p);
208 			tp = sess->s_ttyp;
209 			if (tp != NULL && tty_checkoutq(tp))
210 				flags |= TOTTY;
211 			else
212 				tp = NULL;
213 		} else
214 			PROC_UNLOCK(p);
215 	}
216 	pca.pri = pri;
217 	pca.tty = tp;
218 	pca.flags = flags;
219 	pca.p_bufr = NULL;
220 	if (pca.tty != NULL)
221 		tty_lock(pca.tty);
222 	kvprintf(fmt, putchar, &pca, 10, ap);
223 	if (pca.tty != NULL)
224 		tty_unlock(pca.tty);
225 	if (sess != NULL)
226 		sess_release(sess);
227 	msgbuftrigger = 1;
228 	sx_sunlock(&proctree_lock);
229 }
230 
231 /*
232  * Ttyprintf displays a message on a tty; it should be used only by
233  * the tty driver, or anything that knows the underlying tty will not
234  * be revoke(2)'d away.  Other callers should use tprintf.
235  */
236 int
237 ttyprintf(struct tty *tp, const char *fmt, ...)
238 {
239 	va_list ap;
240 	struct putchar_arg pca;
241 	int retval;
242 
243 	va_start(ap, fmt);
244 	pca.tty = tp;
245 	pca.flags = TOTTY;
246 	pca.p_bufr = NULL;
247 	retval = kvprintf(fmt, putchar, &pca, 10, ap);
248 	va_end(ap);
249 	return (retval);
250 }
251 
252 /*
253  * Log writes to the log buffer, and guarantees not to sleep (so can be
254  * called by interrupt routines).  If there is no process reading the
255  * log yet, it writes to the console also.
256  */
257 void
258 log(int level, const char *fmt, ...)
259 {
260 	va_list ap;
261 	struct putchar_arg pca;
262 #ifdef PRINTF_BUFR_SIZE
263 	char bufr[PRINTF_BUFR_SIZE];
264 #endif
265 
266 	pca.tty = NULL;
267 	pca.pri = level;
268 	pca.flags = log_open ? TOLOG : TOCONS;
269 #ifdef PRINTF_BUFR_SIZE
270 	pca.p_bufr = bufr;
271 	pca.p_next = pca.p_bufr;
272 	pca.n_bufr = sizeof(bufr);
273 	pca.remain = sizeof(bufr);
274 	*pca.p_next = '\0';
275 #else
276 	pca.p_bufr = NULL;
277 #endif
278 
279 	va_start(ap, fmt);
280 	kvprintf(fmt, putchar, &pca, 10, ap);
281 	va_end(ap);
282 
283 #ifdef PRINTF_BUFR_SIZE
284 	/* Write any buffered console/log output: */
285 	if (*pca.p_bufr != '\0') {
286 		if (pca.flags & TOLOG)
287 			msglogstr(pca.p_bufr, level, /*filter_cr*/1);
288 
289 		if (pca.flags & TOCONS)
290 			cnputs(pca.p_bufr);
291 	}
292 #endif
293 	msgbuftrigger = 1;
294 }
295 
296 #define CONSCHUNK 128
297 
298 void
299 log_console(struct uio *uio)
300 {
301 	int c, error, nl;
302 	char *consbuffer;
303 	int pri;
304 
305 	if (!log_console_output)
306 		return;
307 
308 	pri = LOG_INFO | LOG_CONSOLE;
309 	uio = cloneuio(uio);
310 	consbuffer = malloc(CONSCHUNK, M_TEMP, M_WAITOK);
311 
312 	nl = 0;
313 	while (uio->uio_resid > 0) {
314 		c = imin(uio->uio_resid, CONSCHUNK - 1);
315 		error = uiomove(consbuffer, c, uio);
316 		if (error != 0)
317 			break;
318 		/* Make sure we're NUL-terminated */
319 		consbuffer[c] = '\0';
320 		if (consbuffer[c - 1] == '\n')
321 			nl = 1;
322 		else
323 			nl = 0;
324 		msglogstr(consbuffer, pri, /*filter_cr*/ 1);
325 	}
326 	/*
327 	 * The previous behavior in log_console() is preserved when
328 	 * log_console_add_linefeed is non-zero.  For that behavior, if an
329 	 * individual console write came in that was not terminated with a
330 	 * line feed, it would add a line feed.
331 	 *
332 	 * This results in different data in the message buffer than
333 	 * appears on the system console (which doesn't add extra line feed
334 	 * characters).
335 	 *
336 	 * A number of programs and rc scripts write a line feed, or a period
337 	 * and a line feed when they have completed their operation.  On
338 	 * the console, this looks seamless, but when displayed with
339 	 * 'dmesg -a', you wind up with output that looks like this:
340 	 *
341 	 * Updating motd:
342 	 * .
343 	 *
344 	 * On the console, it looks like this:
345 	 * Updating motd:.
346 	 *
347 	 * We could add logic to detect that situation, or just not insert
348 	 * the extra newlines.  Set the kern.log_console_add_linefeed
349 	 * sysctl/tunable variable to get the old behavior.
350 	 */
351 	if (!nl && log_console_add_linefeed) {
352 		consbuffer[0] = '\n';
353 		consbuffer[1] = '\0';
354 		msglogstr(consbuffer, pri, /*filter_cr*/ 1);
355 	}
356 	msgbuftrigger = 1;
357 	free(uio, M_IOV);
358 	free(consbuffer, M_TEMP);
359 	return;
360 }
361 
362 int
363 printf(const char *fmt, ...)
364 {
365 	va_list ap;
366 	int retval;
367 
368 	va_start(ap, fmt);
369 	retval = vprintf(fmt, ap);
370 	va_end(ap);
371 
372 	return (retval);
373 }
374 
375 int
376 vprintf(const char *fmt, va_list ap)
377 {
378 	struct putchar_arg pca;
379 	int retval;
380 #ifdef PRINTF_BUFR_SIZE
381 	char bufr[PRINTF_BUFR_SIZE];
382 #endif
383 
384 	pca.tty = NULL;
385 	pca.flags = TOCONS | TOLOG;
386 	pca.pri = -1;
387 #ifdef PRINTF_BUFR_SIZE
388 	pca.p_bufr = bufr;
389 	pca.p_next = pca.p_bufr;
390 	pca.n_bufr = sizeof(bufr);
391 	pca.remain = sizeof(bufr);
392 	*pca.p_next = '\0';
393 #else
394 	/* Don't buffer console output. */
395 	pca.p_bufr = NULL;
396 #endif
397 
398 	retval = kvprintf(fmt, putchar, &pca, 10, ap);
399 
400 #ifdef PRINTF_BUFR_SIZE
401 	/* Write any buffered console/log output: */
402 	if (*pca.p_bufr != '\0') {
403 		cnputs(pca.p_bufr);
404 		msglogstr(pca.p_bufr, pca.pri, /*filter_cr*/ 1);
405 	}
406 #endif
407 
408 	if (!panicstr)
409 		msgbuftrigger = 1;
410 
411 	return (retval);
412 }
413 
414 static void
415 putbuf(int c, struct putchar_arg *ap)
416 {
417 	/* Check if no console output buffer was provided. */
418 	if (ap->p_bufr == NULL) {
419 		/* Output direct to the console. */
420 		if (ap->flags & TOCONS)
421 			cnputc(c);
422 
423 		if (ap->flags & TOLOG)
424 			msglogchar(c, ap->pri);
425 	} else {
426 		/* Buffer the character: */
427 		*ap->p_next++ = c;
428 		ap->remain--;
429 
430 		/* Always leave the buffer zero terminated. */
431 		*ap->p_next = '\0';
432 
433 		/* Check if the buffer needs to be flushed. */
434 		if (ap->remain == 2 || c == '\n') {
435 
436 			if (ap->flags & TOLOG)
437 				msglogstr(ap->p_bufr, ap->pri, /*filter_cr*/1);
438 
439 			if (ap->flags & TOCONS) {
440 				if ((panicstr == NULL) && (constty != NULL))
441 					msgbuf_addstr(&consmsgbuf, -1,
442 					    ap->p_bufr, /*filter_cr*/ 0);
443 
444 				if ((constty == NULL) ||(always_console_output))
445 					cnputs(ap->p_bufr);
446 			}
447 
448 			ap->p_next = ap->p_bufr;
449 			ap->remain = ap->n_bufr;
450 			*ap->p_next = '\0';
451 		}
452 
453 		/*
454 		 * Since we fill the buffer up one character at a time,
455 		 * this should not happen.  We should always catch it when
456 		 * ap->remain == 2 (if not sooner due to a newline), flush
457 		 * the buffer and move on.  One way this could happen is
458 		 * if someone sets PRINTF_BUFR_SIZE to 1 or something
459 		 * similarly silly.
460 		 */
461 		KASSERT(ap->remain > 2, ("Bad buffer logic, remain = %zd",
462 		    ap->remain));
463 	}
464 }
465 
466 /*
467  * Print a character on console or users terminal.  If destination is
468  * the console then the last bunch of characters are saved in msgbuf for
469  * inspection later.
470  */
471 static void
472 putchar(int c, void *arg)
473 {
474 	struct putchar_arg *ap = (struct putchar_arg*) arg;
475 	struct tty *tp = ap->tty;
476 	int flags = ap->flags;
477 
478 	/* Don't use the tty code after a panic or while in ddb. */
479 	if (kdb_active) {
480 		if (c != '\0')
481 			cnputc(c);
482 		return;
483 	}
484 
485 	if ((flags & TOTTY) && tp != NULL && panicstr == NULL)
486 		tty_putchar(tp, c);
487 
488 	if ((flags & (TOCONS | TOLOG)) && c != '\0')
489 		putbuf(c, ap);
490 }
491 
492 /*
493  * Scaled down version of sprintf(3).
494  */
495 int
496 sprintf(char *buf, const char *cfmt, ...)
497 {
498 	int retval;
499 	va_list ap;
500 
501 	va_start(ap, cfmt);
502 	retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
503 	buf[retval] = '\0';
504 	va_end(ap);
505 	return (retval);
506 }
507 
508 /*
509  * Scaled down version of vsprintf(3).
510  */
511 int
512 vsprintf(char *buf, const char *cfmt, va_list ap)
513 {
514 	int retval;
515 
516 	retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
517 	buf[retval] = '\0';
518 	return (retval);
519 }
520 
521 /*
522  * Scaled down version of snprintf(3).
523  */
524 int
525 snprintf(char *str, size_t size, const char *format, ...)
526 {
527 	int retval;
528 	va_list ap;
529 
530 	va_start(ap, format);
531 	retval = vsnprintf(str, size, format, ap);
532 	va_end(ap);
533 	return(retval);
534 }
535 
536 /*
537  * Scaled down version of vsnprintf(3).
538  */
539 int
540 vsnprintf(char *str, size_t size, const char *format, va_list ap)
541 {
542 	struct snprintf_arg info;
543 	int retval;
544 
545 	info.str = str;
546 	info.remain = size;
547 	retval = kvprintf(format, snprintf_func, &info, 10, ap);
548 	if (info.remain >= 1)
549 		*info.str++ = '\0';
550 	return (retval);
551 }
552 
553 /*
554  * Kernel version which takes radix argument vsnprintf(3).
555  */
556 int
557 vsnrprintf(char *str, size_t size, int radix, const char *format, va_list ap)
558 {
559 	struct snprintf_arg info;
560 	int retval;
561 
562 	info.str = str;
563 	info.remain = size;
564 	retval = kvprintf(format, snprintf_func, &info, radix, ap);
565 	if (info.remain >= 1)
566 		*info.str++ = '\0';
567 	return (retval);
568 }
569 
570 static void
571 snprintf_func(int ch, void *arg)
572 {
573 	struct snprintf_arg *const info = arg;
574 
575 	if (info->remain >= 2) {
576 		*info->str++ = ch;
577 		info->remain--;
578 	}
579 }
580 
581 /*
582  * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
583  * order; return an optional length and a pointer to the last character
584  * written in the buffer (i.e., the first character of the string).
585  * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
586  */
587 static char *
588 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
589 {
590 	char *p, c;
591 
592 	p = nbuf;
593 	*p = '\0';
594 	do {
595 		c = hex2ascii(num % base);
596 		*++p = upper ? toupper(c) : c;
597 	} while (num /= base);
598 	if (lenp)
599 		*lenp = p - nbuf;
600 	return (p);
601 }
602 
603 /*
604  * Scaled down version of printf(3).
605  *
606  * Two additional formats:
607  *
608  * The format %b is supported to decode error registers.
609  * Its usage is:
610  *
611  *	printf("reg=%b\n", regval, "<base><arg>*");
612  *
613  * where <base> is the output base expressed as a control character, e.g.
614  * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
615  * the first of which gives the bit number to be inspected (origin 1), and
616  * the next characters (up to a control character, i.e. a character <= 32),
617  * give the name of the register.  Thus:
618  *
619  *	kvprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
620  *
621  * would produce output:
622  *
623  *	reg=3<BITTWO,BITONE>
624  *
625  * XXX:  %D  -- Hexdump, takes pointer and separator string:
626  *		("%6D", ptr, ":")   -> XX:XX:XX:XX:XX:XX
627  *		("%*D", len, ptr, " " -> XX XX XX XX ...
628  */
629 int
630 kvprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, va_list ap)
631 {
632 #define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; }
633 	char nbuf[MAXNBUF];
634 	char *d;
635 	const char *p, *percent, *q;
636 	u_char *up;
637 	int ch, n;
638 	uintmax_t num;
639 	int base, lflag, qflag, tmp, width, ladjust, sharpflag, neg, sign, dot;
640 	int cflag, hflag, jflag, tflag, zflag;
641 	int dwidth, upper;
642 	char padc;
643 	int stop = 0, retval = 0;
644 
645 	num = 0;
646 	if (!func)
647 		d = (char *) arg;
648 	else
649 		d = NULL;
650 
651 	if (fmt == NULL)
652 		fmt = "(fmt null)\n";
653 
654 	if (radix < 2 || radix > 36)
655 		radix = 10;
656 
657 	for (;;) {
658 		padc = ' ';
659 		width = 0;
660 		while ((ch = (u_char)*fmt++) != '%' || stop) {
661 			if (ch == '\0')
662 				return (retval);
663 			PCHAR(ch);
664 		}
665 		percent = fmt - 1;
666 		qflag = 0; lflag = 0; ladjust = 0; sharpflag = 0; neg = 0;
667 		sign = 0; dot = 0; dwidth = 0; upper = 0;
668 		cflag = 0; hflag = 0; jflag = 0; tflag = 0; zflag = 0;
669 reswitch:	switch (ch = (u_char)*fmt++) {
670 		case '.':
671 			dot = 1;
672 			goto reswitch;
673 		case '#':
674 			sharpflag = 1;
675 			goto reswitch;
676 		case '+':
677 			sign = 1;
678 			goto reswitch;
679 		case '-':
680 			ladjust = 1;
681 			goto reswitch;
682 		case '%':
683 			PCHAR(ch);
684 			break;
685 		case '*':
686 			if (!dot) {
687 				width = va_arg(ap, int);
688 				if (width < 0) {
689 					ladjust = !ladjust;
690 					width = -width;
691 				}
692 			} else {
693 				dwidth = va_arg(ap, int);
694 			}
695 			goto reswitch;
696 		case '0':
697 			if (!dot) {
698 				padc = '0';
699 				goto reswitch;
700 			}
701 		case '1': case '2': case '3': case '4':
702 		case '5': case '6': case '7': case '8': case '9':
703 				for (n = 0;; ++fmt) {
704 					n = n * 10 + ch - '0';
705 					ch = *fmt;
706 					if (ch < '0' || ch > '9')
707 						break;
708 				}
709 			if (dot)
710 				dwidth = n;
711 			else
712 				width = n;
713 			goto reswitch;
714 		case 'b':
715 			num = (u_int)va_arg(ap, int);
716 			p = va_arg(ap, char *);
717 			for (q = ksprintn(nbuf, num, *p++, NULL, 0); *q;)
718 				PCHAR(*q--);
719 
720 			if (num == 0)
721 				break;
722 
723 			for (tmp = 0; *p;) {
724 				n = *p++;
725 				if (num & (1 << (n - 1))) {
726 					PCHAR(tmp ? ',' : '<');
727 					for (; (n = *p) > ' '; ++p)
728 						PCHAR(n);
729 					tmp = 1;
730 				} else
731 					for (; *p > ' '; ++p)
732 						continue;
733 			}
734 			if (tmp)
735 				PCHAR('>');
736 			break;
737 		case 'c':
738 			PCHAR(va_arg(ap, int));
739 			break;
740 		case 'D':
741 			up = va_arg(ap, u_char *);
742 			p = va_arg(ap, char *);
743 			if (!width)
744 				width = 16;
745 			while(width--) {
746 				PCHAR(hex2ascii(*up >> 4));
747 				PCHAR(hex2ascii(*up & 0x0f));
748 				up++;
749 				if (width)
750 					for (q=p;*q;q++)
751 						PCHAR(*q);
752 			}
753 			break;
754 		case 'd':
755 		case 'i':
756 			base = 10;
757 			sign = 1;
758 			goto handle_sign;
759 		case 'h':
760 			if (hflag) {
761 				hflag = 0;
762 				cflag = 1;
763 			} else
764 				hflag = 1;
765 			goto reswitch;
766 		case 'j':
767 			jflag = 1;
768 			goto reswitch;
769 		case 'l':
770 			if (lflag) {
771 				lflag = 0;
772 				qflag = 1;
773 			} else
774 				lflag = 1;
775 			goto reswitch;
776 		case 'n':
777 			if (jflag)
778 				*(va_arg(ap, intmax_t *)) = retval;
779 			else if (qflag)
780 				*(va_arg(ap, quad_t *)) = retval;
781 			else if (lflag)
782 				*(va_arg(ap, long *)) = retval;
783 			else if (zflag)
784 				*(va_arg(ap, size_t *)) = retval;
785 			else if (hflag)
786 				*(va_arg(ap, short *)) = retval;
787 			else if (cflag)
788 				*(va_arg(ap, char *)) = retval;
789 			else
790 				*(va_arg(ap, int *)) = retval;
791 			break;
792 		case 'o':
793 			base = 8;
794 			goto handle_nosign;
795 		case 'p':
796 			base = 16;
797 			sharpflag = (width == 0);
798 			sign = 0;
799 			num = (uintptr_t)va_arg(ap, void *);
800 			goto number;
801 		case 'q':
802 			qflag = 1;
803 			goto reswitch;
804 		case 'r':
805 			base = radix;
806 			if (sign)
807 				goto handle_sign;
808 			goto handle_nosign;
809 		case 's':
810 			p = va_arg(ap, char *);
811 			if (p == NULL)
812 				p = "(null)";
813 			if (!dot)
814 				n = strlen (p);
815 			else
816 				for (n = 0; n < dwidth && p[n]; n++)
817 					continue;
818 
819 			width -= n;
820 
821 			if (!ladjust && width > 0)
822 				while (width--)
823 					PCHAR(padc);
824 			while (n--)
825 				PCHAR(*p++);
826 			if (ladjust && width > 0)
827 				while (width--)
828 					PCHAR(padc);
829 			break;
830 		case 't':
831 			tflag = 1;
832 			goto reswitch;
833 		case 'u':
834 			base = 10;
835 			goto handle_nosign;
836 		case 'X':
837 			upper = 1;
838 		case 'x':
839 			base = 16;
840 			goto handle_nosign;
841 		case 'y':
842 			base = 16;
843 			sign = 1;
844 			goto handle_sign;
845 		case 'z':
846 			zflag = 1;
847 			goto reswitch;
848 handle_nosign:
849 			sign = 0;
850 			if (jflag)
851 				num = va_arg(ap, uintmax_t);
852 			else if (qflag)
853 				num = va_arg(ap, u_quad_t);
854 			else if (tflag)
855 				num = va_arg(ap, ptrdiff_t);
856 			else if (lflag)
857 				num = va_arg(ap, u_long);
858 			else if (zflag)
859 				num = va_arg(ap, size_t);
860 			else if (hflag)
861 				num = (u_short)va_arg(ap, int);
862 			else if (cflag)
863 				num = (u_char)va_arg(ap, int);
864 			else
865 				num = va_arg(ap, u_int);
866 			goto number;
867 handle_sign:
868 			if (jflag)
869 				num = va_arg(ap, intmax_t);
870 			else if (qflag)
871 				num = va_arg(ap, quad_t);
872 			else if (tflag)
873 				num = va_arg(ap, ptrdiff_t);
874 			else if (lflag)
875 				num = va_arg(ap, long);
876 			else if (zflag)
877 				num = va_arg(ap, ssize_t);
878 			else if (hflag)
879 				num = (short)va_arg(ap, int);
880 			else if (cflag)
881 				num = (char)va_arg(ap, int);
882 			else
883 				num = va_arg(ap, int);
884 number:
885 			if (sign && (intmax_t)num < 0) {
886 				neg = 1;
887 				num = -(intmax_t)num;
888 			}
889 			p = ksprintn(nbuf, num, base, &n, upper);
890 			tmp = 0;
891 			if (sharpflag && num != 0) {
892 				if (base == 8)
893 					tmp++;
894 				else if (base == 16)
895 					tmp += 2;
896 			}
897 			if (neg)
898 				tmp++;
899 
900 			if (!ladjust && padc == '0')
901 				dwidth = width - tmp;
902 			width -= tmp + imax(dwidth, n);
903 			dwidth -= n;
904 			if (!ladjust)
905 				while (width-- > 0)
906 					PCHAR(' ');
907 			if (neg)
908 				PCHAR('-');
909 			if (sharpflag && num != 0) {
910 				if (base == 8) {
911 					PCHAR('0');
912 				} else if (base == 16) {
913 					PCHAR('0');
914 					PCHAR('x');
915 				}
916 			}
917 			while (dwidth-- > 0)
918 				PCHAR('0');
919 
920 			while (*p)
921 				PCHAR(*p--);
922 
923 			if (ladjust)
924 				while (width-- > 0)
925 					PCHAR(' ');
926 
927 			break;
928 		default:
929 			while (percent < fmt)
930 				PCHAR(*percent++);
931 			/*
932 			 * Since we ignore an formatting argument it is no
933 			 * longer safe to obey the remaining formatting
934 			 * arguments as the arguments will no longer match
935 			 * the format specs.
936 			 */
937 			stop = 1;
938 			break;
939 		}
940 	}
941 #undef PCHAR
942 }
943 
944 /*
945  * Put character in log buffer with a particular priority.
946  */
947 static void
948 msglogchar(int c, int pri)
949 {
950 	static int lastpri = -1;
951 	static int dangling;
952 	char nbuf[MAXNBUF];
953 	char *p;
954 
955 	if (!msgbufmapped)
956 		return;
957 	if (c == '\0' || c == '\r')
958 		return;
959 	if (pri != -1 && pri != lastpri) {
960 		if (dangling) {
961 			msgbuf_addchar(msgbufp, '\n');
962 			dangling = 0;
963 		}
964 		msgbuf_addchar(msgbufp, '<');
965 		for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
966 			msgbuf_addchar(msgbufp, *p--);
967 		msgbuf_addchar(msgbufp, '>');
968 		lastpri = pri;
969 	}
970 	msgbuf_addchar(msgbufp, c);
971 	if (c == '\n') {
972 		dangling = 0;
973 		lastpri = -1;
974 	} else {
975 		dangling = 1;
976 	}
977 }
978 
979 static void
980 msglogstr(char *str, int pri, int filter_cr)
981 {
982 	if (!msgbufmapped)
983 		return;
984 
985 	msgbuf_addstr(msgbufp, pri, str, filter_cr);
986 }
987 
988 void
989 msgbufinit(void *ptr, int size)
990 {
991 	char *cp;
992 	static struct msgbuf *oldp = NULL;
993 
994 	size -= sizeof(*msgbufp);
995 	cp = (char *)ptr;
996 	msgbufp = (struct msgbuf *)(cp + size);
997 	msgbuf_reinit(msgbufp, cp, size);
998 	if (msgbufmapped && oldp != msgbufp)
999 		msgbuf_copy(oldp, msgbufp);
1000 	msgbufmapped = 1;
1001 	oldp = msgbufp;
1002 }
1003 
1004 static int unprivileged_read_msgbuf = 1;
1005 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_read_msgbuf,
1006     CTLFLAG_RW, &unprivileged_read_msgbuf, 0,
1007     "Unprivileged processes may read the kernel message buffer");
1008 
1009 /* Sysctls for accessing/clearing the msgbuf */
1010 static int
1011 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
1012 {
1013 	char buf[128];
1014 	u_int seq;
1015 	int error, len;
1016 
1017 	if (!unprivileged_read_msgbuf) {
1018 		error = priv_check(req->td, PRIV_MSGBUF);
1019 		if (error)
1020 			return (error);
1021 	}
1022 
1023 	/* Read the whole buffer, one chunk at a time. */
1024 	mtx_lock(&msgbuf_lock);
1025 	msgbuf_peekbytes(msgbufp, NULL, 0, &seq);
1026 	for (;;) {
1027 		len = msgbuf_peekbytes(msgbufp, buf, sizeof(buf), &seq);
1028 		mtx_unlock(&msgbuf_lock);
1029 		if (len == 0)
1030 			return (0);
1031 
1032 		error = sysctl_handle_opaque(oidp, buf, len, req);
1033 		if (error)
1034 			return (error);
1035 
1036 		mtx_lock(&msgbuf_lock);
1037 	}
1038 }
1039 
1040 SYSCTL_PROC(_kern, OID_AUTO, msgbuf,
1041     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
1042     NULL, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
1043 
1044 static int msgbuf_clearflag;
1045 
1046 static int
1047 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
1048 {
1049 	int error;
1050 	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1051 	if (!error && req->newptr) {
1052 		mtx_lock(&msgbuf_lock);
1053 		msgbuf_clear(msgbufp);
1054 		mtx_unlock(&msgbuf_lock);
1055 		msgbuf_clearflag = 0;
1056 	}
1057 	return (error);
1058 }
1059 
1060 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
1061     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE | CTLFLAG_MPSAFE,
1062     &msgbuf_clearflag, 0, sysctl_kern_msgbuf_clear, "I",
1063     "Clear kernel message buffer");
1064 
1065 #ifdef DDB
1066 
1067 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
1068 {
1069 	int i, j;
1070 
1071 	if (!msgbufmapped) {
1072 		db_printf("msgbuf not mapped yet\n");
1073 		return;
1074 	}
1075 	db_printf("msgbufp = %p\n", msgbufp);
1076 	db_printf("magic = %x, size = %d, r= %u, w = %u, ptr = %p, cksum= %u\n",
1077 	    msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_rseq,
1078 	    msgbufp->msg_wseq, msgbufp->msg_ptr, msgbufp->msg_cksum);
1079 	for (i = 0; i < msgbufp->msg_size && !db_pager_quit; i++) {
1080 		j = MSGBUF_SEQ_TO_POS(msgbufp, i + msgbufp->msg_rseq);
1081 		db_printf("%c", msgbufp->msg_ptr[j]);
1082 	}
1083 	db_printf("\n");
1084 }
1085 
1086 #endif /* DDB */
1087 
1088 void
1089 hexdump(const void *ptr, int length, const char *hdr, int flags)
1090 {
1091 	int i, j, k;
1092 	int cols;
1093 	const unsigned char *cp;
1094 	char delim;
1095 
1096 	if ((flags & HD_DELIM_MASK) != 0)
1097 		delim = (flags & HD_DELIM_MASK) >> 8;
1098 	else
1099 		delim = ' ';
1100 
1101 	if ((flags & HD_COLUMN_MASK) != 0)
1102 		cols = flags & HD_COLUMN_MASK;
1103 	else
1104 		cols = 16;
1105 
1106 	cp = ptr;
1107 	for (i = 0; i < length; i+= cols) {
1108 		if (hdr != NULL)
1109 			printf("%s", hdr);
1110 
1111 		if ((flags & HD_OMIT_COUNT) == 0)
1112 			printf("%04x  ", i);
1113 
1114 		if ((flags & HD_OMIT_HEX) == 0) {
1115 			for (j = 0; j < cols; j++) {
1116 				k = i + j;
1117 				if (k < length)
1118 					printf("%c%02x", delim, cp[k]);
1119 				else
1120 					printf("   ");
1121 			}
1122 		}
1123 
1124 		if ((flags & HD_OMIT_CHARS) == 0) {
1125 			printf("  |");
1126 			for (j = 0; j < cols; j++) {
1127 				k = i + j;
1128 				if (k >= length)
1129 					printf(" ");
1130 				else if (cp[k] >= ' ' && cp[k] <= '~')
1131 					printf("%c", cp[k]);
1132 				else
1133 					printf(".");
1134 			}
1135 			printf("|");
1136 		}
1137 		printf("\n");
1138 	}
1139 }
1140 
1141