]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/subr_prf.c
When parsing command line stuff, treat tabs and spaces the same.
[FreeBSD/FreeBSD.git] / sys / kern / subr_prf.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
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.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
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.
23  *
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
34  * SUCH DAMAGE.
35  *
36  *      @(#)subr_prf.c  8.3 (Berkeley) 1/21/94
37  */
38
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
41
42 #ifdef _KERNEL
43 #include "opt_ddb.h"
44 #include "opt_printf.h"
45 #endif  /* _KERNEL */
46
47 #include <sys/param.h>
48 #ifdef _KERNEL
49 #include <sys/systm.h>
50 #include <sys/lock.h>
51 #include <sys/kdb.h>
52 #include <sys/mutex.h>
53 #include <sys/sx.h>
54 #include <sys/kernel.h>
55 #include <sys/msgbuf.h>
56 #include <sys/malloc.h>
57 #include <sys/priv.h>
58 #include <sys/proc.h>
59 #include <sys/stddef.h>
60 #include <sys/sysctl.h>
61 #include <sys/tty.h>
62 #include <sys/syslog.h>
63 #include <sys/cons.h>
64 #include <sys/uio.h>
65 #endif
66 #include <sys/ctype.h>
67 #include <sys/sbuf.h>
68
69 #ifdef DDB
70 #include <ddb/ddb.h>
71 #endif
72
73 /*
74  * Note that stdarg.h and the ANSI style va_start macro is used for both
75  * ANSI and traditional C compilers.
76  */
77 #ifdef _KERNEL
78 #include <machine/stdarg.h>
79 #else
80 #include <stdarg.h>
81 #endif
82
83 /*
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.
86  */
87 #ifndef _KERNEL
88 #include <stdio.h>
89 #endif
90
91 #ifdef _KERNEL
92
93 #define TOCONS  0x01
94 #define TOTTY   0x02
95 #define TOLOG   0x04
96
97 /* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
98 #define MAXNBUF (sizeof(intmax_t) * NBBY + 1)
99
100 struct putchar_arg {
101         int     flags;
102         int     pri;
103         struct  tty *tty;
104         char    *p_bufr;
105         size_t  n_bufr;
106         char    *p_next;
107         size_t  remain;
108 };
109
110 struct snprintf_arg {
111         char    *str;
112         size_t  remain;
113 };
114
115 extern  int log_open;
116
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);
122
123 static bool msgbufmapped;               /* Set when safe to use msgbuf */
124 int msgbuftrigger;
125 struct msgbuf *msgbufp;
126
127 #ifndef BOOT_TAG_SZ
128 #define BOOT_TAG_SZ     32
129 #endif
130 #ifndef BOOT_TAG
131 /* Tag used to mark the start of a boot in dmesg */
132 #define BOOT_TAG        "---<<BOOT>>---"
133 #endif
134
135 static char current_boot_tag[BOOT_TAG_SZ + 1] = BOOT_TAG;
136 SYSCTL_STRING(_kern, OID_AUTO, boot_tag, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
137     current_boot_tag, 0, "Tag added to dmesg at start of boot");
138
139 static int log_console_output = 1;
140 SYSCTL_INT(_kern, OID_AUTO, log_console_output, CTLFLAG_RWTUN,
141     &log_console_output, 0, "Duplicate console output to the syslog");
142
143 /*
144  * See the comment in log_console() below for more explanation of this.
145  */
146 static int log_console_add_linefeed;
147 SYSCTL_INT(_kern, OID_AUTO, log_console_add_linefeed, CTLFLAG_RWTUN,
148     &log_console_add_linefeed, 0, "log_console() adds extra newlines");
149
150 static int always_console_output;
151 SYSCTL_INT(_kern, OID_AUTO, always_console_output, CTLFLAG_RWTUN,
152     &always_console_output, 0, "Always output to console despite TIOCCONS");
153
154 /*
155  * Warn that a system table is full.
156  */
157 void
158 tablefull(const char *tab)
159 {
160
161         log(LOG_ERR, "%s: table is full\n", tab);
162 }
163
164 /*
165  * Uprintf prints to the controlling terminal for the current process.
166  */
167 int
168 uprintf(const char *fmt, ...)
169 {
170         va_list ap;
171         struct putchar_arg pca;
172         struct proc *p;
173         struct thread *td;
174         int retval;
175
176         td = curthread;
177         if (TD_IS_IDLETHREAD(td))
178                 return (0);
179
180         sx_slock(&proctree_lock);
181         p = td->td_proc;
182         PROC_LOCK(p);
183         if ((p->p_flag & P_CONTROLT) == 0) {
184                 PROC_UNLOCK(p);
185                 sx_sunlock(&proctree_lock);
186                 return (0);
187         }
188         SESS_LOCK(p->p_session);
189         pca.tty = p->p_session->s_ttyp;
190         SESS_UNLOCK(p->p_session);
191         PROC_UNLOCK(p);
192         if (pca.tty == NULL) {
193                 sx_sunlock(&proctree_lock);
194                 return (0);
195         }
196         pca.flags = TOTTY;
197         pca.p_bufr = NULL;
198         va_start(ap, fmt);
199         tty_lock(pca.tty);
200         sx_sunlock(&proctree_lock);
201         retval = kvprintf(fmt, putchar, &pca, 10, ap);
202         tty_unlock(pca.tty);
203         va_end(ap);
204         return (retval);
205 }
206
207 /*
208  * tprintf and vtprintf print on the controlling terminal associated with the
209  * given session, possibly to the log as well.
210  */
211 void
212 tprintf(struct proc *p, int pri, const char *fmt, ...)
213 {
214         va_list ap;
215
216         va_start(ap, fmt);
217         vtprintf(p, pri, fmt, ap);
218         va_end(ap);
219 }
220
221 void
222 vtprintf(struct proc *p, int pri, const char *fmt, va_list ap)
223 {
224         struct tty *tp = NULL;
225         int flags = 0;
226         struct putchar_arg pca;
227         struct session *sess = NULL;
228
229         sx_slock(&proctree_lock);
230         if (pri != -1)
231                 flags |= TOLOG;
232         if (p != NULL) {
233                 PROC_LOCK(p);
234                 if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
235                         sess = p->p_session;
236                         sess_hold(sess);
237                         PROC_UNLOCK(p);
238                         tp = sess->s_ttyp;
239                         if (tp != NULL && tty_checkoutq(tp))
240                                 flags |= TOTTY;
241                         else
242                                 tp = NULL;
243                 } else
244                         PROC_UNLOCK(p);
245         }
246         pca.pri = pri;
247         pca.tty = tp;
248         pca.flags = flags;
249         pca.p_bufr = NULL;
250         if (pca.tty != NULL)
251                 tty_lock(pca.tty);
252         sx_sunlock(&proctree_lock);
253         kvprintf(fmt, putchar, &pca, 10, ap);
254         if (pca.tty != NULL)
255                 tty_unlock(pca.tty);
256         if (sess != NULL)
257                 sess_release(sess);
258         msgbuftrigger = 1;
259 }
260
261 static int
262 _vprintf(int level, int flags, const char *fmt, va_list ap)
263 {
264         struct putchar_arg pca;
265         int retval;
266 #ifdef PRINTF_BUFR_SIZE
267         char bufr[PRINTF_BUFR_SIZE];
268 #endif
269
270         TSENTER();
271         pca.tty = NULL;
272         pca.pri = level;
273         pca.flags = flags;
274 #ifdef PRINTF_BUFR_SIZE
275         pca.p_bufr = bufr;
276         pca.p_next = pca.p_bufr;
277         pca.n_bufr = sizeof(bufr);
278         pca.remain = sizeof(bufr);
279         *pca.p_next = '\0';
280 #else
281         /* Don't buffer console output. */
282         pca.p_bufr = NULL;
283 #endif
284
285         retval = kvprintf(fmt, putchar, &pca, 10, ap);
286
287 #ifdef PRINTF_BUFR_SIZE
288         /* Write any buffered console/log output: */
289         if (*pca.p_bufr != '\0') {
290                 if (pca.flags & TOLOG)
291                         msglogstr(pca.p_bufr, level, /*filter_cr*/1);
292
293                 if (pca.flags & TOCONS)
294                         cnputs(pca.p_bufr);
295         }
296 #endif
297
298         TSEXIT();
299         return (retval);
300 }
301
302 /*
303  * Log writes to the log buffer, and guarantees not to sleep (so can be
304  * called by interrupt routines).  If there is no process reading the
305  * log yet, it writes to the console also.
306  */
307 void
308 log(int level, const char *fmt, ...)
309 {
310         va_list ap;
311
312         va_start(ap, fmt);
313         vlog(level, fmt, ap);
314         va_end(ap);
315 }
316
317 void
318 vlog(int level, const char *fmt, va_list ap)
319 {
320
321         (void)_vprintf(level, log_open ? TOLOG : TOCONS | TOLOG, fmt, ap);
322         msgbuftrigger = 1;
323 }
324
325 #define CONSCHUNK 128
326
327 void
328 log_console(struct uio *uio)
329 {
330         int c, error, nl;
331         char *consbuffer;
332         int pri;
333
334         if (!log_console_output)
335                 return;
336
337         pri = LOG_INFO | LOG_CONSOLE;
338         uio = cloneuio(uio);
339         consbuffer = malloc(CONSCHUNK, M_TEMP, M_WAITOK);
340
341         nl = 0;
342         while (uio->uio_resid > 0) {
343                 c = imin(uio->uio_resid, CONSCHUNK - 1);
344                 error = uiomove(consbuffer, c, uio);
345                 if (error != 0)
346                         break;
347                 /* Make sure we're NUL-terminated */
348                 consbuffer[c] = '\0';
349                 if (consbuffer[c - 1] == '\n')
350                         nl = 1;
351                 else
352                         nl = 0;
353                 msglogstr(consbuffer, pri, /*filter_cr*/ 1);
354         }
355         /*
356          * The previous behavior in log_console() is preserved when
357          * log_console_add_linefeed is non-zero.  For that behavior, if an
358          * individual console write came in that was not terminated with a
359          * line feed, it would add a line feed.
360          *
361          * This results in different data in the message buffer than
362          * appears on the system console (which doesn't add extra line feed
363          * characters).
364          *
365          * A number of programs and rc scripts write a line feed, or a period
366          * and a line feed when they have completed their operation.  On
367          * the console, this looks seamless, but when displayed with
368          * 'dmesg -a', you wind up with output that looks like this:
369          *
370          * Updating motd:
371          * .
372          *
373          * On the console, it looks like this:
374          * Updating motd:.
375          *
376          * We could add logic to detect that situation, or just not insert
377          * the extra newlines.  Set the kern.log_console_add_linefeed
378          * sysctl/tunable variable to get the old behavior.
379          */
380         if (!nl && log_console_add_linefeed) {
381                 consbuffer[0] = '\n';
382                 consbuffer[1] = '\0';
383                 msglogstr(consbuffer, pri, /*filter_cr*/ 1);
384         }
385         msgbuftrigger = 1;
386         free(uio, M_IOV);
387         free(consbuffer, M_TEMP);
388 }
389
390 int
391 printf(const char *fmt, ...)
392 {
393         va_list ap;
394         int retval;
395
396         va_start(ap, fmt);
397         retval = vprintf(fmt, ap);
398         va_end(ap);
399
400         return (retval);
401 }
402
403 int
404 vprintf(const char *fmt, va_list ap)
405 {
406         int retval;
407
408         retval = _vprintf(-1, TOCONS | TOLOG, fmt, ap);
409
410         if (!panicstr)
411                 msgbuftrigger = 1;
412
413         return (retval);
414 }
415
416 static void
417 prf_putbuf(char *bufr, int flags, int pri)
418 {
419
420         if (flags & TOLOG)
421                 msglogstr(bufr, pri, /*filter_cr*/1);
422
423         if (flags & TOCONS) {
424                 if ((panicstr == NULL) && (constty != NULL))
425                         msgbuf_addstr(&consmsgbuf, -1,
426                             bufr, /*filter_cr*/ 0);
427
428                 if ((constty == NULL) ||(always_console_output))
429                         cnputs(bufr);
430         }
431 }
432
433 static void
434 putbuf(int c, struct putchar_arg *ap)
435 {
436         /* Check if no console output buffer was provided. */
437         if (ap->p_bufr == NULL) {
438                 /* Output direct to the console. */
439                 if (ap->flags & TOCONS)
440                         cnputc(c);
441
442                 if (ap->flags & TOLOG)
443                         msglogchar(c, ap->pri);
444         } else {
445                 /* Buffer the character: */
446                 *ap->p_next++ = c;
447                 ap->remain--;
448
449                 /* Always leave the buffer zero terminated. */
450                 *ap->p_next = '\0';
451
452                 /* Check if the buffer needs to be flushed. */
453                 if (ap->remain == 2 || c == '\n') {
454                         prf_putbuf(ap->p_bufr, ap->flags, ap->pri);
455
456                         ap->p_next = ap->p_bufr;
457                         ap->remain = ap->n_bufr;
458                         *ap->p_next = '\0';
459                 }
460
461                 /*
462                  * Since we fill the buffer up one character at a time,
463                  * this should not happen.  We should always catch it when
464                  * ap->remain == 2 (if not sooner due to a newline), flush
465                  * the buffer and move on.  One way this could happen is
466                  * if someone sets PRINTF_BUFR_SIZE to 1 or something
467                  * similarly silly.
468                  */
469                 KASSERT(ap->remain > 2, ("Bad buffer logic, remain = %zd",
470                     ap->remain));
471         }
472 }
473
474 /*
475  * Print a character on console or users terminal.  If destination is
476  * the console then the last bunch of characters are saved in msgbuf for
477  * inspection later.
478  */
479 static void
480 putchar(int c, void *arg)
481 {
482         struct putchar_arg *ap = (struct putchar_arg*) arg;
483         struct tty *tp = ap->tty;
484         int flags = ap->flags;
485
486         /* Don't use the tty code after a panic or while in ddb. */
487         if (kdb_active) {
488                 if (c != '\0')
489                         cnputc(c);
490                 return;
491         }
492
493         if ((flags & TOTTY) && tp != NULL && panicstr == NULL)
494                 tty_putchar(tp, c);
495
496         if ((flags & (TOCONS | TOLOG)) && c != '\0')
497                 putbuf(c, ap);
498 }
499
500 /*
501  * Scaled down version of sprintf(3).
502  */
503 int
504 sprintf(char *buf, const char *cfmt, ...)
505 {
506         int retval;
507         va_list ap;
508
509         va_start(ap, cfmt);
510         retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
511         buf[retval] = '\0';
512         va_end(ap);
513         return (retval);
514 }
515
516 /*
517  * Scaled down version of vsprintf(3).
518  */
519 int
520 vsprintf(char *buf, const char *cfmt, va_list ap)
521 {
522         int retval;
523
524         retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
525         buf[retval] = '\0';
526         return (retval);
527 }
528
529 /*
530  * Scaled down version of snprintf(3).
531  */
532 int
533 snprintf(char *str, size_t size, const char *format, ...)
534 {
535         int retval;
536         va_list ap;
537
538         va_start(ap, format);
539         retval = vsnprintf(str, size, format, ap);
540         va_end(ap);
541         return(retval);
542 }
543
544 /*
545  * Scaled down version of vsnprintf(3).
546  */
547 int
548 vsnprintf(char *str, size_t size, const char *format, va_list ap)
549 {
550         struct snprintf_arg info;
551         int retval;
552
553         info.str = str;
554         info.remain = size;
555         retval = kvprintf(format, snprintf_func, &info, 10, ap);
556         if (info.remain >= 1)
557                 *info.str++ = '\0';
558         return (retval);
559 }
560
561 /*
562  * Kernel version which takes radix argument vsnprintf(3).
563  */
564 int
565 vsnrprintf(char *str, size_t size, int radix, const char *format, va_list ap)
566 {
567         struct snprintf_arg info;
568         int retval;
569
570         info.str = str;
571         info.remain = size;
572         retval = kvprintf(format, snprintf_func, &info, radix, ap);
573         if (info.remain >= 1)
574                 *info.str++ = '\0';
575         return (retval);
576 }
577
578 static void
579 snprintf_func(int ch, void *arg)
580 {
581         struct snprintf_arg *const info = arg;
582
583         if (info->remain >= 2) {
584                 *info->str++ = ch;
585                 info->remain--;
586         }
587 }
588
589 /*
590  * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
591  * order; return an optional length and a pointer to the last character
592  * written in the buffer (i.e., the first character of the string).
593  * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
594  */
595 static char *
596 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
597 {
598         char *p, c;
599
600         p = nbuf;
601         *p = '\0';
602         do {
603                 c = hex2ascii(num % base);
604                 *++p = upper ? toupper(c) : c;
605         } while (num /= base);
606         if (lenp)
607                 *lenp = p - nbuf;
608         return (p);
609 }
610
611 /*
612  * Scaled down version of printf(3).
613  *
614  * Two additional formats:
615  *
616  * The format %b is supported to decode error registers.
617  * Its usage is:
618  *
619  *      printf("reg=%b\n", regval, "<base><arg>*");
620  *
621  * where <base> is the output base expressed as a control character, e.g.
622  * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
623  * the first of which gives the bit number to be inspected (origin 1), and
624  * the next characters (up to a control character, i.e. a character <= 32),
625  * give the name of the register.  Thus:
626  *
627  *      kvprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE");
628  *
629  * would produce output:
630  *
631  *      reg=3<BITTWO,BITONE>
632  *
633  * XXX:  %D  -- Hexdump, takes pointer and separator string:
634  *              ("%6D", ptr, ":")   -> XX:XX:XX:XX:XX:XX
635  *              ("%*D", len, ptr, " " -> XX XX XX XX ...
636  */
637 int
638 kvprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, va_list ap)
639 {
640 #define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; }
641         char nbuf[MAXNBUF];
642         char *d;
643         const char *p, *percent, *q;
644         u_char *up;
645         int ch, n;
646         uintmax_t num;
647         int base, lflag, qflag, tmp, width, ladjust, sharpflag, neg, sign, dot;
648         int cflag, hflag, jflag, tflag, zflag;
649         int bconv, dwidth, upper;
650         char padc;
651         int stop = 0, retval = 0;
652
653         num = 0;
654         q = NULL;
655         if (!func)
656                 d = (char *) arg;
657         else
658                 d = NULL;
659
660         if (fmt == NULL)
661                 fmt = "(fmt null)\n";
662
663         if (radix < 2 || radix > 36)
664                 radix = 10;
665
666         for (;;) {
667                 padc = ' ';
668                 width = 0;
669                 while ((ch = (u_char)*fmt++) != '%' || stop) {
670                         if (ch == '\0')
671                                 return (retval);
672                         PCHAR(ch);
673                 }
674                 percent = fmt - 1;
675                 qflag = 0; lflag = 0; ladjust = 0; sharpflag = 0; neg = 0;
676                 sign = 0; dot = 0; bconv = 0; dwidth = 0; upper = 0;
677                 cflag = 0; hflag = 0; jflag = 0; tflag = 0; zflag = 0;
678 reswitch:       switch (ch = (u_char)*fmt++) {
679                 case '.':
680                         dot = 1;
681                         goto reswitch;
682                 case '#':
683                         sharpflag = 1;
684                         goto reswitch;
685                 case '+':
686                         sign = 1;
687                         goto reswitch;
688                 case '-':
689                         ladjust = 1;
690                         goto reswitch;
691                 case '%':
692                         PCHAR(ch);
693                         break;
694                 case '*':
695                         if (!dot) {
696                                 width = va_arg(ap, int);
697                                 if (width < 0) {
698                                         ladjust = !ladjust;
699                                         width = -width;
700                                 }
701                         } else {
702                                 dwidth = va_arg(ap, int);
703                         }
704                         goto reswitch;
705                 case '0':
706                         if (!dot) {
707                                 padc = '0';
708                                 goto reswitch;
709                         }
710                         /* FALLTHROUGH */
711                 case '1': case '2': case '3': case '4':
712                 case '5': case '6': case '7': case '8': case '9':
713                                 for (n = 0;; ++fmt) {
714                                         n = n * 10 + ch - '0';
715                                         ch = *fmt;
716                                         if (ch < '0' || ch > '9')
717                                                 break;
718                                 }
719                         if (dot)
720                                 dwidth = n;
721                         else
722                                 width = n;
723                         goto reswitch;
724                 case 'b':
725                         ladjust = 1;
726                         bconv = 1;
727                         goto handle_nosign;
728                 case 'c':
729                         width -= 1;
730
731                         if (!ladjust && width > 0)
732                                 while (width--)
733                                         PCHAR(padc);
734                         PCHAR(va_arg(ap, int));
735                         if (ladjust && width > 0)
736                                 while (width--)
737                                         PCHAR(padc);
738                         break;
739                 case 'D':
740                         up = va_arg(ap, u_char *);
741                         p = va_arg(ap, char *);
742                         if (!width)
743                                 width = 16;
744                         while(width--) {
745                                 PCHAR(hex2ascii(*up >> 4));
746                                 PCHAR(hex2ascii(*up & 0x0f));
747                                 up++;
748                                 if (width)
749                                         for (q=p;*q;q++)
750                                                 PCHAR(*q);
751                         }
752                         break;
753                 case 'd':
754                 case 'i':
755                         base = 10;
756                         sign = 1;
757                         goto handle_sign;
758                 case 'h':
759                         if (hflag) {
760                                 hflag = 0;
761                                 cflag = 1;
762                         } else
763                                 hflag = 1;
764                         goto reswitch;
765                 case 'j':
766                         jflag = 1;
767                         goto reswitch;
768                 case 'l':
769                         if (lflag) {
770                                 lflag = 0;
771                                 qflag = 1;
772                         } else
773                                 lflag = 1;
774                         goto reswitch;
775                 case 'n':
776                         if (jflag)
777                                 *(va_arg(ap, intmax_t *)) = retval;
778                         else if (qflag)
779                                 *(va_arg(ap, quad_t *)) = retval;
780                         else if (lflag)
781                                 *(va_arg(ap, long *)) = retval;
782                         else if (zflag)
783                                 *(va_arg(ap, size_t *)) = retval;
784                         else if (hflag)
785                                 *(va_arg(ap, short *)) = retval;
786                         else if (cflag)
787                                 *(va_arg(ap, char *)) = retval;
788                         else
789                                 *(va_arg(ap, int *)) = retval;
790                         break;
791                 case 'o':
792                         base = 8;
793                         goto handle_nosign;
794                 case 'p':
795                         base = 16;
796                         sharpflag = (width == 0);
797                         sign = 0;
798                         num = (uintptr_t)va_arg(ap, void *);
799                         goto number;
800                 case 'q':
801                         qflag = 1;
802                         goto reswitch;
803                 case 'r':
804                         base = radix;
805                         if (sign)
806                                 goto handle_sign;
807                         goto handle_nosign;
808                 case 's':
809                         p = va_arg(ap, char *);
810                         if (p == NULL)
811                                 p = "(null)";
812                         if (!dot)
813                                 n = strlen (p);
814                         else
815                                 for (n = 0; n < dwidth && p[n]; n++)
816                                         continue;
817
818                         width -= n;
819
820                         if (!ladjust && width > 0)
821                                 while (width--)
822                                         PCHAR(padc);
823                         while (n--)
824                                 PCHAR(*p++);
825                         if (ladjust && width > 0)
826                                 while (width--)
827                                         PCHAR(padc);
828                         break;
829                 case 't':
830                         tflag = 1;
831                         goto reswitch;
832                 case 'u':
833                         base = 10;
834                         goto handle_nosign;
835                 case 'X':
836                         upper = 1;
837                 case 'x':
838                         base = 16;
839                         goto handle_nosign;
840                 case 'y':
841                         base = 16;
842                         sign = 1;
843                         goto handle_sign;
844                 case 'z':
845                         zflag = 1;
846                         goto reswitch;
847 handle_nosign:
848                         sign = 0;
849                         if (jflag)
850                                 num = va_arg(ap, uintmax_t);
851                         else if (qflag)
852                                 num = va_arg(ap, u_quad_t);
853                         else if (tflag)
854                                 num = va_arg(ap, ptrdiff_t);
855                         else if (lflag)
856                                 num = va_arg(ap, u_long);
857                         else if (zflag)
858                                 num = va_arg(ap, size_t);
859                         else if (hflag)
860                                 num = (u_short)va_arg(ap, int);
861                         else if (cflag)
862                                 num = (u_char)va_arg(ap, int);
863                         else
864                                 num = va_arg(ap, u_int);
865                         if (bconv) {
866                                 q = va_arg(ap, char *);
867                                 base = *q++;
868                         }
869                         goto number;
870 handle_sign:
871                         if (jflag)
872                                 num = va_arg(ap, intmax_t);
873                         else if (qflag)
874                                 num = va_arg(ap, quad_t);
875                         else if (tflag)
876                                 num = va_arg(ap, ptrdiff_t);
877                         else if (lflag)
878                                 num = va_arg(ap, long);
879                         else if (zflag)
880                                 num = va_arg(ap, ssize_t);
881                         else if (hflag)
882                                 num = (short)va_arg(ap, int);
883                         else if (cflag)
884                                 num = (char)va_arg(ap, int);
885                         else
886                                 num = va_arg(ap, int);
887 number:
888                         if (sign && (intmax_t)num < 0) {
889                                 neg = 1;
890                                 num = -(intmax_t)num;
891                         }
892                         p = ksprintn(nbuf, num, base, &n, upper);
893                         tmp = 0;
894                         if (sharpflag && num != 0) {
895                                 if (base == 8)
896                                         tmp++;
897                                 else if (base == 16)
898                                         tmp += 2;
899                         }
900                         if (neg)
901                                 tmp++;
902
903                         if (!ladjust && padc == '0')
904                                 dwidth = width - tmp;
905                         width -= tmp + imax(dwidth, n);
906                         dwidth -= n;
907                         if (!ladjust)
908                                 while (width-- > 0)
909                                         PCHAR(' ');
910                         if (neg)
911                                 PCHAR('-');
912                         if (sharpflag && num != 0) {
913                                 if (base == 8) {
914                                         PCHAR('0');
915                                 } else if (base == 16) {
916                                         PCHAR('0');
917                                         PCHAR('x');
918                                 }
919                         }
920                         while (dwidth-- > 0)
921                                 PCHAR('0');
922
923                         while (*p)
924                                 PCHAR(*p--);
925
926                         if (bconv && num != 0) {
927                                 /* %b conversion flag format. */
928                                 tmp = retval;
929                                 while (*q) {
930                                         n = *q++;
931                                         if (num & (1 << (n - 1))) {
932                                                 PCHAR(retval != tmp ?
933                                                     ',' : '<');
934                                                 for (; (n = *q) > ' '; ++q)
935                                                         PCHAR(n);
936                                         } else
937                                                 for (; *q > ' '; ++q)
938                                                         continue;
939                                 }
940                                 if (retval != tmp) {
941                                         PCHAR('>');
942                                         width -= retval - tmp;
943                                 }
944                         }
945
946                         if (ladjust)
947                                 while (width-- > 0)
948                                         PCHAR(' ');
949
950                         break;
951                 default:
952                         while (percent < fmt)
953                                 PCHAR(*percent++);
954                         /*
955                          * Since we ignore a formatting argument it is no
956                          * longer safe to obey the remaining formatting
957                          * arguments as the arguments will no longer match
958                          * the format specs.
959                          */
960                         stop = 1;
961                         break;
962                 }
963         }
964 #undef PCHAR
965 }
966
967 /*
968  * Put character in log buffer with a particular priority.
969  */
970 static void
971 msglogchar(int c, int pri)
972 {
973         static int lastpri = -1;
974         static int dangling;
975         char nbuf[MAXNBUF];
976         char *p;
977
978         if (!msgbufmapped)
979                 return;
980         if (c == '\0' || c == '\r')
981                 return;
982         if (pri != -1 && pri != lastpri) {
983                 if (dangling) {
984                         msgbuf_addchar(msgbufp, '\n');
985                         dangling = 0;
986                 }
987                 msgbuf_addchar(msgbufp, '<');
988                 for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
989                         msgbuf_addchar(msgbufp, *p--);
990                 msgbuf_addchar(msgbufp, '>');
991                 lastpri = pri;
992         }
993         msgbuf_addchar(msgbufp, c);
994         if (c == '\n') {
995                 dangling = 0;
996                 lastpri = -1;
997         } else {
998                 dangling = 1;
999         }
1000 }
1001
1002 static void
1003 msglogstr(char *str, int pri, int filter_cr)
1004 {
1005         if (!msgbufmapped)
1006                 return;
1007
1008         msgbuf_addstr(msgbufp, pri, str, filter_cr);
1009 }
1010
1011 void
1012 msgbufinit(void *ptr, int size)
1013 {
1014         char *cp;
1015         static struct msgbuf *oldp = NULL;
1016         bool print_boot_tag;
1017
1018         size -= sizeof(*msgbufp);
1019         cp = (char *)ptr;
1020         print_boot_tag = !msgbufmapped;
1021         /* Attempt to fetch kern.boot_tag tunable on first mapping */
1022         if (!msgbufmapped)
1023                 TUNABLE_STR_FETCH("kern.boot_tag", current_boot_tag,
1024                     sizeof(current_boot_tag));
1025         msgbufp = (struct msgbuf *)(cp + size);
1026         msgbuf_reinit(msgbufp, cp, size);
1027         if (msgbufmapped && oldp != msgbufp)
1028                 msgbuf_copy(oldp, msgbufp);
1029         msgbufmapped = true;
1030         if (print_boot_tag && *current_boot_tag != '\0')
1031                 printf("%s\n", current_boot_tag);
1032         oldp = msgbufp;
1033 }
1034
1035 /* Sysctls for accessing/clearing the msgbuf */
1036 static int
1037 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
1038 {
1039         char buf[128];
1040         u_int seq;
1041         int error, len;
1042
1043         error = priv_check(req->td, PRIV_MSGBUF);
1044         if (error)
1045                 return (error);
1046
1047         /* Read the whole buffer, one chunk at a time. */
1048         mtx_lock(&msgbuf_lock);
1049         msgbuf_peekbytes(msgbufp, NULL, 0, &seq);
1050         for (;;) {
1051                 len = msgbuf_peekbytes(msgbufp, buf, sizeof(buf), &seq);
1052                 mtx_unlock(&msgbuf_lock);
1053                 if (len == 0)
1054                         return (SYSCTL_OUT(req, "", 1)); /* add nulterm */
1055
1056                 error = sysctl_handle_opaque(oidp, buf, len, req);
1057                 if (error)
1058                         return (error);
1059
1060                 mtx_lock(&msgbuf_lock);
1061         }
1062 }
1063
1064 SYSCTL_PROC(_kern, OID_AUTO, msgbuf,
1065     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
1066     NULL, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
1067
1068 static int msgbuf_clearflag;
1069
1070 static int
1071 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
1072 {
1073         int error;
1074         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1075         if (!error && req->newptr) {
1076                 mtx_lock(&msgbuf_lock);
1077                 msgbuf_clear(msgbufp);
1078                 mtx_unlock(&msgbuf_lock);
1079                 msgbuf_clearflag = 0;
1080         }
1081         return (error);
1082 }
1083
1084 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
1085     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE | CTLFLAG_MPSAFE,
1086     &msgbuf_clearflag, 0, sysctl_kern_msgbuf_clear, "I",
1087     "Clear kernel message buffer");
1088
1089 #ifdef DDB
1090
1091 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
1092 {
1093         int i, j;
1094
1095         if (!msgbufmapped) {
1096                 db_printf("msgbuf not mapped yet\n");
1097                 return;
1098         }
1099         db_printf("msgbufp = %p\n", msgbufp);
1100         db_printf("magic = %x, size = %d, r= %u, w = %u, ptr = %p, cksum= %u\n",
1101             msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_rseq,
1102             msgbufp->msg_wseq, msgbufp->msg_ptr, msgbufp->msg_cksum);
1103         for (i = 0; i < msgbufp->msg_size && !db_pager_quit; i++) {
1104                 j = MSGBUF_SEQ_TO_POS(msgbufp, i + msgbufp->msg_rseq);
1105                 db_printf("%c", msgbufp->msg_ptr[j]);
1106         }
1107         db_printf("\n");
1108 }
1109
1110 #endif /* DDB */
1111
1112 void
1113 hexdump(const void *ptr, int length, const char *hdr, int flags)
1114 {
1115         int i, j, k;
1116         int cols;
1117         const unsigned char *cp;
1118         char delim;
1119
1120         if ((flags & HD_DELIM_MASK) != 0)
1121                 delim = (flags & HD_DELIM_MASK) >> 8;
1122         else
1123                 delim = ' ';
1124
1125         if ((flags & HD_COLUMN_MASK) != 0)
1126                 cols = flags & HD_COLUMN_MASK;
1127         else
1128                 cols = 16;
1129
1130         cp = ptr;
1131         for (i = 0; i < length; i+= cols) {
1132                 if (hdr != NULL)
1133                         printf("%s", hdr);
1134
1135                 if ((flags & HD_OMIT_COUNT) == 0)
1136                         printf("%04x  ", i);
1137
1138                 if ((flags & HD_OMIT_HEX) == 0) {
1139                         for (j = 0; j < cols; j++) {
1140                                 k = i + j;
1141                                 if (k < length)
1142                                         printf("%c%02x", delim, cp[k]);
1143                                 else
1144                                         printf("   ");
1145                         }
1146                 }
1147
1148                 if ((flags & HD_OMIT_CHARS) == 0) {
1149                         printf("  |");
1150                         for (j = 0; j < cols; j++) {
1151                                 k = i + j;
1152                                 if (k >= length)
1153                                         printf(" ");
1154                                 else if (cp[k] >= ' ' && cp[k] <= '~')
1155                                         printf("%c", cp[k]);
1156                                 else
1157                                         printf(".");
1158                         }
1159                         printf("|");
1160                 }
1161                 printf("\n");
1162         }
1163 }
1164 #endif /* _KERNEL */
1165
1166 void
1167 sbuf_hexdump(struct sbuf *sb, const void *ptr, int length, const char *hdr,
1168              int flags)
1169 {
1170         int i, j, k;
1171         int cols;
1172         const unsigned char *cp;
1173         char delim;
1174
1175         if ((flags & HD_DELIM_MASK) != 0)
1176                 delim = (flags & HD_DELIM_MASK) >> 8;
1177         else
1178                 delim = ' ';
1179
1180         if ((flags & HD_COLUMN_MASK) != 0)
1181                 cols = flags & HD_COLUMN_MASK;
1182         else
1183                 cols = 16;
1184
1185         cp = ptr;
1186         for (i = 0; i < length; i+= cols) {
1187                 if (hdr != NULL)
1188                         sbuf_printf(sb, "%s", hdr);
1189
1190                 if ((flags & HD_OMIT_COUNT) == 0)
1191                         sbuf_printf(sb, "%04x  ", i);
1192
1193                 if ((flags & HD_OMIT_HEX) == 0) {
1194                         for (j = 0; j < cols; j++) {
1195                                 k = i + j;
1196                                 if (k < length)
1197                                         sbuf_printf(sb, "%c%02x", delim, cp[k]);
1198                                 else
1199                                         sbuf_printf(sb, "   ");
1200                         }
1201                 }
1202
1203                 if ((flags & HD_OMIT_CHARS) == 0) {
1204                         sbuf_printf(sb, "  |");
1205                         for (j = 0; j < cols; j++) {
1206                                 k = i + j;
1207                                 if (k >= length)
1208                                         sbuf_printf(sb, " ");
1209                                 else if (cp[k] >= ' ' && cp[k] <= '~')
1210                                         sbuf_printf(sb, "%c", cp[k]);
1211                                 else
1212                                         sbuf_printf(sb, ".");
1213                         }
1214                         sbuf_printf(sb, "|");
1215                 }
1216                 sbuf_printf(sb, "\n");
1217         }
1218 }
1219
1220 #ifdef _KERNEL
1221 void
1222 counted_warning(unsigned *counter, const char *msg)
1223 {
1224         struct thread *td;
1225         unsigned c;
1226
1227         for (;;) {
1228                 c = *counter;
1229                 if (c == 0)
1230                         break;
1231                 if (atomic_cmpset_int(counter, c, c - 1)) {
1232                         td = curthread;
1233                         log(LOG_INFO, "pid %d (%s) %s%s\n",
1234                             td->td_proc->p_pid, td->td_name, msg,
1235                             c > 1 ? "" : " - not logging anymore");
1236                         break;
1237                 }
1238         }
1239 }
1240 #endif
1241
1242 #ifdef _KERNEL
1243 void
1244 sbuf_putbuf(struct sbuf *sb)
1245 {
1246
1247         prf_putbuf(sbuf_data(sb), TOLOG | TOCONS, -1);
1248 }
1249 #else
1250 void
1251 sbuf_putbuf(struct sbuf *sb)
1252 {
1253
1254         printf("%s", sbuf_data(sb));
1255 }
1256 #endif