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