hexdump.c revision 110316
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 * 3. All advertising materials mentioning features or use of this software
19 *    must display the following acknowledgement:
20 *	This product includes software developed by the University of
21 *	California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 *    may be used to endorse or promote products derived from this software
24 *    without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * SUCH DAMAGE.
37 *
38 *	@(#)subr_prf.c	8.3 (Berkeley) 1/21/94
39 * $FreeBSD: head/sys/kern/subr_prf.c 110316 2003-02-04 10:00:34Z phk $
40 */
41
42#include "opt_ddb.h"
43
44#include <sys/param.h>
45#include <sys/systm.h>
46#include <sys/lock.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/proc.h>
53#include <sys/stddef.h>
54#include <sys/stdint.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
61#ifdef DDB
62#include <ddb/ddb.h>
63#endif
64
65/*
66 * Note that stdarg.h and the ANSI style va_start macro is used for both
67 * ANSI and traditional C compilers.
68 */
69#include <machine/stdarg.h>
70
71#define TOCONS	0x01
72#define TOTTY	0x02
73#define TOLOG	0x04
74
75/* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
76#define MAXNBUF	(sizeof(intmax_t) * NBBY + 1)
77
78struct putchar_arg {
79	int	flags;
80	int	pri;
81	struct	tty *tty;
82};
83
84struct snprintf_arg {
85	char	*str;
86	size_t	remain;
87};
88
89extern	int log_open;
90
91struct	tty *constty;			/* pointer to console "window" tty */
92
93static void (*v_putc)(int) = cnputc;	/* routine to putc on virtual console */
94static void  msglogchar(int c, int pri);
95static void  msgaddchar(int c, void *dummy);
96static void  putchar(int ch, void *arg);
97static char *ksprintn(char *nbuf, uintmax_t num, int base, int *len);
98static void  snprintf_func(int ch, void *arg);
99
100static int consintr = 1;		/* Ok to handle console interrupts? */
101static int msgbufmapped;		/* Set when safe to use msgbuf */
102int msgbuftrigger;
103
104static int      log_console_output = 1;
105TUNABLE_INT("kern.log_console_output", &log_console_output);
106SYSCTL_INT(_kern, OID_AUTO, log_console_output, CTLFLAG_RW,
107    &log_console_output, 0, "");
108
109/*
110 * Warn that a system table is full.
111 */
112void
113tablefull(const char *tab)
114{
115
116	log(LOG_ERR, "%s: table is full\n", tab);
117}
118
119/*
120 * Uprintf prints to the controlling terminal for the current process.
121 * It may block if the tty queue is overfull.  No message is printed if
122 * the queue does not clear in a reasonable time.
123 */
124int
125uprintf(const char *fmt, ...)
126{
127	struct thread *td = curthread;
128	struct proc *p = td->td_proc;
129	va_list ap;
130	struct putchar_arg pca;
131	int retval;
132
133	if (td == NULL || td == PCPU_GET(idlethread))
134		return (0);
135
136	p = td->td_proc;
137	PROC_LOCK(p);
138	if ((p->p_flag & P_CONTROLT) == 0) {
139		PROC_UNLOCK(p);
140		return (0);
141	}
142	SESS_LOCK(p->p_session);
143	pca.tty = p->p_session->s_ttyp;
144	SESS_UNLOCK(p->p_session);
145	PROC_UNLOCK(p);
146	if (pca.tty == NULL)
147		return (0);
148	pca.flags = TOTTY;
149	va_start(ap, fmt);
150	retval = kvprintf(fmt, putchar, &pca, 10, ap);
151	va_end(ap);
152
153	return (retval);
154}
155
156/*
157 * tprintf prints on the controlling terminal associated
158 * with the given session, possibly to the log as well.
159 */
160void
161tprintf(struct proc *p, int pri, const char *fmt, ...)
162{
163	struct tty *tp = NULL;
164	int flags = 0, shld = 0;
165	va_list ap;
166	struct putchar_arg pca;
167	int retval;
168
169	if (pri != -1)
170		flags |= TOLOG;
171	if (p != NULL) {
172		PROC_LOCK(p);
173		if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
174			SESS_LOCK(p->p_session);
175			SESSHOLD(p->p_session);
176			tp = p->p_session->s_ttyp;
177			SESS_UNLOCK(p->p_session);
178			PROC_UNLOCK(p);
179			shld++;
180			if (ttycheckoutq(tp, 0))
181				flags |= TOTTY;
182			else
183				tp = NULL;
184		} else
185			PROC_UNLOCK(p);
186	}
187	pca.pri = pri;
188	pca.tty = tp;
189	pca.flags = flags;
190	va_start(ap, fmt);
191	retval = kvprintf(fmt, putchar, &pca, 10, ap);
192	va_end(ap);
193	if (shld) {
194		PROC_LOCK(p);
195		SESS_LOCK(p->p_session);
196		SESSRELE(p->p_session);
197		SESS_UNLOCK(p->p_session);
198		PROC_UNLOCK(p);
199	}
200	msgbuftrigger = 1;
201}
202
203/*
204 * Ttyprintf displays a message on a tty; it should be used only by
205 * the tty driver, or anything that knows the underlying tty will not
206 * be revoke(2)'d away.  Other callers should use tprintf.
207 */
208int
209ttyprintf(struct tty *tp, const char *fmt, ...)
210{
211	va_list ap;
212	struct putchar_arg pca;
213	int retval;
214
215	va_start(ap, fmt);
216	pca.tty = tp;
217	pca.flags = TOTTY;
218	retval = kvprintf(fmt, putchar, &pca, 10, ap);
219	va_end(ap);
220	return (retval);
221}
222
223/*
224 * Log writes to the log buffer, and guarantees not to sleep (so can be
225 * called by interrupt routines).  If there is no process reading the
226 * log yet, it writes to the console also.
227 */
228void
229log(int level, const char *fmt, ...)
230{
231	va_list ap;
232	int retval;
233	struct putchar_arg pca;
234
235	pca.tty = NULL;
236	pca.pri = level;
237	pca.flags = log_open ? TOLOG : TOCONS;
238
239	va_start(ap, fmt);
240	retval = kvprintf(fmt, putchar, &pca, 10, ap);
241	va_end(ap);
242
243	msgbuftrigger = 1;
244}
245
246#define CONSCHUNK 128
247
248void
249log_console(struct uio *uio)
250{
251	int c, i, error, iovlen, nl;
252	struct uio muio;
253	struct iovec *miov = NULL;
254	char *consbuffer;
255	int pri;
256
257	if (!log_console_output)
258		return;
259
260	pri = LOG_INFO | LOG_CONSOLE;
261	muio = *uio;
262	iovlen = uio->uio_iovcnt * sizeof (struct iovec);
263	MALLOC(miov, struct iovec *, iovlen, M_TEMP, 0);
264	MALLOC(consbuffer, char *, CONSCHUNK, M_TEMP, 0);
265	bcopy(muio.uio_iov, miov, iovlen);
266	muio.uio_iov = miov;
267	uio = &muio;
268
269	nl = 0;
270	while (uio->uio_resid > 0) {
271		c = imin(uio->uio_resid, CONSCHUNK);
272		error = uiomove(consbuffer, c, uio);
273		if (error != 0)
274			break;
275		for (i = 0; i < c; i++) {
276			msglogchar(consbuffer[i], pri);
277			if (consbuffer[i] == '\n')
278				nl = 1;
279			else
280				nl = 0;
281		}
282	}
283	if (!nl)
284		msglogchar('\n', pri);
285	msgbuftrigger = 1;
286	FREE(miov, M_TEMP);
287	FREE(consbuffer, M_TEMP);
288	return;
289}
290
291int
292printf(const char *fmt, ...)
293{
294	va_list ap;
295	int savintr;
296	struct putchar_arg pca;
297	int retval;
298
299	savintr = consintr;		/* disable interrupts */
300	consintr = 0;
301	va_start(ap, fmt);
302	pca.tty = NULL;
303	pca.flags = TOCONS | TOLOG;
304	pca.pri = -1;
305	retval = kvprintf(fmt, putchar, &pca, 10, ap);
306	va_end(ap);
307	if (!panicstr)
308		msgbuftrigger = 1;
309	consintr = savintr;		/* reenable interrupts */
310	return (retval);
311}
312
313int
314vprintf(const char *fmt, va_list ap)
315{
316	int savintr;
317	struct putchar_arg pca;
318	int retval;
319
320	savintr = consintr;		/* disable interrupts */
321	consintr = 0;
322	pca.tty = NULL;
323	pca.flags = TOCONS | TOLOG;
324	pca.pri = -1;
325	retval = kvprintf(fmt, putchar, &pca, 10, ap);
326	if (!panicstr)
327		msgbuftrigger = 1;
328	consintr = savintr;		/* reenable interrupts */
329	return (retval);
330}
331
332/*
333 * Print a character on console or users terminal.  If destination is
334 * the console then the last bunch of characters are saved in msgbuf for
335 * inspection later.
336 */
337static void
338putchar(int c, void *arg)
339{
340	struct putchar_arg *ap = (struct putchar_arg*) arg;
341	int flags = ap->flags;
342	struct tty *tp = ap->tty;
343	if (panicstr)
344		constty = NULL;
345	if ((flags & TOCONS) && tp == NULL && constty) {
346		tp = constty;
347		flags |= TOTTY;
348	}
349	if ((flags & TOTTY) && tp && tputchar(c, tp) < 0 &&
350	    (flags & TOCONS) && tp == constty)
351		constty = NULL;
352	if ((flags & TOLOG))
353		msglogchar(c, ap->pri);
354	if ((flags & TOCONS) && constty == NULL && c != '\0')
355		(*v_putc)(c);
356}
357
358/*
359 * Scaled down version of sprintf(3).
360 */
361int
362sprintf(char *buf, const char *cfmt, ...)
363{
364	int retval;
365	va_list ap;
366
367	va_start(ap, cfmt);
368	retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
369	buf[retval] = '\0';
370	va_end(ap);
371	return (retval);
372}
373
374/*
375 * Scaled down version of vsprintf(3).
376 */
377int
378vsprintf(char *buf, const char *cfmt, va_list ap)
379{
380	int retval;
381
382	retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
383	buf[retval] = '\0';
384	return (retval);
385}
386
387/*
388 * Scaled down version of snprintf(3).
389 */
390int
391snprintf(char *str, size_t size, const char *format, ...)
392{
393	int retval;
394	va_list ap;
395
396	va_start(ap, format);
397	retval = vsnprintf(str, size, format, ap);
398	va_end(ap);
399	return(retval);
400}
401
402/*
403 * Scaled down version of vsnprintf(3).
404 */
405int
406vsnprintf(char *str, size_t size, const char *format, va_list ap)
407{
408	struct snprintf_arg info;
409	int retval;
410
411	info.str = str;
412	info.remain = size;
413	retval = kvprintf(format, snprintf_func, &info, 10, ap);
414	if (info.remain >= 1)
415		*info.str++ = '\0';
416	return (retval);
417}
418
419/*
420 * Kernel version which takes radix argument vsnprintf(3).
421 */
422int
423vsnrprintf(char *str, size_t size, int radix, const char *format, va_list ap)
424{
425	struct snprintf_arg info;
426	int retval;
427
428	info.str = str;
429	info.remain = size;
430	retval = kvprintf(format, snprintf_func, &info, radix, ap);
431	if (info.remain >= 1)
432		*info.str++ = '\0';
433	return (retval);
434}
435
436static void
437snprintf_func(int ch, void *arg)
438{
439	struct snprintf_arg *const info = arg;
440
441	if (info->remain >= 2) {
442		*info->str++ = ch;
443		info->remain--;
444	}
445}
446
447/*
448 * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
449 * order; return an optional length and a pointer to the last character
450 * written in the buffer (i.e., the first character of the string).
451 * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
452 */
453static char *
454ksprintn(char *nbuf, uintmax_t num, int base, int *lenp)
455{
456	char *p;
457
458	p = nbuf;
459	*p = '\0';
460	do {
461		*++p = hex2ascii(num % base);
462	} while (num /= base);
463	if (lenp)
464		*lenp = p - nbuf;
465	return (p);
466}
467
468/*
469 * Scaled down version of printf(3).
470 *
471 * Two additional formats:
472 *
473 * The format %b is supported to decode error registers.
474 * Its usage is:
475 *
476 *	printf("reg=%b\n", regval, "<base><arg>*");
477 *
478 * where <base> is the output base expressed as a control character, e.g.
479 * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
480 * the first of which gives the bit number to be inspected (origin 1), and
481 * the next characters (up to a control character, i.e. a character <= 32),
482 * give the name of the register.  Thus:
483 *
484 *	kvprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
485 *
486 * would produce output:
487 *
488 *	reg=3<BITTWO,BITONE>
489 *
490 * XXX:  %D  -- Hexdump, takes pointer and separator string:
491 *		("%6D", ptr, ":")   -> XX:XX:XX:XX:XX:XX
492 *		("%*D", len, ptr, " " -> XX XX XX XX ...
493 */
494int
495kvprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, va_list ap)
496{
497#define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; }
498	char nbuf[MAXNBUF];
499	char *d;
500	const char *p, *percent, *q;
501	u_char *up;
502	int ch, n;
503	uintmax_t num;
504	int base, lflag, qflag, tmp, width, ladjust, sharpflag, neg, sign, dot;
505	int jflag, tflag, zflag;
506	int dwidth;
507	char padc;
508	int retval = 0;
509
510	num = 0;
511	if (!func)
512		d = (char *) arg;
513	else
514		d = NULL;
515
516	if (fmt == NULL)
517		fmt = "(fmt null)\n";
518
519	if (radix < 2 || radix > 36)
520		radix = 10;
521
522	for (;;) {
523		padc = ' ';
524		width = 0;
525		while ((ch = (u_char)*fmt++) != '%') {
526			if (ch == '\0')
527				return (retval);
528			PCHAR(ch);
529		}
530		percent = fmt - 1;
531		qflag = 0; lflag = 0; ladjust = 0; sharpflag = 0; neg = 0;
532		sign = 0; dot = 0; dwidth = 0;
533		jflag = 0; tflag = 0; zflag = 0;
534reswitch:	switch (ch = (u_char)*fmt++) {
535		case '.':
536			dot = 1;
537			goto reswitch;
538		case '#':
539			sharpflag = 1;
540			goto reswitch;
541		case '+':
542			sign = 1;
543			goto reswitch;
544		case '-':
545			ladjust = 1;
546			goto reswitch;
547		case '%':
548			PCHAR(ch);
549			break;
550		case '*':
551			if (!dot) {
552				width = va_arg(ap, int);
553				if (width < 0) {
554					ladjust = !ladjust;
555					width = -width;
556				}
557			} else {
558				dwidth = va_arg(ap, int);
559			}
560			goto reswitch;
561		case '0':
562			if (!dot) {
563				padc = '0';
564				goto reswitch;
565			}
566		case '1': case '2': case '3': case '4':
567		case '5': case '6': case '7': case '8': case '9':
568				for (n = 0;; ++fmt) {
569					n = n * 10 + ch - '0';
570					ch = *fmt;
571					if (ch < '0' || ch > '9')
572						break;
573				}
574			if (dot)
575				dwidth = n;
576			else
577				width = n;
578			goto reswitch;
579		case 'b':
580			num = (u_int)va_arg(ap, int);
581			p = va_arg(ap, char *);
582			for (q = ksprintn(nbuf, num, *p++, NULL); *q;)
583				PCHAR(*q--);
584
585			if (num == 0)
586				break;
587
588			for (tmp = 0; *p;) {
589				n = *p++;
590				if (num & (1 << (n - 1))) {
591					PCHAR(tmp ? ',' : '<');
592					for (; (n = *p) > ' '; ++p)
593						PCHAR(n);
594					tmp = 1;
595				} else
596					for (; *p > ' '; ++p)
597						continue;
598			}
599			if (tmp)
600				PCHAR('>');
601			break;
602		case 'c':
603			PCHAR(va_arg(ap, int));
604			break;
605		case 'D':
606			up = va_arg(ap, u_char *);
607			p = va_arg(ap, char *);
608			if (!width)
609				width = 16;
610			while(width--) {
611				PCHAR(hex2ascii(*up >> 4));
612				PCHAR(hex2ascii(*up & 0x0f));
613				up++;
614				if (width)
615					for (q=p;*q;q++)
616						PCHAR(*q);
617			}
618			break;
619		case 'd':
620		case 'i':
621			base = 10;
622			sign = 1;
623			goto handle_sign;
624		case 'j':
625			jflag = 1;
626			goto reswitch;
627		case 'l':
628			if (lflag) {
629				lflag = 0;
630				qflag = 1;
631			} else
632				lflag = 1;
633			goto reswitch;
634		case 'n':
635			if (jflag)
636				*(va_arg(ap, intmax_t *)) = retval;
637			else if (qflag)
638				*(va_arg(ap, quad_t *)) = retval;
639			else if (lflag)
640				*(va_arg(ap, long *)) = retval;
641			else if (zflag)
642				*(va_arg(ap, size_t *)) = retval;
643			else
644				*(va_arg(ap, int *)) = retval;
645			break;
646		case 'o':
647			base = 8;
648			goto handle_nosign;
649		case 'p':
650			base = 16;
651			sharpflag = (width == 0);
652			sign = 0;
653			num = (uintptr_t)va_arg(ap, void *);
654			goto number;
655		case 'q':
656			qflag = 1;
657			goto reswitch;
658		case 'r':
659			base = radix;
660			if (sign)
661				goto handle_sign;
662			goto handle_nosign;
663		case 's':
664			p = va_arg(ap, char *);
665			if (p == NULL)
666				p = "(null)";
667			if (!dot)
668				n = strlen (p);
669			else
670				for (n = 0; n < dwidth && p[n]; n++)
671					continue;
672
673			width -= n;
674
675			if (!ladjust && width > 0)
676				while (width--)
677					PCHAR(padc);
678			while (n--)
679				PCHAR(*p++);
680			if (ladjust && width > 0)
681				while (width--)
682					PCHAR(padc);
683			break;
684		case 't':
685			tflag = 1;
686			goto reswitch;
687			break;
688		case 'u':
689			base = 10;
690			goto handle_nosign;
691		case 'x':
692		case 'X':
693			base = 16;
694			goto handle_nosign;
695		case 'y':
696			base = 16;
697			sign = 1;
698			goto handle_sign;
699		case 'z':
700			zflag = 1;
701			goto reswitch;
702handle_nosign:
703			sign = 0;
704			if (jflag)
705				num = va_arg(ap, uintmax_t);
706			else if (qflag)
707				num = va_arg(ap, u_quad_t);
708			else if (tflag)
709				num = va_arg(ap, ptrdiff_t);
710			else if (lflag)
711				num = va_arg(ap, u_long);
712			else if (zflag)
713				num = va_arg(ap, size_t);
714			else
715				num = va_arg(ap, u_int);
716			goto number;
717handle_sign:
718			if (jflag)
719				num = va_arg(ap, intmax_t);
720			else if (qflag)
721				num = va_arg(ap, quad_t);
722			else if (tflag)
723				num = va_arg(ap, ptrdiff_t);
724			else if (lflag)
725				num = va_arg(ap, long);
726			else if (zflag)
727				num = va_arg(ap, size_t);
728			else
729				num = va_arg(ap, int);
730number:
731			if (sign && (intmax_t)num < 0) {
732				neg = 1;
733				num = -(intmax_t)num;
734			}
735			p = ksprintn(nbuf, num, base, &tmp);
736			if (sharpflag && num != 0) {
737				if (base == 8)
738					tmp++;
739				else if (base == 16)
740					tmp += 2;
741			}
742			if (neg)
743				tmp++;
744
745			if (!ladjust && width && (width -= tmp) > 0)
746				while (width--)
747					PCHAR(padc);
748			if (neg)
749				PCHAR('-');
750			if (sharpflag && num != 0) {
751				if (base == 8) {
752					PCHAR('0');
753				} else if (base == 16) {
754					PCHAR('0');
755					PCHAR('x');
756				}
757			}
758
759			while (*p)
760				PCHAR(*p--);
761
762			if (ladjust && width && (width -= tmp) > 0)
763				while (width--)
764					PCHAR(padc);
765
766			break;
767		default:
768			while (percent < fmt)
769				PCHAR(*percent++);
770			break;
771		}
772	}
773#undef PCHAR
774}
775
776/*
777 * Put character in log buffer with a particular priority.
778 */
779static void
780msglogchar(int c, int pri)
781{
782	static int lastpri = -1;
783	static int dangling;
784	char nbuf[MAXNBUF];
785	char *p;
786
787	if (!msgbufmapped)
788		return;
789	if (c == '\0' || c == '\r')
790		return;
791	if (pri != -1 && pri != lastpri) {
792		if (dangling) {
793			msgaddchar('\n', NULL);
794			dangling = 0;
795		}
796		msgaddchar('<', NULL);
797		for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL); *p;)
798			msgaddchar(*p--, NULL);
799		msgaddchar('>', NULL);
800		lastpri = pri;
801	}
802	msgaddchar(c, NULL);
803	if (c == '\n') {
804		dangling = 0;
805		lastpri = -1;
806	} else {
807		dangling = 1;
808	}
809}
810
811/*
812 * Put char in log buffer
813 */
814static void
815msgaddchar(int c, void *dummy)
816{
817	struct msgbuf *mbp;
818
819	if (!msgbufmapped)
820		return;
821	mbp = msgbufp;
822	mbp->msg_ptr[mbp->msg_bufx++] = c;
823	if (mbp->msg_bufx >= mbp->msg_size)
824		mbp->msg_bufx = 0;
825	/* If the buffer is full, keep the most recent data. */
826	if (mbp->msg_bufr == mbp->msg_bufx) {
827		if (++mbp->msg_bufr >= mbp->msg_size)
828			mbp->msg_bufr = 0;
829	}
830}
831
832static void
833msgbufcopy(struct msgbuf *oldp)
834{
835	int pos;
836
837	pos = oldp->msg_bufr;
838	while (pos != oldp->msg_bufx) {
839		msglogchar(oldp->msg_ptr[pos], -1);
840		if (++pos >= oldp->msg_size)
841			pos = 0;
842	}
843}
844
845void
846msgbufinit(void *ptr, int size)
847{
848	char *cp;
849	static struct msgbuf *oldp = NULL;
850
851	size -= sizeof(*msgbufp);
852	cp = (char *)ptr;
853	msgbufp = (struct msgbuf *) (cp + size);
854	if (msgbufp->msg_magic != MSG_MAGIC || msgbufp->msg_size != size ||
855	    msgbufp->msg_bufx >= size || msgbufp->msg_bufx < 0 ||
856	    msgbufp->msg_bufr >= size || msgbufp->msg_bufr < 0) {
857		bzero(cp, size);
858		bzero(msgbufp, sizeof(*msgbufp));
859		msgbufp->msg_magic = MSG_MAGIC;
860		msgbufp->msg_size = (char *)msgbufp - cp;
861	}
862	msgbufp->msg_ptr = cp;
863	if (msgbufmapped && oldp != msgbufp)
864		msgbufcopy(oldp);
865	msgbufmapped = 1;
866	oldp = msgbufp;
867}
868
869SYSCTL_DECL(_security_bsd);
870
871static int unprivileged_read_msgbuf = 1;
872SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_read_msgbuf,
873    CTLFLAG_RW, &unprivileged_read_msgbuf, 0,
874    "Unprivileged processes may read the kernel message buffer");
875
876/* Sysctls for accessing/clearing the msgbuf */
877static int
878sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
879{
880	int error;
881
882	if (!unprivileged_read_msgbuf) {
883		error = suser(req->td);
884		if (error)
885			return (error);
886	}
887
888	/*
889	 * Unwind the buffer, so that it's linear (possibly starting with
890	 * some initial nulls).
891	 */
892	error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr + msgbufp->msg_bufx,
893	    msgbufp->msg_size - msgbufp->msg_bufx, req);
894	if (error)
895		return (error);
896	if (msgbufp->msg_bufx > 0) {
897		error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr,
898		    msgbufp->msg_bufx, req);
899	}
900	return (error);
901}
902
903SYSCTL_PROC(_kern, OID_AUTO, msgbuf, CTLTYPE_STRING | CTLFLAG_RD,
904    0, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
905
906static int msgbuf_clear;
907
908static int
909sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
910{
911	int error;
912	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
913	if (!error && req->newptr) {
914		/* Clear the buffer and reset write pointer */
915		bzero(msgbufp->msg_ptr, msgbufp->msg_size);
916		msgbufp->msg_bufr = msgbufp->msg_bufx = 0;
917		msgbuf_clear = 0;
918	}
919	return (error);
920}
921
922SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
923    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, &msgbuf_clear, 0,
924    sysctl_kern_msgbuf_clear, "I", "Clear kernel message buffer");
925
926#ifdef DDB
927
928DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
929{
930	int i, j;
931
932	if (!msgbufmapped) {
933		db_printf("msgbuf not mapped yet\n");
934		return;
935	}
936	db_printf("msgbufp = %p\n", msgbufp);
937	db_printf("magic = %x, size = %d, r= %d, w = %d, ptr = %p\n",
938	    msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_bufr,
939	    msgbufp->msg_bufx, msgbufp->msg_ptr);
940	for (i = 0; i < msgbufp->msg_size; i++) {
941		j = (i + msgbufp->msg_bufr) % msgbufp->msg_size;
942		db_printf("%c", msgbufp->msg_ptr[j]);
943	}
944	db_printf("\n");
945}
946
947#endif /* DDB */
948