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