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