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 * 3. 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$");
42 #include "opt_printf.h"
45 #include <sys/param.h>
47 #include <sys/systm.h>
50 #include <sys/mutex.h>
52 #include <sys/kernel.h>
53 #include <sys/msgbuf.h>
54 #include <sys/malloc.h>
57 #include <sys/stddef.h>
58 #include <sys/sysctl.h>
60 #include <sys/syslog.h>
64 #include <sys/ctype.h>
72 * Note that stdarg.h and the ANSI style va_start macro is used for both
73 * ANSI and traditional C compilers.
75 #include <machine/stdarg.h>
83 /* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
84 #define MAXNBUF (sizeof(intmax_t) * NBBY + 1)
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);
109 static int msgbufmapped; /* Set when safe to use msgbuf */
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");
117 * See the comment in log_console() below for more explanation of this.
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");
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");
128 * Warn that a system table is full.
131 tablefull(const char *tab)
134 log(LOG_ERR, "%s: table is full\n", tab);
138 * Uprintf prints to the controlling terminal for the current process.
141 uprintf(const char *fmt, ...)
144 struct putchar_arg pca;
150 if (TD_IS_IDLETHREAD(td))
153 sx_slock(&proctree_lock);
156 if ((p->p_flag & P_CONTROLT) == 0) {
158 sx_sunlock(&proctree_lock);
161 SESS_LOCK(p->p_session);
162 pca.tty = p->p_session->s_ttyp;
163 SESS_UNLOCK(p->p_session);
165 if (pca.tty == NULL) {
166 sx_sunlock(&proctree_lock);
173 sx_sunlock(&proctree_lock);
174 retval = kvprintf(fmt, putchar, &pca, 10, ap);
181 * tprintf and vtprintf print on the controlling terminal associated with the
182 * given session, possibly to the log as well.
185 tprintf(struct proc *p, int pri, const char *fmt, ...)
190 vtprintf(p, pri, fmt, ap);
195 vtprintf(struct proc *p, int pri, const char *fmt, va_list ap)
197 struct tty *tp = NULL;
199 struct putchar_arg pca;
200 struct session *sess = NULL;
202 sx_slock(&proctree_lock);
207 if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
212 if (tp != NULL && tty_checkoutq(tp))
225 sx_sunlock(&proctree_lock);
226 kvprintf(fmt, putchar, &pca, 10, ap);
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.
240 ttyprintf(struct tty *tp, const char *fmt, ...)
243 struct putchar_arg pca;
250 retval = kvprintf(fmt, putchar, &pca, 10, ap);
256 _vprintf(int level, int flags, const char *fmt, va_list ap)
258 struct putchar_arg pca;
260 #ifdef PRINTF_BUFR_SIZE
261 char bufr[PRINTF_BUFR_SIZE];
267 #ifdef PRINTF_BUFR_SIZE
269 pca.p_next = pca.p_bufr;
270 pca.n_bufr = sizeof(bufr);
271 pca.remain = sizeof(bufr);
274 /* Don't buffer console output. */
278 retval = kvprintf(fmt, putchar, &pca, 10, ap);
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);
286 if (pca.flags & TOCONS)
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.
300 log(int level, const char *fmt, ...)
305 vlog(level, fmt, ap);
310 vlog(int level, const char *fmt, va_list ap)
313 (void)_vprintf(level, log_open ? TOLOG : TOCONS | TOLOG, fmt, ap);
317 #define CONSCHUNK 128
320 log_console(struct uio *uio)
326 if (!log_console_output)
329 pri = LOG_INFO | LOG_CONSOLE;
331 consbuffer = malloc(CONSCHUNK, M_TEMP, M_WAITOK);
334 while (uio->uio_resid > 0) {
335 c = imin(uio->uio_resid, CONSCHUNK - 1);
336 error = uiomove(consbuffer, c, uio);
339 /* Make sure we're NUL-terminated */
340 consbuffer[c] = '\0';
341 if (consbuffer[c - 1] == '\n')
345 msglogstr(consbuffer, pri, /*filter_cr*/ 1);
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.
353 * This results in different data in the message buffer than
354 * appears on the system console (which doesn't add extra line feed
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:
365 * On the console, it looks like this:
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.
372 if (!nl && log_console_add_linefeed) {
373 consbuffer[0] = '\n';
374 consbuffer[1] = '\0';
375 msglogstr(consbuffer, pri, /*filter_cr*/ 1);
379 free(consbuffer, M_TEMP);
384 printf(const char *fmt, ...)
390 retval = vprintf(fmt, ap);
397 vprintf(const char *fmt, va_list ap)
401 retval = _vprintf(-1, TOCONS | TOLOG, fmt, ap);
410 putbuf(int c, struct putchar_arg *ap)
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)
418 if (ap->flags & TOLOG)
419 msglogchar(c, ap->pri);
421 /* Buffer the character: */
425 /* Always leave the buffer zero terminated. */
428 /* Check if the buffer needs to be flushed. */
429 if (ap->remain == 2 || c == '\n') {
431 if (ap->flags & TOLOG)
432 msglogstr(ap->p_bufr, ap->pri, /*filter_cr*/1);
434 if (ap->flags & TOCONS) {
435 if ((panicstr == NULL) && (constty != NULL))
436 msgbuf_addstr(&consmsgbuf, -1,
437 ap->p_bufr, /*filter_cr*/ 0);
439 if ((constty == NULL) ||(always_console_output))
443 ap->p_next = ap->p_bufr;
444 ap->remain = ap->n_bufr;
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
456 KASSERT(ap->remain > 2, ("Bad buffer logic, remain = %zd",
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
467 putchar(int c, void *arg)
469 struct putchar_arg *ap = (struct putchar_arg*) arg;
470 struct tty *tp = ap->tty;
471 int flags = ap->flags;
473 /* Don't use the tty code after a panic or while in ddb. */
480 if ((flags & TOTTY) && tp != NULL && panicstr == NULL)
483 if ((flags & (TOCONS | TOLOG)) && c != '\0')
488 * Scaled down version of sprintf(3).
491 sprintf(char *buf, const char *cfmt, ...)
497 retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
504 * Scaled down version of vsprintf(3).
507 vsprintf(char *buf, const char *cfmt, va_list ap)
511 retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
517 * Scaled down version of snprintf(3).
520 snprintf(char *str, size_t size, const char *format, ...)
525 va_start(ap, format);
526 retval = vsnprintf(str, size, format, ap);
532 * Scaled down version of vsnprintf(3).
535 vsnprintf(char *str, size_t size, const char *format, va_list ap)
537 struct snprintf_arg info;
542 retval = kvprintf(format, snprintf_func, &info, 10, ap);
543 if (info.remain >= 1)
549 * Kernel version which takes radix argument vsnprintf(3).
552 vsnrprintf(char *str, size_t size, int radix, const char *format, va_list ap)
554 struct snprintf_arg info;
559 retval = kvprintf(format, snprintf_func, &info, radix, ap);
560 if (info.remain >= 1)
566 snprintf_func(int ch, void *arg)
568 struct snprintf_arg *const info = arg;
570 if (info->remain >= 2) {
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.
583 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
590 c = hex2ascii(num % base);
591 *++p = upper ? toupper(c) : c;
592 } while (num /= base);
599 * Scaled down version of printf(3).
601 * Two additional formats:
603 * The format %b is supported to decode error registers.
606 * printf("reg=%b\n", regval, "<base><arg>*");
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:
614 * kvprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE");
616 * would produce output:
618 * reg=3<BITTWO,BITONE>
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 ...
625 kvprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, va_list ap)
627 #define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; }
630 const char *p, *percent, *q;
634 int base, lflag, qflag, tmp, width, ladjust, sharpflag, neg, sign, dot;
635 int cflag, hflag, jflag, tflag, zflag;
638 int stop = 0, retval = 0;
647 fmt = "(fmt null)\n";
649 if (radix < 2 || radix > 36)
655 while ((ch = (u_char)*fmt++) != '%' || stop) {
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++) {
682 width = va_arg(ap, int);
688 dwidth = va_arg(ap, int);
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';
701 if (ch < '0' || ch > '9')
710 num = (u_int)va_arg(ap, int);
711 p = va_arg(ap, char *);
712 for (q = ksprintn(nbuf, num, *p++, NULL, 0); *q;)
720 if (num & (1 << (n - 1))) {
721 PCHAR(tmp ? ',' : '<');
722 for (; (n = *p) > ' '; ++p)
726 for (; *p > ' '; ++p)
735 if (!ladjust && width > 0)
738 PCHAR(va_arg(ap, int));
739 if (ladjust && width > 0)
744 up = va_arg(ap, u_char *);
745 p = va_arg(ap, char *);
749 PCHAR(hex2ascii(*up >> 4));
750 PCHAR(hex2ascii(*up & 0x0f));
781 *(va_arg(ap, intmax_t *)) = retval;
783 *(va_arg(ap, quad_t *)) = retval;
785 *(va_arg(ap, long *)) = retval;
787 *(va_arg(ap, size_t *)) = retval;
789 *(va_arg(ap, short *)) = retval;
791 *(va_arg(ap, char *)) = retval;
793 *(va_arg(ap, int *)) = retval;
800 sharpflag = (width == 0);
802 num = (uintptr_t)va_arg(ap, void *);
813 p = va_arg(ap, char *);
819 for (n = 0; n < dwidth && p[n]; n++)
824 if (!ladjust && width > 0)
829 if (ladjust && width > 0)
854 num = va_arg(ap, uintmax_t);
856 num = va_arg(ap, u_quad_t);
858 num = va_arg(ap, ptrdiff_t);
860 num = va_arg(ap, u_long);
862 num = va_arg(ap, size_t);
864 num = (u_short)va_arg(ap, int);
866 num = (u_char)va_arg(ap, int);
868 num = va_arg(ap, u_int);
872 num = va_arg(ap, intmax_t);
874 num = va_arg(ap, quad_t);
876 num = va_arg(ap, ptrdiff_t);
878 num = va_arg(ap, long);
880 num = va_arg(ap, ssize_t);
882 num = (short)va_arg(ap, int);
884 num = (char)va_arg(ap, int);
886 num = va_arg(ap, int);
888 if (sign && (intmax_t)num < 0) {
890 num = -(intmax_t)num;
892 p = ksprintn(nbuf, num, base, &n, upper);
894 if (sharpflag && num != 0) {
903 if (!ladjust && padc == '0')
904 dwidth = width - tmp;
905 width -= tmp + imax(dwidth, n);
912 if (sharpflag && num != 0) {
915 } else if (base == 16) {
932 while (percent < fmt)
935 * Since we ignore a formatting argument it is no
936 * longer safe to obey the remaining formatting
937 * arguments as the arguments will no longer match
948 * Put character in log buffer with a particular priority.
951 msglogchar(int c, int pri)
953 static int lastpri = -1;
960 if (c == '\0' || c == '\r')
962 if (pri != -1 && pri != lastpri) {
964 msgbuf_addchar(msgbufp, '\n');
967 msgbuf_addchar(msgbufp, '<');
968 for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
969 msgbuf_addchar(msgbufp, *p--);
970 msgbuf_addchar(msgbufp, '>');
973 msgbuf_addchar(msgbufp, c);
983 msglogstr(char *str, int pri, int filter_cr)
988 msgbuf_addstr(msgbufp, pri, str, filter_cr);
992 msgbufinit(void *ptr, int size)
995 static struct msgbuf *oldp = NULL;
997 size -= sizeof(*msgbufp);
999 msgbufp = (struct msgbuf *)(cp + size);
1000 msgbuf_reinit(msgbufp, cp, size);
1001 if (msgbufmapped && oldp != msgbufp)
1002 msgbuf_copy(oldp, msgbufp);
1007 static int unprivileged_read_msgbuf = 1;
1008 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_read_msgbuf,
1009 CTLFLAG_RW, &unprivileged_read_msgbuf, 0,
1010 "Unprivileged processes may read the kernel message buffer");
1012 /* Sysctls for accessing/clearing the msgbuf */
1014 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
1020 if (!unprivileged_read_msgbuf) {
1021 error = priv_check(req->td, PRIV_MSGBUF);
1026 /* Read the whole buffer, one chunk at a time. */
1027 mtx_lock(&msgbuf_lock);
1028 msgbuf_peekbytes(msgbufp, NULL, 0, &seq);
1030 len = msgbuf_peekbytes(msgbufp, buf, sizeof(buf), &seq);
1031 mtx_unlock(&msgbuf_lock);
1033 return (SYSCTL_OUT(req, "", 1)); /* add nulterm */
1035 error = sysctl_handle_opaque(oidp, buf, len, req);
1039 mtx_lock(&msgbuf_lock);
1043 SYSCTL_PROC(_kern, OID_AUTO, msgbuf,
1044 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
1045 NULL, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
1047 static int msgbuf_clearflag;
1050 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
1053 error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1054 if (!error && req->newptr) {
1055 mtx_lock(&msgbuf_lock);
1056 msgbuf_clear(msgbufp);
1057 mtx_unlock(&msgbuf_lock);
1058 msgbuf_clearflag = 0;
1063 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
1064 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE | CTLFLAG_MPSAFE,
1065 &msgbuf_clearflag, 0, sysctl_kern_msgbuf_clear, "I",
1066 "Clear kernel message buffer");
1070 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
1074 if (!msgbufmapped) {
1075 db_printf("msgbuf not mapped yet\n");
1078 db_printf("msgbufp = %p\n", msgbufp);
1079 db_printf("magic = %x, size = %d, r= %u, w = %u, ptr = %p, cksum= %u\n",
1080 msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_rseq,
1081 msgbufp->msg_wseq, msgbufp->msg_ptr, msgbufp->msg_cksum);
1082 for (i = 0; i < msgbufp->msg_size && !db_pager_quit; i++) {
1083 j = MSGBUF_SEQ_TO_POS(msgbufp, i + msgbufp->msg_rseq);
1084 db_printf("%c", msgbufp->msg_ptr[j]);
1092 hexdump(const void *ptr, int length, const char *hdr, int flags)
1096 const unsigned char *cp;
1099 if ((flags & HD_DELIM_MASK) != 0)
1100 delim = (flags & HD_DELIM_MASK) >> 8;
1104 if ((flags & HD_COLUMN_MASK) != 0)
1105 cols = flags & HD_COLUMN_MASK;
1110 for (i = 0; i < length; i+= cols) {
1114 if ((flags & HD_OMIT_COUNT) == 0)
1117 if ((flags & HD_OMIT_HEX) == 0) {
1118 for (j = 0; j < cols; j++) {
1121 printf("%c%02x", delim, cp[k]);
1127 if ((flags & HD_OMIT_CHARS) == 0) {
1129 for (j = 0; j < cols; j++) {
1133 else if (cp[k] >= ' ' && cp[k] <= '~')
1134 printf("%c", cp[k]);
1143 #endif /* _KERNEL */
1146 sbuf_hexdump(struct sbuf *sb, const void *ptr, int length, const char *hdr,
1151 const unsigned char *cp;
1154 if ((flags & HD_DELIM_MASK) != 0)
1155 delim = (flags & HD_DELIM_MASK) >> 8;
1159 if ((flags & HD_COLUMN_MASK) != 0)
1160 cols = flags & HD_COLUMN_MASK;
1165 for (i = 0; i < length; i+= cols) {
1167 sbuf_printf(sb, "%s", hdr);
1169 if ((flags & HD_OMIT_COUNT) == 0)
1170 sbuf_printf(sb, "%04x ", i);
1172 if ((flags & HD_OMIT_HEX) == 0) {
1173 for (j = 0; j < cols; j++) {
1176 sbuf_printf(sb, "%c%02x", delim, cp[k]);
1178 sbuf_printf(sb, " ");
1182 if ((flags & HD_OMIT_CHARS) == 0) {
1183 sbuf_printf(sb, " |");
1184 for (j = 0; j < cols; j++) {
1187 sbuf_printf(sb, " ");
1188 else if (cp[k] >= ' ' && cp[k] <= '~')
1189 sbuf_printf(sb, "%c", cp[k]);
1191 sbuf_printf(sb, ".");
1193 sbuf_printf(sb, "|");
1195 sbuf_printf(sb, "\n");
1201 counted_warning(unsigned *counter, const char *msg)
1210 if (atomic_cmpset_int(counter, c, c - 1)) {
1212 log(LOG_INFO, "pid %d (%s) %s%s\n",
1213 td->td_proc->p_pid, td->td_name, msg,
1214 c > 1 ? "" : " - not logging anymore");