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