hexdump.c revision 97749
1204076Spjd/*-
2204076Spjd * Copyright (c) 1986, 1988, 1991, 1993
3204076Spjd *	The Regents of the University of California.  All rights reserved.
4204076Spjd * (c) UNIX System Laboratories, Inc.
5204076Spjd * All or some portions of this file are derived from material licensed
6204076Spjd * to the University of California by American Telephone and Telegraph
7204076Spjd * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8204076Spjd * the permission of UNIX System Laboratories, Inc.
9204076Spjd *
10204076Spjd * Redistribution and use in source and binary forms, with or without
11204076Spjd * modification, are permitted provided that the following conditions
12204076Spjd * are met:
13204076Spjd * 1. Redistributions of source code must retain the above copyright
14204076Spjd *    notice, this list of conditions and the following disclaimer.
15204076Spjd * 2. Redistributions in binary form must reproduce the above copyright
16204076Spjd *    notice, this list of conditions and the following disclaimer in the
17204076Spjd *    documentation and/or other materials provided with the distribution.
18204076Spjd * 3. All advertising materials mentioning features or use of this software
19204076Spjd *    must display the following acknowledgement:
20204076Spjd *	This product includes software developed by the University of
21204076Spjd *	California, Berkeley and its contributors.
22204076Spjd * 4. Neither the name of the University nor the names of its contributors
23204076Spjd *    may be used to endorse or promote products derived from this software
24204076Spjd *    without specific prior written permission.
25204076Spjd *
26204076Spjd * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27204076Spjd * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28204076Spjd * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29204076Spjd * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30204076Spjd * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31204076Spjd * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32204076Spjd * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33204076Spjd * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34204076Spjd * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35204076Spjd * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36204076Spjd * SUCH DAMAGE.
37204076Spjd *
38204076Spjd *	@(#)subr_prf.c	8.3 (Berkeley) 1/21/94
39204076Spjd * $FreeBSD: head/sys/kern/subr_prf.c 97749 2002-06-02 21:54:55Z des $
40204076Spjd */
41204076Spjd
42204076Spjd#include <sys/param.h>
43204076Spjd#include <sys/systm.h>
44204076Spjd#include <sys/lock.h>
45204076Spjd#include <sys/mutex.h>
46204076Spjd#include <sys/sx.h>
47204076Spjd#include <sys/kernel.h>
48204076Spjd#include <sys/msgbuf.h>
49204076Spjd#include <sys/malloc.h>
50204076Spjd#include <sys/proc.h>
51204076Spjd#include <sys/stdint.h>
52204076Spjd#include <sys/sysctl.h>
53204076Spjd#include <sys/tty.h>
54204076Spjd#include <sys/syslog.h>
55204076Spjd#include <sys/cons.h>
56204076Spjd#include <sys/uio.h>
57204076Spjd
58204076Spjd/*
59204076Spjd * Note that stdarg.h and the ANSI style va_start macro is used for both
60204076Spjd * ANSI and traditional C compilers.
61204076Spjd */
62204076Spjd#include <machine/stdarg.h>
63204076Spjd
64204076Spjd#define TOCONS	0x01
65204076Spjd#define TOTTY	0x02
66204076Spjd#define TOLOG	0x04
67204076Spjd
68204076Spjd/* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
69204076Spjd#define MAXNBUF	(sizeof(intmax_t) * NBBY + 1)
70204076Spjd
71204076Spjdstruct putchar_arg {
72204076Spjd	int	flags;
73204076Spjd	int	pri;
74204076Spjd	struct	tty *tty;
75204076Spjd};
76204076Spjd
77204076Spjdstruct snprintf_arg {
78204076Spjd	char	*str;
79204076Spjd	size_t	remain;
80204076Spjd};
81204076Spjd
82204076Spjdextern	int log_open;
83204076Spjd
84204076Spjdstruct	tty *constty;			/* pointer to console "window" tty */
85204076Spjd
86204076Spjdstatic void (*v_putc)(int) = cnputc;	/* routine to putc on virtual console */
87204076Spjdstatic void  msglogchar(int c, int pri);
88204076Spjdstatic void  msgaddchar(int c, void *dummy);
89204076Spjdstatic void  putchar(int ch, void *arg);
90204076Spjdstatic char *ksprintn(char *nbuf, uintmax_t num, int base, int *len);
91204076Spjdstatic void  snprintf_func(int ch, void *arg);
92204076Spjd
93204076Spjdstatic int consintr = 1;		/* Ok to handle console interrupts? */
94204076Spjdstatic int msgbufmapped;		/* Set when safe to use msgbuf */
95204076Spjdint msgbuftrigger;
96204076Spjd
97204076Spjdstatic int      log_console_output = 1;
98204076SpjdSYSCTL_INT(_kern, OID_AUTO, log_console_output, CTLFLAG_RW,
99209179Spjd    &log_console_output, 0, "");
100204076Spjd
101204076Spjd/*
102204076Spjd * Warn that a system table is full.
103204076Spjd */
104204076Spjdvoid
105204076Spjdtablefull(const char *tab)
106204076Spjd{
107204076Spjd
108204076Spjd	log(LOG_ERR, "%s: table is full\n", tab);
109204076Spjd}
110204076Spjd
111204076Spjd/*
112204076Spjd * Uprintf prints to the controlling terminal for the current process.
113204076Spjd * It may block if the tty queue is overfull.  No message is printed if
114204076Spjd * the queue does not clear in a reasonable time.
115204076Spjd */
116204076Spjdint
117204076Spjduprintf(const char *fmt, ...)
118204076Spjd{
119204076Spjd	struct thread *td = curthread;
120204076Spjd	struct proc *p = td->td_proc;
121207343Spjd	va_list ap;
122204076Spjd	struct putchar_arg pca;
123204076Spjd	int retval;
124204076Spjd
125204076Spjd	if (td == NULL || td == PCPU_GET(idlethread))
126204076Spjd		return (0);
127204076Spjd
128204076Spjd	p = td->td_proc;
129204076Spjd	PROC_LOCK(p);
130204076Spjd	if ((p->p_flag & P_CONTROLT) == 0) {
131204076Spjd		PROC_UNLOCK(p);
132204076Spjd		return (0);
133204076Spjd	}
134204076Spjd	SESS_LOCK(p->p_session);
135204076Spjd	pca.tty = p->p_session->s_ttyp;
136204076Spjd	SESS_UNLOCK(p->p_session);
137204076Spjd	PROC_UNLOCK(p);
138204076Spjd	if (pca.tty == NULL)
139204076Spjd		return (0);
140204076Spjd	pca.flags = TOTTY;
141204076Spjd	va_start(ap, fmt);
142204076Spjd	retval = kvprintf(fmt, putchar, &pca, 10, ap);
143204076Spjd	va_end(ap);
144204076Spjd
145204076Spjd	return (retval);
146204076Spjd}
147204076Spjd
148204076Spjd/*
149204076Spjd * tprintf prints on the controlling terminal associated
150204076Spjd * with the given session, possibly to the log as well.
151204076Spjd */
152204076Spjdvoid
153204076Spjdtprintf(struct proc *p, int pri, const char *fmt, ...)
154204076Spjd{
155204076Spjd	struct tty *tp = NULL;
156204076Spjd	int flags = 0, shld = 0;
157204076Spjd	va_list ap;
158209179Spjd	struct putchar_arg pca;
159204076Spjd	int retval;
160204076Spjd
161204076Spjd	if (pri != -1)
162204076Spjd		flags |= TOLOG;
163204076Spjd	if (p != NULL) {
164204076Spjd		PROC_LOCK(p);
165204076Spjd		if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
166204076Spjd			SESS_LOCK(p->p_session);
167204076Spjd			SESSHOLD(p->p_session);
168204076Spjd			tp = p->p_session->s_ttyp;
169204076Spjd			SESS_UNLOCK(p->p_session);
170204076Spjd			PROC_UNLOCK(p);
171204076Spjd			shld++;
172204076Spjd			if (ttycheckoutq(tp, 0))
173204076Spjd				flags |= TOTTY;
174204076Spjd			else
175204076Spjd				tp = NULL;
176204076Spjd		} else
177209179Spjd			PROC_UNLOCK(p);
178204076Spjd	}
179204076Spjd	pca.pri = pri;
180204076Spjd	pca.tty = tp;
181204076Spjd	pca.flags = flags;
182204076Spjd	va_start(ap, fmt);
183204076Spjd	retval = kvprintf(fmt, putchar, &pca, 10, ap);
184204076Spjd	va_end(ap);
185204076Spjd	if (shld) {
186209179Spjd		PROC_LOCK(p);
187209179Spjd		SESS_LOCK(p->p_session);
188204076Spjd		SESSRELE(p->p_session);
189204076Spjd		SESS_UNLOCK(p->p_session);
190204076Spjd		PROC_UNLOCK(p);
191204076Spjd	}
192204076Spjd	msgbuftrigger = 1;
193204076Spjd}
194204076Spjd
195204076Spjd/*
196204076Spjd * Ttyprintf displays a message on a tty; it should be used only by
197204076Spjd * the tty driver, or anything that knows the underlying tty will not
198204076Spjd * be revoke(2)'d away.  Other callers should use tprintf.
199204076Spjd */
200204076Spjdint
201204076Spjdttyprintf(struct tty *tp, const char *fmt, ...)
202204076Spjd{
203204076Spjd	va_list ap;
204204076Spjd	struct putchar_arg pca;
205204076Spjd	int retval;
206204076Spjd
207209179Spjd	va_start(ap, fmt);
208204076Spjd	pca.tty = tp;
209204076Spjd	pca.flags = TOTTY;
210204076Spjd	retval = kvprintf(fmt, putchar, &pca, 10, ap);
211204076Spjd	va_end(ap);
212204076Spjd	return (retval);
213204076Spjd}
214204076Spjd
215204076Spjd/*
216204076Spjd * Log writes to the log buffer, and guarantees not to sleep (so can be
217204076Spjd * called by interrupt routines).  If there is no process reading the
218204076Spjd * log yet, it writes to the console also.
219209179Spjd */
220204076Spjdvoid
221209179Spjdlog(int level, const char *fmt, ...)
222209179Spjd{
223204076Spjd	va_list ap;
224204076Spjd	int retval;
225209179Spjd	struct putchar_arg pca;
226204076Spjd
227	pca.tty = NULL;
228	pca.pri = level;
229	pca.flags = log_open ? TOLOG : TOCONS;
230
231	va_start(ap, fmt);
232	retval = kvprintf(fmt, putchar, &pca, 10, ap);
233	va_end(ap);
234
235	msgbuftrigger = 1;
236}
237
238#define CONSCHUNK 128
239
240void
241log_console(struct uio *uio)
242{
243	int c, i, error, iovlen, nl;
244	struct uio muio;
245	struct iovec *miov = NULL;
246	char *consbuffer;
247	int pri;
248
249	if (!log_console_output)
250		return;
251
252	pri = LOG_INFO | LOG_CONSOLE;
253	muio = *uio;
254	iovlen = uio->uio_iovcnt * sizeof (struct iovec);
255	MALLOC(miov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
256	MALLOC(consbuffer, char *, CONSCHUNK, M_TEMP, M_WAITOK);
257	bcopy((caddr_t)muio.uio_iov, (caddr_t)miov, iovlen);
258	muio.uio_iov = miov;
259	uio = &muio;
260
261	nl = 0;
262	while (uio->uio_resid > 0) {
263		c = imin(uio->uio_resid, CONSCHUNK);
264		error = uiomove(consbuffer, c, uio);
265		if (error != 0)
266			return;
267		for (i = 0; i < c; i++) {
268			msglogchar(consbuffer[i], pri);
269			if (consbuffer[i] == '\n')
270				nl = 1;
271			else
272				nl = 0;
273		}
274	}
275	if (!nl)
276		msglogchar('\n', pri);
277	msgbuftrigger = 1;
278	FREE(miov, M_TEMP);
279	FREE(consbuffer, M_TEMP);
280	return;
281}
282
283int
284printf(const char *fmt, ...)
285{
286	va_list ap;
287	int savintr;
288	struct putchar_arg pca;
289	int retval;
290
291	savintr = consintr;		/* disable interrupts */
292	consintr = 0;
293	va_start(ap, fmt);
294	pca.tty = NULL;
295	pca.flags = TOCONS | TOLOG;
296	pca.pri = -1;
297	retval = kvprintf(fmt, putchar, &pca, 10, ap);
298	va_end(ap);
299	if (!panicstr)
300		msgbuftrigger = 1;
301	consintr = savintr;		/* reenable interrupts */
302	return (retval);
303}
304
305int
306vprintf(const char *fmt, va_list ap)
307{
308	int savintr;
309	struct putchar_arg pca;
310	int retval;
311
312	savintr = consintr;		/* disable interrupts */
313	consintr = 0;
314	pca.tty = NULL;
315	pca.flags = TOCONS | TOLOG;
316	pca.pri = -1;
317	retval = kvprintf(fmt, putchar, &pca, 10, ap);
318	if (!panicstr)
319		msgbuftrigger = 1;
320	consintr = savintr;		/* reenable interrupts */
321	return (retval);
322}
323
324/*
325 * Print a character on console or users terminal.  If destination is
326 * the console then the last bunch of characters are saved in msgbuf for
327 * inspection later.
328 */
329static void
330putchar(int c, void *arg)
331{
332	struct putchar_arg *ap = (struct putchar_arg*) arg;
333	int flags = ap->flags;
334	struct tty *tp = ap->tty;
335	if (panicstr)
336		constty = NULL;
337	if ((flags & TOCONS) && tp == NULL && constty) {
338		tp = constty;
339		flags |= TOTTY;
340	}
341	if ((flags & TOTTY) && tp && tputchar(c, tp) < 0 &&
342	    (flags & TOCONS) && tp == constty)
343		constty = NULL;
344	if ((flags & TOLOG))
345		msglogchar(c, ap->pri);
346	if ((flags & TOCONS) && constty == NULL && c != '\0')
347		(*v_putc)(c);
348}
349
350/*
351 * Scaled down version of sprintf(3).
352 */
353int
354sprintf(char *buf, const char *cfmt, ...)
355{
356	int retval;
357	va_list ap;
358
359	va_start(ap, cfmt);
360	retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
361	buf[retval] = '\0';
362	va_end(ap);
363	return (retval);
364}
365
366/*
367 * Scaled down version of vsprintf(3).
368 */
369int
370vsprintf(char *buf, const char *cfmt, va_list ap)
371{
372	int retval;
373
374	retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
375	buf[retval] = '\0';
376	return (retval);
377}
378
379/*
380 * Scaled down version of snprintf(3).
381 */
382int
383snprintf(char *str, size_t size, const char *format, ...)
384{
385	int retval;
386	va_list ap;
387
388	va_start(ap, format);
389	retval = vsnprintf(str, size, format, ap);
390	va_end(ap);
391	return(retval);
392}
393
394/*
395 * Scaled down version of vsnprintf(3).
396 */
397int
398vsnprintf(char *str, size_t size, const char *format, va_list ap)
399{
400	struct snprintf_arg info;
401	int retval;
402
403	info.str = str;
404	info.remain = size;
405	retval = kvprintf(format, snprintf_func, &info, 10, ap);
406	if (info.remain >= 1)
407		*info.str++ = '\0';
408	return (retval);
409}
410
411static void
412snprintf_func(int ch, void *arg)
413{
414	struct snprintf_arg *const info = arg;
415
416	if (info->remain >= 2) {
417		*info->str++ = ch;
418		info->remain--;
419	}
420}
421
422/*
423 * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
424 * order; return an optional length and a pointer to the last character
425 * written in the buffer (i.e., the first character of the string).
426 * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
427 */
428static char *
429ksprintn(nbuf, num, base, lenp)
430	char *nbuf;
431	uintmax_t num;
432	int base, *lenp;
433{
434	char *p;
435
436	p = nbuf;
437	*p = '\0';
438	do {
439		*++p = hex2ascii(num % base);
440	} while (num /= base);
441	if (lenp)
442		*lenp = p - nbuf;
443	return (p);
444}
445
446/*
447 * Scaled down version of printf(3).
448 *
449 * Two additional formats:
450 *
451 * The format %b is supported to decode error registers.
452 * Its usage is:
453 *
454 *	printf("reg=%b\n", regval, "<base><arg>*");
455 *
456 * where <base> is the output base expressed as a control character, e.g.
457 * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
458 * the first of which gives the bit number to be inspected (origin 1), and
459 * the next characters (up to a control character, i.e. a character <= 32),
460 * give the name of the register.  Thus:
461 *
462 *	kvprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
463 *
464 * would produce output:
465 *
466 *	reg=3<BITTWO,BITONE>
467 *
468 * XXX:  %D  -- Hexdump, takes pointer and separator string:
469 *		("%6D", ptr, ":")   -> XX:XX:XX:XX:XX:XX
470 *		("%*D", len, ptr, " " -> XX XX XX XX ...
471 */
472int
473kvprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, va_list ap)
474{
475#define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; }
476	char nbuf[MAXNBUF];
477	char *d;
478	const char *p, *percent, *q;
479	u_char *up;
480	int ch, n;
481	uintmax_t num;
482	int base, lflag, qflag, tmp, width, ladjust, sharpflag, neg, sign, dot;
483	int jflag;
484	int dwidth;
485	char padc;
486	int retval = 0;
487
488	num = 0;
489	if (!func)
490		d = (char *) arg;
491	else
492		d = NULL;
493
494	if (fmt == NULL)
495		fmt = "(fmt null)\n";
496
497	if (radix < 2 || radix > 36)
498		radix = 10;
499
500	for (;;) {
501		padc = ' ';
502		width = 0;
503		while ((ch = (u_char)*fmt++) != '%') {
504			if (ch == '\0')
505				return (retval);
506			PCHAR(ch);
507		}
508		percent = fmt - 1;
509		qflag = 0; lflag = 0; ladjust = 0; sharpflag = 0; neg = 0;
510		sign = 0; dot = 0; dwidth = 0;
511		jflag = 0;
512reswitch:	switch (ch = (u_char)*fmt++) {
513		case '.':
514			dot = 1;
515			goto reswitch;
516		case '#':
517			sharpflag = 1;
518			goto reswitch;
519		case '+':
520			sign = 1;
521			goto reswitch;
522		case '-':
523			ladjust = 1;
524			goto reswitch;
525		case '%':
526			PCHAR(ch);
527			break;
528		case '*':
529			if (!dot) {
530				width = va_arg(ap, int);
531				if (width < 0) {
532					ladjust = !ladjust;
533					width = -width;
534				}
535			} else {
536				dwidth = va_arg(ap, int);
537			}
538			goto reswitch;
539		case '0':
540			if (!dot) {
541				padc = '0';
542				goto reswitch;
543			}
544		case '1': case '2': case '3': case '4':
545		case '5': case '6': case '7': case '8': case '9':
546				for (n = 0;; ++fmt) {
547					n = n * 10 + ch - '0';
548					ch = *fmt;
549					if (ch < '0' || ch > '9')
550						break;
551				}
552			if (dot)
553				dwidth = n;
554			else
555				width = n;
556			goto reswitch;
557		case 'b':
558			num = va_arg(ap, int);
559			p = va_arg(ap, char *);
560			for (q = ksprintn(nbuf, num, *p++, NULL); *q;)
561				PCHAR(*q--);
562
563			if (num == 0)
564				break;
565
566			for (tmp = 0; *p;) {
567				n = *p++;
568				if (num & (1 << (n - 1))) {
569					PCHAR(tmp ? ',' : '<');
570					for (; (n = *p) > ' '; ++p)
571						PCHAR(n);
572					tmp = 1;
573				} else
574					for (; *p > ' '; ++p)
575						continue;
576			}
577			if (tmp)
578				PCHAR('>');
579			break;
580		case 'c':
581			PCHAR(va_arg(ap, int));
582			break;
583		case 'D':
584			up = va_arg(ap, u_char *);
585			p = va_arg(ap, char *);
586			if (!width)
587				width = 16;
588			while(width--) {
589				PCHAR(hex2ascii(*up >> 4));
590				PCHAR(hex2ascii(*up & 0x0f));
591				up++;
592				if (width)
593					for (q=p;*q;q++)
594						PCHAR(*q);
595			}
596			break;
597		case 'd':
598			base = 10;
599			sign = 1;
600			goto handle_sign;
601		case 'j':
602			jflag = 1;
603			goto reswitch;
604		case 'l':
605			if (lflag) {
606				lflag = 0;
607				qflag = 1;
608			} else
609				lflag = 1;
610			goto reswitch;
611		case 'n':
612			if (jflag)
613				*(va_arg(ap, intmax_t *)) = retval;
614			else if (qflag)
615				*(va_arg(ap, quad_t *)) = retval;
616			else if (lflag)
617				*(va_arg(ap, long *)) = retval;
618			else
619				*(va_arg(ap, int *)) = retval;
620			break;
621		case 'o':
622			base = 8;
623			goto handle_nosign;
624		case 'p':
625			base = 16;
626			sharpflag = (width == 0);
627			sign = 0;
628			num = (uintptr_t)va_arg(ap, void *);
629			goto number;
630		case 'q':
631			qflag = 1;
632			goto reswitch;
633		case 'r':
634			base = radix;
635			if (sign)
636				goto handle_sign;
637			goto handle_nosign;
638		case 's':
639			p = va_arg(ap, char *);
640			if (p == NULL)
641				p = "(null)";
642			if (!dot)
643				n = strlen (p);
644			else
645				for (n = 0; n < dwidth && p[n]; n++)
646					continue;
647
648			width -= n;
649
650			if (!ladjust && width > 0)
651				while (width--)
652					PCHAR(padc);
653			while (n--)
654				PCHAR(*p++);
655			if (ladjust && width > 0)
656				while (width--)
657					PCHAR(padc);
658			break;
659		case 'u':
660			base = 10;
661			goto handle_nosign;
662		case 'x':
663		case 'X':
664			base = 16;
665			goto handle_nosign;
666		case 'z':
667			base = 16;
668			if (sign)
669				goto handle_sign;
670handle_nosign:
671			sign = 0;
672			if (jflag)
673				num = va_arg(ap, uintmax_t);
674			else if (qflag)
675				num = va_arg(ap, u_quad_t);
676			else if (lflag)
677				num = va_arg(ap, u_long);
678			else
679				num = va_arg(ap, u_int);
680			goto number;
681handle_sign:
682			if (jflag)
683				num = va_arg(ap, intmax_t);
684			else if (qflag)
685				num = va_arg(ap, quad_t);
686			else if (lflag)
687				num = va_arg(ap, long);
688			else
689				num = va_arg(ap, int);
690number:
691			if (sign && (intmax_t)num < 0) {
692				neg = 1;
693				num = -(intmax_t)num;
694			}
695			p = ksprintn(nbuf, num, base, &tmp);
696			if (sharpflag && num != 0) {
697				if (base == 8)
698					tmp++;
699				else if (base == 16)
700					tmp += 2;
701			}
702			if (neg)
703				tmp++;
704
705			if (!ladjust && width && (width -= tmp) > 0)
706				while (width--)
707					PCHAR(padc);
708			if (neg)
709				PCHAR('-');
710			if (sharpflag && num != 0) {
711				if (base == 8) {
712					PCHAR('0');
713				} else if (base == 16) {
714					PCHAR('0');
715					PCHAR('x');
716				}
717			}
718
719			while (*p)
720				PCHAR(*p--);
721
722			if (ladjust && width && (width -= tmp) > 0)
723				while (width--)
724					PCHAR(padc);
725
726			break;
727		default:
728			while (percent < fmt)
729				PCHAR(*percent++);
730			break;
731		}
732	}
733#undef PCHAR
734}
735
736/*
737 * Put character in log buffer with a particular priority.
738 */
739static void
740msglogchar(int c, int pri)
741{
742	static int lastpri = -1;
743	static int dangling;
744	char nbuf[MAXNBUF];
745	char *p;
746
747	if (!msgbufmapped)
748		return;
749	if (c == '\0' || c == '\r')
750		return;
751	if (pri != -1 && pri != lastpri) {
752		if (dangling) {
753			msgaddchar('\n', NULL);
754			dangling = 0;
755		}
756		msgaddchar('<', NULL);
757		for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL); *p;)
758			msgaddchar(*p--, NULL);
759		msgaddchar('>', NULL);
760		lastpri = pri;
761	}
762	msgaddchar(c, NULL);
763	if (c == '\n') {
764		dangling = 0;
765		lastpri = -1;
766	} else {
767		dangling = 1;
768	}
769}
770
771/*
772 * Put char in log buffer
773 */
774static void
775msgaddchar(int c, void *dummy)
776{
777	struct msgbuf *mbp;
778
779	if (!msgbufmapped)
780		return;
781	mbp = msgbufp;
782	mbp->msg_ptr[mbp->msg_bufx++] = c;
783	if (mbp->msg_bufx >= mbp->msg_size)
784		mbp->msg_bufx = 0;
785	/* If the buffer is full, keep the most recent data. */
786	if (mbp->msg_bufr == mbp->msg_bufx) {
787		if (++mbp->msg_bufr >= mbp->msg_size)
788			mbp->msg_bufr = 0;
789	}
790}
791
792static void
793msgbufcopy(struct msgbuf *oldp)
794{
795	int pos;
796
797	pos = oldp->msg_bufr;
798	while (pos != oldp->msg_bufx) {
799		msglogchar(oldp->msg_ptr[pos], -1);
800		if (++pos >= oldp->msg_size)
801			pos = 0;
802	}
803}
804
805void
806msgbufinit(void *ptr, size_t size)
807{
808	char *cp;
809	static struct msgbuf *oldp = NULL;
810
811	size -= sizeof(*msgbufp);
812	cp = (char *)ptr;
813	msgbufp = (struct msgbuf *) (cp + size);
814	if (msgbufp->msg_magic != MSG_MAGIC || msgbufp->msg_size != size ||
815	    msgbufp->msg_bufx >= size || msgbufp->msg_bufr >= size) {
816		bzero(cp, size);
817		bzero(msgbufp, sizeof(*msgbufp));
818		msgbufp->msg_magic = MSG_MAGIC;
819		msgbufp->msg_size = (char *)msgbufp - cp;
820	}
821	msgbufp->msg_ptr = cp;
822	if (msgbufmapped && oldp != msgbufp)
823		msgbufcopy(oldp);
824	msgbufmapped = 1;
825	oldp = msgbufp;
826}
827
828SYSCTL_DECL(_security_bsd);
829
830static int unprivileged_read_msgbuf = 1;
831SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_read_msgbuf,
832    CTLFLAG_RW, &unprivileged_read_msgbuf, 0,
833    "Unprivileged processes may read the kernel message buffer");
834
835/* Sysctls for accessing/clearing the msgbuf */
836static int
837sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
838{
839	int error;
840
841	if (!unprivileged_read_msgbuf) {
842		error = suser(req->td);
843		if (error)
844			return (error);
845	}
846
847	/*
848	 * Unwind the buffer, so that it's linear (possibly starting with
849	 * some initial nulls).
850	 */
851	error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr + msgbufp->msg_bufx,
852	    msgbufp->msg_size - msgbufp->msg_bufx, req);
853	if (error)
854		return (error);
855	if (msgbufp->msg_bufx > 0) {
856		error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr,
857		    msgbufp->msg_bufx, req);
858	}
859	return (error);
860}
861
862SYSCTL_PROC(_kern, OID_AUTO, msgbuf, CTLTYPE_STRING | CTLFLAG_RD,
863    0, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
864
865static int msgbuf_clear;
866
867static int
868sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
869{
870	int error;
871	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
872	if (!error && req->newptr) {
873		/* Clear the buffer and reset write pointer */
874		bzero(msgbufp->msg_ptr, msgbufp->msg_size);
875		msgbufp->msg_bufr = msgbufp->msg_bufx = 0;
876		msgbuf_clear = 0;
877	}
878	return (error);
879}
880
881SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
882    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, &msgbuf_clear, 0,
883    sysctl_kern_msgbuf_clear, "I", "Clear kernel message buffer");
884
885#include "opt_ddb.h"
886#ifdef DDB
887#include <ddb/ddb.h>
888
889DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
890{
891	int i, j;
892
893	if (!msgbufmapped) {
894		db_printf("msgbuf not mapped yet\n");
895		return;
896	}
897	db_printf("msgbufp = %p\n", msgbufp);
898	db_printf("magic = %x, size = %d, r= %d, w = %d, ptr = %p\n",
899	    msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_bufr,
900	    msgbufp->msg_bufx, msgbufp->msg_ptr);
901	for (i = 0; i < msgbufp->msg_size; i++) {
902		j = (i + msgbufp->msg_bufr) % msgbufp->msg_size;
903		db_printf("%c", msgbufp->msg_ptr[j]);
904	}
905	db_printf("\n");
906}
907
908#endif /* DDB */
909