hexdump.c revision 127911
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: head/sys/kern/subr_prf.c 127911 2004-04-05 21:03:37Z imp $");
39
40#include "opt_ddb.h"
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/stddef.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#ifdef DDB
59#include <ddb/ddb.h>
60#endif
61
62/*
63 * Note that stdarg.h and the ANSI style va_start macro is used for both
64 * ANSI and traditional C compilers.
65 */
66#include <machine/stdarg.h>
67
68#define TOCONS	0x01
69#define TOTTY	0x02
70#define TOLOG	0x04
71
72/* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
73#define MAXNBUF	(sizeof(intmax_t) * NBBY + 1)
74
75struct putchar_arg {
76	int	flags;
77	int	pri;
78	struct	tty *tty;
79};
80
81struct snprintf_arg {
82	char	*str;
83	size_t	remain;
84};
85
86extern	int log_open;
87
88static void  msglogchar(int c, int pri);
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;
158	va_list ap;
159	struct putchar_arg pca;
160	struct session *sess = NULL;
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 = p->p_session;
168			SESS_LOCK(sess);
169			PROC_UNLOCK(p);
170			SESSHOLD(sess);
171			tp = sess->s_ttyp;
172			SESS_UNLOCK(sess);
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	kvprintf(fmt, putchar, &pca, 10, ap);
185	va_end(ap);
186	if (sess != NULL) {
187		SESS_LOCK(sess);
188		SESSRELE(sess);
189		SESS_UNLOCK(sess);
190	}
191	msgbuftrigger = 1;
192}
193
194/*
195 * Ttyprintf displays a message on a tty; it should be used only by
196 * the tty driver, or anything that knows the underlying tty will not
197 * be revoke(2)'d away.  Other callers should use tprintf.
198 */
199int
200ttyprintf(struct tty *tp, const char *fmt, ...)
201{
202	va_list ap;
203	struct putchar_arg pca;
204	int retval;
205
206	va_start(ap, fmt);
207	pca.tty = tp;
208	pca.flags = TOTTY;
209	retval = kvprintf(fmt, putchar, &pca, 10, ap);
210	va_end(ap);
211	return (retval);
212}
213
214/*
215 * Log writes to the log buffer, and guarantees not to sleep (so can be
216 * called by interrupt routines).  If there is no process reading the
217 * log yet, it writes to the console also.
218 */
219void
220log(int level, const char *fmt, ...)
221{
222	va_list ap;
223	struct putchar_arg pca;
224
225	pca.tty = NULL;
226	pca.pri = level;
227	pca.flags = log_open ? TOLOG : TOCONS;
228
229	va_start(ap, fmt);
230	kvprintf(fmt, putchar, &pca, 10, ap);
231	va_end(ap);
232
233	msgbuftrigger = 1;
234}
235
236#define CONSCHUNK 128
237
238void
239log_console(struct uio *uio)
240{
241	int c, i, error, iovlen, nl;
242	struct uio muio;
243	struct iovec *miov = NULL;
244	char *consbuffer;
245	int pri;
246
247	if (!log_console_output)
248		return;
249
250	pri = LOG_INFO | LOG_CONSOLE;
251	muio = *uio;
252	iovlen = uio->uio_iovcnt * sizeof (struct iovec);
253	MALLOC(miov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
254	MALLOC(consbuffer, char *, CONSCHUNK, M_TEMP, M_WAITOK);
255	bcopy(muio.uio_iov, miov, iovlen);
256	muio.uio_iov = miov;
257	uio = &muio;
258
259	nl = 0;
260	while (uio->uio_resid > 0) {
261		c = imin(uio->uio_resid, CONSCHUNK);
262		error = uiomove(consbuffer, c, uio);
263		if (error != 0)
264			break;
265		for (i = 0; i < c; i++) {
266			msglogchar(consbuffer[i], pri);
267			if (consbuffer[i] == '\n')
268				nl = 1;
269			else
270				nl = 0;
271		}
272	}
273	if (!nl)
274		msglogchar('\n', pri);
275	msgbuftrigger = 1;
276	FREE(miov, M_TEMP);
277	FREE(consbuffer, M_TEMP);
278	return;
279}
280
281int
282printf(const char *fmt, ...)
283{
284	va_list ap;
285	int savintr;
286	struct putchar_arg pca;
287	int retval;
288
289	savintr = consintr;		/* disable interrupts */
290	consintr = 0;
291	va_start(ap, fmt);
292	pca.tty = NULL;
293	pca.flags = TOCONS | TOLOG;
294	pca.pri = -1;
295	retval = kvprintf(fmt, putchar, &pca, 10, ap);
296	va_end(ap);
297	if (!panicstr)
298		msgbuftrigger = 1;
299	consintr = savintr;		/* reenable interrupts */
300	return (retval);
301}
302
303int
304vprintf(const char *fmt, va_list ap)
305{
306	int savintr;
307	struct putchar_arg pca;
308	int retval;
309
310	savintr = consintr;		/* disable interrupts */
311	consintr = 0;
312	pca.tty = NULL;
313	pca.flags = TOCONS | TOLOG;
314	pca.pri = -1;
315	retval = kvprintf(fmt, putchar, &pca, 10, ap);
316	if (!panicstr)
317		msgbuftrigger = 1;
318	consintr = savintr;		/* reenable interrupts */
319	return (retval);
320}
321
322/*
323 * Print a character on console or users terminal.  If destination is
324 * the console then the last bunch of characters are saved in msgbuf for
325 * inspection later.
326 */
327static void
328putchar(int c, void *arg)
329{
330	struct putchar_arg *ap = (struct putchar_arg*) arg;
331	struct tty *tp = ap->tty;
332	int consdirect, flags = ap->flags;
333
334	consdirect = ((flags & TOCONS) && constty == NULL);
335	/* Don't use the tty code after a panic or while in ddb. */
336	if (panicstr)
337		consdirect = 1;
338#ifdef DDB
339	if (db_active)
340		consdirect = 1;
341#endif
342	if (consdirect) {
343		if (c != '\0')
344			cnputc(c);
345	} else {
346		if ((flags & TOTTY) && tp != NULL)
347			tputchar(c, tp);
348		if ((flags & TOCONS) && constty != NULL)
349			msgbuf_addchar(&consmsgbuf, c);
350	}
351	if ((flags & TOLOG))
352		msglogchar(c, ap->pri);
353}
354
355/*
356 * Scaled down version of sprintf(3).
357 */
358int
359sprintf(char *buf, const char *cfmt, ...)
360{
361	int retval;
362	va_list ap;
363
364	va_start(ap, cfmt);
365	retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
366	buf[retval] = '\0';
367	va_end(ap);
368	return (retval);
369}
370
371/*
372 * Scaled down version of vsprintf(3).
373 */
374int
375vsprintf(char *buf, const char *cfmt, va_list ap)
376{
377	int retval;
378
379	retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
380	buf[retval] = '\0';
381	return (retval);
382}
383
384/*
385 * Scaled down version of snprintf(3).
386 */
387int
388snprintf(char *str, size_t size, const char *format, ...)
389{
390	int retval;
391	va_list ap;
392
393	va_start(ap, format);
394	retval = vsnprintf(str, size, format, ap);
395	va_end(ap);
396	return(retval);
397}
398
399/*
400 * Scaled down version of vsnprintf(3).
401 */
402int
403vsnprintf(char *str, size_t size, const char *format, va_list ap)
404{
405	struct snprintf_arg info;
406	int retval;
407
408	info.str = str;
409	info.remain = size;
410	retval = kvprintf(format, snprintf_func, &info, 10, ap);
411	if (info.remain >= 1)
412		*info.str++ = '\0';
413	return (retval);
414}
415
416/*
417 * Kernel version which takes radix argument vsnprintf(3).
418 */
419int
420vsnrprintf(char *str, size_t size, int radix, const char *format, va_list ap)
421{
422	struct snprintf_arg info;
423	int retval;
424
425	info.str = str;
426	info.remain = size;
427	retval = kvprintf(format, snprintf_func, &info, radix, ap);
428	if (info.remain >= 1)
429		*info.str++ = '\0';
430	return (retval);
431}
432
433static void
434snprintf_func(int ch, void *arg)
435{
436	struct snprintf_arg *const info = arg;
437
438	if (info->remain >= 2) {
439		*info->str++ = ch;
440		info->remain--;
441	}
442}
443
444/*
445 * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
446 * order; return an optional length and a pointer to the last character
447 * written in the buffer (i.e., the first character of the string).
448 * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
449 */
450static char *
451ksprintn(char *nbuf, uintmax_t num, int base, int *lenp)
452{
453	char *p;
454
455	p = nbuf;
456	*p = '\0';
457	do {
458		*++p = hex2ascii(num % base);
459	} while (num /= base);
460	if (lenp)
461		*lenp = p - nbuf;
462	return (p);
463}
464
465/*
466 * Scaled down version of printf(3).
467 *
468 * Two additional formats:
469 *
470 * The format %b is supported to decode error registers.
471 * Its usage is:
472 *
473 *	printf("reg=%b\n", regval, "<base><arg>*");
474 *
475 * where <base> is the output base expressed as a control character, e.g.
476 * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
477 * the first of which gives the bit number to be inspected (origin 1), and
478 * the next characters (up to a control character, i.e. a character <= 32),
479 * give the name of the register.  Thus:
480 *
481 *	kvprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
482 *
483 * would produce output:
484 *
485 *	reg=3<BITTWO,BITONE>
486 *
487 * XXX:  %D  -- Hexdump, takes pointer and separator string:
488 *		("%6D", ptr, ":")   -> XX:XX:XX:XX:XX:XX
489 *		("%*D", len, ptr, " " -> XX XX XX XX ...
490 */
491int
492kvprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, va_list ap)
493{
494#define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; }
495	char nbuf[MAXNBUF];
496	char *d;
497	const char *p, *percent, *q;
498	u_char *up;
499	int ch, n;
500	uintmax_t num;
501	int base, lflag, qflag, tmp, width, ladjust, sharpflag, neg, sign, dot;
502	int cflag, hflag, jflag, tflag, zflag;
503	int dwidth;
504	char padc;
505	int retval = 0;
506
507	num = 0;
508	if (!func)
509		d = (char *) arg;
510	else
511		d = NULL;
512
513	if (fmt == NULL)
514		fmt = "(fmt null)\n";
515
516	if (radix < 2 || radix > 36)
517		radix = 10;
518
519	for (;;) {
520		padc = ' ';
521		width = 0;
522		while ((ch = (u_char)*fmt++) != '%') {
523			if (ch == '\0')
524				return (retval);
525			PCHAR(ch);
526		}
527		percent = fmt - 1;
528		qflag = 0; lflag = 0; ladjust = 0; sharpflag = 0; neg = 0;
529		sign = 0; dot = 0; dwidth = 0;
530		cflag = 0; hflag = 0; jflag = 0; tflag = 0; zflag = 0;
531reswitch:	switch (ch = (u_char)*fmt++) {
532		case '.':
533			dot = 1;
534			goto reswitch;
535		case '#':
536			sharpflag = 1;
537			goto reswitch;
538		case '+':
539			sign = 1;
540			goto reswitch;
541		case '-':
542			ladjust = 1;
543			goto reswitch;
544		case '%':
545			PCHAR(ch);
546			break;
547		case '*':
548			if (!dot) {
549				width = va_arg(ap, int);
550				if (width < 0) {
551					ladjust = !ladjust;
552					width = -width;
553				}
554			} else {
555				dwidth = va_arg(ap, int);
556			}
557			goto reswitch;
558		case '0':
559			if (!dot) {
560				padc = '0';
561				goto reswitch;
562			}
563		case '1': case '2': case '3': case '4':
564		case '5': case '6': case '7': case '8': case '9':
565				for (n = 0;; ++fmt) {
566					n = n * 10 + ch - '0';
567					ch = *fmt;
568					if (ch < '0' || ch > '9')
569						break;
570				}
571			if (dot)
572				dwidth = n;
573			else
574				width = n;
575			goto reswitch;
576		case 'b':
577			num = (u_int)va_arg(ap, int);
578			p = va_arg(ap, char *);
579			for (q = ksprintn(nbuf, num, *p++, NULL); *q;)
580				PCHAR(*q--);
581
582			if (num == 0)
583				break;
584
585			for (tmp = 0; *p;) {
586				n = *p++;
587				if (num & (1 << (n - 1))) {
588					PCHAR(tmp ? ',' : '<');
589					for (; (n = *p) > ' '; ++p)
590						PCHAR(n);
591					tmp = 1;
592				} else
593					for (; *p > ' '; ++p)
594						continue;
595			}
596			if (tmp)
597				PCHAR('>');
598			break;
599		case 'c':
600			PCHAR(va_arg(ap, int));
601			break;
602		case 'D':
603			up = va_arg(ap, u_char *);
604			p = va_arg(ap, char *);
605			if (!width)
606				width = 16;
607			while(width--) {
608				PCHAR(hex2ascii(*up >> 4));
609				PCHAR(hex2ascii(*up & 0x0f));
610				up++;
611				if (width)
612					for (q=p;*q;q++)
613						PCHAR(*q);
614			}
615			break;
616		case 'd':
617		case 'i':
618			base = 10;
619			sign = 1;
620			goto handle_sign;
621		case 'h':
622			if (hflag) {
623				hflag = 0;
624				cflag = 1;
625			} else
626				hflag = 1;
627			goto reswitch;
628		case 'j':
629			jflag = 1;
630			goto reswitch;
631		case 'l':
632			if (lflag) {
633				lflag = 0;
634				qflag = 1;
635			} else
636				lflag = 1;
637			goto reswitch;
638		case 'n':
639			if (jflag)
640				*(va_arg(ap, intmax_t *)) = retval;
641			else if (qflag)
642				*(va_arg(ap, quad_t *)) = retval;
643			else if (lflag)
644				*(va_arg(ap, long *)) = retval;
645			else if (zflag)
646				*(va_arg(ap, size_t *)) = retval;
647			else if (hflag)
648				*(va_arg(ap, short *)) = retval;
649			else if (cflag)
650				*(va_arg(ap, char *)) = retval;
651			else
652				*(va_arg(ap, int *)) = retval;
653			break;
654		case 'o':
655			base = 8;
656			goto handle_nosign;
657		case 'p':
658			base = 16;
659			sharpflag = (width == 0);
660			sign = 0;
661			num = (uintptr_t)va_arg(ap, void *);
662			goto number;
663		case 'q':
664			qflag = 1;
665			goto reswitch;
666		case 'r':
667			base = radix;
668			if (sign)
669				goto handle_sign;
670			goto handle_nosign;
671		case 's':
672			p = va_arg(ap, char *);
673			if (p == NULL)
674				p = "(null)";
675			if (!dot)
676				n = strlen (p);
677			else
678				for (n = 0; n < dwidth && p[n]; n++)
679					continue;
680
681			width -= n;
682
683			if (!ladjust && width > 0)
684				while (width--)
685					PCHAR(padc);
686			while (n--)
687				PCHAR(*p++);
688			if (ladjust && width > 0)
689				while (width--)
690					PCHAR(padc);
691			break;
692		case 't':
693			tflag = 1;
694			goto reswitch;
695		case 'u':
696			base = 10;
697			goto handle_nosign;
698		case 'x':
699		case 'X':
700			base = 16;
701			goto handle_nosign;
702		case 'y':
703			base = 16;
704			sign = 1;
705			goto handle_sign;
706		case 'z':
707			zflag = 1;
708			goto reswitch;
709handle_nosign:
710			sign = 0;
711			if (jflag)
712				num = va_arg(ap, uintmax_t);
713			else if (qflag)
714				num = va_arg(ap, u_quad_t);
715			else if (tflag)
716				num = va_arg(ap, ptrdiff_t);
717			else if (lflag)
718				num = va_arg(ap, u_long);
719			else if (zflag)
720				num = va_arg(ap, size_t);
721			else if (hflag)
722				num = (u_short)va_arg(ap, int);
723			else if (cflag)
724				num = (u_char)va_arg(ap, int);
725			else
726				num = va_arg(ap, u_int);
727			goto number;
728handle_sign:
729			if (jflag)
730				num = va_arg(ap, intmax_t);
731			else if (qflag)
732				num = va_arg(ap, quad_t);
733			else if (tflag)
734				num = va_arg(ap, ptrdiff_t);
735			else if (lflag)
736				num = va_arg(ap, long);
737			else if (zflag)
738				num = va_arg(ap, size_t);
739			else if (hflag)
740				num = (short)va_arg(ap, int);
741			else if (cflag)
742				num = (char)va_arg(ap, int);
743			else
744				num = va_arg(ap, int);
745number:
746			if (sign && (intmax_t)num < 0) {
747				neg = 1;
748				num = -(intmax_t)num;
749			}
750			p = ksprintn(nbuf, num, base, &tmp);
751			if (sharpflag && num != 0) {
752				if (base == 8)
753					tmp++;
754				else if (base == 16)
755					tmp += 2;
756			}
757			if (neg)
758				tmp++;
759
760			if (!ladjust && width && (width -= tmp) > 0)
761				while (width--)
762					PCHAR(padc);
763			if (neg)
764				PCHAR('-');
765			if (sharpflag && num != 0) {
766				if (base == 8) {
767					PCHAR('0');
768				} else if (base == 16) {
769					PCHAR('0');
770					PCHAR('x');
771				}
772			}
773
774			while (*p)
775				PCHAR(*p--);
776
777			if (ladjust && width && (width -= tmp) > 0)
778				while (width--)
779					PCHAR(padc);
780
781			break;
782		default:
783			while (percent < fmt)
784				PCHAR(*percent++);
785			break;
786		}
787	}
788#undef PCHAR
789}
790
791/*
792 * Put character in log buffer with a particular priority.
793 */
794static void
795msglogchar(int c, int pri)
796{
797	static int lastpri = -1;
798	static int dangling;
799	char nbuf[MAXNBUF];
800	char *p;
801
802	if (!msgbufmapped)
803		return;
804	if (c == '\0' || c == '\r')
805		return;
806	if (pri != -1 && pri != lastpri) {
807		if (dangling) {
808			msgbuf_addchar(msgbufp, '\n');
809			dangling = 0;
810		}
811		msgbuf_addchar(msgbufp, '<');
812		for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL); *p;)
813			msgbuf_addchar(msgbufp, *p--);
814		msgbuf_addchar(msgbufp, '>');
815		lastpri = pri;
816	}
817	msgbuf_addchar(msgbufp, c);
818	if (c == '\n') {
819		dangling = 0;
820		lastpri = -1;
821	} else {
822		dangling = 1;
823	}
824}
825
826void
827msgbufinit(void *ptr, int size)
828{
829	char *cp;
830	static struct msgbuf *oldp = NULL;
831
832	size -= sizeof(*msgbufp);
833	cp = (char *)ptr;
834	msgbufp = (struct msgbuf *)(cp + size);
835	msgbuf_reinit(msgbufp, cp, size);
836	if (msgbufmapped && oldp != msgbufp)
837		msgbuf_copy(oldp, msgbufp);
838	msgbufmapped = 1;
839	oldp = msgbufp;
840}
841
842SYSCTL_DECL(_security_bsd);
843
844static int unprivileged_read_msgbuf = 1;
845SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_read_msgbuf,
846    CTLFLAG_RW, &unprivileged_read_msgbuf, 0,
847    "Unprivileged processes may read the kernel message buffer");
848
849/* Sysctls for accessing/clearing the msgbuf */
850static int
851sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
852{
853	char buf[128];
854	u_int seq;
855	int error, len;
856
857	if (!unprivileged_read_msgbuf) {
858		error = suser(req->td);
859		if (error)
860			return (error);
861	}
862
863	/* Read the whole buffer, one chunk at a time. */
864	msgbuf_peekbytes(msgbufp, NULL, 0, &seq);
865	while ((len = msgbuf_peekbytes(msgbufp, buf, sizeof(buf), &seq)) > 0) {
866		error = sysctl_handle_opaque(oidp, buf, len, req);
867		if (error)
868			return (error);
869	}
870	return (0);
871}
872
873SYSCTL_PROC(_kern, OID_AUTO, msgbuf, CTLTYPE_STRING | CTLFLAG_RD,
874    0, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
875
876static int msgbuf_clearflag;
877
878static int
879sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
880{
881	int error;
882	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
883	if (!error && req->newptr) {
884		msgbuf_clear(msgbufp);
885		msgbuf_clearflag = 0;
886	}
887	return (error);
888}
889
890SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
891    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, &msgbuf_clearflag, 0,
892    sysctl_kern_msgbuf_clear, "I", "Clear kernel message buffer");
893
894#ifdef DDB
895
896DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
897{
898	int i, j;
899
900	if (!msgbufmapped) {
901		db_printf("msgbuf not mapped yet\n");
902		return;
903	}
904	db_printf("msgbufp = %p\n", msgbufp);
905	db_printf("magic = %x, size = %d, r= %u, w = %u, ptr = %p, cksum= %u\n",
906	    msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_rseq,
907	    msgbufp->msg_wseq, msgbufp->msg_ptr, msgbufp->msg_cksum);
908	for (i = 0; i < msgbufp->msg_size; i++) {
909		j = MSGBUF_SEQ_TO_POS(msgbufp, i + msgbufp->msg_rseq);
910		db_printf("%c", msgbufp->msg_ptr[j]);
911	}
912	db_printf("\n");
913}
914
915#endif /* DDB */
916
917void
918hexdump(void *ptr, int length, const char *hdr, int flags)
919{
920	int i, j, k;
921	int cols;
922	unsigned char *cp;
923	char delim;
924
925	if ((flags & HD_DELIM_MASK) != 0)
926		delim = (flags & HD_DELIM_MASK) >> 8;
927	else
928		delim = ' ';
929
930	if ((flags & HD_COLUMN_MASK) != 0)
931		cols = flags & HD_COLUMN_MASK;
932	else
933		cols = 16;
934
935	cp = ptr;
936	for (i = 0; i < length; i+= cols) {
937		if (hdr != NULL)
938			printf("%s", hdr);
939
940		if ((flags & HD_OMIT_COUNT) == 0)
941			printf("%04x  ", i);
942
943		if ((flags & HD_OMIT_HEX) == 0) {
944			for (j = 0; j < cols; j++) {
945				k = i + j;
946				if (k < length)
947					printf("%c%02x", delim, cp[k]);
948				else
949					printf("   ");
950			}
951		}
952
953		if ((flags & HD_OMIT_CHARS) == 0) {
954			printf("  |");
955			for (j = 0; j < cols; j++) {
956				k = i + j;
957				if (k >= length)
958					printf(" ");
959				else if (cp[k] >= ' ' && cp[k] <= '~')
960					printf("%c", cp[k]);
961				else
962					printf(".");
963			}
964			printf("|\n");
965		}
966	}
967}
968
969