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