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.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
34 * @(#)subr_prf.c 8.3 (Berkeley) 1/21/94
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
41 #include "opt_printf.h"
43 #include <sys/param.h>
44 #include <sys/systm.h>
47 #include <sys/mutex.h>
49 #include <sys/kernel.h>
50 #include <sys/msgbuf.h>
51 #include <sys/malloc.h>
54 #include <sys/stddef.h>
55 #include <sys/sysctl.h>
57 #include <sys/syslog.h>
60 #include <sys/ctype.h>
67 * Note that stdarg.h and the ANSI style va_start macro is used for both
68 * ANSI and traditional C compilers.
70 #include <machine/stdarg.h>
76 /* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
77 #define MAXNBUF (sizeof(intmax_t) * NBBY + 1)
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);
102 static int msgbufmapped; /* Set when safe to use msgbuf */
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.");
111 * See the comment in log_console() below for more explanation of this.
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.");
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.");
124 * Warn that a system table is full.
127 tablefull(const char *tab)
130 log(LOG_ERR, "%s: table is full\n", tab);
134 * Uprintf prints to the controlling terminal for the current process.
137 uprintf(const char *fmt, ...)
140 struct putchar_arg pca;
146 if (TD_IS_IDLETHREAD(td))
149 sx_slock(&proctree_lock);
152 if ((p->p_flag & P_CONTROLT) == 0) {
157 SESS_LOCK(p->p_session);
158 pca.tty = p->p_session->s_ttyp;
159 SESS_UNLOCK(p->p_session);
161 if (pca.tty == NULL) {
169 retval = kvprintf(fmt, putchar, &pca, 10, ap);
173 sx_sunlock(&proctree_lock);
178 * tprintf prints on the controlling terminal associated with the given
179 * session, possibly to the log as well.
182 tprintf(struct proc *p, int pri, const char *fmt, ...)
184 struct tty *tp = NULL;
187 struct putchar_arg pca;
188 struct session *sess = NULL;
190 sx_slock(&proctree_lock);
195 if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
200 if (tp != NULL && tty_checkoutq(tp))
214 kvprintf(fmt, putchar, &pca, 10, ap);
221 sx_sunlock(&proctree_lock);
225 * Ttyprintf displays a message on a tty; it should be used only by
226 * the tty driver, or anything that knows the underlying tty will not
227 * be revoke(2)'d away. Other callers should use tprintf.
230 ttyprintf(struct tty *tp, const char *fmt, ...)
233 struct putchar_arg pca;
240 retval = kvprintf(fmt, putchar, &pca, 10, ap);
246 * Log writes to the log buffer, and guarantees not to sleep (so can be
247 * called by interrupt routines). If there is no process reading the
248 * log yet, it writes to the console also.
251 log(int level, const char *fmt, ...)
254 struct putchar_arg pca;
255 #ifdef PRINTF_BUFR_SIZE
256 char bufr[PRINTF_BUFR_SIZE];
261 pca.flags = log_open ? TOLOG : TOCONS;
262 #ifdef PRINTF_BUFR_SIZE
264 pca.p_next = pca.p_bufr;
265 pca.n_bufr = sizeof(bufr);
266 pca.remain = sizeof(bufr);
273 kvprintf(fmt, putchar, &pca, 10, ap);
276 #ifdef PRINTF_BUFR_SIZE
277 /* Write any buffered console/log output: */
278 if (*pca.p_bufr != '\0') {
279 if (pca.flags & TOLOG)
280 msglogstr(pca.p_bufr, level, /*filter_cr*/1);
282 if (pca.flags & TOCONS)
289 #define CONSCHUNK 128
292 log_console(struct uio *uio)
298 if (!log_console_output)
301 pri = LOG_INFO | LOG_CONSOLE;
303 consbuffer = malloc(CONSCHUNK, M_TEMP, M_WAITOK);
306 while (uio->uio_resid > 0) {
307 c = imin(uio->uio_resid, CONSCHUNK - 1);
308 error = uiomove(consbuffer, c, uio);
311 /* Make sure we're NUL-terminated */
312 consbuffer[c] = '\0';
313 if (consbuffer[c - 1] == '\n')
317 msglogstr(consbuffer, pri, /*filter_cr*/ 1);
320 * The previous behavior in log_console() is preserved when
321 * log_console_add_linefeed is non-zero. For that behavior, if an
322 * individual console write came in that was not terminated with a
323 * line feed, it would add a line feed.
325 * This results in different data in the message buffer than
326 * appears on the system console (which doesn't add extra line feed
329 * A number of programs and rc scripts write a line feed, or a period
330 * and a line feed when they have completed their operation. On
331 * the console, this looks seamless, but when displayed with
332 * 'dmesg -a', you wind up with output that looks like this:
337 * On the console, it looks like this:
340 * We could add logic to detect that situation, or just not insert
341 * the extra newlines. Set the kern.log_console_add_linefeed
342 * sysctl/tunable variable to get the old behavior.
344 if (!nl && log_console_add_linefeed) {
345 consbuffer[0] = '\n';
346 consbuffer[1] = '\0';
347 msglogstr(consbuffer, pri, /*filter_cr*/ 1);
351 free(consbuffer, M_TEMP);
356 printf(const char *fmt, ...)
362 retval = vprintf(fmt, ap);
369 vprintf(const char *fmt, va_list ap)
371 struct putchar_arg pca;
373 #ifdef PRINTF_BUFR_SIZE
374 char bufr[PRINTF_BUFR_SIZE];
378 pca.flags = TOCONS | TOLOG;
380 #ifdef PRINTF_BUFR_SIZE
382 pca.p_next = pca.p_bufr;
383 pca.n_bufr = sizeof(bufr);
384 pca.remain = sizeof(bufr);
387 /* Don't buffer console output. */
391 retval = kvprintf(fmt, putchar, &pca, 10, ap);
393 #ifdef PRINTF_BUFR_SIZE
394 /* Write any buffered console/log output: */
395 if (*pca.p_bufr != '\0') {
397 msglogstr(pca.p_bufr, pca.pri, /*filter_cr*/ 1);
408 putbuf(int c, struct putchar_arg *ap)
410 /* Check if no console output buffer was provided. */
411 if (ap->p_bufr == NULL) {
412 /* Output direct to the console. */
413 if (ap->flags & TOCONS)
416 if (ap->flags & TOLOG)
417 msglogchar(c, ap->pri);
419 /* Buffer the character: */
423 /* Always leave the buffer zero terminated. */
426 /* Check if the buffer needs to be flushed. */
427 if (ap->remain == 2 || c == '\n') {
429 if (ap->flags & TOLOG)
430 msglogstr(ap->p_bufr, ap->pri, /*filter_cr*/1);
432 if (ap->flags & TOCONS) {
433 if ((panicstr == NULL) && (constty != NULL))
434 msgbuf_addstr(&consmsgbuf, -1,
435 ap->p_bufr, /*filter_cr*/ 0);
437 if ((constty == NULL) ||(always_console_output))
441 ap->p_next = ap->p_bufr;
442 ap->remain = ap->n_bufr;
447 * Since we fill the buffer up one character at a time,
448 * this should not happen. We should always catch it when
449 * ap->remain == 2 (if not sooner due to a newline), flush
450 * the buffer and move on. One way this could happen is
451 * if someone sets PRINTF_BUFR_SIZE to 1 or something
454 KASSERT(ap->remain > 2, ("Bad buffer logic, remain = %zd",
460 * Print a character on console or users terminal. If destination is
461 * the console then the last bunch of characters are saved in msgbuf for
465 putchar(int c, void *arg)
467 struct putchar_arg *ap = (struct putchar_arg*) arg;
468 struct tty *tp = ap->tty;
469 int flags = ap->flags;
472 /* Don't use the tty code after a panic or while in ddb. */
477 if ((panicstr == NULL) && (flags & TOTTY) && (tp != NULL))
480 if (flags & TOCONS) {
485 if ((flags & TOLOG) && (putbuf_done == 0)) {
492 * Scaled down version of sprintf(3).
495 sprintf(char *buf, const char *cfmt, ...)
501 retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
508 * Scaled down version of vsprintf(3).
511 vsprintf(char *buf, const char *cfmt, va_list ap)
515 retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
521 * Scaled down version of snprintf(3).
524 snprintf(char *str, size_t size, const char *format, ...)
529 va_start(ap, format);
530 retval = vsnprintf(str, size, format, ap);
536 * Scaled down version of vsnprintf(3).
539 vsnprintf(char *str, size_t size, const char *format, va_list ap)
541 struct snprintf_arg info;
546 retval = kvprintf(format, snprintf_func, &info, 10, ap);
547 if (info.remain >= 1)
553 * Kernel version which takes radix argument vsnprintf(3).
556 vsnrprintf(char *str, size_t size, int radix, const char *format, va_list ap)
558 struct snprintf_arg info;
563 retval = kvprintf(format, snprintf_func, &info, radix, ap);
564 if (info.remain >= 1)
570 snprintf_func(int ch, void *arg)
572 struct snprintf_arg *const info = arg;
574 if (info->remain >= 2) {
581 * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
582 * order; return an optional length and a pointer to the last character
583 * written in the buffer (i.e., the first character of the string).
584 * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
587 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
594 c = hex2ascii(num % base);
595 *++p = upper ? toupper(c) : c;
596 } while (num /= base);
603 * Scaled down version of printf(3).
605 * Two additional formats:
607 * The format %b is supported to decode error registers.
610 * printf("reg=%b\n", regval, "<base><arg>*");
612 * where <base> is the output base expressed as a control character, e.g.
613 * \10 gives octal; \20 gives hex. Each arg is a sequence of characters,
614 * the first of which gives the bit number to be inspected (origin 1), and
615 * the next characters (up to a control character, i.e. a character <= 32),
616 * give the name of the register. Thus:
618 * kvprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
620 * would produce output:
622 * reg=3<BITTWO,BITONE>
624 * XXX: %D -- Hexdump, takes pointer and separator string:
625 * ("%6D", ptr, ":") -> XX:XX:XX:XX:XX:XX
626 * ("%*D", len, ptr, " " -> XX XX XX XX ...
629 kvprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, va_list ap)
631 #define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; }
634 const char *p, *percent, *q;
638 int base, lflag, qflag, tmp, width, ladjust, sharpflag, neg, sign, dot;
639 int cflag, hflag, jflag, tflag, zflag;
642 int stop = 0, retval = 0;
651 fmt = "(fmt null)\n";
653 if (radix < 2 || radix > 36)
659 while ((ch = (u_char)*fmt++) != '%' || stop) {
665 qflag = 0; lflag = 0; ladjust = 0; sharpflag = 0; neg = 0;
666 sign = 0; dot = 0; dwidth = 0; upper = 0;
667 cflag = 0; hflag = 0; jflag = 0; tflag = 0; zflag = 0;
668 reswitch: switch (ch = (u_char)*fmt++) {
686 width = va_arg(ap, int);
692 dwidth = va_arg(ap, int);
700 case '1': case '2': case '3': case '4':
701 case '5': case '6': case '7': case '8': case '9':
702 for (n = 0;; ++fmt) {
703 n = n * 10 + ch - '0';
705 if (ch < '0' || ch > '9')
714 num = (u_int)va_arg(ap, int);
715 p = va_arg(ap, char *);
716 for (q = ksprintn(nbuf, num, *p++, NULL, 0); *q;)
724 if (num & (1 << (n - 1))) {
725 PCHAR(tmp ? ',' : '<');
726 for (; (n = *p) > ' '; ++p)
730 for (; *p > ' '; ++p)
737 PCHAR(va_arg(ap, int));
740 up = va_arg(ap, u_char *);
741 p = va_arg(ap, char *);
745 PCHAR(hex2ascii(*up >> 4));
746 PCHAR(hex2ascii(*up & 0x0f));
777 *(va_arg(ap, intmax_t *)) = retval;
779 *(va_arg(ap, quad_t *)) = retval;
781 *(va_arg(ap, long *)) = retval;
783 *(va_arg(ap, size_t *)) = retval;
785 *(va_arg(ap, short *)) = retval;
787 *(va_arg(ap, char *)) = retval;
789 *(va_arg(ap, int *)) = retval;
796 sharpflag = (width == 0);
798 num = (uintptr_t)va_arg(ap, void *);
809 p = va_arg(ap, char *);
815 for (n = 0; n < dwidth && p[n]; n++)
820 if (!ladjust && width > 0)
825 if (ladjust && width > 0)
850 num = va_arg(ap, uintmax_t);
852 num = va_arg(ap, u_quad_t);
854 num = va_arg(ap, ptrdiff_t);
856 num = va_arg(ap, u_long);
858 num = va_arg(ap, size_t);
860 num = (u_short)va_arg(ap, int);
862 num = (u_char)va_arg(ap, int);
864 num = va_arg(ap, u_int);
868 num = va_arg(ap, intmax_t);
870 num = va_arg(ap, quad_t);
872 num = va_arg(ap, ptrdiff_t);
874 num = va_arg(ap, long);
876 num = va_arg(ap, ssize_t);
878 num = (short)va_arg(ap, int);
880 num = (char)va_arg(ap, int);
882 num = va_arg(ap, int);
884 if (sign && (intmax_t)num < 0) {
886 num = -(intmax_t)num;
888 p = ksprintn(nbuf, num, base, &n, upper);
890 if (sharpflag && num != 0) {
899 if (!ladjust && padc == '0')
900 dwidth = width - tmp;
901 width -= tmp + imax(dwidth, n);
908 if (sharpflag && num != 0) {
911 } else if (base == 16) {
928 while (percent < fmt)
931 * Since we ignore an formatting argument it is no
932 * longer safe to obey the remaining formatting
933 * arguments as the arguments will no longer match
944 * Put character in log buffer with a particular priority.
947 msglogchar(int c, int pri)
949 static int lastpri = -1;
956 if (c == '\0' || c == '\r')
958 if (pri != -1 && pri != lastpri) {
960 msgbuf_addchar(msgbufp, '\n');
963 msgbuf_addchar(msgbufp, '<');
964 for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
965 msgbuf_addchar(msgbufp, *p--);
966 msgbuf_addchar(msgbufp, '>');
969 msgbuf_addchar(msgbufp, c);
979 msglogstr(char *str, int pri, int filter_cr)
984 msgbuf_addstr(msgbufp, pri, str, filter_cr);
988 msgbufinit(void *ptr, int size)
991 static struct msgbuf *oldp = NULL;
993 size -= sizeof(*msgbufp);
995 msgbufp = (struct msgbuf *)(cp + size);
996 msgbuf_reinit(msgbufp, cp, size);
997 if (msgbufmapped && oldp != msgbufp)
998 msgbuf_copy(oldp, msgbufp);
1003 static int unprivileged_read_msgbuf = 1;
1004 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_read_msgbuf,
1005 CTLFLAG_RW, &unprivileged_read_msgbuf, 0,
1006 "Unprivileged processes may read the kernel message buffer");
1008 /* Sysctls for accessing/clearing the msgbuf */
1010 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
1016 if (!unprivileged_read_msgbuf) {
1017 error = priv_check(req->td, PRIV_MSGBUF);
1022 /* Read the whole buffer, one chunk at a time. */
1023 mtx_lock(&msgbuf_lock);
1024 msgbuf_peekbytes(msgbufp, NULL, 0, &seq);
1026 len = msgbuf_peekbytes(msgbufp, buf, sizeof(buf), &seq);
1027 mtx_unlock(&msgbuf_lock);
1031 error = sysctl_handle_opaque(oidp, buf, len, req);
1035 mtx_lock(&msgbuf_lock);
1039 SYSCTL_PROC(_kern, OID_AUTO, msgbuf,
1040 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
1041 NULL, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
1043 static int msgbuf_clearflag;
1046 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
1049 error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1050 if (!error && req->newptr) {
1051 mtx_lock(&msgbuf_lock);
1052 msgbuf_clear(msgbufp);
1053 mtx_unlock(&msgbuf_lock);
1054 msgbuf_clearflag = 0;
1059 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
1060 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE | CTLFLAG_MPSAFE,
1061 &msgbuf_clearflag, 0, sysctl_kern_msgbuf_clear, "I",
1062 "Clear kernel message buffer");
1066 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
1070 if (!msgbufmapped) {
1071 db_printf("msgbuf not mapped yet\n");
1074 db_printf("msgbufp = %p\n", msgbufp);
1075 db_printf("magic = %x, size = %d, r= %u, w = %u, ptr = %p, cksum= %u\n",
1076 msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_rseq,
1077 msgbufp->msg_wseq, msgbufp->msg_ptr, msgbufp->msg_cksum);
1078 for (i = 0; i < msgbufp->msg_size && !db_pager_quit; i++) {
1079 j = MSGBUF_SEQ_TO_POS(msgbufp, i + msgbufp->msg_rseq);
1080 db_printf("%c", msgbufp->msg_ptr[j]);
1088 hexdump(const void *ptr, int length, const char *hdr, int flags)
1092 const unsigned char *cp;
1095 if ((flags & HD_DELIM_MASK) != 0)
1096 delim = (flags & HD_DELIM_MASK) >> 8;
1100 if ((flags & HD_COLUMN_MASK) != 0)
1101 cols = flags & HD_COLUMN_MASK;
1106 for (i = 0; i < length; i+= cols) {
1110 if ((flags & HD_OMIT_COUNT) == 0)
1113 if ((flags & HD_OMIT_HEX) == 0) {
1114 for (j = 0; j < cols; j++) {
1117 printf("%c%02x", delim, cp[k]);
1123 if ((flags & HD_OMIT_CHARS) == 0) {
1125 for (j = 0; j < cols; j++) {
1129 else if (cp[k] >= ' ' && cp[k] <= '~')
1130 printf("%c", cp[k]);