Home | History | Annotate | Line # | Download | only in kern
subr_prf.c revision 1.53
      1 /*	$NetBSD: subr_prf.c,v 1.53 1998/09/12 13:12:14 pk Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1986, 1988, 1991, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  * (c) UNIX System Laboratories, Inc.
      7  * All or some portions of this file are derived from material licensed
      8  * to the University of California by American Telephone and Telegraph
      9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     10  * the permission of UNIX System Laboratories, Inc.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. All advertising materials mentioning features or use of this software
     21  *    must display the following acknowledgement:
     22  *	This product includes software developed by the University of
     23  *	California, Berkeley and its contributors.
     24  * 4. Neither the name of the University nor the names of its contributors
     25  *    may be used to endorse or promote products derived from this software
     26  *    without specific prior written permission.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     38  * SUCH DAMAGE.
     39  *
     40  *	@(#)subr_prf.c	8.4 (Berkeley) 5/4/95
     41  */
     42 #include "opt_ddb.h"
     43 #include "ipkdb.h"
     44 
     45 #include <sys/param.h>
     46 #include <sys/systm.h>
     47 #include <sys/buf.h>
     48 #include <sys/conf.h>
     49 #include <sys/reboot.h>
     50 #include <sys/msgbuf.h>
     51 #include <sys/proc.h>
     52 #include <sys/ioctl.h>
     53 #include <sys/vnode.h>
     54 #include <sys/file.h>
     55 #include <sys/tty.h>
     56 #include <sys/tprintf.h>
     57 #include <sys/syslog.h>
     58 #include <sys/malloc.h>
     59 
     60 #include <dev/cons.h>
     61 
     62 #ifdef DDB
     63 #include <ddb/ddbvar.h>
     64 #endif
     65 
     66 
     67 /*
     68  * note that stdarg.h and the ansi style va_start macro is used for both
     69  * ansi and traditional c complers.
     70  * XXX: this requires that stdarg.h define: va_alist and va_dcl
     71  */
     72 #include <machine/stdarg.h>
     73 
     74 
     75 #ifdef KGDB
     76 #include <sys/kgdb.h>
     77 #include <machine/cpu.h>
     78 #endif
     79 #ifdef DDB
     80 #include <ddb/db_output.h>	/* db_printf, db_putchar prototypes */
     81 extern	int db_radix;		/* XXX: for non-standard '%r' format */
     82 #endif
     83 
     84 
     85 /*
     86  * defines
     87  */
     88 
     89 /* flags for kprintf */
     90 #define TOCONS		0x01	/* to the console */
     91 #define TOTTY		0x02	/* to the process' tty */
     92 #define TOLOG		0x04	/* to the kernel message buffer */
     93 #define TOBUFONLY	0x08	/* to the buffer (only) [for sprintf] */
     94 #define TODDB		0x10	/* to ddb console */
     95 
     96 /* max size buffer kprintf needs to print quad_t [size in base 8 + \0] */
     97 #define KPRINTF_BUFSIZE		(sizeof(quad_t) * NBBY / 3 + 2)
     98 
     99 
    100 /*
    101  * local prototypes
    102  */
    103 
    104 static int	 kprintf __P((const char *, int, struct tty *,
    105 				char *, va_list));
    106 static void	 putchar __P((int, int, struct tty *));
    107 
    108 
    109 /*
    110  * globals
    111  */
    112 
    113 struct	tty *constty;	/* pointer to console "window" tty */
    114 int	consintr = 1;	/* ok to handle console interrupts? */
    115 extern	int log_open;	/* subr_log: is /dev/klog open? */
    116 const	char *panicstr; /* arg to first call to panic (used as a flag
    117 			   to indicate that panic has already been called). */
    118 
    119 /*
    120  * v_putc: routine to putc on virtual console
    121  *
    122  * the v_putc pointer can be used to redirect the console cnputc elsewhere
    123  * [e.g. to a "virtual console"].
    124  */
    125 
    126 void (*v_putc) __P((int)) = cnputc;	/* start with cnputc (normal cons) */
    127 
    128 
    129 /*
    130  * functions
    131  */
    132 
    133 /*
    134  * tablefull: warn that a system table is full
    135  */
    136 
    137 void
    138 tablefull(tab)
    139 	const char *tab;
    140 {
    141 	log(LOG_ERR, "%s: table is full\n", tab);
    142 }
    143 
    144 /*
    145  * panic: handle an unresolvable fatal error
    146  *
    147  * prints "panic: <message>" and reboots.   if called twice (i.e. recursive
    148  * call) we avoid trying to sync the disk and just reboot (to avoid
    149  * recursive panics).
    150  */
    151 
    152 void
    153 #ifdef __STDC__
    154 panic(const char *fmt, ...)
    155 #else
    156 panic(fmt, va_alist)
    157 	char *fmt;
    158 	va_dcl
    159 #endif
    160 {
    161 	int bootopt;
    162 	va_list ap;
    163 
    164 	bootopt = RB_AUTOBOOT | RB_DUMP;
    165 	if (panicstr)
    166 		bootopt |= RB_NOSYNC;
    167 	else
    168 		panicstr = fmt;
    169 
    170 	va_start(ap, fmt);
    171 	printf("panic: ");
    172 	vprintf(fmt, ap);
    173 	printf("\n");
    174 	va_end(ap);
    175 
    176 #if NIPKDB > 0
    177 	ipkdb_panic();
    178 #endif
    179 #ifdef KGDB
    180 	kgdb_panic();
    181 #endif
    182 #ifdef KADB
    183 	if (boothowto & RB_KDB)
    184 		kdbpanic();
    185 #endif
    186 #ifdef DDB
    187 	if (db_onpanic)
    188 		Debugger();
    189 #endif
    190 	cpu_reboot(bootopt, NULL);
    191 }
    192 
    193 /*
    194  * kernel logging functions: log, logpri, addlog
    195  */
    196 
    197 /*
    198  * log: write to the log buffer
    199  *
    200  * => will not sleep [so safe to call from interrupt]
    201  * => will log to console if /dev/klog isn't open
    202  */
    203 
    204 void
    205 #ifdef __STDC__
    206 log(int level, const char *fmt, ...)
    207 #else
    208 log(level, fmt, va_alist)
    209 	int level;
    210 	char *fmt;
    211 	va_dcl
    212 #endif
    213 {
    214 	register int s;
    215 	va_list ap;
    216 
    217 	s = splhigh();
    218 	logpri(level);		/* log the level first */
    219 	va_start(ap, fmt);
    220 	kprintf(fmt, TOLOG, NULL, NULL, ap);
    221 	splx(s);
    222 	va_end(ap);
    223 	if (!log_open) {
    224 		va_start(ap, fmt);
    225 		kprintf(fmt, TOCONS, NULL, NULL, ap);
    226 		va_end(ap);
    227 	}
    228 	logwakeup();		/* wake up anyone waiting for log msgs */
    229 }
    230 
    231 /*
    232  * logpri: log the priority level to the klog
    233  */
    234 
    235 void			/* XXXCDC: should be static? */
    236 logpri(level)
    237 	int level;
    238 {
    239 	char *p;
    240 	char snbuf[KPRINTF_BUFSIZE];
    241 
    242 	putchar('<', TOLOG, NULL);
    243 	sprintf(snbuf, "%d", level);
    244 	for (p = snbuf ; *p ; p++)
    245 		putchar(*p, TOLOG, NULL);
    246 	putchar('>', TOLOG, NULL);
    247 }
    248 
    249 /*
    250  * addlog: add info to previous log message
    251  */
    252 
    253 void
    254 #ifdef __STDC__
    255 addlog(const char *fmt, ...)
    256 #else
    257 addlog(fmt, va_alist)
    258 	char *fmt;
    259 	va_dcl
    260 #endif
    261 {
    262 	register int s;
    263 	va_list ap;
    264 
    265 	s = splhigh();
    266 	va_start(ap, fmt);
    267 	kprintf(fmt, TOLOG, NULL, NULL, ap);
    268 	splx(s);
    269 	va_end(ap);
    270 	if (!log_open) {
    271 		va_start(ap, fmt);
    272 		kprintf(fmt, TOCONS, NULL, NULL, ap);
    273 		va_end(ap);
    274 	}
    275 	logwakeup();
    276 }
    277 
    278 
    279 /*
    280  * putchar: print a single character on console or user terminal.
    281  *
    282  * => if console, then the last MSGBUFS chars are saved in msgbuf
    283  *	for inspection later (e.g. dmesg/syslog)
    284  */
    285 static void
    286 putchar(c, flags, tp)
    287 	register int c;
    288 	int flags;
    289 	struct tty *tp;
    290 {
    291 	register struct kern_msgbuf *mbp;
    292 
    293 	if (panicstr)
    294 		constty = NULL;
    295 	if ((flags & TOCONS) && tp == NULL && constty) {
    296 		tp = constty;
    297 		flags |= TOTTY;
    298 	}
    299 	if ((flags & TOTTY) && tp && tputchar(c, tp) < 0 &&
    300 	    (flags & TOCONS) && tp == constty)
    301 		constty = NULL;
    302 	if ((flags & TOLOG) &&
    303 	    c != '\0' && c != '\r' && c != 0177 && msgbufenabled) {
    304 		mbp = msgbufp;
    305 		if (mbp->msg_magic != MSG_MAGIC) {
    306 			/*
    307 			 * Arguably should panic or somehow notify the
    308 			 * user...  but how?  Panic may be too drastic,
    309 			 * and would obliterate the message being kicked
    310 			 * out (maybe a panic itself), and printf
    311 			 * would invoke us recursively.  Silently punt
    312 			 * for now.  If syslog is running, it should
    313 			 * notice.
    314 			 */
    315 			msgbufenabled = 0;
    316 		} else {
    317 			mbp->msg_bufc[mbp->msg_bufx++] = c;
    318 			if (mbp->msg_bufx < 0 || mbp->msg_bufx >= mbp->msg_bufs)
    319 				mbp->msg_bufx = 0;
    320 			/* If the buffer is full, keep the most recent data. */
    321 			if (mbp->msg_bufr == mbp->msg_bufx) {
    322 				 if (++mbp->msg_bufr >= mbp->msg_bufs)
    323 					mbp->msg_bufr = 0;
    324 			}
    325 		}
    326 	}
    327 	if ((flags & TOCONS) && constty == NULL && c != '\0')
    328 		(*v_putc)(c);
    329 #ifdef DDB
    330 	if (flags & TODDB)
    331 		db_putchar(c);
    332 #endif
    333 }
    334 
    335 
    336 /*
    337  * uprintf: print to the controlling tty of the current process
    338  *
    339  * => we may block if the tty queue is full
    340  * => no message is printed if the queue doesn't clear in a reasonable
    341  *	time
    342  */
    343 
    344 void
    345 #ifdef __STDC__
    346 uprintf(const char *fmt, ...)
    347 #else
    348 uprintf(fmt, va_alist)
    349 	char *fmt;
    350 	va_dcl
    351 #endif
    352 {
    353 	register struct proc *p = curproc;
    354 	va_list ap;
    355 
    356 	if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
    357 		va_start(ap, fmt);
    358 		kprintf(fmt, TOTTY, p->p_session->s_ttyp, NULL, ap);
    359 		va_end(ap);
    360 	}
    361 }
    362 
    363 /*
    364  * tprintf functions: used to send messages to a specific process
    365  *
    366  * usage:
    367  *   get a tpr_t handle on a process "p" by using "tprintf_open(p)"
    368  *   use the handle when calling "tprintf"
    369  *   when done, do a "tprintf_close" to drop the handle
    370  */
    371 
    372 /*
    373  * tprintf_open: get a tprintf handle on a process "p"
    374  *
    375  * => returns NULL if process can't be printed to
    376  */
    377 
    378 tpr_t
    379 tprintf_open(p)
    380 	register struct proc *p;
    381 {
    382 
    383 	if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
    384 		SESSHOLD(p->p_session);
    385 		return ((tpr_t) p->p_session);
    386 	}
    387 	return ((tpr_t) NULL);
    388 }
    389 
    390 /*
    391  * tprintf_close: dispose of a tprintf handle obtained with tprintf_open
    392  */
    393 
    394 void
    395 tprintf_close(sess)
    396 	tpr_t sess;
    397 {
    398 
    399 	if (sess)
    400 		SESSRELE((struct session *) sess);
    401 }
    402 
    403 /*
    404  * tprintf: given tprintf handle to a process [obtained with tprintf_open],
    405  * send a message to the controlling tty for that process.
    406  *
    407  * => also sends message to /dev/klog
    408  */
    409 void
    410 #ifdef __STDC__
    411 tprintf(tpr_t tpr, const char *fmt, ...)
    412 #else
    413 tprintf(tpr, fmt, va_alist)
    414 	tpr_t tpr;
    415 	char *fmt;
    416 	va_dcl
    417 #endif
    418 {
    419 	register struct session *sess = (struct session *)tpr;
    420 	struct tty *tp = NULL;
    421 	int flags = TOLOG;
    422 	va_list ap;
    423 
    424 	logpri(LOG_INFO);
    425 	if (sess && sess->s_ttyvp && ttycheckoutq(sess->s_ttyp, 0)) {
    426 		flags |= TOTTY;
    427 		tp = sess->s_ttyp;
    428 	}
    429 	va_start(ap, fmt);
    430 	kprintf(fmt, flags, tp, NULL, ap);
    431 	va_end(ap);
    432 	logwakeup();
    433 }
    434 
    435 
    436 /*
    437  * ttyprintf: send a message to a specific tty
    438  *
    439  * => should be used only by tty driver or anything that knows the
    440  *    underlying tty will not be revoked(2)'d away.  [otherwise,
    441  *    use tprintf]
    442  */
    443 void
    444 #ifdef __STDC__
    445 ttyprintf(struct tty *tp, const char *fmt, ...)
    446 #else
    447 ttyprintf(tp, fmt, va_alist)
    448 	struct tty *tp;
    449 	char *fmt;
    450 	va_dcl
    451 #endif
    452 {
    453 	va_list ap;
    454 
    455 	va_start(ap, fmt);
    456 	kprintf(fmt, TOTTY, tp, NULL, ap);
    457 	va_end(ap);
    458 }
    459 
    460 #ifdef DDB
    461 
    462 /*
    463  * db_printf: printf for DDB (via db_putchar)
    464  */
    465 
    466 void
    467 #ifdef __STDC__
    468 db_printf(const char *fmt, ...)
    469 #else
    470 db_printf(fmt, va_alist)
    471 	char *fmt;
    472 	va_dcl
    473 #endif
    474 {
    475 	va_list ap;
    476 
    477 	va_start(ap, fmt);
    478 	kprintf(fmt, TODDB, NULL, NULL, ap);
    479 	va_end(ap);
    480 }
    481 
    482 #endif /* DDB */
    483 
    484 
    485 /*
    486  * normal kernel printf functions: printf, vprintf, sprintf
    487  */
    488 
    489 /*
    490  * printf: print a message to the console and the log
    491  */
    492 void
    493 #ifdef __STDC__
    494 printf(const char *fmt, ...)
    495 #else
    496 printf(fmt, va_alist)
    497 	char *fmt;
    498 	va_dcl
    499 #endif
    500 {
    501 	va_list ap;
    502 	int savintr;
    503 
    504 	savintr = consintr;		/* disable interrupts */
    505 	consintr = 0;
    506 	va_start(ap, fmt);
    507 	kprintf(fmt, TOCONS | TOLOG, NULL, NULL, ap);
    508 	va_end(ap);
    509 	if (!panicstr)
    510 		logwakeup();
    511 	consintr = savintr;		/* reenable interrupts */
    512 }
    513 
    514 /*
    515  * vprintf: print a message to the console and the log [already have
    516  *	va_alist]
    517  */
    518 
    519 void
    520 vprintf(fmt, ap)
    521 	const char *fmt;
    522 	va_list ap;
    523 {
    524 	int savintr;
    525 
    526 	savintr = consintr;		/* disable interrupts */
    527 	consintr = 0;
    528 	kprintf(fmt, TOCONS | TOLOG, NULL, NULL, ap);
    529 	if (!panicstr)
    530 		logwakeup();
    531 	consintr = savintr;		/* reenable interrupts */
    532 }
    533 
    534 /*
    535  * sprintf: print a message to a buffer
    536  */
    537 int
    538 #ifdef __STDC__
    539 sprintf(char *buf, const char *fmt, ...)
    540 #else
    541 sprintf(buf, fmt, va_alist)
    542         char *buf;
    543         const char *cfmt;
    544         va_dcl
    545 #endif
    546 {
    547 	int retval;
    548 	va_list ap;
    549 
    550 	va_start(ap, fmt);
    551 	retval = kprintf(fmt, TOBUFONLY, NULL, buf, ap);
    552 	va_end(ap);
    553 	*(buf + retval) = 0;	/* null terminate */
    554 	return(retval);
    555 }
    556 
    557 /*
    558  * bitmask_snprintf: print a kernel-printf "%b" message to a buffer
    559  *
    560  * => returns pointer to the buffer
    561  * => XXX: useful vs. kernel %b?
    562  */
    563 char *
    564 bitmask_snprintf(val, p, buf, buflen)
    565 	u_quad_t val;
    566 	const char *p;
    567 	char *buf;
    568 	size_t buflen;
    569 {
    570 	char *bp, *q;
    571 	size_t left;
    572 	char *sbase, snbuf[KPRINTF_BUFSIZE];
    573 	int base, bit, ch, len, sep;
    574 	u_quad_t field;
    575 
    576 	bp = buf;
    577 	memset(buf, 0, buflen);
    578 
    579 	/*
    580 	 * Always leave room for the trailing NULL.
    581 	 */
    582 	left = buflen - 1;
    583 
    584 	/*
    585 	 * Print the value into the buffer.  Abort if there's not
    586 	 * enough room.
    587 	 */
    588 	if (buflen < KPRINTF_BUFSIZE)
    589 		return (buf);
    590 
    591 	ch = *p++;
    592 	base = ch != '\177' ? ch : *p++;
    593 	sbase = base == 8 ? "%qo" : base == 10 ? "%qd" : base == 16 ? "%qx" : 0;
    594 	if (sbase == 0)
    595 		return (buf);	/* punt if not oct, dec, or hex */
    596 
    597 	sprintf(snbuf, sbase, val);
    598 	for (q = snbuf ; *q ; q++) {
    599 		*bp++ = *q;
    600 		left--;
    601 	}
    602 
    603 	/*
    604 	 * If the value we printed was 0, or if we don't have room for
    605 	 * "<x>", we're done.
    606 	 */
    607 	if (val == 0 || left < 3)
    608 		return (buf);
    609 
    610 #define PUTBYTE(b, c, l)	\
    611 	*(b)++ = (c);		\
    612 	if (--(l) == 0)		\
    613 		goto out;
    614 #define PUTSTR(b, p, l) do {		\
    615 	int c;				\
    616 	while ((c = *(p)++) != 0) {	\
    617 		*(b)++ = c;		\
    618 		if (--(l) == 0)		\
    619 			goto out;	\
    620 	}				\
    621 } while (0)
    622 
    623 	/*
    624 	 * Chris Torek's new style %b format is identified by a leading \177
    625 	 */
    626 	sep = '<';
    627 	if (ch != '\177') {
    628 		/* old (standard) %b format. */
    629 		for (;(bit = *p++) != 0;) {
    630 			if (val & (1 << (bit - 1))) {
    631 				PUTBYTE(bp, sep, left);
    632 				for (; (ch = *p) > ' '; ++p) {
    633 					PUTBYTE(bp, ch, left);
    634 				}
    635 				sep = ',';
    636 			} else
    637 				for (; *p > ' '; ++p)
    638 					continue;
    639 		}
    640 	} else {
    641 		/* new quad-capable %b format; also does fields. */
    642 		field = val;
    643 		while ((ch = *p++) != '\0') {
    644 			bit = *p++;	/* now 0-origin */
    645 			switch (ch) {
    646 			case 'b':
    647 				if (((u_int)(val >> bit) & 1) == 0)
    648 					goto skip;
    649 				PUTBYTE(bp, sep, left);
    650 				PUTSTR(bp, p, left);
    651 				sep = ',';
    652 				break;
    653 			case 'f':
    654 			case 'F':
    655 				len = *p++;	/* field length */
    656 				field = (val >> bit) & ((1ULL << len) - 1);
    657 				if (ch == 'F')	/* just extract */
    658 					break;
    659 				PUTBYTE(bp, sep, left);
    660 				sep = ',';
    661 				PUTSTR(bp, p, left);
    662 				PUTBYTE(bp, '=', left);
    663 				sprintf(snbuf, sbase, field);
    664 				q = snbuf; PUTSTR(bp, q, left);
    665 				break;
    666 			case '=':
    667 			case ':':
    668 				/*
    669 				 * Here "bit" is actually a value instead,
    670 				 * to be compared against the last field.
    671 				 * This only works for values in [0..255],
    672 				 * of course.
    673 				 */
    674 				if ((int)field != bit)
    675 					goto skip;
    676 				if (ch == '=')
    677 					PUTBYTE(bp, '=', left);
    678 				PUTSTR(bp, p, left);
    679 				break;
    680 			default:
    681 			skip:
    682 				while (*p++ != '\0')
    683 					continue;
    684 				break;
    685 			}
    686 		}
    687 	}
    688 	if (sep != '<')
    689 		PUTBYTE(bp, '>', left);
    690 
    691 out:
    692 	return (buf);
    693 
    694 #undef PUTBYTE
    695 #undef PUTSTR
    696 }
    697 
    698 /*
    699  * kprintf: scaled down version of printf(3).
    700  *
    701  * this version based on vfprintf() from libc which was derived from
    702  * software contributed to Berkeley by Chris Torek.
    703  *
    704  * Two additional formats:
    705  *
    706  * The format %b is supported to decode error registers.
    707  * Its usage is:
    708  *
    709  *	printf("reg=%b\n", regval, "<base><arg>*");
    710  *
    711  * where <base> is the output base expressed as a control character, e.g.
    712  * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
    713  * the first of which gives the bit number to be inspected (origin 1), and
    714  * the next characters (up to a control character, i.e. a character <= 32),
    715  * give the name of the register.  Thus:
    716  *
    717  *	kprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
    718  *
    719  * would produce output:
    720  *
    721  *	reg=3<BITTWO,BITONE>
    722  *
    723  * The format %: passes an additional format string and argument list
    724  * recursively.  Its usage is:
    725  *
    726  * fn(char *fmt, ...)
    727  * {
    728  *	va_list ap;
    729  *	va_start(ap, fmt);
    730  *	printf("prefix: %: suffix\n", fmt, ap);
    731  *	va_end(ap);
    732  * }
    733  *
    734  * this is the actual printf innards
    735  *
    736  * This code is large and complicated...
    737  */
    738 
    739 /*
    740  * macros for converting digits to letters and vice versa
    741  */
    742 #define	to_digit(c)	((c) - '0')
    743 #define is_digit(c)	((unsigned)to_digit(c) <= 9)
    744 #define	to_char(n)	((n) + '0')
    745 
    746 /*
    747  * flags used during conversion.
    748  */
    749 #define	ALT		0x001		/* alternate form */
    750 #define	HEXPREFIX	0x002		/* add 0x or 0X prefix */
    751 #define	LADJUST		0x004		/* left adjustment */
    752 #define	LONGDBL		0x008		/* long double; unimplemented */
    753 #define	LONGINT		0x010		/* long integer */
    754 #define	QUADINT		0x020		/* quad integer */
    755 #define	SHORTINT	0x040		/* short integer */
    756 #define	ZEROPAD		0x080		/* zero (as opposed to blank) pad */
    757 #define FPT		0x100		/* Floating point number */
    758 
    759 	/*
    760 	 * To extend shorts properly, we need both signed and unsigned
    761 	 * argument extraction methods.
    762 	 */
    763 #define	SARG() \
    764 	(flags&QUADINT ? va_arg(ap, quad_t) : \
    765 	    flags&LONGINT ? va_arg(ap, long) : \
    766 	    flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
    767 	    (long)va_arg(ap, int))
    768 #define	UARG() \
    769 	(flags&QUADINT ? va_arg(ap, u_quad_t) : \
    770 	    flags&LONGINT ? va_arg(ap, u_long) : \
    771 	    flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \
    772 	    (u_long)va_arg(ap, u_int))
    773 
    774 #define KPRINTF_PUTCHAR(C) \
    775 	(oflags == TOBUFONLY) ? *sbuf++ = (C) : putchar((C), oflags, tp);
    776 
    777 int
    778 kprintf(fmt0, oflags, tp, sbuf, ap)
    779 	const char *fmt0;
    780 	int oflags;
    781 	struct tty *tp;
    782 	char *sbuf;
    783 	va_list ap;
    784 {
    785 	char *fmt;		/* format string */
    786 	int ch;			/* character from fmt */
    787 	int n;			/* handy integer (short term usage) */
    788 	char *cp;		/* handy char pointer (short term usage) */
    789 	int flags;		/* flags as above */
    790 	int ret;		/* return value accumulator */
    791 	int width;		/* width from format (%8d), or 0 */
    792 	int prec;		/* precision from format (%.3d), or -1 */
    793 	char sign;		/* sign prefix (' ', '+', '-', or \0) */
    794 
    795 	u_quad_t _uquad;	/* integer arguments %[diouxX] */
    796 	enum { OCT, DEC, HEX } base;/* base for [diouxX] conversion */
    797 	int dprec;		/* a copy of prec if [diouxX], 0 otherwise */
    798 	int realsz;		/* field size expanded by dprec */
    799 	int size;		/* size of converted field or string */
    800 	char *xdigs;		/* digits for [xX] conversion */
    801 	char buf[KPRINTF_BUFSIZE]; /* space for %c, %[diouxX] */
    802 
    803 	cp = NULL;	/* XXX: shutup gcc */
    804 	size = 0;	/* XXX: shutup gcc */
    805 
    806 	fmt = (char *)fmt0;
    807 	ret = 0;
    808 
    809 	xdigs = NULL;		/* XXX: shut up gcc warning */
    810 
    811 	/*
    812 	 * Scan the format for conversions (`%' character).
    813 	 */
    814 	for (;;) {
    815 		while (*fmt != '%' && *fmt) {
    816 			KPRINTF_PUTCHAR(*fmt++);
    817 			ret++;
    818 		}
    819 		if (*fmt == 0)
    820 			goto done;
    821 
    822 		fmt++;		/* skip over '%' */
    823 
    824 		flags = 0;
    825 		dprec = 0;
    826 		width = 0;
    827 		prec = -1;
    828 		sign = '\0';
    829 
    830 rflag:		ch = *fmt++;
    831 reswitch:	switch (ch) {
    832 		/* XXX: non-standard '%:' format */
    833 #ifndef __powerpc__
    834 		case ':':
    835 			if (oflags != TOBUFONLY) {
    836 				cp = va_arg(ap, char *);
    837 				kprintf(cp, oflags, tp,
    838 					NULL, va_arg(ap, va_list));
    839 			}
    840 			continue;	/* no output */
    841 #endif
    842 		/* XXX: non-standard '%b' format */
    843 		case 'b': {
    844 			char *b, *z;
    845 			int tmp;
    846 			_uquad = va_arg(ap, int);
    847 			b = va_arg(ap, char *);
    848 			if (*b == 8)
    849 				sprintf(buf, "%qo", _uquad);
    850 			else if (*b == 10)
    851 				sprintf(buf, "%qd", _uquad);
    852 			else if (*b == 16)
    853 				sprintf(buf, "%qx", _uquad);
    854 			else
    855 				break;
    856 			b++;
    857 
    858 			z = buf;
    859 			while (*z) {
    860 				KPRINTF_PUTCHAR(*z++);
    861 				ret++;
    862 			}
    863 
    864 			if (_uquad) {
    865 				tmp = 0;
    866 				while ((n = *b++) != 0) {
    867 					if (_uquad & (1 << (n - 1))) {
    868 						KPRINTF_PUTCHAR(tmp ? ',':'<');
    869 						ret++;
    870 						while ((n = *b) > ' ') {
    871 							KPRINTF_PUTCHAR(n);
    872 							ret++;
    873 							b++;
    874 						}
    875 						tmp = 1;
    876 					} else {
    877 						while(*b > ' ')
    878 							b++;
    879 					}
    880 				}
    881 				if (tmp) {
    882 					KPRINTF_PUTCHAR('>');
    883 					ret++;
    884 				}
    885 			}
    886 			continue;	/* no output */
    887 		}
    888 
    889 #ifdef DDB
    890 		/* XXX: non-standard '%r' format (print int in db_radix) */
    891 		case 'r':
    892 			if ((oflags & TODDB) == 0)
    893 				goto default_case;
    894 
    895 			if (db_radix == 16)
    896 				goto case_z;	/* signed hex */
    897 			_uquad = SARG();
    898 			if ((quad_t)_uquad < 0) {
    899 				_uquad = -_uquad;
    900 				sign = '-';
    901 			}
    902 			base = (db_radix == 8) ? OCT : DEC;
    903 			goto number;
    904 
    905 
    906 		/* XXX: non-standard '%z' format ("signed hex", a "hex %i")*/
    907 		case 'z':
    908 		case_z:
    909 			if ((oflags & TODDB) == 0)
    910 				goto default_case;
    911 
    912 			xdigs = "0123456789abcdef";
    913 			ch = 'x';	/* the 'x' in '0x' (below) */
    914 			_uquad = SARG();
    915 			base = HEX;
    916 			/* leading 0x/X only if non-zero */
    917 			if (flags & ALT && _uquad != 0)
    918 				flags |= HEXPREFIX;
    919 			if ((quad_t)_uquad < 0) {
    920 				_uquad = -_uquad;
    921 				sign = '-';
    922 			}
    923 			goto number;
    924 #endif
    925 
    926 		case ' ':
    927 			/*
    928 			 * ``If the space and + flags both appear, the space
    929 			 * flag will be ignored.''
    930 			 *	-- ANSI X3J11
    931 			 */
    932 			if (!sign)
    933 				sign = ' ';
    934 			goto rflag;
    935 		case '#':
    936 			flags |= ALT;
    937 			goto rflag;
    938 		case '*':
    939 			/*
    940 			 * ``A negative field width argument is taken as a
    941 			 * - flag followed by a positive field width.''
    942 			 *	-- ANSI X3J11
    943 			 * They don't exclude field widths read from args.
    944 			 */
    945 			if ((width = va_arg(ap, int)) >= 0)
    946 				goto rflag;
    947 			width = -width;
    948 			/* FALLTHROUGH */
    949 		case '-':
    950 			flags |= LADJUST;
    951 			goto rflag;
    952 		case '+':
    953 			sign = '+';
    954 			goto rflag;
    955 		case '.':
    956 			if ((ch = *fmt++) == '*') {
    957 				n = va_arg(ap, int);
    958 				prec = n < 0 ? -1 : n;
    959 				goto rflag;
    960 			}
    961 			n = 0;
    962 			while (is_digit(ch)) {
    963 				n = 10 * n + to_digit(ch);
    964 				ch = *fmt++;
    965 			}
    966 			prec = n < 0 ? -1 : n;
    967 			goto reswitch;
    968 		case '0':
    969 			/*
    970 			 * ``Note that 0 is taken as a flag, not as the
    971 			 * beginning of a field width.''
    972 			 *	-- ANSI X3J11
    973 			 */
    974 			flags |= ZEROPAD;
    975 			goto rflag;
    976 		case '1': case '2': case '3': case '4':
    977 		case '5': case '6': case '7': case '8': case '9':
    978 			n = 0;
    979 			do {
    980 				n = 10 * n + to_digit(ch);
    981 				ch = *fmt++;
    982 			} while (is_digit(ch));
    983 			width = n;
    984 			goto reswitch;
    985 		case 'h':
    986 			flags |= SHORTINT;
    987 			goto rflag;
    988 		case 'l':
    989 			if (*fmt == 'l') {
    990 				fmt++;
    991 				flags |= QUADINT;
    992 			} else {
    993 				flags |= LONGINT;
    994 			}
    995 			goto rflag;
    996 		case 'q':
    997 			flags |= QUADINT;
    998 			goto rflag;
    999 		case 'c':
   1000 			*(cp = buf) = va_arg(ap, int);
   1001 			size = 1;
   1002 			sign = '\0';
   1003 			break;
   1004 		case 'D':
   1005 			flags |= LONGINT;
   1006 			/*FALLTHROUGH*/
   1007 		case 'd':
   1008 		case 'i':
   1009 			_uquad = SARG();
   1010 			if ((quad_t)_uquad < 0) {
   1011 				_uquad = -_uquad;
   1012 				sign = '-';
   1013 			}
   1014 			base = DEC;
   1015 			goto number;
   1016 		case 'n':
   1017 #ifdef DDB
   1018 		/* XXX: non-standard '%n' format */
   1019 		/*
   1020 		 * XXX: HACK!   DDB wants '%n' to be a '%u' printed
   1021 		 * in db_radix format.   this should die since '%n'
   1022 		 * is already defined in standard printf to write
   1023 		 * the number of chars printed so far to the arg (which
   1024 		 * should be a pointer.
   1025 		 */
   1026 			if (oflags & TODDB) {
   1027 				if (db_radix == 16)
   1028 					ch = 'x';	/* convert to %x */
   1029 				else if (db_radix == 8)
   1030 					ch = 'o';	/* convert to %o */
   1031 				else
   1032 					ch = 'u';	/* convert to %u */
   1033 
   1034 				/* ... and start again */
   1035 				goto reswitch;
   1036 			}
   1037 
   1038 #endif
   1039 			if (flags & QUADINT)
   1040 				*va_arg(ap, quad_t *) = ret;
   1041 			else if (flags & LONGINT)
   1042 				*va_arg(ap, long *) = ret;
   1043 			else if (flags & SHORTINT)
   1044 				*va_arg(ap, short *) = ret;
   1045 			else
   1046 				*va_arg(ap, int *) = ret;
   1047 			continue;	/* no output */
   1048 		case 'O':
   1049 			flags |= LONGINT;
   1050 			/*FALLTHROUGH*/
   1051 		case 'o':
   1052 			_uquad = UARG();
   1053 			base = OCT;
   1054 			goto nosign;
   1055 		case 'p':
   1056 			/*
   1057 			 * ``The argument shall be a pointer to void.  The
   1058 			 * value of the pointer is converted to a sequence
   1059 			 * of printable characters, in an implementation-
   1060 			 * defined manner.''
   1061 			 *	-- ANSI X3J11
   1062 			 */
   1063 			/* NOSTRICT */
   1064 			_uquad = (u_long)va_arg(ap, void *);
   1065 			base = HEX;
   1066 			xdigs = "0123456789abcdef";
   1067 			flags |= HEXPREFIX;
   1068 			ch = 'x';
   1069 			goto nosign;
   1070 		case 's':
   1071 			if ((cp = va_arg(ap, char *)) == NULL)
   1072 				cp = "(null)";
   1073 			if (prec >= 0) {
   1074 				/*
   1075 				 * can't use strlen; can only look for the
   1076 				 * NUL in the first `prec' characters, and
   1077 				 * strlen() will go further.
   1078 				 */
   1079 				char *p = memchr(cp, 0, prec);
   1080 
   1081 				if (p != NULL) {
   1082 					size = p - cp;
   1083 					if (size > prec)
   1084 						size = prec;
   1085 				} else
   1086 					size = prec;
   1087 			} else
   1088 				size = strlen(cp);
   1089 			sign = '\0';
   1090 			break;
   1091 		case 'U':
   1092 			flags |= LONGINT;
   1093 			/*FALLTHROUGH*/
   1094 		case 'u':
   1095 			_uquad = UARG();
   1096 			base = DEC;
   1097 			goto nosign;
   1098 		case 'X':
   1099 			xdigs = "0123456789ABCDEF";
   1100 			goto hex;
   1101 		case 'x':
   1102 			xdigs = "0123456789abcdef";
   1103 hex:			_uquad = UARG();
   1104 			base = HEX;
   1105 			/* leading 0x/X only if non-zero */
   1106 			if (flags & ALT && _uquad != 0)
   1107 				flags |= HEXPREFIX;
   1108 
   1109 			/* unsigned conversions */
   1110 nosign:			sign = '\0';
   1111 			/*
   1112 			 * ``... diouXx conversions ... if a precision is
   1113 			 * specified, the 0 flag will be ignored.''
   1114 			 *	-- ANSI X3J11
   1115 			 */
   1116 number:			if ((dprec = prec) >= 0)
   1117 				flags &= ~ZEROPAD;
   1118 
   1119 			/*
   1120 			 * ``The result of converting a zero value with an
   1121 			 * explicit precision of zero is no characters.''
   1122 			 *	-- ANSI X3J11
   1123 			 */
   1124 			cp = buf + KPRINTF_BUFSIZE;
   1125 			if (_uquad != 0 || prec != 0) {
   1126 				/*
   1127 				 * Unsigned mod is hard, and unsigned mod
   1128 				 * by a constant is easier than that by
   1129 				 * a variable; hence this switch.
   1130 				 */
   1131 				switch (base) {
   1132 				case OCT:
   1133 					do {
   1134 						*--cp = to_char(_uquad & 7);
   1135 						_uquad >>= 3;
   1136 					} while (_uquad);
   1137 					/* handle octal leading 0 */
   1138 					if (flags & ALT && *cp != '0')
   1139 						*--cp = '0';
   1140 					break;
   1141 
   1142 				case DEC:
   1143 					/* many numbers are 1 digit */
   1144 					while (_uquad >= 10) {
   1145 						*--cp = to_char(_uquad % 10);
   1146 						_uquad /= 10;
   1147 					}
   1148 					*--cp = to_char(_uquad);
   1149 					break;
   1150 
   1151 				case HEX:
   1152 					do {
   1153 						*--cp = xdigs[_uquad & 15];
   1154 						_uquad >>= 4;
   1155 					} while (_uquad);
   1156 					break;
   1157 
   1158 				default:
   1159 					cp = "bug in kprintf: bad base";
   1160 					size = strlen(cp);
   1161 					goto skipsize;
   1162 				}
   1163 			}
   1164 			size = buf + KPRINTF_BUFSIZE - cp;
   1165 		skipsize:
   1166 			break;
   1167 		default:	/* "%?" prints ?, unless ? is NUL */
   1168 #ifdef DDB
   1169 		default_case:	/* DDB */
   1170 #endif
   1171 			if (ch == '\0')
   1172 				goto done;
   1173 			/* pretend it was %c with argument ch */
   1174 			cp = buf;
   1175 			*cp = ch;
   1176 			size = 1;
   1177 			sign = '\0';
   1178 			break;
   1179 		}
   1180 
   1181 		/*
   1182 		 * All reasonable formats wind up here.  At this point, `cp'
   1183 		 * points to a string which (if not flags&LADJUST) should be
   1184 		 * padded out to `width' places.  If flags&ZEROPAD, it should
   1185 		 * first be prefixed by any sign or other prefix; otherwise,
   1186 		 * it should be blank padded before the prefix is emitted.
   1187 		 * After any left-hand padding and prefixing, emit zeroes
   1188 		 * required by a decimal [diouxX] precision, then print the
   1189 		 * string proper, then emit zeroes required by any leftover
   1190 		 * floating precision; finally, if LADJUST, pad with blanks.
   1191 		 *
   1192 		 * Compute actual size, so we know how much to pad.
   1193 		 * size excludes decimal prec; realsz includes it.
   1194 		 */
   1195 		realsz = dprec > size ? dprec : size;
   1196 		if (sign)
   1197 			realsz++;
   1198 		else if (flags & HEXPREFIX)
   1199 			realsz+= 2;
   1200 
   1201 		/* right-adjusting blank padding */
   1202 		if ((flags & (LADJUST|ZEROPAD)) == 0) {
   1203 			n = width - realsz;
   1204 			while (n-- > 0)
   1205 				KPRINTF_PUTCHAR(' ');
   1206 		}
   1207 
   1208 		/* prefix */
   1209 		if (sign) {
   1210 			KPRINTF_PUTCHAR(sign);
   1211 		} else if (flags & HEXPREFIX) {
   1212 			KPRINTF_PUTCHAR('0');
   1213 			KPRINTF_PUTCHAR(ch);
   1214 		}
   1215 
   1216 		/* right-adjusting zero padding */
   1217 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD) {
   1218 			n = width - realsz;
   1219 			while (n-- > 0)
   1220 				KPRINTF_PUTCHAR('0');
   1221 		}
   1222 
   1223 		/* leading zeroes from decimal precision */
   1224 		n = dprec - size;
   1225 		while (n-- > 0)
   1226 			KPRINTF_PUTCHAR('0');
   1227 
   1228 		/* the string or number proper */
   1229 		while (size--)
   1230 			KPRINTF_PUTCHAR(*cp++);
   1231 		/* left-adjusting padding (always blank) */
   1232 		if (flags & LADJUST) {
   1233 			n = width - realsz;
   1234 			while (n-- > 0)
   1235 				KPRINTF_PUTCHAR(' ');
   1236 		}
   1237 
   1238 		/* finally, adjust ret */
   1239 		ret += width > realsz ? width : realsz;
   1240 
   1241 	}
   1242 done:
   1243 	return (ret);
   1244 	/* NOTREACHED */
   1245 }
   1246