hexdump.c revision 14816
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 * $Id: subr_prf.c,v 1.33 1996/03/23 21:41:00 jkh Exp $
40 */
41
42#include "opt_ddb.h"
43
44#include <sys/param.h>
45#include <sys/systm.h>
46#include <sys/reboot.h>
47#include <sys/msgbuf.h>
48#include <sys/proc.h>
49#include <sys/vnode.h>
50#include <sys/tty.h>
51#include <sys/tprintf.h>
52#include <sys/syslog.h>
53#include <sys/malloc.h>
54#include <sys/kernel.h>
55#include <sys/sysctl.h>
56#include <machine/cons.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#if defined(DDB) || defined (KGDB)
65#ifdef DDB_UNATTENDED
66	static int debugger_on_panic = 0;
67#else
68	static int debugger_on_panic = 1;
69#endif
70
71SYSCTL_INT(_debug, OID_AUTO, debugger_on_panic, CTLFLAG_RW,
72	&debugger_on_panic, 0, "");
73#endif
74
75#define TOCONS	0x01
76#define TOTTY	0x02
77#define TOLOG	0x04
78
79struct	tty *constty;			/* pointer to console "window" tty */
80
81static void (*v_putc)(int) = cnputc;	/* routine to putc on virtual console */
82
83static void  logpri __P((int level));
84static void  msglogchar(int c, void *dummyarg);
85struct putchar_arg {int flags; struct tty *tty; };
86static void  putchar __P((int ch, void *arg));
87static char *ksprintn __P((u_long num, int base, int *len));
88
89static int consintr = 1;		/* Ok to handle console interrupts? */
90
91/*
92 * Variable panicstr contains argument to first call to panic; used as flag
93 * to indicate that the kernel has already called panic.
94 */
95const char *panicstr;
96
97/*
98 * Panic is called on unresolvable fatal errors.  It prints "panic: mesg",
99 * and then reboots.  If we are called twice, then we avoid trying to sync
100 * the disks as this often leads to recursive panics.
101 */
102#ifdef __GNUC__
103__dead			/* panic() does not return */
104#endif
105void
106panic(const char *fmt, ...)
107{
108	int bootopt;
109	va_list ap;
110
111	bootopt = RB_AUTOBOOT | RB_DUMP;
112	if (panicstr)
113		bootopt |= RB_NOSYNC;
114	else
115		panicstr = fmt;
116
117	printf("panic: ");
118	va_start(ap, fmt);
119	vprintf(fmt, ap);
120	va_end(ap);
121	printf("\n");
122
123#if defined(DDB) || defined (KGDB)
124	if (debugger_on_panic) {
125#ifdef KGDB
126		kgdb_panic();
127#endif
128#ifdef DDB
129		Debugger ("panic");
130#endif
131	}
132#endif
133	boot(bootopt);
134}
135
136/*
137 * Warn that a system table is full.
138 */
139void
140tablefull(tab)
141	const char *tab;
142{
143
144	log(LOG_ERR, "%s: table is full\n", tab);
145}
146
147/*
148 * Uprintf prints to the controlling terminal for the current process.
149 * It may block if the tty queue is overfull.  No message is printed if
150 * the queue does not clear in a reasonable time.
151 */
152void
153uprintf(const char *fmt, ...)
154{
155	struct proc *p = curproc;
156	va_list ap;
157	struct putchar_arg pca;
158
159	if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
160		va_start(ap, fmt);
161		pca.tty = p->p_session->s_ttyp;
162		pca.flags = TOTTY;
163		kvprintf(fmt, putchar, &pca, 10, ap);
164		va_end(ap);
165	}
166}
167
168tpr_t
169tprintf_open(p)
170	register struct proc *p;
171{
172
173	if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
174		SESSHOLD(p->p_session);
175		return ((tpr_t) p->p_session);
176	}
177	return ((tpr_t) NULL);
178}
179
180void
181tprintf_close(sess)
182	tpr_t sess;
183{
184
185	if (sess)
186		SESSRELE((struct session *) sess);
187}
188
189/*
190 * tprintf prints on the controlling terminal associated
191 * with the given session.
192 */
193void
194tprintf(tpr_t tpr, const char *fmt, ...)
195{
196	register struct session *sess = (struct session *)tpr;
197	struct tty *tp = NULL;
198	int flags = TOLOG;
199	va_list ap;
200	struct putchar_arg pca;
201
202	logpri(LOG_INFO);
203	if (sess && sess->s_ttyvp && ttycheckoutq(sess->s_ttyp, 0)) {
204		flags |= TOTTY;
205		tp = sess->s_ttyp;
206	}
207	va_start(ap, fmt);
208	pca.tty = tp;
209	pca.flags = flags;
210	kvprintf(fmt, putchar, &pca, 10, ap);
211	va_end(ap);
212	logwakeup();
213}
214
215/*
216 * Ttyprintf displays a message on a tty; it should be used only by
217 * the tty driver, or anything that knows the underlying tty will not
218 * be revoke(2)'d away.  Other callers should use tprintf.
219 */
220void
221ttyprintf(struct tty *tp, const char *fmt, ...)
222{
223	va_list ap;
224	struct putchar_arg pca;
225	va_start(ap, fmt);
226	pca.tty = tp;
227	pca.flags = TOTTY;
228	kvprintf(fmt, putchar, &pca, 10, ap);
229	va_end(ap);
230}
231
232extern	int log_open;
233
234/*
235 * Log writes to the log buffer, and guarantees not to sleep (so can be
236 * called by interrupt routines).  If there is no process reading the
237 * log yet, it writes to the console also.
238 */
239void
240log(int level, const char *fmt, ...)
241{
242	register int s;
243	va_list ap;
244
245	s = splhigh();
246	logpri(level);
247	va_start(ap, fmt);
248
249	kvprintf(fmt, msglogchar, NULL, 10, ap);
250	va_end(ap);
251
252	splx(s);
253	if (!log_open) {
254		struct putchar_arg pca;
255		va_start(ap, fmt);
256		pca.tty = NULL;
257		pca.flags = TOCONS;
258		kvprintf(fmt, putchar, &pca, 10, ap);
259		va_end(ap);
260	}
261	logwakeup();
262}
263
264static void
265logpri(level)
266	int level;
267{
268	register char *p;
269
270	msglogchar('<', NULL);
271	for (p = ksprintn((u_long)level, 10, NULL); *p;)
272		msglogchar(*p--, NULL);
273	msglogchar('>', NULL);
274}
275
276void
277addlog(const char *fmt, ...)
278{
279	register int s;
280	va_list ap;
281
282	s = splhigh();
283	va_start(ap, fmt);
284	kvprintf(fmt, msglogchar, NULL, 10, ap);
285	splx(s);
286	va_end(ap);
287	if (!log_open) {
288		struct putchar_arg pca;
289		va_start(ap, fmt);
290		pca.tty = NULL;
291		pca.flags = TOCONS;
292		kvprintf(fmt, putchar, &pca, 10, ap);
293		va_end(ap);
294	}
295	logwakeup();
296}
297
298int
299printf(const char *fmt, ...)
300{
301	va_list ap;
302	register int savintr;
303	struct putchar_arg pca;
304	int retval;
305
306	savintr = consintr;		/* disable interrupts */
307	consintr = 0;
308	va_start(ap, fmt);
309	pca.tty = NULL;
310	pca.flags = TOCONS | TOLOG;
311	retval = kvprintf(fmt, putchar, &pca, 10, ap);
312	va_end(ap);
313	if (!panicstr)
314		logwakeup();
315	consintr = savintr;		/* reenable interrupts */
316	return retval;
317}
318
319void
320vprintf(const char *fmt, va_list ap)
321{
322	register int savintr;
323	struct putchar_arg pca;
324
325	savintr = consintr;		/* disable interrupts */
326	consintr = 0;
327	pca.tty = NULL;
328	pca.flags = TOCONS | TOLOG;
329	kvprintf(fmt, putchar, &pca, 10, ap);
330	if (!panicstr)
331		logwakeup();
332	consintr = savintr;		/* reenable interrupts */
333}
334
335/*
336 * Print a character on console or users terminal.  If destination is
337 * the console then the last MSGBUFS characters are saved in msgbuf for
338 * inspection later.
339 */
340static void
341putchar(int c, void *arg)
342{
343	struct putchar_arg *ap = (struct putchar_arg*) arg;
344	int flags = ap->flags;
345	struct tty *tp = ap->tty;
346	if (panicstr)
347		constty = NULL;
348	if ((flags & TOCONS) && tp == NULL && constty) {
349		tp = constty;
350		flags |= TOTTY;
351	}
352	if ((flags & TOTTY) && tp && tputchar(c, tp) < 0 &&
353	    (flags & TOCONS) && tp == constty)
354		constty = NULL;
355	if ((flags & TOLOG))
356		msglogchar(c, NULL);
357	if ((flags & TOCONS) && constty == NULL && c != '\0')
358		(*v_putc)(c);
359}
360
361/*
362 * Scaled down version of sprintf(3).
363 */
364int
365sprintf(char *buf, const char *cfmt, ...)
366{
367	int retval;
368	va_list ap;
369
370	va_start(ap, cfmt);
371	retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
372	buf[retval] = '\0';
373	va_end(ap);
374	return retval;
375}
376
377/*
378 * Put a number (base <= 16) in a buffer in reverse order; return an
379 * optional length and a pointer to the NULL terminated (preceded?)
380 * buffer.
381 */
382static char *
383ksprintn(ul, base, lenp)
384	register u_long ul;
385	register int base, *lenp;
386{					/* A long in base 8, plus NULL. */
387	static char buf[sizeof(long) * NBBY / 3 + 2];
388	register char *p;
389
390	p = buf;
391	do {
392		*++p = hex2ascii(ul % base);
393	} while (ul /= base);
394	if (lenp)
395		*lenp = p - buf;
396	return (p);
397}
398
399/*
400 * Scaled down version of printf(3).
401 *
402 * Two additional formats:
403 *
404 * The format %b is supported to decode error registers.
405 * Its usage is:
406 *
407 *	printf("reg=%b\n", regval, "<base><arg>*");
408 *
409 * where <base> is the output base expressed as a control character, e.g.
410 * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
411 * the first of which gives the bit number to be inspected (origin 1), and
412 * the next characters (up to a control character, i.e. a character <= 32),
413 * give the name of the register.  Thus:
414 *
415 *	kprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
416 *
417 * would produce output:
418 *
419 *	reg=3<BITTWO,BITONE>
420 *
421 * XXX:  %D  -- Hexdump, takes pointer and separator string:
422 *		("%6D", ptr, ":")   -> XX:XX:XX:XX:XX:XX
423 *		("%*D", len, ptr, " " -> XX XX XX XX ...
424 */
425int
426kvprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, va_list ap)
427{
428#define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; }
429	char *p, *q, *d;
430	u_char *up;
431	int ch, n;
432	u_long ul;
433	int base, lflag, tmp, width, ladjust, sharpflag, neg, sign, dot;
434	int dwidth;
435	char padc;
436	int retval = 0;
437
438	if (!func)
439		d = (char *) arg;
440	else
441		d = NULL;
442
443	if (fmt == NULL)
444		fmt = "(fmt null)\n";
445
446	if (radix < 2 || radix > 36)
447		radix = 10;
448
449	for (;;) {
450		padc = ' ';
451		width = 0;
452		while ((ch = *(u_char *)fmt++) != '%') {
453			if (ch == '\0')
454				return retval;
455			PCHAR(ch);
456		}
457		lflag = 0; ladjust = 0; sharpflag = 0; neg = 0;
458		sign = 0; dot = 0; dwidth = 0;
459reswitch:	switch (ch = *(u_char *)fmt++) {
460		case '.':
461			dot = 1;
462			goto reswitch;
463		case '#':
464			sharpflag = 1;
465			goto reswitch;
466		case '+':
467			sign = 1;
468			goto reswitch;
469		case '-':
470			ladjust = 1;
471			goto reswitch;
472		case '%':
473			PCHAR(ch);
474			break;
475		case '*':
476			if (!dot) {
477				width = va_arg(ap, int);
478				if (width < 0) {
479					ladjust = !ladjust;
480					width = -width;
481				}
482			} else {
483				dwidth = va_arg(ap, int);
484			}
485			goto reswitch;
486		case '0':
487			if (!dot) {
488				padc = '0';
489				goto reswitch;
490			}
491		case '1': case '2': case '3': case '4':
492		case '5': case '6': case '7': case '8': case '9':
493				for (n = 0;; ++fmt) {
494					n = n * 10 + ch - '0';
495					ch = *fmt;
496					if (ch < '0' || ch > '9')
497						break;
498				}
499			if (dot)
500				dwidth = n;
501			else
502				width = n;
503			goto reswitch;
504		case 'b':
505			ul = va_arg(ap, int);
506			p = va_arg(ap, char *);
507			for (q = ksprintn(ul, *p++, NULL); *q;)
508				PCHAR(*q--);
509
510			if (!ul)
511				break;
512
513			for (tmp = 0; *p;) {
514				n = *p++;
515				if (ul & (1 << (n - 1))) {
516					PCHAR(tmp ? ',' : '<');
517					for (; (n = *p) > ' '; ++p)
518						PCHAR(n);
519					tmp = 1;
520				} else
521					for (; *p > ' '; ++p)
522						continue;
523			}
524			if (tmp)
525				PCHAR('>');
526			break;
527		case 'c':
528			PCHAR(va_arg(ap, int));
529			break;
530		case 'D':
531			up = va_arg(ap, u_char *);
532			p = va_arg(ap, char *);
533			if (!width)
534				width = 16;
535			while(width--) {
536				PCHAR(hex2ascii(*up >> 4));
537				PCHAR(hex2ascii(*up & 0x0f));
538				up++;
539				if (width)
540					for (q=p;*q;q++)
541						PCHAR(*q);
542			}
543			break;
544		case 'd':
545			ul = lflag ? va_arg(ap, long) : va_arg(ap, int);
546			sign = 1;
547			base = 10;
548			goto number;
549		case 'l':
550			lflag = 1;
551			goto reswitch;
552		case 'n':
553			ul = lflag ? va_arg(ap, u_long) : va_arg(ap, u_int);
554			base = radix;
555			goto number;
556		case 'o':
557			ul = lflag ? va_arg(ap, u_long) : va_arg(ap, u_int);
558			base = 8;
559			goto number;
560		case 'p':
561			ul = (u_long)va_arg(ap, void *);
562			base = 16;
563			PCHAR('0');
564			PCHAR('x');
565			goto number;
566		case 's':
567			p = va_arg(ap, char *);
568			if (p == NULL)
569				p = "(null)";
570			if (!dot)
571				n = strlen (p);
572			else
573				for (n = 0; n < dwidth && p[n]; n++)
574					continue;
575
576			width -= n;
577
578			if (!ladjust && width > 0)
579				while (width--)
580					PCHAR(padc);
581			while (n--)
582				PCHAR(*p++);
583			if (ladjust && width > 0)
584				while (width--)
585					PCHAR(padc);
586			break;
587		case 'u':
588			ul = lflag ? va_arg(ap, u_long) : va_arg(ap, u_int);
589			base = 10;
590			goto number;
591		case 'x':
592			ul = lflag ? va_arg(ap, u_long) : va_arg(ap, u_int);
593			base = 16;
594number:			if (sign && (long)ul < 0L) {
595				neg = 1;
596				ul = -(long)ul;
597			}
598			p = ksprintn(ul, base, &tmp);
599			if (sharpflag && ul != 0) {
600				if (base == 8)
601					tmp++;
602				else if (base == 16)
603					tmp += 2;
604			}
605			if (neg)
606				tmp++;
607
608			if (!ladjust && width && (width -= tmp) > 0)
609				while (width--)
610					PCHAR(padc);
611			if (neg)
612				PCHAR('-');
613			if (sharpflag && ul != 0) {
614				if (base == 8) {
615					PCHAR('0');
616				} else if (base == 16) {
617					PCHAR('0');
618					PCHAR('x');
619				}
620			}
621
622			while (*p)
623				PCHAR(*p--);
624
625			if (ladjust && width && (width -= tmp) > 0)
626				while (width--)
627					PCHAR(padc);
628
629			break;
630		default:
631			PCHAR('%');
632			if (lflag)
633				PCHAR('l');
634			PCHAR(ch);
635			break;
636		}
637	}
638#undef PCHAR
639}
640
641/*
642 * Put character in log buffer.
643 */
644static void
645msglogchar(int c, void *dummyarg)
646{
647	struct msgbuf *mbp;
648
649	if (c != '\0' && c != '\r' && c != 0177 && msgbufmapped) {
650		mbp = msgbufp;
651		if (mbp->msg_magic != MSG_MAGIC ||
652		    mbp->msg_bufx >= MSG_BSIZE ||
653		    mbp->msg_bufr >= MSG_BSIZE) {
654			bzero(mbp, sizeof(struct msgbuf));
655			mbp->msg_magic = MSG_MAGIC;
656		}
657		mbp->msg_bufc[mbp->msg_bufx++] = c;
658		if (mbp->msg_bufx >= MSG_BSIZE)
659			mbp->msg_bufx = 0;
660		/* If the buffer is full, keep the most recent data. */
661		if (mbp->msg_bufr == mbp->msg_bufx) {
662			if (++mbp->msg_bufr >= MSG_BSIZE)
663				mbp->msg_bufr = 0;
664		}
665	}
666}
667