xref: /openbsd/sys/kern/subr_prf.c (revision 7b36286a)
1 /*	$OpenBSD: subr_prf.c,v 1.74 2008/06/27 17:23:24 miod Exp $	*/
2 /*	$NetBSD: subr_prf.c,v 1.45 1997/10/24 18:14:25 chuck Exp $	*/
3 
4 /*-
5  * Copyright (c) 1986, 1988, 1991, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  * (c) UNIX System Laboratories, Inc.
8  * All or some portions of this file are derived from material licensed
9  * to the University of California by American Telephone and Telegraph
10  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
11  * the permission of UNIX System Laboratories, Inc.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *	@(#)subr_prf.c	8.3 (Berkeley) 1/21/94
38  */
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/buf.h>
43 #include <sys/conf.h>
44 #include <sys/reboot.h>
45 #include <sys/msgbuf.h>
46 #include <sys/proc.h>
47 #include <sys/ioctl.h>
48 #include <sys/vnode.h>
49 #include <sys/file.h>
50 #include <sys/tty.h>
51 #include <sys/tprintf.h>
52 #include <sys/syslog.h>
53 #include <sys/malloc.h>
54 #include <sys/pool.h>
55 #include <sys/mutex.h>
56 
57 #include <dev/cons.h>
58 
59 /*
60  * note that stdarg.h and the ansi style va_start macro is used for both
61  * ansi and traditional c compilers.
62  */
63 #include <sys/stdarg.h>
64 
65 #ifdef KGDB
66 #include <sys/kgdb.h>
67 #include <machine/cpu.h>
68 #endif
69 #ifdef DDB
70 #include <ddb/db_output.h>	/* db_printf, db_putchar prototypes */
71 #include <ddb/db_var.h>		/* db_log, db_radix */
72 #endif
73 
74 
75 /*
76  * defines
77  */
78 
79 /* flags for kprintf */
80 #define TOCONS		0x01	/* to the console */
81 #define TOTTY		0x02	/* to the process' tty */
82 #define TOLOG		0x04	/* to the kernel message buffer */
83 #define TOBUFONLY	0x08	/* to the buffer (only) [for snprintf] */
84 #define TODDB		0x10	/* to ddb console */
85 #define TOCOUNT		0x20	/* act like [v]snprintf */
86 
87 /* max size buffer kprintf needs to print quad_t [size in base 8 + \0] */
88 #define KPRINTF_BUFSIZE		(sizeof(quad_t) * NBBY / 3 + 2)
89 
90 
91 /*
92  * local prototypes
93  */
94 
95 int	 kprintf(const char *, int, void *, char *, va_list);
96 void	 kputchar(int, int, struct tty *);
97 
98 struct mutex kprintf_mutex = MUTEX_INITIALIZER(IPL_HIGH);
99 
100 /*
101  * globals
102  */
103 
104 extern struct	tty *constty;	/* pointer to console "window" tty */
105 extern	int log_open;	/* subr_log: is /dev/klog open? */
106 const	char *panicstr; /* arg to first call to panic (used as a flag
107 			   to indicate that panic has already been called). */
108 #ifdef DDB
109 /*
110  * Enter ddb on panic.
111  */
112 int	db_panic = 1;
113 
114 /*
115  * db_console controls if we can be able to enter ddb by a special key
116  * combination (machine dependent).
117  * If DDB_SAFE_CONSOLE is defined in the kernel configuration it allows
118  * to break into console during boot. It's _really_ useful when debugging
119  * some things in the kernel that can cause init(8) to crash.
120  */
121 #ifdef DDB_SAFE_CONSOLE
122 int	db_console = 1;
123 #else
124 int	db_console = 0;
125 #endif
126 #endif
127 
128 /*
129  * panic on spl assertion failure?
130  */
131 int splassert_ctl = 1;
132 
133 /*
134  * v_putc: routine to putc on virtual console
135  *
136  * the v_putc pointer can be used to redirect the console cnputc elsewhere
137  * [e.g. to a "virtual console"].
138  */
139 
140 void (*v_putc)(int) = cnputc;	/* start with cnputc (normal cons) */
141 
142 
143 /*
144  * functions
145  */
146 
147 /*
148  *	Partial support (the failure case) of the assertion facility
149  *	commonly found in userland.
150  */
151 void
152 __assert(const char *t, const char *f, int l, const char *e)
153 {
154 
155 	panic("kernel %sassertion \"%s\" failed: file \"%s\", line %d",
156 		t, e, f, l);
157 }
158 
159 /*
160  * tablefull: warn that a system table is full
161  */
162 
163 void
164 tablefull(const char *tab)
165 {
166 	log(LOG_ERR, "%s: table is full\n", tab);
167 }
168 
169 /*
170  * panic: handle an unresolvable fatal error
171  *
172  * prints "panic: <message>" and reboots.   if called twice (i.e. recursive
173  * call) we avoid trying to sync the disk and just reboot (to avoid
174  * recursive panics).
175  */
176 
177 void
178 panic(const char *fmt, ...)
179 {
180 	static char panicbuf[512];
181 	int bootopt;
182 	va_list ap;
183 
184 	bootopt = RB_AUTOBOOT | RB_DUMP;
185 	va_start(ap, fmt);
186 	if (panicstr)
187 		bootopt |= RB_NOSYNC;
188 	else {
189 		vsnprintf(panicbuf, sizeof panicbuf, fmt, ap);
190 		panicstr = panicbuf;
191 	}
192 	va_end(ap);
193 
194 	printf("panic: ");
195 	va_start(ap, fmt);
196 	vprintf(fmt, ap);
197 	printf("\n");
198 	va_end(ap);
199 
200 #ifdef KGDB
201 	kgdb_panic();
202 #endif
203 #ifdef KADB
204 	if (boothowto & RB_KDB)
205 		kdbpanic();
206 #endif
207 #ifdef DDB
208 	if (db_panic)
209 		Debugger();
210 	else
211 		db_stack_dump();
212 #endif
213 	boot(bootopt);
214 }
215 
216 /*
217  * We print only the function name. The file name is usually very long and
218  * would eat tons of space in the kernel.
219  */
220 void
221 splassert_fail(int wantipl, int haveipl, const char *func)
222 {
223 
224 	printf("splassert: %s: want %d have %d\n", func, wantipl, haveipl);
225 	switch (splassert_ctl) {
226 	case 1:
227 		break;
228 	case 2:
229 #ifdef DDB
230 		db_stack_dump();
231 #endif
232 		break;
233 	case 3:
234 #ifdef DDB
235 		db_stack_dump();
236 		Debugger();
237 #endif
238 		break;
239 	default:
240 		panic("spl assertion failure in %s", func);
241 	}
242 }
243 
244 /*
245  * kernel logging functions: log, logpri, addlog
246  */
247 
248 /*
249  * log: write to the log buffer
250  *
251  * => will not sleep [so safe to call from interrupt]
252  * => will log to console if /dev/klog isn't open
253  */
254 
255 void
256 log(int level, const char *fmt, ...)
257 {
258 	int s;
259 	va_list ap;
260 
261 	s = splhigh();
262 	logpri(level);		/* log the level first */
263 	va_start(ap, fmt);
264 	kprintf(fmt, TOLOG, NULL, NULL, ap);
265 	va_end(ap);
266 	splx(s);
267 	if (!log_open) {
268 		va_start(ap, fmt);
269 		kprintf(fmt, TOCONS, NULL, NULL, ap);
270 		va_end(ap);
271 	}
272 	logwakeup();		/* wake up anyone waiting for log msgs */
273 }
274 
275 /*
276  * logpri: log the priority level to the klog
277  */
278 
279 void
280 logpri(int level)
281 {
282 	char *p;
283 	char snbuf[KPRINTF_BUFSIZE];
284 
285 	kputchar('<', TOLOG, NULL);
286 	snprintf(snbuf, sizeof snbuf, "%d", level);
287 	for (p = snbuf ; *p ; p++)
288 		kputchar(*p, TOLOG, NULL);
289 	kputchar('>', TOLOG, NULL);
290 }
291 
292 /*
293  * addlog: add info to previous log message
294  */
295 
296 int
297 addlog(const char *fmt, ...)
298 {
299 	int s;
300 	va_list ap;
301 
302 	s = splhigh();
303 	va_start(ap, fmt);
304 	kprintf(fmt, TOLOG, NULL, NULL, ap);
305 	va_end(ap);
306 	splx(s);
307 	if (!log_open) {
308 		va_start(ap, fmt);
309 		kprintf(fmt, TOCONS, NULL, NULL, ap);
310 		va_end(ap);
311 	}
312 	logwakeup();
313 	return(0);
314 }
315 
316 
317 /*
318  * kputchar: print a single character on console or user terminal.
319  *
320  * => if console, then the last MSGBUFS chars are saved in msgbuf
321  *	for inspection later (e.g. dmesg/syslog)
322  */
323 void
324 kputchar(int c, int flags, struct tty *tp)
325 {
326 	extern int msgbufmapped;
327 
328 	if (panicstr)
329 		constty = NULL;
330 	if ((flags & TOCONS) && tp == NULL && constty) {
331 		tp = constty;
332 		flags |= TOTTY;
333 	}
334 	if ((flags & TOTTY) && tp && tputchar(c, tp) < 0 &&
335 	    (flags & TOCONS) && tp == constty)
336 		constty = NULL;
337 	if ((flags & TOLOG) &&
338 	    c != '\0' && c != '\r' && c != 0177 && msgbufmapped)
339 		msgbuf_putchar(c);
340 	if ((flags & TOCONS) && constty == NULL && c != '\0')
341 		(*v_putc)(c);
342 #ifdef DDB
343 	if (flags & TODDB)
344 		db_putchar(c);
345 #endif
346 }
347 
348 
349 /*
350  * uprintf: print to the controlling tty of the current process
351  *
352  * => we may block if the tty queue is full
353  * => no message is printed if the queue doesn't clear in a reasonable
354  *	time
355  */
356 
357 void
358 uprintf(const char *fmt, ...)
359 {
360 	struct proc *p = curproc;
361 	va_list ap;
362 
363 	if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
364 		va_start(ap, fmt);
365 		kprintf(fmt, TOTTY, p->p_session->s_ttyp, NULL, ap);
366 		va_end(ap);
367 	}
368 }
369 
370 #if defined(NFSSERVER) || defined(NFSCLIENT)
371 
372 /*
373  * tprintf functions: used to send messages to a specific process
374  *
375  * usage:
376  *   get a tpr_t handle on a process "p" by using "tprintf_open(p)"
377  *   use the handle when calling "tprintf"
378  *   when done, do a "tprintf_close" to drop the handle
379  */
380 
381 /*
382  * tprintf_open: get a tprintf handle on a process "p"
383  *
384  * => returns NULL if process can't be printed to
385  */
386 
387 tpr_t
388 tprintf_open(struct proc *p)
389 {
390 
391 	if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
392 		SESSHOLD(p->p_session);
393 		return ((tpr_t) p->p_session);
394 	}
395 	return ((tpr_t) NULL);
396 }
397 
398 /*
399  * tprintf_close: dispose of a tprintf handle obtained with tprintf_open
400  */
401 
402 void
403 tprintf_close(tpr_t sess)
404 {
405 
406 	if (sess)
407 		SESSRELE((struct session *) sess);
408 }
409 
410 /*
411  * tprintf: given tprintf handle to a process [obtained with tprintf_open],
412  * send a message to the controlling tty for that process.
413  *
414  * => also sends message to /dev/klog
415  */
416 void
417 tprintf(tpr_t tpr, const char *fmt, ...)
418 {
419 	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 #endif	/* NFSSERVER || NFSCLIENT */
436 
437 
438 /*
439  * ttyprintf: send a message to a specific tty
440  *
441  * => should be used only by tty driver or anything that knows the
442  *	underlying tty will not be revoked(2)'d away.  [otherwise,
443  *	use tprintf]
444  */
445 void
446 ttyprintf(struct tty *tp, const char *fmt, ...)
447 {
448 	va_list ap;
449 
450 	va_start(ap, fmt);
451 	kprintf(fmt, TOTTY, tp, NULL, ap);
452 	va_end(ap);
453 }
454 
455 #ifdef DDB
456 
457 /*
458  * db_printf: printf for DDB (via db_putchar)
459  */
460 
461 int
462 db_printf(const char *fmt, ...)
463 {
464 	va_list ap;
465 	int flags, retval;
466 
467 	flags = TODDB;
468 	if (db_log)
469 		flags |= TOLOG;
470 	va_start(ap, fmt);
471 	retval = kprintf(fmt, flags, NULL, NULL, ap);
472 	va_end(ap);
473 	return(retval);
474 }
475 
476 #endif /* DDB */
477 
478 
479 /*
480  * normal kernel printf functions: printf, vprintf, snprintf
481  */
482 
483 /*
484  * printf: print a message to the console and the log
485  */
486 int
487 printf(const char *fmt, ...)
488 {
489 	va_list ap;
490 	int retval;
491 
492 	mtx_enter(&kprintf_mutex);
493 
494 	va_start(ap, fmt);
495 	retval = kprintf(fmt, TOCONS | TOLOG, NULL, NULL, ap);
496 	va_end(ap);
497 	if (!panicstr)
498 		logwakeup();
499 
500 	mtx_leave(&kprintf_mutex);
501 
502 	return(retval);
503 }
504 
505 /*
506  * vprintf: print a message to the console and the log [already have a
507  *	va_list]
508  */
509 
510 int
511 vprintf(const char *fmt, va_list ap)
512 {
513 	int retval;
514 
515 	mtx_enter(&kprintf_mutex);
516 
517 	retval = kprintf(fmt, TOCONS | TOLOG, NULL, NULL, ap);
518 	if (!panicstr)
519 		logwakeup();
520 
521 	mtx_leave(&kprintf_mutex);
522 
523 	return (retval);
524 }
525 
526 /*
527  * snprintf: print a message to a buffer
528  */
529 int
530 snprintf(char *buf, size_t size, const char *fmt, ...)
531 {
532 	int retval;
533 	va_list ap;
534 	char *p;
535 
536 	p = buf + size - 1;
537 	if (size < 1)
538 		p = buf;
539 	va_start(ap, fmt);
540 	retval = kprintf(fmt, TOBUFONLY | TOCOUNT, &p, buf, ap);
541 	va_end(ap);
542 	if (size > 0)
543 		*(p) = 0;	/* null terminate */
544 	return(retval);
545 }
546 
547 /*
548  * vsnprintf: print a message to a buffer [already have va_alist]
549  */
550 int
551 vsnprintf(char *buf, size_t size, const char *fmt, va_list ap)
552 {
553 	int retval;
554 	char *p;
555 
556 	p = buf + size - 1;
557 	if (size < 1)
558 		p = buf;
559 	retval = kprintf(fmt, TOBUFONLY | TOCOUNT, &p, buf, ap);
560 	if (size > 0)
561 		*(p) = 0;	/* null terminate */
562 	return(retval);
563 }
564 
565 /*
566  * kprintf: scaled down version of printf(3).
567  *
568  * this version based on vfprintf() from libc which was derived from
569  * software contributed to Berkeley by Chris Torek.
570  *
571  * The additional format %b is supported to decode error registers.
572  * Its usage is:
573  *
574  *	printf("reg=%b\n", regval, "<base><arg>*");
575  *
576  * where <base> is the output base expressed as a control character, e.g.
577  * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
578  * the first of which gives the bit number to be inspected (origin 1), and
579  * the next characters (up to a control character, i.e. a character <= 32),
580  * give the name of the register.  Thus:
581  *
582  *	kprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
583  *
584  * would produce output:
585  *
586  *	reg=3<BITTWO,BITONE>
587  *
588  * To support larger integers (> 32 bits), %b formatting will also accept
589  * control characters in the region 0x80 - 0xff.  0x80 refers to bit 0,
590  * 0x81 refers to bit 1, and so on.  The equivalent string to the above is:
591  *
592  *	kprintf("reg=%b\n", 3, "\10\201BITTWO\200BITONE\n");
593  *
594  * and would produce the same output.
595  *
596  * Like the rest of printf, %b can be prefixed to handle various size
597  * modifiers, eg. %b is for "int", %lb is for "long", and %llb supports
598  * "long long".
599  *
600  * This code is large and complicated...
601  */
602 
603 /*
604  * macros for converting digits to letters and vice versa
605  */
606 #define	to_digit(c)	((c) - '0')
607 #define is_digit(c)	((unsigned)to_digit(c) <= 9)
608 #define	to_char(n)	((n) + '0')
609 
610 /*
611  * flags used during conversion.
612  */
613 #define	ALT		0x001		/* alternate form */
614 #define	HEXPREFIX	0x002		/* add 0x or 0X prefix */
615 #define	LADJUST		0x004		/* left adjustment */
616 #define	LONGDBL		0x008		/* long double; unimplemented */
617 #define	LONGINT		0x010		/* long integer */
618 #define	QUADINT		0x020		/* quad integer */
619 #define	SHORTINT	0x040		/* short integer */
620 #define	ZEROPAD		0x080		/* zero (as opposed to blank) pad */
621 #define FPT		0x100		/* Floating point number */
622 #define SIZEINT		0x200		/* (signed) size_t */
623 
624 	/*
625 	 * To extend shorts properly, we need both signed and unsigned
626 	 * argument extraction methods.
627 	 */
628 #define	SARG() \
629 	(flags&QUADINT ? va_arg(ap, quad_t) : \
630 	    flags&LONGINT ? va_arg(ap, long) : \
631 	    flags&SIZEINT ? va_arg(ap, ssize_t) : \
632 	    flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
633 	    (long)va_arg(ap, int))
634 #define	UARG() \
635 	(flags&QUADINT ? va_arg(ap, u_quad_t) : \
636 	    flags&LONGINT ? va_arg(ap, u_long) : \
637 	    flags&SIZEINT ? va_arg(ap, size_t) : \
638 	    flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \
639 	    (u_long)va_arg(ap, u_int))
640 
641 #define KPRINTF_PUTCHAR(C) do {					\
642 	int chr = (C);							\
643 	ret += 1;							\
644 	if (oflags & TOBUFONLY) {					\
645 		if ((vp != NULL) && (sbuf == tailp)) {			\
646 			if (!(oflags & TOCOUNT))				\
647 				goto overflow;				\
648 		} else							\
649 			*sbuf++ = chr;					\
650 	} else {							\
651 		kputchar(chr, oflags, (struct tty *)vp);			\
652 	}								\
653 } while(0)
654 
655 int
656 kprintf(const char *fmt0, int oflags, void *vp, char *sbuf, va_list ap)
657 {
658 	char *fmt;		/* format string */
659 	int ch;			/* character from fmt */
660 	int n;			/* handy integer (short term usage) */
661 	char *cp = NULL;	/* handy char pointer (short term usage) */
662 	int flags;		/* flags as above */
663 	int ret;		/* return value accumulator */
664 	int width;		/* width from format (%8d), or 0 */
665 	int prec;		/* precision from format (%.3d), or -1 */
666 	char sign;		/* sign prefix (' ', '+', '-', or \0) */
667 
668 	u_quad_t _uquad;	/* integer arguments %[diouxX] */
669 	enum { OCT, DEC, HEX } base;/* base for [diouxX] conversion */
670 	int dprec;		/* a copy of prec if [diouxX], 0 otherwise */
671 	int realsz;		/* field size expanded by dprec */
672 	int size = 0;		/* size of converted field or string */
673 	char *xdigs = NULL;	/* digits for [xX] conversion */
674 	char buf[KPRINTF_BUFSIZE]; /* space for %c, %[diouxX] */
675 	char *tailp = NULL;	/* tail pointer for snprintf */
676 
677 	if ((oflags & TOBUFONLY) && (vp != NULL))
678 		tailp = *(char **)vp;
679 
680 	fmt = (char *)fmt0;
681 	ret = 0;
682 
683 	/*
684 	 * Scan the format for conversions (`%' character).
685 	 */
686 	for (;;) {
687 		while (*fmt != '%' && *fmt) {
688 			KPRINTF_PUTCHAR(*fmt++);
689 		}
690 		if (*fmt == 0)
691 			goto done;
692 
693 		fmt++;		/* skip over '%' */
694 
695 		flags = 0;
696 		dprec = 0;
697 		width = 0;
698 		prec = -1;
699 		sign = '\0';
700 
701 rflag:		ch = *fmt++;
702 reswitch:	switch (ch) {
703 		/* XXX: non-standard '%b' format */
704 		case 'b': {
705 			char *b, *z;
706 			int tmp;
707 			_uquad = UARG();
708 			b = va_arg(ap, char *);
709 			if (*b == 8)
710 				snprintf(buf, sizeof buf, "%llo", _uquad);
711 			else if (*b == 10)
712 				snprintf(buf, sizeof buf, "%lld", _uquad);
713 			else if (*b == 16)
714 				snprintf(buf, sizeof buf, "%llx", _uquad);
715 			else
716 				break;
717 			b++;
718 
719 			z = buf;
720 			while (*z) {
721 				KPRINTF_PUTCHAR(*z++);
722 			}
723 
724 			if (_uquad) {
725 				tmp = 0;
726 				while ((n = *b++) != 0) {
727 					if (n & 0x80)
728 						n &= 0x7f;
729 					else if (n <= ' ')
730 						n = n - 1;
731 					if (_uquad & (1LL << n)) {
732 						KPRINTF_PUTCHAR(tmp ? ',':'<');
733 						while (*b > ' ' &&
734 						    (*b & 0x80) == 0) {
735 							KPRINTF_PUTCHAR(*b);
736 							b++;
737 						}
738 						tmp = 1;
739 					} else {
740 						while (*b > ' ' &&
741 						    (*b & 0x80) == 0)
742 							b++;
743 					}
744 				}
745 				if (tmp) {
746 					KPRINTF_PUTCHAR('>');
747 				}
748 			}
749 			continue;	/* no output */
750 		}
751 
752 		case ' ':
753 			/*
754 			 * ``If the space and + flags both appear, the space
755 			 * flag will be ignored.''
756 			 *	-- ANSI X3J11
757 			 */
758 			if (!sign)
759 				sign = ' ';
760 			goto rflag;
761 		case '#':
762 			flags |= ALT;
763 			goto rflag;
764 		case '*':
765 			/*
766 			 * ``A negative field width argument is taken as a
767 			 * - flag followed by a positive field width.''
768 			 *	-- ANSI X3J11
769 			 * They don't exclude field widths read from args.
770 			 */
771 			if ((width = va_arg(ap, int)) >= 0)
772 				goto rflag;
773 			width = -width;
774 			/* FALLTHROUGH */
775 		case '-':
776 			flags |= LADJUST;
777 			goto rflag;
778 		case '+':
779 			sign = '+';
780 			goto rflag;
781 		case '.':
782 			if ((ch = *fmt++) == '*') {
783 				n = va_arg(ap, int);
784 				prec = n < 0 ? -1 : n;
785 				goto rflag;
786 			}
787 			n = 0;
788 			while (is_digit(ch)) {
789 				n = 10 * n + to_digit(ch);
790 				ch = *fmt++;
791 			}
792 			prec = n < 0 ? -1 : n;
793 			goto reswitch;
794 		case '0':
795 			/*
796 			 * ``Note that 0 is taken as a flag, not as the
797 			 * beginning of a field width.''
798 			 *	-- ANSI X3J11
799 			 */
800 			flags |= ZEROPAD;
801 			goto rflag;
802 		case '1': case '2': case '3': case '4':
803 		case '5': case '6': case '7': case '8': case '9':
804 			n = 0;
805 			do {
806 				n = 10 * n + to_digit(ch);
807 				ch = *fmt++;
808 			} while (is_digit(ch));
809 			width = n;
810 			goto reswitch;
811 		case 'h':
812 			flags |= SHORTINT;
813 			goto rflag;
814 		case 'l':
815 			if (*fmt == 'l') {
816 				fmt++;
817 				flags |= QUADINT;
818 			} else {
819 				flags |= LONGINT;
820 			}
821 			goto rflag;
822 		case 'q':
823 			flags |= QUADINT;
824 			goto rflag;
825 		case 'z':
826 			flags |= SIZEINT;
827 			goto rflag;
828 		case 'c':
829 			*(cp = buf) = va_arg(ap, int);
830 			size = 1;
831 			sign = '\0';
832 			break;
833 		case 'D':
834 			flags |= LONGINT;
835 			/*FALLTHROUGH*/
836 		case 'd':
837 		case 'i':
838 			_uquad = SARG();
839 			if ((quad_t)_uquad < 0) {
840 				_uquad = -_uquad;
841 				sign = '-';
842 			}
843 			base = DEC;
844 			goto number;
845 		case 'n':
846 			if (flags & QUADINT)
847 				*va_arg(ap, quad_t *) = ret;
848 			else if (flags & LONGINT)
849 				*va_arg(ap, long *) = ret;
850 			else if (flags & SHORTINT)
851 				*va_arg(ap, short *) = ret;
852 			else if (flags & SIZEINT)
853 				*va_arg(ap, ssize_t *) = ret;
854 			else
855 				*va_arg(ap, int *) = ret;
856 			continue;	/* no output */
857 		case 'O':
858 			flags |= LONGINT;
859 			/*FALLTHROUGH*/
860 		case 'o':
861 			_uquad = UARG();
862 			base = OCT;
863 			goto nosign;
864 		case 'p':
865 			/*
866 			 * ``The argument shall be a pointer to void.  The
867 			 * value of the pointer is converted to a sequence
868 			 * of printable characters, in an implementation-
869 			 * defined manner.''
870 			 *	-- ANSI X3J11
871 			 */
872 			/* NOSTRICT */
873 			_uquad = (u_long)va_arg(ap, void *);
874 			base = HEX;
875 			xdigs = "0123456789abcdef";
876 			flags |= HEXPREFIX;
877 			ch = 'x';
878 			goto nosign;
879 		case 's':
880 			if ((cp = va_arg(ap, char *)) == NULL)
881 				cp = "(null)";
882 			if (prec >= 0) {
883 				/*
884 				 * can't use strlen; can only look for the
885 				 * NUL in the first `prec' characters, and
886 				 * strlen() will go further.
887 				 */
888 				char *p = memchr(cp, 0, prec);
889 
890 				if (p != NULL) {
891 					size = p - cp;
892 					if (size > prec)
893 						size = prec;
894 				} else
895 					size = prec;
896 			} else
897 				size = strlen(cp);
898 			sign = '\0';
899 			break;
900 		case 'U':
901 			flags |= LONGINT;
902 			/*FALLTHROUGH*/
903 		case 'u':
904 			_uquad = UARG();
905 			base = DEC;
906 			goto nosign;
907 		case 'X':
908 			xdigs = "0123456789ABCDEF";
909 			goto hex;
910 		case 'x':
911 			xdigs = "0123456789abcdef";
912 hex:			_uquad = UARG();
913 			base = HEX;
914 			/* leading 0x/X only if non-zero */
915 			if (flags & ALT && _uquad != 0)
916 				flags |= HEXPREFIX;
917 
918 			/* unsigned conversions */
919 nosign:			sign = '\0';
920 			/*
921 			 * ``... diouXx conversions ... if a precision is
922 			 * specified, the 0 flag will be ignored.''
923 			 *	-- ANSI X3J11
924 			 */
925 number:			if ((dprec = prec) >= 0)
926 				flags &= ~ZEROPAD;
927 
928 			/*
929 			 * ``The result of converting a zero value with an
930 			 * explicit precision of zero is no characters.''
931 			 *	-- ANSI X3J11
932 			 */
933 			cp = buf + KPRINTF_BUFSIZE;
934 			if (_uquad != 0 || prec != 0) {
935 				/*
936 				 * Unsigned mod is hard, and unsigned mod
937 				 * by a constant is easier than that by
938 				 * a variable; hence this switch.
939 				 */
940 				switch (base) {
941 				case OCT:
942 					do {
943 						*--cp = to_char(_uquad & 7);
944 						_uquad >>= 3;
945 					} while (_uquad);
946 					/* handle octal leading 0 */
947 					if (flags & ALT && *cp != '0')
948 						*--cp = '0';
949 					break;
950 
951 				case DEC:
952 					/* many numbers are 1 digit */
953 					while (_uquad >= 10) {
954 						*--cp = to_char(_uquad % 10);
955 						_uquad /= 10;
956 					}
957 					*--cp = to_char(_uquad);
958 					break;
959 
960 				case HEX:
961 					do {
962 						*--cp = xdigs[_uquad & 15];
963 						_uquad >>= 4;
964 					} while (_uquad);
965 					break;
966 
967 				default:
968 					cp = "bug in kprintf: bad base";
969 					size = strlen(cp);
970 					goto skipsize;
971 				}
972 			}
973 			size = buf + KPRINTF_BUFSIZE - cp;
974 		skipsize:
975 			break;
976 		default:	/* "%?" prints ?, unless ? is NUL */
977 			if (ch == '\0')
978 				goto done;
979 			/* pretend it was %c with argument ch */
980 			cp = buf;
981 			*cp = ch;
982 			size = 1;
983 			sign = '\0';
984 			break;
985 		}
986 
987 		/*
988 		 * All reasonable formats wind up here.  At this point, `cp'
989 		 * points to a string which (if not flags&LADJUST) should be
990 		 * padded out to `width' places.  If flags&ZEROPAD, it should
991 		 * first be prefixed by any sign or other prefix; otherwise,
992 		 * it should be blank padded before the prefix is emitted.
993 		 * After any left-hand padding and prefixing, emit zeroes
994 		 * required by a decimal [diouxX] precision, then print the
995 		 * string proper, then emit zeroes required by any leftover
996 		 * floating precision; finally, if LADJUST, pad with blanks.
997 		 *
998 		 * Compute actual size, so we know how much to pad.
999 		 * size excludes decimal prec; realsz includes it.
1000 		 */
1001 		realsz = dprec > size ? dprec : size;
1002 		if (sign)
1003 			realsz++;
1004 		else if (flags & HEXPREFIX)
1005 			realsz+= 2;
1006 
1007 		/* right-adjusting blank padding */
1008 		if ((flags & (LADJUST|ZEROPAD)) == 0) {
1009 			n = width - realsz;
1010 			while (n-- > 0)
1011 				KPRINTF_PUTCHAR(' ');
1012 		}
1013 
1014 		/* prefix */
1015 		if (sign) {
1016 			KPRINTF_PUTCHAR(sign);
1017 		} else if (flags & HEXPREFIX) {
1018 			KPRINTF_PUTCHAR('0');
1019 			KPRINTF_PUTCHAR(ch);
1020 		}
1021 
1022 		/* right-adjusting zero padding */
1023 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD) {
1024 			n = width - realsz;
1025 			while (n-- > 0)
1026 				KPRINTF_PUTCHAR('0');
1027 		}
1028 
1029 		/* leading zeroes from decimal precision */
1030 		n = dprec - size;
1031 		while (n-- > 0)
1032 			KPRINTF_PUTCHAR('0');
1033 
1034 		/* the string or number proper */
1035 		while (size--)
1036 			KPRINTF_PUTCHAR(*cp++);
1037 		/* left-adjusting padding (always blank) */
1038 		if (flags & LADJUST) {
1039 			n = width - realsz;
1040 			while (n-- > 0)
1041 				KPRINTF_PUTCHAR(' ');
1042 		}
1043 	}
1044 
1045 done:
1046 	if ((oflags & TOBUFONLY) && (vp != NULL))
1047 		*(char **)vp = sbuf;
1048 overflow:
1049 	return (ret);
1050 	/* NOTREACHED */
1051 }
1052 
1053 #if __GNUC_PREREQ__(2,96)
1054 /*
1055  * XXX - these functions shouldn't be in the kernel, but gcc 3.X feels like
1056  *       translating some printf calls to puts and since it doesn't seem
1057  *       possible to just turn off parts of those optimizations (some of
1058  *       them are really useful), we have to provide a dummy puts and putchar
1059  *	 that are wrappers around printf.
1060  */
1061 int	puts(const char *);
1062 int	putchar(int c);
1063 
1064 int
1065 puts(const char *str)
1066 {
1067 	printf("%s\n", str);
1068 
1069 	return (0);
1070 }
1071 
1072 int
1073 putchar(int c)
1074 {
1075 	printf("%c", c);
1076 
1077 	return (c);
1078 }
1079 
1080 
1081 #endif
1082