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