Home | History | Annotate | Line # | Download | only in kern
subr_prf.c revision 1.51
      1 /*	$NetBSD: subr_prf.c,v 1.51 1998/08/23 22:42:32 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 	(p)++;				\
    622 } while (0)
    623 
    624 	/*
    625 	 * Chris Torek's new style %b format is identified by a leading \177
    626 	 */
    627 	sep = '<';
    628 	if (ch != '\177') {
    629 		/* old (standard) %b format. */
    630 		for (;(bit = *p++) != 0;) {
    631 			if (val & (1 << (bit - 1))) {
    632 				PUTBYTE(bp, sep, left);
    633 				for (; (ch = *p) > ' '; ++p) {
    634 					PUTBYTE(bp, ch, left);
    635 				}
    636 				sep = ',';
    637 			} else
    638 				for (; *p > ' '; ++p)
    639 					continue;
    640 		}
    641 	} else {
    642 		/* new quad-capable %b format; also does fields. */
    643 		field = val;
    644 		while ((ch = *p++) != '\0') {
    645 			bit = *p++;	/* now 0-origin */
    646 			switch (ch) {
    647 			case 'b':
    648 				if (((u_int)(val >> bit) & 1) == 0)
    649 					goto skip;
    650 				PUTBYTE(bp, sep, left);
    651 				PUTSTR(bp, p, left);
    652 				sep = ',';
    653 				break;
    654 			case 'f':
    655 			case 'F':
    656 				len = *p++;	/* field length */
    657 				field = (val >> bit) & ((1ULL << len) - 1);
    658 				if (ch == 'F')	/* just extract */
    659 					break;
    660 				PUTBYTE(bp, sep, left);
    661 				sep = ',';
    662 				PUTSTR(bp, p, left);
    663 				PUTBYTE(bp, '=', left);
    664 				sprintf(snbuf, sbase, field);
    665 				q = snbuf; PUTSTR(bp, q, left);
    666 				break;
    667 			case '=':
    668 			case ':':
    669 				/*
    670 				 * Here "bit" is actually a value instead,
    671 				 * to be compared against the last field.
    672 				 * This only works for values in [0..255],
    673 				 * of course.
    674 				 */
    675 				if ((int)field != bit)
    676 					goto skip;
    677 				if (ch == '=')
    678 					PUTBYTE(bp, '=', left);
    679 				PUTSTR(bp, p, left);
    680 				break;
    681 			default:
    682 			skip:
    683 				while (*p++ != '\0')
    684 					continue;
    685 				break;
    686 			}
    687 		}
    688 	}
    689 	if (sep != '<')
    690 		PUTBYTE(bp, '>', left);
    691 
    692 out:
    693 	return (buf);
    694 
    695 #undef PUTBYTE
    696 #undef PUTSTR
    697 }
    698 
    699 /*
    700  * kprintf: scaled down version of printf(3).
    701  *
    702  * this version based on vfprintf() from libc which was derived from
    703  * software contributed to Berkeley by Chris Torek.
    704  *
    705  * Two additional formats:
    706  *
    707  * The format %b is supported to decode error registers.
    708  * Its usage is:
    709  *
    710  *	printf("reg=%b\n", regval, "<base><arg>*");
    711  *
    712  * where <base> is the output base expressed as a control character, e.g.
    713  * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
    714  * the first of which gives the bit number to be inspected (origin 1), and
    715  * the next characters (up to a control character, i.e. a character <= 32),
    716  * give the name of the register.  Thus:
    717  *
    718  *	kprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
    719  *
    720  * would produce output:
    721  *
    722  *	reg=3<BITTWO,BITONE>
    723  *
    724  * The format %: passes an additional format string and argument list
    725  * recursively.  Its usage is:
    726  *
    727  * fn(char *fmt, ...)
    728  * {
    729  *	va_list ap;
    730  *	va_start(ap, fmt);
    731  *	printf("prefix: %: suffix\n", fmt, ap);
    732  *	va_end(ap);
    733  * }
    734  *
    735  * this is the actual printf innards
    736  *
    737  * This code is large and complicated...
    738  */
    739 
    740 /*
    741  * macros for converting digits to letters and vice versa
    742  */
    743 #define	to_digit(c)	((c) - '0')
    744 #define is_digit(c)	((unsigned)to_digit(c) <= 9)
    745 #define	to_char(n)	((n) + '0')
    746 
    747 /*
    748  * flags used during conversion.
    749  */
    750 #define	ALT		0x001		/* alternate form */
    751 #define	HEXPREFIX	0x002		/* add 0x or 0X prefix */
    752 #define	LADJUST		0x004		/* left adjustment */
    753 #define	LONGDBL		0x008		/* long double; unimplemented */
    754 #define	LONGINT		0x010		/* long integer */
    755 #define	QUADINT		0x020		/* quad integer */
    756 #define	SHORTINT	0x040		/* short integer */
    757 #define	ZEROPAD		0x080		/* zero (as opposed to blank) pad */
    758 #define FPT		0x100		/* Floating point number */
    759 
    760 	/*
    761 	 * To extend shorts properly, we need both signed and unsigned
    762 	 * argument extraction methods.
    763 	 */
    764 #define	SARG() \
    765 	(flags&QUADINT ? va_arg(ap, quad_t) : \
    766 	    flags&LONGINT ? va_arg(ap, long) : \
    767 	    flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
    768 	    (long)va_arg(ap, int))
    769 #define	UARG() \
    770 	(flags&QUADINT ? va_arg(ap, u_quad_t) : \
    771 	    flags&LONGINT ? va_arg(ap, u_long) : \
    772 	    flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \
    773 	    (u_long)va_arg(ap, u_int))
    774 
    775 #define KPRINTF_PUTCHAR(C) \
    776 	(oflags == TOBUFONLY) ? *sbuf++ = (C) : putchar((C), oflags, tp);
    777 
    778 int
    779 kprintf(fmt0, oflags, tp, sbuf, ap)
    780 	const char *fmt0;
    781 	int oflags;
    782 	struct tty *tp;
    783 	char *sbuf;
    784 	va_list ap;
    785 {
    786 	char *fmt;		/* format string */
    787 	int ch;			/* character from fmt */
    788 	int n;			/* handy integer (short term usage) */
    789 	char *cp;		/* handy char pointer (short term usage) */
    790 	int flags;		/* flags as above */
    791 	int ret;		/* return value accumulator */
    792 	int width;		/* width from format (%8d), or 0 */
    793 	int prec;		/* precision from format (%.3d), or -1 */
    794 	char sign;		/* sign prefix (' ', '+', '-', or \0) */
    795 
    796 	u_quad_t _uquad;	/* integer arguments %[diouxX] */
    797 	enum { OCT, DEC, HEX } base;/* base for [diouxX] conversion */
    798 	int dprec;		/* a copy of prec if [diouxX], 0 otherwise */
    799 	int realsz;		/* field size expanded by dprec */
    800 	int size;		/* size of converted field or string */
    801 	char *xdigs;		/* digits for [xX] conversion */
    802 	char buf[KPRINTF_BUFSIZE]; /* space for %c, %[diouxX] */
    803 
    804 	cp = NULL;	/* XXX: shutup gcc */
    805 	size = 0;	/* XXX: shutup gcc */
    806 
    807 	fmt = (char *)fmt0;
    808 	ret = 0;
    809 
    810 	xdigs = NULL;		/* XXX: shut up gcc warning */
    811 
    812 	/*
    813 	 * Scan the format for conversions (`%' character).
    814 	 */
    815 	for (;;) {
    816 		while (*fmt != '%' && *fmt) {
    817 			KPRINTF_PUTCHAR(*fmt++);
    818 			ret++;
    819 		}
    820 		if (*fmt == 0)
    821 			goto done;
    822 
    823 		fmt++;		/* skip over '%' */
    824 
    825 		flags = 0;
    826 		dprec = 0;
    827 		width = 0;
    828 		prec = -1;
    829 		sign = '\0';
    830 
    831 rflag:		ch = *fmt++;
    832 reswitch:	switch (ch) {
    833 		/* XXX: non-standard '%:' format */
    834 #ifndef __powerpc__
    835 		case ':':
    836 			if (oflags != TOBUFONLY) {
    837 				cp = va_arg(ap, char *);
    838 				kprintf(cp, oflags, tp,
    839 					NULL, va_arg(ap, va_list));
    840 			}
    841 			continue;	/* no output */
    842 #endif
    843 		/* XXX: non-standard '%b' format */
    844 		case 'b': {
    845 			char *b, *z;
    846 			int tmp;
    847 			_uquad = va_arg(ap, int);
    848 			b = va_arg(ap, char *);
    849 			if (*b == 8)
    850 				sprintf(buf, "%qo", _uquad);
    851 			else if (*b == 10)
    852 				sprintf(buf, "%qd", _uquad);
    853 			else if (*b == 16)
    854 				sprintf(buf, "%qx", _uquad);
    855 			else
    856 				break;
    857 			b++;
    858 
    859 			z = buf;
    860 			while (*z) {
    861 				KPRINTF_PUTCHAR(*z++);
    862 				ret++;
    863 			}
    864 
    865 			if (_uquad) {
    866 				tmp = 0;
    867 				while ((n = *b++) != 0) {
    868 					if (_uquad & (1 << (n - 1))) {
    869 						KPRINTF_PUTCHAR(tmp ? ',':'<');
    870 						ret++;
    871 						while ((n = *b) > ' ') {
    872 							KPRINTF_PUTCHAR(n);
    873 							ret++;
    874 							b++;
    875 						}
    876 						tmp = 1;
    877 					} else {
    878 						while(*b > ' ')
    879 							b++;
    880 					}
    881 				}
    882 				if (tmp) {
    883 					KPRINTF_PUTCHAR('>');
    884 					ret++;
    885 				}
    886 			}
    887 			continue;	/* no output */
    888 		}
    889 
    890 #ifdef DDB
    891 		/* XXX: non-standard '%r' format (print int in db_radix) */
    892 		case 'r':
    893 			if ((oflags & TODDB) == 0)
    894 				goto default_case;
    895 
    896 			if (db_radix == 16)
    897 				goto case_z;	/* signed hex */
    898 			_uquad = SARG();
    899 			if ((quad_t)_uquad < 0) {
    900 				_uquad = -_uquad;
    901 				sign = '-';
    902 			}
    903 			base = (db_radix == 8) ? OCT : DEC;
    904 			goto number;
    905 
    906 
    907 		/* XXX: non-standard '%z' format ("signed hex", a "hex %i")*/
    908 		case 'z':
    909 		case_z:
    910 			if ((oflags & TODDB) == 0)
    911 				goto default_case;
    912 
    913 			xdigs = "0123456789abcdef";
    914 			ch = 'x';	/* the 'x' in '0x' (below) */
    915 			_uquad = SARG();
    916 			base = HEX;
    917 			/* leading 0x/X only if non-zero */
    918 			if (flags & ALT && _uquad != 0)
    919 				flags |= HEXPREFIX;
    920 			if ((quad_t)_uquad < 0) {
    921 				_uquad = -_uquad;
    922 				sign = '-';
    923 			}
    924 			goto number;
    925 #endif
    926 
    927 		case ' ':
    928 			/*
    929 			 * ``If the space and + flags both appear, the space
    930 			 * flag will be ignored.''
    931 			 *	-- ANSI X3J11
    932 			 */
    933 			if (!sign)
    934 				sign = ' ';
    935 			goto rflag;
    936 		case '#':
    937 			flags |= ALT;
    938 			goto rflag;
    939 		case '*':
    940 			/*
    941 			 * ``A negative field width argument is taken as a
    942 			 * - flag followed by a positive field width.''
    943 			 *	-- ANSI X3J11
    944 			 * They don't exclude field widths read from args.
    945 			 */
    946 			if ((width = va_arg(ap, int)) >= 0)
    947 				goto rflag;
    948 			width = -width;
    949 			/* FALLTHROUGH */
    950 		case '-':
    951 			flags |= LADJUST;
    952 			goto rflag;
    953 		case '+':
    954 			sign = '+';
    955 			goto rflag;
    956 		case '.':
    957 			if ((ch = *fmt++) == '*') {
    958 				n = va_arg(ap, int);
    959 				prec = n < 0 ? -1 : n;
    960 				goto rflag;
    961 			}
    962 			n = 0;
    963 			while (is_digit(ch)) {
    964 				n = 10 * n + to_digit(ch);
    965 				ch = *fmt++;
    966 			}
    967 			prec = n < 0 ? -1 : n;
    968 			goto reswitch;
    969 		case '0':
    970 			/*
    971 			 * ``Note that 0 is taken as a flag, not as the
    972 			 * beginning of a field width.''
    973 			 *	-- ANSI X3J11
    974 			 */
    975 			flags |= ZEROPAD;
    976 			goto rflag;
    977 		case '1': case '2': case '3': case '4':
    978 		case '5': case '6': case '7': case '8': case '9':
    979 			n = 0;
    980 			do {
    981 				n = 10 * n + to_digit(ch);
    982 				ch = *fmt++;
    983 			} while (is_digit(ch));
    984 			width = n;
    985 			goto reswitch;
    986 		case 'h':
    987 			flags |= SHORTINT;
    988 			goto rflag;
    989 		case 'l':
    990 			if (*fmt == 'l') {
    991 				fmt++;
    992 				flags |= QUADINT;
    993 			} else {
    994 				flags |= LONGINT;
    995 			}
    996 			goto rflag;
    997 		case 'q':
    998 			flags |= QUADINT;
    999 			goto rflag;
   1000 		case 'c':
   1001 			*(cp = buf) = va_arg(ap, int);
   1002 			size = 1;
   1003 			sign = '\0';
   1004 			break;
   1005 		case 'D':
   1006 			flags |= LONGINT;
   1007 			/*FALLTHROUGH*/
   1008 		case 'd':
   1009 		case 'i':
   1010 			_uquad = SARG();
   1011 			if ((quad_t)_uquad < 0) {
   1012 				_uquad = -_uquad;
   1013 				sign = '-';
   1014 			}
   1015 			base = DEC;
   1016 			goto number;
   1017 		case 'n':
   1018 #ifdef DDB
   1019 		/* XXX: non-standard '%n' format */
   1020 		/*
   1021 		 * XXX: HACK!   DDB wants '%n' to be a '%u' printed
   1022 		 * in db_radix format.   this should die since '%n'
   1023 		 * is already defined in standard printf to write
   1024 		 * the number of chars printed so far to the arg (which
   1025 		 * should be a pointer.
   1026 		 */
   1027 			if (oflags & TODDB) {
   1028 				if (db_radix == 16)
   1029 					ch = 'x';	/* convert to %x */
   1030 				else if (db_radix == 8)
   1031 					ch = 'o';	/* convert to %o */
   1032 				else
   1033 					ch = 'u';	/* convert to %u */
   1034 
   1035 				/* ... and start again */
   1036 				goto reswitch;
   1037 			}
   1038 
   1039 #endif
   1040 			if (flags & QUADINT)
   1041 				*va_arg(ap, quad_t *) = ret;
   1042 			else if (flags & LONGINT)
   1043 				*va_arg(ap, long *) = ret;
   1044 			else if (flags & SHORTINT)
   1045 				*va_arg(ap, short *) = ret;
   1046 			else
   1047 				*va_arg(ap, int *) = ret;
   1048 			continue;	/* no output */
   1049 		case 'O':
   1050 			flags |= LONGINT;
   1051 			/*FALLTHROUGH*/
   1052 		case 'o':
   1053 			_uquad = UARG();
   1054 			base = OCT;
   1055 			goto nosign;
   1056 		case 'p':
   1057 			/*
   1058 			 * ``The argument shall be a pointer to void.  The
   1059 			 * value of the pointer is converted to a sequence
   1060 			 * of printable characters, in an implementation-
   1061 			 * defined manner.''
   1062 			 *	-- ANSI X3J11
   1063 			 */
   1064 			/* NOSTRICT */
   1065 			_uquad = (u_long)va_arg(ap, void *);
   1066 			base = HEX;
   1067 			xdigs = "0123456789abcdef";
   1068 			flags |= HEXPREFIX;
   1069 			ch = 'x';
   1070 			goto nosign;
   1071 		case 's':
   1072 			if ((cp = va_arg(ap, char *)) == NULL)
   1073 				cp = "(null)";
   1074 			if (prec >= 0) {
   1075 				/*
   1076 				 * can't use strlen; can only look for the
   1077 				 * NUL in the first `prec' characters, and
   1078 				 * strlen() will go further.
   1079 				 */
   1080 				char *p = memchr(cp, 0, prec);
   1081 
   1082 				if (p != NULL) {
   1083 					size = p - cp;
   1084 					if (size > prec)
   1085 						size = prec;
   1086 				} else
   1087 					size = prec;
   1088 			} else
   1089 				size = strlen(cp);
   1090 			sign = '\0';
   1091 			break;
   1092 		case 'U':
   1093 			flags |= LONGINT;
   1094 			/*FALLTHROUGH*/
   1095 		case 'u':
   1096 			_uquad = UARG();
   1097 			base = DEC;
   1098 			goto nosign;
   1099 		case 'X':
   1100 			xdigs = "0123456789ABCDEF";
   1101 			goto hex;
   1102 		case 'x':
   1103 			xdigs = "0123456789abcdef";
   1104 hex:			_uquad = UARG();
   1105 			base = HEX;
   1106 			/* leading 0x/X only if non-zero */
   1107 			if (flags & ALT && _uquad != 0)
   1108 				flags |= HEXPREFIX;
   1109 
   1110 			/* unsigned conversions */
   1111 nosign:			sign = '\0';
   1112 			/*
   1113 			 * ``... diouXx conversions ... if a precision is
   1114 			 * specified, the 0 flag will be ignored.''
   1115 			 *	-- ANSI X3J11
   1116 			 */
   1117 number:			if ((dprec = prec) >= 0)
   1118 				flags &= ~ZEROPAD;
   1119 
   1120 			/*
   1121 			 * ``The result of converting a zero value with an
   1122 			 * explicit precision of zero is no characters.''
   1123 			 *	-- ANSI X3J11
   1124 			 */
   1125 			cp = buf + KPRINTF_BUFSIZE;
   1126 			if (_uquad != 0 || prec != 0) {
   1127 				/*
   1128 				 * Unsigned mod is hard, and unsigned mod
   1129 				 * by a constant is easier than that by
   1130 				 * a variable; hence this switch.
   1131 				 */
   1132 				switch (base) {
   1133 				case OCT:
   1134 					do {
   1135 						*--cp = to_char(_uquad & 7);
   1136 						_uquad >>= 3;
   1137 					} while (_uquad);
   1138 					/* handle octal leading 0 */
   1139 					if (flags & ALT && *cp != '0')
   1140 						*--cp = '0';
   1141 					break;
   1142 
   1143 				case DEC:
   1144 					/* many numbers are 1 digit */
   1145 					while (_uquad >= 10) {
   1146 						*--cp = to_char(_uquad % 10);
   1147 						_uquad /= 10;
   1148 					}
   1149 					*--cp = to_char(_uquad);
   1150 					break;
   1151 
   1152 				case HEX:
   1153 					do {
   1154 						*--cp = xdigs[_uquad & 15];
   1155 						_uquad >>= 4;
   1156 					} while (_uquad);
   1157 					break;
   1158 
   1159 				default:
   1160 					cp = "bug in kprintf: bad base";
   1161 					size = strlen(cp);
   1162 					goto skipsize;
   1163 				}
   1164 			}
   1165 			size = buf + KPRINTF_BUFSIZE - cp;
   1166 		skipsize:
   1167 			break;
   1168 		default:	/* "%?" prints ?, unless ? is NUL */
   1169 #ifdef DDB
   1170 		default_case:	/* DDB */
   1171 #endif
   1172 			if (ch == '\0')
   1173 				goto done;
   1174 			/* pretend it was %c with argument ch */
   1175 			cp = buf;
   1176 			*cp = ch;
   1177 			size = 1;
   1178 			sign = '\0';
   1179 			break;
   1180 		}
   1181 
   1182 		/*
   1183 		 * All reasonable formats wind up here.  At this point, `cp'
   1184 		 * points to a string which (if not flags&LADJUST) should be
   1185 		 * padded out to `width' places.  If flags&ZEROPAD, it should
   1186 		 * first be prefixed by any sign or other prefix; otherwise,
   1187 		 * it should be blank padded before the prefix is emitted.
   1188 		 * After any left-hand padding and prefixing, emit zeroes
   1189 		 * required by a decimal [diouxX] precision, then print the
   1190 		 * string proper, then emit zeroes required by any leftover
   1191 		 * floating precision; finally, if LADJUST, pad with blanks.
   1192 		 *
   1193 		 * Compute actual size, so we know how much to pad.
   1194 		 * size excludes decimal prec; realsz includes it.
   1195 		 */
   1196 		realsz = dprec > size ? dprec : size;
   1197 		if (sign)
   1198 			realsz++;
   1199 		else if (flags & HEXPREFIX)
   1200 			realsz+= 2;
   1201 
   1202 		/* right-adjusting blank padding */
   1203 		if ((flags & (LADJUST|ZEROPAD)) == 0) {
   1204 			n = width - realsz;
   1205 			while (n-- > 0)
   1206 				KPRINTF_PUTCHAR(' ');
   1207 		}
   1208 
   1209 		/* prefix */
   1210 		if (sign) {
   1211 			KPRINTF_PUTCHAR(sign);
   1212 		} else if (flags & HEXPREFIX) {
   1213 			KPRINTF_PUTCHAR('0');
   1214 			KPRINTF_PUTCHAR(ch);
   1215 		}
   1216 
   1217 		/* right-adjusting zero padding */
   1218 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD) {
   1219 			n = width - realsz;
   1220 			while (n-- > 0)
   1221 				KPRINTF_PUTCHAR('0');
   1222 		}
   1223 
   1224 		/* leading zeroes from decimal precision */
   1225 		n = dprec - size;
   1226 		while (n-- > 0)
   1227 			KPRINTF_PUTCHAR('0');
   1228 
   1229 		/* the string or number proper */
   1230 		while (size--)
   1231 			KPRINTF_PUTCHAR(*cp++);
   1232 		/* left-adjusting padding (always blank) */
   1233 		if (flags & LADJUST) {
   1234 			n = width - realsz;
   1235 			while (n-- > 0)
   1236 				KPRINTF_PUTCHAR(' ');
   1237 		}
   1238 
   1239 		/* finally, adjust ret */
   1240 		ret += width > realsz ? width : realsz;
   1241 
   1242 	}
   1243 done:
   1244 	return (ret);
   1245 	/* NOTREACHED */
   1246 }
   1247