2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1986, 1988, 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * @(#)subr_prf.c 8.3 (Berkeley) 1/21/94
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
44 #include "opt_printf.h"
47 #include <sys/param.h>
49 #include <sys/systm.h>
52 #include <sys/mutex.h>
54 #include <sys/kernel.h>
55 #include <sys/msgbuf.h>
56 #include <sys/malloc.h>
59 #include <sys/stddef.h>
60 #include <sys/sysctl.h>
62 #include <sys/syslog.h>
66 #include <sys/ctype.h>
74 * Note that stdarg.h and the ANSI style va_start macro is used for both
75 * ANSI and traditional C compilers.
78 #include <machine/stdarg.h>
84 * This is needed for sbuf_putbuf() when compiled into userland. Due to the
85 * shared nature of this file, it's the only place to put it.
97 /* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
98 #define MAXNBUF (sizeof(intmax_t) * NBBY + 1)
110 struct snprintf_arg {
117 static void msglogchar(int c, int pri);
118 static void msglogstr(char *str, int pri, int filter_cr);
119 static void putchar(int ch, void *arg);
120 static char *ksprintn(char *nbuf, uintmax_t num, int base, int *len, int upper);
121 static void snprintf_func(int ch, void *arg);
123 static int msgbufmapped; /* Set when safe to use msgbuf */
125 struct msgbuf *msgbufp;
127 static int log_console_output = 1;
128 SYSCTL_INT(_kern, OID_AUTO, log_console_output, CTLFLAG_RWTUN,
129 &log_console_output, 0, "Duplicate console output to the syslog");
132 * See the comment in log_console() below for more explanation of this.
134 static int log_console_add_linefeed;
135 SYSCTL_INT(_kern, OID_AUTO, log_console_add_linefeed, CTLFLAG_RWTUN,
136 &log_console_add_linefeed, 0, "log_console() adds extra newlines");
138 static int always_console_output;
139 SYSCTL_INT(_kern, OID_AUTO, always_console_output, CTLFLAG_RWTUN,
140 &always_console_output, 0, "Always output to console despite TIOCCONS");
143 * Warn that a system table is full.
146 tablefull(const char *tab)
149 log(LOG_ERR, "%s: table is full\n", tab);
153 * Uprintf prints to the controlling terminal for the current process.
156 uprintf(const char *fmt, ...)
159 struct putchar_arg pca;
165 if (TD_IS_IDLETHREAD(td))
168 sx_slock(&proctree_lock);
171 if ((p->p_flag & P_CONTROLT) == 0) {
173 sx_sunlock(&proctree_lock);
176 SESS_LOCK(p->p_session);
177 pca.tty = p->p_session->s_ttyp;
178 SESS_UNLOCK(p->p_session);
180 if (pca.tty == NULL) {
181 sx_sunlock(&proctree_lock);
188 sx_sunlock(&proctree_lock);
189 retval = kvprintf(fmt, putchar, &pca, 10, ap);
196 * tprintf and vtprintf print on the controlling terminal associated with the
197 * given session, possibly to the log as well.
200 tprintf(struct proc *p, int pri, const char *fmt, ...)
205 vtprintf(p, pri, fmt, ap);
210 vtprintf(struct proc *p, int pri, const char *fmt, va_list ap)
212 struct tty *tp = NULL;
214 struct putchar_arg pca;
215 struct session *sess = NULL;
217 sx_slock(&proctree_lock);
222 if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
227 if (tp != NULL && tty_checkoutq(tp))
240 sx_sunlock(&proctree_lock);
241 kvprintf(fmt, putchar, &pca, 10, ap);
250 * Ttyprintf displays a message on a tty; it should be used only by
251 * the tty driver, or anything that knows the underlying tty will not
252 * be revoke(2)'d away. Other callers should use tprintf.
255 ttyprintf(struct tty *tp, const char *fmt, ...)
258 struct putchar_arg pca;
265 retval = kvprintf(fmt, putchar, &pca, 10, ap);
271 _vprintf(int level, int flags, const char *fmt, va_list ap)
273 struct putchar_arg pca;
275 #ifdef PRINTF_BUFR_SIZE
276 char bufr[PRINTF_BUFR_SIZE];
283 #ifdef PRINTF_BUFR_SIZE
285 pca.p_next = pca.p_bufr;
286 pca.n_bufr = sizeof(bufr);
287 pca.remain = sizeof(bufr);
290 /* Don't buffer console output. */
294 retval = kvprintf(fmt, putchar, &pca, 10, ap);
296 #ifdef PRINTF_BUFR_SIZE
297 /* Write any buffered console/log output: */
298 if (*pca.p_bufr != '\0') {
299 if (pca.flags & TOLOG)
300 msglogstr(pca.p_bufr, level, /*filter_cr*/1);
302 if (pca.flags & TOCONS)
312 * Log writes to the log buffer, and guarantees not to sleep (so can be
313 * called by interrupt routines). If there is no process reading the
314 * log yet, it writes to the console also.
317 log(int level, const char *fmt, ...)
322 vlog(level, fmt, ap);
327 vlog(int level, const char *fmt, va_list ap)
330 (void)_vprintf(level, log_open ? TOLOG : TOCONS | TOLOG, fmt, ap);
334 #define CONSCHUNK 128
337 log_console(struct uio *uio)
343 if (!log_console_output)
346 pri = LOG_INFO | LOG_CONSOLE;
348 consbuffer = malloc(CONSCHUNK, M_TEMP, M_WAITOK);
351 while (uio->uio_resid > 0) {
352 c = imin(uio->uio_resid, CONSCHUNK - 1);
353 error = uiomove(consbuffer, c, uio);
356 /* Make sure we're NUL-terminated */
357 consbuffer[c] = '\0';
358 if (consbuffer[c - 1] == '\n')
362 msglogstr(consbuffer, pri, /*filter_cr*/ 1);
365 * The previous behavior in log_console() is preserved when
366 * log_console_add_linefeed is non-zero. For that behavior, if an
367 * individual console write came in that was not terminated with a
368 * line feed, it would add a line feed.
370 * This results in different data in the message buffer than
371 * appears on the system console (which doesn't add extra line feed
374 * A number of programs and rc scripts write a line feed, or a period
375 * and a line feed when they have completed their operation. On
376 * the console, this looks seamless, but when displayed with
377 * 'dmesg -a', you wind up with output that looks like this:
382 * On the console, it looks like this:
385 * We could add logic to detect that situation, or just not insert
386 * the extra newlines. Set the kern.log_console_add_linefeed
387 * sysctl/tunable variable to get the old behavior.
389 if (!nl && log_console_add_linefeed) {
390 consbuffer[0] = '\n';
391 consbuffer[1] = '\0';
392 msglogstr(consbuffer, pri, /*filter_cr*/ 1);
396 free(consbuffer, M_TEMP);
400 printf(const char *fmt, ...)
406 retval = vprintf(fmt, ap);
413 vprintf(const char *fmt, va_list ap)
417 retval = _vprintf(-1, TOCONS | TOLOG, fmt, ap);
426 prf_putbuf(char *bufr, int flags, int pri)
430 msglogstr(bufr, pri, /*filter_cr*/1);
432 if (flags & TOCONS) {
433 if ((panicstr == NULL) && (constty != NULL))
434 msgbuf_addstr(&consmsgbuf, -1,
435 bufr, /*filter_cr*/ 0);
437 if ((constty == NULL) ||(always_console_output))
443 putbuf(int c, struct putchar_arg *ap)
445 /* Check if no console output buffer was provided. */
446 if (ap->p_bufr == NULL) {
447 /* Output direct to the console. */
448 if (ap->flags & TOCONS)
451 if (ap->flags & TOLOG)
452 msglogchar(c, ap->pri);
454 /* Buffer the character: */
458 /* Always leave the buffer zero terminated. */
461 /* Check if the buffer needs to be flushed. */
462 if (ap->remain == 2 || c == '\n') {
463 prf_putbuf(ap->p_bufr, ap->flags, ap->pri);
465 ap->p_next = ap->p_bufr;
466 ap->remain = ap->n_bufr;
471 * Since we fill the buffer up one character at a time,
472 * this should not happen. We should always catch it when
473 * ap->remain == 2 (if not sooner due to a newline), flush
474 * the buffer and move on. One way this could happen is
475 * if someone sets PRINTF_BUFR_SIZE to 1 or something
478 KASSERT(ap->remain > 2, ("Bad buffer logic, remain = %zd",
484 * Print a character on console or users terminal. If destination is
485 * the console then the last bunch of characters are saved in msgbuf for
489 putchar(int c, void *arg)
491 struct putchar_arg *ap = (struct putchar_arg*) arg;
492 struct tty *tp = ap->tty;
493 int flags = ap->flags;
495 /* Don't use the tty code after a panic or while in ddb. */
502 if ((flags & TOTTY) && tp != NULL && panicstr == NULL)
505 if ((flags & (TOCONS | TOLOG)) && c != '\0')
510 * Scaled down version of sprintf(3).
513 sprintf(char *buf, const char *cfmt, ...)
519 retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
526 * Scaled down version of vsprintf(3).
529 vsprintf(char *buf, const char *cfmt, va_list ap)
533 retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
539 * Scaled down version of snprintf(3).
542 snprintf(char *str, size_t size, const char *format, ...)
547 va_start(ap, format);
548 retval = vsnprintf(str, size, format, ap);
554 * Scaled down version of vsnprintf(3).
557 vsnprintf(char *str, size_t size, const char *format, va_list ap)
559 struct snprintf_arg info;
564 retval = kvprintf(format, snprintf_func, &info, 10, ap);
565 if (info.remain >= 1)
571 * Kernel version which takes radix argument vsnprintf(3).
574 vsnrprintf(char *str, size_t size, int radix, const char *format, va_list ap)
576 struct snprintf_arg info;
581 retval = kvprintf(format, snprintf_func, &info, radix, ap);
582 if (info.remain >= 1)
588 snprintf_func(int ch, void *arg)
590 struct snprintf_arg *const info = arg;
592 if (info->remain >= 2) {
599 * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
600 * order; return an optional length and a pointer to the last character
601 * written in the buffer (i.e., the first character of the string).
602 * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
605 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
612 c = hex2ascii(num % base);
613 *++p = upper ? toupper(c) : c;
614 } while (num /= base);
621 * Scaled down version of printf(3).
623 * Two additional formats:
625 * The format %b is supported to decode error registers.
628 * printf("reg=%b\n", regval, "<base><arg>*");
630 * where <base> is the output base expressed as a control character, e.g.
631 * \10 gives octal; \20 gives hex. Each arg is a sequence of characters,
632 * the first of which gives the bit number to be inspected (origin 1), and
633 * the next characters (up to a control character, i.e. a character <= 32),
634 * give the name of the register. Thus:
636 * kvprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE");
638 * would produce output:
640 * reg=3<BITTWO,BITONE>
642 * XXX: %D -- Hexdump, takes pointer and separator string:
643 * ("%6D", ptr, ":") -> XX:XX:XX:XX:XX:XX
644 * ("%*D", len, ptr, " " -> XX XX XX XX ...
647 kvprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, va_list ap)
649 #define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; }
652 const char *p, *percent, *q;
656 int base, lflag, qflag, tmp, width, ladjust, sharpflag, neg, sign, dot;
657 int cflag, hflag, jflag, tflag, zflag;
658 int bconv, dwidth, upper;
660 int stop = 0, retval = 0;
670 fmt = "(fmt null)\n";
672 if (radix < 2 || radix > 36)
678 while ((ch = (u_char)*fmt++) != '%' || stop) {
684 qflag = 0; lflag = 0; ladjust = 0; sharpflag = 0; neg = 0;
685 sign = 0; dot = 0; bconv = 0; dwidth = 0; upper = 0;
686 cflag = 0; hflag = 0; jflag = 0; tflag = 0; zflag = 0;
687 reswitch: switch (ch = (u_char)*fmt++) {
705 width = va_arg(ap, int);
711 dwidth = va_arg(ap, int);
720 case '1': case '2': case '3': case '4':
721 case '5': case '6': case '7': case '8': case '9':
722 for (n = 0;; ++fmt) {
723 n = n * 10 + ch - '0';
725 if (ch < '0' || ch > '9')
740 if (!ladjust && width > 0)
743 PCHAR(va_arg(ap, int));
744 if (ladjust && width > 0)
749 up = va_arg(ap, u_char *);
750 p = va_arg(ap, char *);
754 PCHAR(hex2ascii(*up >> 4));
755 PCHAR(hex2ascii(*up & 0x0f));
786 *(va_arg(ap, intmax_t *)) = retval;
788 *(va_arg(ap, quad_t *)) = retval;
790 *(va_arg(ap, long *)) = retval;
792 *(va_arg(ap, size_t *)) = retval;
794 *(va_arg(ap, short *)) = retval;
796 *(va_arg(ap, char *)) = retval;
798 *(va_arg(ap, int *)) = retval;
805 sharpflag = (width == 0);
807 num = (uintptr_t)va_arg(ap, void *);
818 p = va_arg(ap, char *);
824 for (n = 0; n < dwidth && p[n]; n++)
829 if (!ladjust && width > 0)
834 if (ladjust && width > 0)
859 num = va_arg(ap, uintmax_t);
861 num = va_arg(ap, u_quad_t);
863 num = va_arg(ap, ptrdiff_t);
865 num = va_arg(ap, u_long);
867 num = va_arg(ap, size_t);
869 num = (u_short)va_arg(ap, int);
871 num = (u_char)va_arg(ap, int);
873 num = va_arg(ap, u_int);
875 q = va_arg(ap, char *);
881 num = va_arg(ap, intmax_t);
883 num = va_arg(ap, quad_t);
885 num = va_arg(ap, ptrdiff_t);
887 num = va_arg(ap, long);
889 num = va_arg(ap, ssize_t);
891 num = (short)va_arg(ap, int);
893 num = (char)va_arg(ap, int);
895 num = va_arg(ap, int);
897 if (sign && (intmax_t)num < 0) {
899 num = -(intmax_t)num;
901 p = ksprintn(nbuf, num, base, &n, upper);
903 if (sharpflag && num != 0) {
912 if (!ladjust && padc == '0')
913 dwidth = width - tmp;
914 width -= tmp + imax(dwidth, n);
921 if (sharpflag && num != 0) {
924 } else if (base == 16) {
935 if (bconv && num != 0) {
936 /* %b conversion flag format. */
940 if (num & (1 << (n - 1))) {
941 PCHAR(retval != tmp ?
943 for (; (n = *q) > ' '; ++q)
946 for (; *q > ' '; ++q)
951 width -= retval - tmp;
961 while (percent < fmt)
964 * Since we ignore a formatting argument it is no
965 * longer safe to obey the remaining formatting
966 * arguments as the arguments will no longer match
977 * Put character in log buffer with a particular priority.
980 msglogchar(int c, int pri)
982 static int lastpri = -1;
989 if (c == '\0' || c == '\r')
991 if (pri != -1 && pri != lastpri) {
993 msgbuf_addchar(msgbufp, '\n');
996 msgbuf_addchar(msgbufp, '<');
997 for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
998 msgbuf_addchar(msgbufp, *p--);
999 msgbuf_addchar(msgbufp, '>');
1002 msgbuf_addchar(msgbufp, c);
1012 msglogstr(char *str, int pri, int filter_cr)
1017 msgbuf_addstr(msgbufp, pri, str, filter_cr);
1021 msgbufinit(void *ptr, int size)
1024 static struct msgbuf *oldp = NULL;
1026 size -= sizeof(*msgbufp);
1028 msgbufp = (struct msgbuf *)(cp + size);
1029 msgbuf_reinit(msgbufp, cp, size);
1030 if (msgbufmapped && oldp != msgbufp)
1031 msgbuf_copy(oldp, msgbufp);
1036 static int unprivileged_read_msgbuf = 1;
1037 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_read_msgbuf,
1038 CTLFLAG_RW, &unprivileged_read_msgbuf, 0,
1039 "Unprivileged processes may read the kernel message buffer");
1041 /* Sysctls for accessing/clearing the msgbuf */
1043 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
1049 if (!unprivileged_read_msgbuf) {
1050 error = priv_check(req->td, PRIV_MSGBUF);
1055 /* Read the whole buffer, one chunk at a time. */
1056 mtx_lock(&msgbuf_lock);
1057 msgbuf_peekbytes(msgbufp, NULL, 0, &seq);
1059 len = msgbuf_peekbytes(msgbufp, buf, sizeof(buf), &seq);
1060 mtx_unlock(&msgbuf_lock);
1062 return (SYSCTL_OUT(req, "", 1)); /* add nulterm */
1064 error = sysctl_handle_opaque(oidp, buf, len, req);
1068 mtx_lock(&msgbuf_lock);
1072 SYSCTL_PROC(_kern, OID_AUTO, msgbuf,
1073 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
1074 NULL, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
1076 static int msgbuf_clearflag;
1079 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
1082 error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1083 if (!error && req->newptr) {
1084 mtx_lock(&msgbuf_lock);
1085 msgbuf_clear(msgbufp);
1086 mtx_unlock(&msgbuf_lock);
1087 msgbuf_clearflag = 0;
1092 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
1093 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE | CTLFLAG_MPSAFE,
1094 &msgbuf_clearflag, 0, sysctl_kern_msgbuf_clear, "I",
1095 "Clear kernel message buffer");
1099 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
1103 if (!msgbufmapped) {
1104 db_printf("msgbuf not mapped yet\n");
1107 db_printf("msgbufp = %p\n", msgbufp);
1108 db_printf("magic = %x, size = %d, r= %u, w = %u, ptr = %p, cksum= %u\n",
1109 msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_rseq,
1110 msgbufp->msg_wseq, msgbufp->msg_ptr, msgbufp->msg_cksum);
1111 for (i = 0; i < msgbufp->msg_size && !db_pager_quit; i++) {
1112 j = MSGBUF_SEQ_TO_POS(msgbufp, i + msgbufp->msg_rseq);
1113 db_printf("%c", msgbufp->msg_ptr[j]);
1121 hexdump(const void *ptr, int length, const char *hdr, int flags)
1125 const unsigned char *cp;
1128 if ((flags & HD_DELIM_MASK) != 0)
1129 delim = (flags & HD_DELIM_MASK) >> 8;
1133 if ((flags & HD_COLUMN_MASK) != 0)
1134 cols = flags & HD_COLUMN_MASK;
1139 for (i = 0; i < length; i+= cols) {
1143 if ((flags & HD_OMIT_COUNT) == 0)
1146 if ((flags & HD_OMIT_HEX) == 0) {
1147 for (j = 0; j < cols; j++) {
1150 printf("%c%02x", delim, cp[k]);
1156 if ((flags & HD_OMIT_CHARS) == 0) {
1158 for (j = 0; j < cols; j++) {
1162 else if (cp[k] >= ' ' && cp[k] <= '~')
1163 printf("%c", cp[k]);
1172 #endif /* _KERNEL */
1175 sbuf_hexdump(struct sbuf *sb, const void *ptr, int length, const char *hdr,
1180 const unsigned char *cp;
1183 if ((flags & HD_DELIM_MASK) != 0)
1184 delim = (flags & HD_DELIM_MASK) >> 8;
1188 if ((flags & HD_COLUMN_MASK) != 0)
1189 cols = flags & HD_COLUMN_MASK;
1194 for (i = 0; i < length; i+= cols) {
1196 sbuf_printf(sb, "%s", hdr);
1198 if ((flags & HD_OMIT_COUNT) == 0)
1199 sbuf_printf(sb, "%04x ", i);
1201 if ((flags & HD_OMIT_HEX) == 0) {
1202 for (j = 0; j < cols; j++) {
1205 sbuf_printf(sb, "%c%02x", delim, cp[k]);
1207 sbuf_printf(sb, " ");
1211 if ((flags & HD_OMIT_CHARS) == 0) {
1212 sbuf_printf(sb, " |");
1213 for (j = 0; j < cols; j++) {
1216 sbuf_printf(sb, " ");
1217 else if (cp[k] >= ' ' && cp[k] <= '~')
1218 sbuf_printf(sb, "%c", cp[k]);
1220 sbuf_printf(sb, ".");
1222 sbuf_printf(sb, "|");
1224 sbuf_printf(sb, "\n");
1230 counted_warning(unsigned *counter, const char *msg)
1239 if (atomic_cmpset_int(counter, c, c - 1)) {
1241 log(LOG_INFO, "pid %d (%s) %s%s\n",
1242 td->td_proc->p_pid, td->td_name, msg,
1243 c > 1 ? "" : " - not logging anymore");
1252 sbuf_putbuf(struct sbuf *sb)
1255 prf_putbuf(sbuf_data(sb), TOLOG | TOCONS, -1);
1259 sbuf_putbuf(struct sbuf *sb)
1262 printf("%s", sbuf_data(sb));