hexdump.c revision 149784
155714Skris/*-
255714Skris * Copyright (c) 1986, 1988, 1991, 1993
3194206Ssimon *	The Regents of the University of California.  All rights reserved.
455714Skris * (c) UNIX System Laboratories, Inc.
555714Skris * All or some portions of this file are derived from material licensed
655714Skris * to the University of California by American Telephone and Telegraph
755714Skris * Co. or Unix System Laboratories, Inc. and are reproduced herein with
855714Skris * the permission of UNIX System Laboratories, Inc.
955714Skris *
10296465Sdelphij * Redistribution and use in source and binary forms, with or without
1155714Skris * modification, are permitted provided that the following conditions
1255714Skris * are met:
1355714Skris * 1. Redistributions of source code must retain the above copyright
1455714Skris *    notice, this list of conditions and the following disclaimer.
1555714Skris * 2. Redistributions in binary form must reproduce the above copyright
1655714Skris *    notice, this list of conditions and the following disclaimer in the
1755714Skris *    documentation and/or other materials provided with the distribution.
1855714Skris * 4. Neither the name of the University nor the names of its contributors
1955714Skris *    may be used to endorse or promote products derived from this software
2055714Skris *    without specific prior written permission.
2155714Skris *
2255714Skris * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2355714Skris * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2455714Skris * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2555714Skris * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2655714Skris * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2755714Skris * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2855714Skris * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2955714Skris * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3055714Skris * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3155714Skris * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3255714Skris * SUCH DAMAGE.
3355714Skris *
3455714Skris *	@(#)subr_prf.c	8.3 (Berkeley) 1/21/94
3555714Skris */
3655714Skris
3755714Skris#include <sys/cdefs.h>
3855714Skris__FBSDID("$FreeBSD: head/sys/kern/subr_prf.c 149784 2005-09-04 18:03:45Z delphij $");
3955714Skris
4055714Skris#include "opt_ddb.h"
4155714Skris
4255714Skris#include <sys/param.h>
4355714Skris#include <sys/systm.h>
4455714Skris#include <sys/lock.h>
4555714Skris#include <sys/kdb.h>
4655714Skris#include <sys/mutex.h>
4755714Skris#include <sys/sx.h>
4855714Skris#include <sys/kernel.h>
4955714Skris#include <sys/msgbuf.h>
5055714Skris#include <sys/malloc.h>
5155714Skris#include <sys/proc.h>
52296465Sdelphij#include <sys/stddef.h>
5355714Skris#include <sys/sysctl.h>
5455714Skris#include <sys/tty.h>
5555714Skris#include <sys/syslog.h>
5655714Skris#include <sys/cons.h>
5755714Skris#include <sys/uio.h>
5855714Skris
5955714Skris#ifdef DDB
6055714Skris#include <ddb/ddb.h>
6155714Skris#endif
6255714Skris
63296465Sdelphij/*
6455714Skris * Note that stdarg.h and the ANSI style va_start macro is used for both
65296465Sdelphij * ANSI and traditional C compilers.
6655714Skris */
67296465Sdelphij#include <machine/stdarg.h>
68296465Sdelphij
6955714Skris#define TOCONS	0x01
70296465Sdelphij#define TOTTY	0x02
71296465Sdelphij#define TOLOG	0x04
72296465Sdelphij
73296465Sdelphij/* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
74296465Sdelphij#define MAXNBUF	(sizeof(intmax_t) * NBBY + 1)
75296465Sdelphij
76296465Sdelphijstruct putchar_arg {
77296465Sdelphij	int	flags;
78296465Sdelphij	int	pri;
79296465Sdelphij	struct	tty *tty;
80296465Sdelphij};
81296465Sdelphij
82296465Sdelphijstruct snprintf_arg {
83296465Sdelphij	char	*str;
8455714Skris	size_t	remain;
85296465Sdelphij};
8655714Skris
87296465Sdelphijextern	int log_open;
8855714Skris
89296465Sdelphijstatic void  msglogchar(int c, int pri);
9055714Skrisstatic void  putchar(int ch, void *arg);
91296465Sdelphijstatic char *ksprintn(char *nbuf, uintmax_t num, int base, int *len);
92296465Sdelphijstatic void  snprintf_func(int ch, void *arg);
9359191Skris
94296465Sdelphijstatic int consintr = 1;		/* Ok to handle console interrupts? */
9555714Skrisstatic int msgbufmapped;		/* Set when safe to use msgbuf */
9655714Skrisint msgbuftrigger;
9755714Skris
98296465Sdelphijstatic int      log_console_output = 1;
9955714SkrisTUNABLE_INT("kern.log_console_output", &log_console_output);
100296465SdelphijSYSCTL_INT(_kern, OID_AUTO, log_console_output, CTLFLAG_RW,
101296465Sdelphij    &log_console_output, 0, "Duplicate console output to the syslog.");
102296465Sdelphij
103296465Sdelphijstatic int	always_console_output = 0;
104296465SdelphijTUNABLE_INT("kern.always_console_output", &always_console_output);
105296465SdelphijSYSCTL_INT(_kern, OID_AUTO, always_console_output, CTLFLAG_RW,
106296465Sdelphij    &always_console_output, 0, "Always output to console despite TIOCCONS.");
107296465Sdelphij
10855714Skris/*
109296465Sdelphij * Warn that a system table is full.
11055714Skris */
11155714Skrisvoid
11255714Skristablefull(const char *tab)
113296465Sdelphij{
11455714Skris
11555714Skris	log(LOG_ERR, "%s: table is full\n", tab);
11655714Skris}
117296465Sdelphij
11855714Skris/*
11955714Skris * Uprintf prints to the controlling terminal for the current process.
120296465Sdelphij * It may block if the tty queue is overfull.  No message is printed if
12155714Skris * the queue does not clear in a reasonable time.
12255714Skris */
123296465Sdelphijint
12455714Skrisuprintf(const char *fmt, ...)
12555714Skris{
12655714Skris	struct thread *td = curthread;
127296465Sdelphij	struct proc *p = td->td_proc;
12855714Skris	va_list ap;
12955714Skris	struct putchar_arg pca;
130296465Sdelphij	int retval;
13155714Skris
13255714Skris	if (td == NULL || td == PCPU_GET(idlethread))
133296465Sdelphij		return (0);
13455714Skris
13555714Skris	p = td->td_proc;
13655714Skris	PROC_LOCK(p);
137296465Sdelphij	if ((p->p_flag & P_CONTROLT) == 0) {
13855714Skris		PROC_UNLOCK(p);
13955714Skris		return (0);
14055714Skris	}
14155714Skris	SESS_LOCK(p->p_session);
14255714Skris	pca.tty = p->p_session->s_ttyp;
14355714Skris	SESS_UNLOCK(p->p_session);
14455714Skris	PROC_UNLOCK(p);
145160814Ssimon	if (pca.tty == NULL)
146296465Sdelphij		return (0);
14759191Skris	pca.flags = TOTTY;
14859191Skris	va_start(ap, fmt);
149296465Sdelphij	retval = kvprintf(fmt, putchar, &pca, 10, ap);
15059191Skris	va_end(ap);
15159191Skris
152296465Sdelphij	return (retval);
15359191Skris}
154296465Sdelphij
15559191Skris/*
156109998Smarkm * tprintf prints on the controlling terminal associated
15755714Skris * with the given session, possibly to the log as well.
15855714Skris */
15955714Skrisvoid
16055714Skristprintf(struct proc *p, int pri, const char *fmt, ...)
161296465Sdelphij{
16255714Skris	struct tty *tp = NULL;
163109998Smarkm	int flags = 0;
164296465Sdelphij	va_list ap;
165296465Sdelphij	struct putchar_arg pca;
166296465Sdelphij	struct session *sess = NULL;
167296465Sdelphij
168296465Sdelphij	if (pri != -1)
169296465Sdelphij		flags |= TOLOG;
170296465Sdelphij	if (p != NULL) {
171296465Sdelphij		PROC_LOCK(p);
172194206Ssimon		if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
173296465Sdelphij			sess = p->p_session;
174296465Sdelphij			SESS_LOCK(sess);
175296465Sdelphij			PROC_UNLOCK(p);
176296465Sdelphij			SESSHOLD(sess);
177296465Sdelphij			tp = sess->s_ttyp;
178296465Sdelphij			SESS_UNLOCK(sess);
179296465Sdelphij			if (ttycheckoutq(tp, 0))
180296465Sdelphij				flags |= TOTTY;
181194206Ssimon			else
182296465Sdelphij				tp = NULL;
183296465Sdelphij		} else
184296465Sdelphij			PROC_UNLOCK(p);
185296465Sdelphij	}
186296465Sdelphij	pca.pri = pri;
187296465Sdelphij	pca.tty = tp;
18855714Skris	pca.flags = flags;
18955714Skris	va_start(ap, fmt);
190296465Sdelphij	kvprintf(fmt, putchar, &pca, 10, ap);
19155714Skris	va_end(ap);
19255714Skris	if (sess != NULL)
193296465Sdelphij		SESSRELE(sess);
19455714Skris	msgbuftrigger = 1;
19555714Skris}
19655714Skris
19755714Skris/*
198296465Sdelphij * Ttyprintf displays a message on a tty; it should be used only by
199296465Sdelphij * the tty driver, or anything that knows the underlying tty will not
200296465Sdelphij * be revoke(2)'d away.  Other callers should use tprintf.
201160814Ssimon */
202296465Sdelphijint
203160814Ssimonttyprintf(struct tty *tp, const char *fmt, ...)
204160814Ssimon{
205160814Ssimon	va_list ap;
206160814Ssimon	struct putchar_arg pca;
207160814Ssimon	int retval;
208160814Ssimon
209296465Sdelphij	va_start(ap, fmt);
210296465Sdelphij	pca.tty = tp;
211296465Sdelphij	pca.flags = TOTTY;
212296465Sdelphij	retval = kvprintf(fmt, putchar, &pca, 10, ap);
213296465Sdelphij	va_end(ap);
214296465Sdelphij	return (retval);
215296465Sdelphij}
216194206Ssimon
217160814Ssimon/*
218160814Ssimon * Log writes to the log buffer, and guarantees not to sleep (so can be
219296465Sdelphij * called by interrupt routines).  If there is no process reading the
220296465Sdelphij * log yet, it writes to the console also.
221296465Sdelphij */
222296465Sdelphijvoid
223160814Ssimonlog(int level, const char *fmt, ...)
224296465Sdelphij{
225296465Sdelphij	va_list ap;
226296465Sdelphij	struct putchar_arg pca;
227296465Sdelphij
228296465Sdelphij	pca.tty = NULL;
229296465Sdelphij	pca.pri = level;
230296465Sdelphij	pca.flags = log_open ? TOLOG : TOCONS;
231296465Sdelphij
232296465Sdelphij	va_start(ap, fmt);
233296465Sdelphij	kvprintf(fmt, putchar, &pca, 10, ap);
234296465Sdelphij	va_end(ap);
235296465Sdelphij
23655714Skris	msgbuftrigger = 1;
23755714Skris}
23855714Skris
239296465Sdelphij#define CONSCHUNK 128
240296465Sdelphij
241296465Sdelphijvoid
242296465Sdelphijlog_console(struct uio *uio)
243296465Sdelphij{
244296465Sdelphij	int c, i, error, nl;
245296465Sdelphij	char *consbuffer;
246296465Sdelphij	int pri;
247296465Sdelphij
248296465Sdelphij	if (!log_console_output)
249194206Ssimon		return;
250194206Ssimon
251296465Sdelphij	pri = LOG_INFO | LOG_CONSOLE;
252296465Sdelphij	uio = cloneuio(uio);
253160814Ssimon	consbuffer = malloc(CONSCHUNK, M_TEMP, M_WAITOK);
254296465Sdelphij
255296465Sdelphij	nl = 0;
256296465Sdelphij	while (uio->uio_resid > 0) {
257160814Ssimon		c = imin(uio->uio_resid, CONSCHUNK);
258160814Ssimon		error = uiomove(consbuffer, c, uio);
259296465Sdelphij		if (error != 0)
260296465Sdelphij			break;
261296465Sdelphij		for (i = 0; i < c; i++) {
262296465Sdelphij			msglogchar(consbuffer[i], pri);
263296465Sdelphij			if (consbuffer[i] == '\n')
264296465Sdelphij				nl = 1;
265296465Sdelphij			else
266296465Sdelphij				nl = 0;
267296465Sdelphij		}
268296465Sdelphij	}
269296465Sdelphij	if (!nl)
270296465Sdelphij		msglogchar('\n', pri);
27155714Skris	msgbuftrigger = 1;
27255714Skris	free(uio, M_IOV);
27355714Skris	free(consbuffer, M_TEMP);
27455714Skris	return;
27555714Skris}
27655714Skris
27755714Skrisint
278296465Sdelphijprintf(const char *fmt, ...)
279296465Sdelphij{
280296465Sdelphij	va_list ap;
281296465Sdelphij	int savintr;
282296465Sdelphij	struct putchar_arg pca;
283296465Sdelphij	int retval;
28455714Skris
285296465Sdelphij	savintr = consintr;		/* disable interrupts */
286296465Sdelphij	consintr = 0;
28755714Skris	va_start(ap, fmt);
288296465Sdelphij	pca.tty = NULL;
289296465Sdelphij	pca.flags = TOCONS | TOLOG;
290296465Sdelphij	pca.pri = -1;
291296465Sdelphij	retval = kvprintf(fmt, putchar, &pca, 10, ap);
292296465Sdelphij	va_end(ap);
293296465Sdelphij	if (!panicstr)
294296465Sdelphij		msgbuftrigger = 1;
295296465Sdelphij	consintr = savintr;		/* reenable interrupts */
296296465Sdelphij	return (retval);
29755714Skris}
298296465Sdelphij
299296465Sdelphijint
300296465Sdelphijvprintf(const char *fmt, va_list ap)
30155714Skris{
302296465Sdelphij	int savintr;
303296465Sdelphij	struct putchar_arg pca;
304296465Sdelphij	int retval;
305296465Sdelphij
306296465Sdelphij	savintr = consintr;		/* disable interrupts */
307296465Sdelphij	consintr = 0;
308296465Sdelphij	pca.tty = NULL;
309296465Sdelphij	pca.flags = TOCONS | TOLOG;
310296465Sdelphij	pca.pri = -1;
311296465Sdelphij	retval = kvprintf(fmt, putchar, &pca, 10, ap);
312296465Sdelphij	if (!panicstr)
313296465Sdelphij		msgbuftrigger = 1;
314296465Sdelphij	consintr = savintr;		/* reenable interrupts */
315296465Sdelphij	return (retval);
31655714Skris}
317296465Sdelphij
318296465Sdelphij/*
319296465Sdelphij * Print a character on console or users terminal.  If destination is
320296465Sdelphij * the console then the last bunch of characters are saved in msgbuf for
321296465Sdelphij * inspection later.
322296465Sdelphij */
323296465Sdelphijstatic void
32455714Skrisputchar(int c, void *arg)
325296465Sdelphij{
326296465Sdelphij	struct putchar_arg *ap = (struct putchar_arg*) arg;
327296465Sdelphij	struct tty *tp = ap->tty;
328296465Sdelphij	int consdirect, flags = ap->flags;
329296465Sdelphij
330296465Sdelphij	consdirect = ((flags & TOCONS) && constty == NULL);
331296465Sdelphij	/* Don't use the tty code after a panic or while in ddb. */
33255714Skris	if (panicstr)
333296465Sdelphij		consdirect = 1;
334296465Sdelphij	if (kdb_active)
335296465Sdelphij		consdirect = 1;
336296465Sdelphij	if (consdirect) {
33755714Skris		if (c != '\0')
338296465Sdelphij			cnputc(c);
339296465Sdelphij	} else {
340296465Sdelphij		if ((flags & TOTTY) && tp != NULL)
341296465Sdelphij			tputchar(c, tp);
34255714Skris		if (flags & TOCONS) {
343296465Sdelphij			if (constty != NULL)
344296465Sdelphij				msgbuf_addchar(&consmsgbuf, c);
34555714Skris			if (always_console_output && c != '\0')
346296465Sdelphij				cnputc(c);
347296465Sdelphij		}
348296465Sdelphij	}
349296465Sdelphij	if ((flags & TOLOG))
350296465Sdelphij		msglogchar(c, ap->pri);
351296465Sdelphij}
35255714Skris
353296465Sdelphij/*
35455714Skris * Scaled down version of sprintf(3).
355296465Sdelphij */
356296465Sdelphijint
35755714Skrissprintf(char *buf, const char *cfmt, ...)
358296465Sdelphij{
359296465Sdelphij	int retval;
36055714Skris	va_list ap;
361296465Sdelphij
362296465Sdelphij	va_start(ap, cfmt);
363296465Sdelphij	retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
364296465Sdelphij	buf[retval] = '\0';
36555714Skris	va_end(ap);
36659191Skris	return (retval);
367296465Sdelphij}
36859191Skris
369296465Sdelphij/*
37059191Skris * Scaled down version of vsprintf(3).
37155714Skris */
372296465Sdelphijint
373296465Sdelphijvsprintf(char *buf, const char *cfmt, va_list ap)
374109998Smarkm{
375109998Smarkm	int retval;
376212961Srpaulo
377296465Sdelphij	retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
378109998Smarkm	buf[retval] = '\0';
379109998Smarkm	return (retval);
380109998Smarkm}
381109998Smarkm
382109998Smarkm/*
383109998Smarkm * Scaled down version of snprintf(3).
384109998Smarkm */
385109998Smarkmint
386109998Smarkmsnprintf(char *str, size_t size, const char *format, ...)
387109998Smarkm{
388109998Smarkm	int retval;
389109998Smarkm	va_list ap;
390109998Smarkm
391296465Sdelphij	va_start(ap, format);
392109998Smarkm	retval = vsnprintf(str, size, format, ap);
393296465Sdelphij	va_end(ap);
394212961Srpaulo	return(retval);
395212961Srpaulo}
396212961Srpaulo
397212961Srpaulo/*
398212961Srpaulo * Scaled down version of vsnprintf(3).
399212961Srpaulo */
400212961Srpauloint
401296465Sdelphijvsnprintf(char *str, size_t size, const char *format, va_list ap)
402109998Smarkm{
403212961Srpaulo	struct snprintf_arg info;
404109998Smarkm	int retval;
405212961Srpaulo
406	info.str = str;
407	info.remain = size;
408	retval = kvprintf(format, snprintf_func, &info, 10, ap);
409	if (info.remain >= 1)
410		*info.str++ = '\0';
411	return (retval);
412}
413
414/*
415 * Kernel version which takes radix argument vsnprintf(3).
416 */
417int
418vsnrprintf(char *str, size_t size, int radix, const char *format, va_list ap)
419{
420	struct snprintf_arg info;
421	int retval;
422
423	info.str = str;
424	info.remain = size;
425	retval = kvprintf(format, snprintf_func, &info, radix, ap);
426	if (info.remain >= 1)
427		*info.str++ = '\0';
428	return (retval);
429}
430
431static void
432snprintf_func(int ch, void *arg)
433{
434	struct snprintf_arg *const info = arg;
435
436	if (info->remain >= 2) {
437		*info->str++ = ch;
438		info->remain--;
439	}
440}
441
442/*
443 * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
444 * order; return an optional length and a pointer to the last character
445 * written in the buffer (i.e., the first character of the string).
446 * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
447 */
448static char *
449ksprintn(char *nbuf, uintmax_t num, int base, int *lenp)
450{
451	char *p;
452
453	p = nbuf;
454	*p = '\0';
455	do {
456		*++p = hex2ascii(num % base);
457	} while (num /= base);
458	if (lenp)
459		*lenp = p - nbuf;
460	return (p);
461}
462
463/*
464 * Scaled down version of printf(3).
465 *
466 * Two additional formats:
467 *
468 * The format %b is supported to decode error registers.
469 * Its usage is:
470 *
471 *	printf("reg=%b\n", regval, "<base><arg>*");
472 *
473 * where <base> is the output base expressed as a control character, e.g.
474 * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
475 * the first of which gives the bit number to be inspected (origin 1), and
476 * the next characters (up to a control character, i.e. a character <= 32),
477 * give the name of the register.  Thus:
478 *
479 *	kvprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
480 *
481 * would produce output:
482 *
483 *	reg=3<BITTWO,BITONE>
484 *
485 * XXX:  %D  -- Hexdump, takes pointer and separator string:
486 *		("%6D", ptr, ":")   -> XX:XX:XX:XX:XX:XX
487 *		("%*D", len, ptr, " " -> XX XX XX XX ...
488 */
489int
490kvprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, va_list ap)
491{
492#define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; }
493	char nbuf[MAXNBUF];
494	char *d;
495	const char *p, *percent, *q;
496	u_char *up;
497	int ch, n;
498	uintmax_t num;
499	int base, lflag, qflag, tmp, width, ladjust, sharpflag, neg, sign, dot;
500	int cflag, hflag, jflag, tflag, zflag;
501	int dwidth;
502	char padc;
503	int stop = 0, retval = 0;
504
505	num = 0;
506	if (!func)
507		d = (char *) arg;
508	else
509		d = NULL;
510
511	if (fmt == NULL)
512		fmt = "(fmt null)\n";
513
514	if (radix < 2 || radix > 36)
515		radix = 10;
516
517	for (;;) {
518		padc = ' ';
519		width = 0;
520		while ((ch = (u_char)*fmt++) != '%' || stop) {
521			if (ch == '\0')
522				return (retval);
523			PCHAR(ch);
524		}
525		percent = fmt - 1;
526		qflag = 0; lflag = 0; ladjust = 0; sharpflag = 0; neg = 0;
527		sign = 0; dot = 0; dwidth = 0;
528		cflag = 0; hflag = 0; jflag = 0; tflag = 0; zflag = 0;
529reswitch:	switch (ch = (u_char)*fmt++) {
530		case '.':
531			dot = 1;
532			goto reswitch;
533		case '#':
534			sharpflag = 1;
535			goto reswitch;
536		case '+':
537			sign = 1;
538			goto reswitch;
539		case '-':
540			ladjust = 1;
541			goto reswitch;
542		case '%':
543			PCHAR(ch);
544			break;
545		case '*':
546			if (!dot) {
547				width = va_arg(ap, int);
548				if (width < 0) {
549					ladjust = !ladjust;
550					width = -width;
551				}
552			} else {
553				dwidth = va_arg(ap, int);
554			}
555			goto reswitch;
556		case '0':
557			if (!dot) {
558				padc = '0';
559				goto reswitch;
560			}
561		case '1': case '2': case '3': case '4':
562		case '5': case '6': case '7': case '8': case '9':
563				for (n = 0;; ++fmt) {
564					n = n * 10 + ch - '0';
565					ch = *fmt;
566					if (ch < '0' || ch > '9')
567						break;
568				}
569			if (dot)
570				dwidth = n;
571			else
572				width = n;
573			goto reswitch;
574		case 'b':
575			num = (u_int)va_arg(ap, int);
576			p = va_arg(ap, char *);
577			for (q = ksprintn(nbuf, num, *p++, NULL); *q;)
578				PCHAR(*q--);
579
580			if (num == 0)
581				break;
582
583			for (tmp = 0; *p;) {
584				n = *p++;
585				if (num & (1 << (n - 1))) {
586					PCHAR(tmp ? ',' : '<');
587					for (; (n = *p) > ' '; ++p)
588						PCHAR(n);
589					tmp = 1;
590				} else
591					for (; *p > ' '; ++p)
592						continue;
593			}
594			if (tmp)
595				PCHAR('>');
596			break;
597		case 'c':
598			PCHAR(va_arg(ap, int));
599			break;
600		case 'D':
601			up = va_arg(ap, u_char *);
602			p = va_arg(ap, char *);
603			if (!width)
604				width = 16;
605			while(width--) {
606				PCHAR(hex2ascii(*up >> 4));
607				PCHAR(hex2ascii(*up & 0x0f));
608				up++;
609				if (width)
610					for (q=p;*q;q++)
611						PCHAR(*q);
612			}
613			break;
614		case 'd':
615		case 'i':
616			base = 10;
617			sign = 1;
618			goto handle_sign;
619		case 'h':
620			if (hflag) {
621				hflag = 0;
622				cflag = 1;
623			} else
624				hflag = 1;
625			goto reswitch;
626		case 'j':
627			jflag = 1;
628			goto reswitch;
629		case 'l':
630			if (lflag) {
631				lflag = 0;
632				qflag = 1;
633			} else
634				lflag = 1;
635			goto reswitch;
636		case 'n':
637			if (jflag)
638				*(va_arg(ap, intmax_t *)) = retval;
639			else if (qflag)
640				*(va_arg(ap, quad_t *)) = retval;
641			else if (lflag)
642				*(va_arg(ap, long *)) = retval;
643			else if (zflag)
644				*(va_arg(ap, size_t *)) = retval;
645			else if (hflag)
646				*(va_arg(ap, short *)) = retval;
647			else if (cflag)
648				*(va_arg(ap, char *)) = retval;
649			else
650				*(va_arg(ap, int *)) = retval;
651			break;
652		case 'o':
653			base = 8;
654			goto handle_nosign;
655		case 'p':
656			base = 16;
657			sharpflag = (width == 0);
658			sign = 0;
659			num = (uintptr_t)va_arg(ap, void *);
660			goto number;
661		case 'q':
662			qflag = 1;
663			goto reswitch;
664		case 'r':
665			base = radix;
666			if (sign)
667				goto handle_sign;
668			goto handle_nosign;
669		case 's':
670			p = va_arg(ap, char *);
671			if (p == NULL)
672				p = "(null)";
673			if (!dot)
674				n = strlen (p);
675			else
676				for (n = 0; n < dwidth && p[n]; n++)
677					continue;
678
679			width -= n;
680
681			if (!ladjust && width > 0)
682				while (width--)
683					PCHAR(padc);
684			while (n--)
685				PCHAR(*p++);
686			if (ladjust && width > 0)
687				while (width--)
688					PCHAR(padc);
689			break;
690		case 't':
691			tflag = 1;
692			goto reswitch;
693		case 'u':
694			base = 10;
695			goto handle_nosign;
696		case 'x':
697		case 'X':
698			base = 16;
699			goto handle_nosign;
700		case 'y':
701			base = 16;
702			sign = 1;
703			goto handle_sign;
704		case 'z':
705			zflag = 1;
706			goto reswitch;
707handle_nosign:
708			sign = 0;
709			if (jflag)
710				num = va_arg(ap, uintmax_t);
711			else if (qflag)
712				num = va_arg(ap, u_quad_t);
713			else if (tflag)
714				num = va_arg(ap, ptrdiff_t);
715			else if (lflag)
716				num = va_arg(ap, u_long);
717			else if (zflag)
718				num = va_arg(ap, size_t);
719			else if (hflag)
720				num = (u_short)va_arg(ap, int);
721			else if (cflag)
722				num = (u_char)va_arg(ap, int);
723			else
724				num = va_arg(ap, u_int);
725			goto number;
726handle_sign:
727			if (jflag)
728				num = va_arg(ap, intmax_t);
729			else if (qflag)
730				num = va_arg(ap, quad_t);
731			else if (tflag)
732				num = va_arg(ap, ptrdiff_t);
733			else if (lflag)
734				num = va_arg(ap, long);
735			else if (zflag)
736				num = va_arg(ap, size_t);
737			else if (hflag)
738				num = (short)va_arg(ap, int);
739			else if (cflag)
740				num = (char)va_arg(ap, int);
741			else
742				num = va_arg(ap, int);
743number:
744			if (sign && (intmax_t)num < 0) {
745				neg = 1;
746				num = -(intmax_t)num;
747			}
748			p = ksprintn(nbuf, num, base, &tmp);
749			if (sharpflag && num != 0) {
750				if (base == 8)
751					tmp++;
752				else if (base == 16)
753					tmp += 2;
754			}
755			if (neg)
756				tmp++;
757
758			if (!ladjust && padc != '0' && width
759			    && (width -= tmp) > 0)
760				while (width--)
761					PCHAR(padc);
762			if (neg)
763				PCHAR('-');
764			if (sharpflag && num != 0) {
765				if (base == 8) {
766					PCHAR('0');
767				} else if (base == 16) {
768					PCHAR('0');
769					PCHAR('x');
770				}
771			}
772			if (!ladjust && width && (width -= tmp) > 0)
773				while (width--)
774					PCHAR(padc);
775
776			while (*p)
777				PCHAR(*p--);
778
779			if (ladjust && width && (width -= tmp) > 0)
780				while (width--)
781					PCHAR(padc);
782
783			break;
784		default:
785			while (percent < fmt)
786				PCHAR(*percent++);
787			/*
788			 * Since we ignore an formatting argument it is no
789			 * longer safe to obey the remaining formatting
790			 * arguments as the arguments will no longer match
791			 * the format specs.
792			 */
793			stop = 1;
794			break;
795		}
796	}
797#undef PCHAR
798}
799
800/*
801 * Put character in log buffer with a particular priority.
802 */
803static void
804msglogchar(int c, int pri)
805{
806	static int lastpri = -1;
807	static int dangling;
808	char nbuf[MAXNBUF];
809	char *p;
810
811	if (!msgbufmapped)
812		return;
813	if (c == '\0' || c == '\r')
814		return;
815	if (pri != -1 && pri != lastpri) {
816		if (dangling) {
817			msgbuf_addchar(msgbufp, '\n');
818			dangling = 0;
819		}
820		msgbuf_addchar(msgbufp, '<');
821		for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL); *p;)
822			msgbuf_addchar(msgbufp, *p--);
823		msgbuf_addchar(msgbufp, '>');
824		lastpri = pri;
825	}
826	msgbuf_addchar(msgbufp, c);
827	if (c == '\n') {
828		dangling = 0;
829		lastpri = -1;
830	} else {
831		dangling = 1;
832	}
833}
834
835void
836msgbufinit(void *ptr, int size)
837{
838	char *cp;
839	static struct msgbuf *oldp = NULL;
840
841	size -= sizeof(*msgbufp);
842	cp = (char *)ptr;
843	msgbufp = (struct msgbuf *)(cp + size);
844	msgbuf_reinit(msgbufp, cp, size);
845	if (msgbufmapped && oldp != msgbufp)
846		msgbuf_copy(oldp, msgbufp);
847	msgbufmapped = 1;
848	oldp = msgbufp;
849}
850
851SYSCTL_DECL(_security_bsd);
852
853static int unprivileged_read_msgbuf = 1;
854SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_read_msgbuf,
855    CTLFLAG_RW, &unprivileged_read_msgbuf, 0,
856    "Unprivileged processes may read the kernel message buffer");
857
858/* Sysctls for accessing/clearing the msgbuf */
859static int
860sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
861{
862	char buf[128];
863	u_int seq;
864	int error, len;
865
866	if (!unprivileged_read_msgbuf) {
867		error = suser(req->td);
868		if (error)
869			return (error);
870	}
871
872	/* Read the whole buffer, one chunk at a time. */
873	msgbuf_peekbytes(msgbufp, NULL, 0, &seq);
874	while ((len = msgbuf_peekbytes(msgbufp, buf, sizeof(buf), &seq)) > 0) {
875		error = sysctl_handle_opaque(oidp, buf, len, req);
876		if (error)
877			return (error);
878	}
879	return (0);
880}
881
882SYSCTL_PROC(_kern, OID_AUTO, msgbuf, CTLTYPE_STRING | CTLFLAG_RD,
883    0, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
884
885static int msgbuf_clearflag;
886
887static int
888sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
889{
890	int error;
891	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
892	if (!error && req->newptr) {
893		msgbuf_clear(msgbufp);
894		msgbuf_clearflag = 0;
895	}
896	return (error);
897}
898
899SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
900    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, &msgbuf_clearflag, 0,
901    sysctl_kern_msgbuf_clear, "I", "Clear kernel message buffer");
902
903#ifdef DDB
904
905DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
906{
907	int i, j, quit;
908
909	quit = 0;
910
911	if (!msgbufmapped) {
912		db_printf("msgbuf not mapped yet\n");
913		return;
914	}
915	db_setup_paging(db_simple_pager, &quit, db_lines_per_page);
916	db_printf("msgbufp = %p\n", msgbufp);
917	db_printf("magic = %x, size = %d, r= %u, w = %u, ptr = %p, cksum= %u\n",
918	    msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_rseq,
919	    msgbufp->msg_wseq, msgbufp->msg_ptr, msgbufp->msg_cksum);
920	for (i = 0; i < msgbufp->msg_size && !quit; i++) {
921		j = MSGBUF_SEQ_TO_POS(msgbufp, i + msgbufp->msg_rseq);
922		db_printf("%c", msgbufp->msg_ptr[j]);
923	}
924	db_printf("\n");
925}
926
927#endif /* DDB */
928
929void
930hexdump(const void *ptr, int length, const char *hdr, int flags)
931{
932	int i, j, k;
933	int cols;
934	const unsigned char *cp;
935	char delim;
936
937	if ((flags & HD_DELIM_MASK) != 0)
938		delim = (flags & HD_DELIM_MASK) >> 8;
939	else
940		delim = ' ';
941
942	if ((flags & HD_COLUMN_MASK) != 0)
943		cols = flags & HD_COLUMN_MASK;
944	else
945		cols = 16;
946
947	cp = ptr;
948	for (i = 0; i < length; i+= cols) {
949		if (hdr != NULL)
950			printf("%s", hdr);
951
952		if ((flags & HD_OMIT_COUNT) == 0)
953			printf("%04x  ", i);
954
955		if ((flags & HD_OMIT_HEX) == 0) {
956			for (j = 0; j < cols; j++) {
957				k = i + j;
958				if (k < length)
959					printf("%c%02x", delim, cp[k]);
960				else
961					printf("   ");
962			}
963		}
964
965		if ((flags & HD_OMIT_CHARS) == 0) {
966			printf("  |");
967			for (j = 0; j < cols; j++) {
968				k = i + j;
969				if (k >= length)
970					printf(" ");
971				else if (cp[k] >= ' ' && cp[k] <= '~')
972					printf("%c", cp[k]);
973				else
974					printf(".");
975			}
976			printf("|\n");
977		}
978	}
979}
980
981