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