Home | History | Annotate | Line # | Download | only in stdio
vfprintf.c revision 1.37
      1 /*	$NetBSD: vfprintf.c,v 1.37 2001/11/04 13:57:30 lukem Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1990 The Regents of the University of California.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Chris Torek.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the University of
     21  *	California, Berkeley and its contributors.
     22  * 4. Neither the name of the University nor the names of its contributors
     23  *    may be used to endorse or promote products derived from this software
     24  *    without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     36  * SUCH DAMAGE.
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 #if defined(LIBC_SCCS) && !defined(lint)
     41 #if 0
     42 static char *sccsid = "@(#)vfprintf.c	5.50 (Berkeley) 12/16/92";
     43 #else
     44 __RCSID("$NetBSD: vfprintf.c,v 1.37 2001/11/04 13:57:30 lukem Exp $");
     45 #endif
     46 #endif /* LIBC_SCCS and not lint */
     47 
     48 /*
     49  * Actual printf innards.
     50  *
     51  * This code is large and complicated...
     52  */
     53 
     54 #include "namespace.h"
     55 #include <sys/types.h>
     56 
     57 #include <assert.h>
     58 #include <errno.h>
     59 #include <stddef.h>
     60 #include <stdint.h>
     61 #include <stdio.h>
     62 #include <stdlib.h>
     63 #include <string.h>
     64 #include <wchar.h>
     65 
     66 #if __STDC__
     67 #include <stdarg.h>
     68 #else
     69 #include <varargs.h>
     70 #endif
     71 
     72 #include "local.h"
     73 #include "fvwrite.h"
     74 #include "extern.h"
     75 #include "reentrant.h"
     76 
     77 static int __sprint __P((FILE *, struct __suio *));
     78 static int __sbprintf __P((FILE *, const char *, va_list))
     79      __attribute__((__format__(__printf__, 2, 0)));
     80 
     81 /*
     82  * Flush out all the vectors defined by the given uio,
     83  * then reset it so that it can be reused.
     84  */
     85 static int
     86 __sprint(fp, uio)
     87 	FILE *fp;
     88 	struct __suio *uio;
     89 {
     90 	int err;
     91 
     92 	_DIAGASSERT(fp != NULL);
     93 	_DIAGASSERT(uio != NULL);
     94 
     95 	if (uio->uio_resid == 0) {
     96 		uio->uio_iovcnt = 0;
     97 		return (0);
     98 	}
     99 	err = __sfvwrite(fp, uio);
    100 	uio->uio_resid = 0;
    101 	uio->uio_iovcnt = 0;
    102 	return (err);
    103 }
    104 
    105 /*
    106  * Helper function for `fprintf to unbuffered unix file': creates a
    107  * temporary buffer.  We only work on write-only files; this avoids
    108  * worries about ungetc buffers and so forth.
    109  */
    110 static int
    111 __sbprintf(fp, fmt, ap)
    112 	FILE *fp;
    113 	const char *fmt;
    114 	va_list ap;
    115 {
    116 	int ret;
    117 	FILE fake;
    118 	unsigned char buf[BUFSIZ];
    119 
    120 	_DIAGASSERT(fp != NULL);
    121 	_DIAGASSERT(fmt != NULL);
    122 
    123 	/* copy the important variables */
    124 	fake._flags = fp->_flags & ~__SNBF;
    125 	fake._file = fp->_file;
    126 	fake._cookie = fp->_cookie;
    127 	fake._write = fp->_write;
    128 
    129 	/* set up the buffer */
    130 	fake._bf._base = fake._p = buf;
    131 	fake._bf._size = fake._w = sizeof(buf);
    132 	fake._lbfsize = 0;	/* not actually used, but Just In Case */
    133 
    134 	/* do the work, then copy any error status */
    135 	ret = vfprintf(&fake, fmt, ap);
    136 	if (ret >= 0 && fflush(&fake))
    137 		ret = -1;
    138 	if (fake._flags & __SERR)
    139 		fp->_flags |= __SERR;
    140 	return (ret);
    141 }
    142 
    143 
    144 #ifdef FLOATING_POINT
    145 #include <locale.h>
    146 #include <math.h>
    147 #include "floatio.h"
    148 
    149 #define	BUF		(MAXEXP+MAXFRACT+1)	/* + decimal point */
    150 #define	DEFPREC		6
    151 
    152 static char *cvt __P((double, int, int, char *, int *, int, int *));
    153 static int exponent __P((char *, int, int));
    154 
    155 #else /* no FLOATING_POINT */
    156 
    157 #define	BUF		40
    158 
    159 #endif /* FLOATING_POINT */
    160 
    161 #ifdef lint
    162 static __inline void *__UNCONST __P((const void *));
    163 static __inline void *
    164 __UNCONST(v)
    165 	const void *v;
    166 {
    167 	/* LINTED */
    168 	return (void *) v;
    169 }
    170 #else
    171 #define __UNCONST(v)	(void *)(v)
    172 #endif
    173 
    174 /*
    175  * Macros for converting digits to letters and vice versa
    176  */
    177 #define	to_digit(c)	((c) - '0')
    178 #define is_digit(c)	((unsigned)to_digit(c) <= 9)
    179 #define	to_char(n)	((char)((n) + '0'))
    180 
    181 /*
    182  * Flags used during conversion.
    183  */
    184 #define	ALT		0x001		/* alternate form */
    185 #define	HEXPREFIX	0x002		/* add 0x or 0X prefix */
    186 #define	LADJUST		0x004		/* left adjustment */
    187 #define	LONGDBL		0x008		/* long double; unimplemented */
    188 #define	LONGINT		0x010		/* long integer */
    189 #define	QUADINT		0x020		/* quad integer */
    190 #define	SHORTINT	0x040		/* short integer */
    191 #define	MAXINT		0x080		/* (unsigned) intmax_t */
    192 #define	PTRINT		0x100		/* (unsigned) ptrdiff_t */
    193 #define	SIZEINT		0x200		/* (signed) size_t */
    194 #define	ZEROPAD		0x400		/* zero (as opposed to blank) pad */
    195 #define FPT		0x800		/* Floating point number */
    196 int
    197 vfprintf(fp, fmt0, ap)
    198 	FILE *fp;
    199 	const char *fmt0;
    200 	_BSD_VA_LIST_ ap;
    201 {
    202 	const char *fmt;/* format string */
    203 	int ch;	/* character from fmt */
    204 	int n, m;	/* handy integers (short term usage) */
    205 	const char *cp;	/* handy char pointer (short term usage) */
    206 	char *bp;	/* handy char pointer (short term usage) */
    207 	struct __siov *iovp;/* for PRINT macro */
    208 	int flags;	/* flags as above */
    209 	int ret;		/* return value accumulator */
    210 	int width;		/* width from format (%8d), or 0 */
    211 	int prec;		/* precision from format (%.3d), or -1 */
    212 	char sign;		/* sign prefix (' ', '+', '-', or \0) */
    213 	wchar_t wc;
    214 	mbstate_t ps;
    215 #ifdef FLOATING_POINT
    216 	char *decimal_point = localeconv()->decimal_point;
    217 	char softsign;		/* temporary negative sign for floats */
    218 	double _double = 0;	/* double precision arguments %[eEfgG] */
    219 	int expt;		/* integer value of exponent */
    220 	int expsize = 0;	/* character count for expstr */
    221 	int ndig;		/* actual number of digits returned by cvt */
    222 	char expstr[7];		/* buffer for exponent string */
    223 #endif
    224 
    225 #ifdef __GNUC__			/* gcc has builtin quad type (long long) SOS */
    226 #define	quad_t	  long long
    227 #define	u_quad_t  unsigned long long
    228 #endif
    229 
    230 #define	INTMAX_T	intmax_t
    231 #define	UINTMAX_T	uintmax_t
    232 
    233 	UINTMAX_T _uintmax;	/* integer arguments %[diouxX] */
    234 	enum { OCT, DEC, HEX } base;/* base for [diouxX] conversion */
    235 	int dprec;		/* a copy of prec if [diouxX], 0 otherwise */
    236 	int realsz;		/* field size expanded by dprec */
    237 	int size;		/* size of converted field or string */
    238 	char *xdigs = NULL;	/* digits for [xX] conversion */
    239 #define NIOV 8
    240 	struct __suio uio;	/* output information: summary */
    241 	struct __siov iov[NIOV];/* ... and individual io vectors */
    242 	char buf[BUF];		/* space for %c, %[diouxX], %[eEfgG] */
    243 	char ox[2];		/* space for 0x hex-prefix */
    244 
    245 	/*
    246 	 * Choose PADSIZE to trade efficiency vs. size.  If larger printf
    247 	 * fields occur frequently, increase PADSIZE and make the initialisers
    248 	 * below longer.
    249 	 */
    250 #define	PADSIZE	16		/* pad chunk size */
    251 	static const char blanks[PADSIZE] =
    252 	 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
    253 	static const char zeroes[PADSIZE] =
    254 	 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
    255 
    256 	/*
    257 	 * BEWARE, these `goto error' on error, and PAD uses `n'.
    258 	 */
    259 #define	PRINT(ptr, len) { \
    260 	iovp->iov_base = __UNCONST(ptr); \
    261 	iovp->iov_len = (len); \
    262 	uio.uio_resid += (len); \
    263 	iovp++; \
    264 	if (++uio.uio_iovcnt >= NIOV) { \
    265 		if (__sprint(fp, &uio)) \
    266 			goto error; \
    267 		iovp = iov; \
    268 	} \
    269 }
    270 #define	PAD(howmany, with) { \
    271 	if ((n = (howmany)) > 0) { \
    272 		while (n > PADSIZE) { \
    273 			PRINT(with, PADSIZE); \
    274 			n -= PADSIZE; \
    275 		} \
    276 		PRINT(with, n); \
    277 	} \
    278 }
    279 #define	FLUSH() { \
    280 	if (uio.uio_resid && __sprint(fp, &uio)) \
    281 		goto error; \
    282 	uio.uio_iovcnt = 0; \
    283 	iovp = iov; \
    284 }
    285 
    286 	/*
    287 	 * To extend shorts properly, we need both signed and unsigned
    288 	 * argument extraction methods.
    289 	 */
    290 #define	SARG() \
    291 	(flags&MAXINT ? va_arg(ap, intmax_t) : \
    292 	    flags&PTRINT ? va_arg(ap, ptrdiff_t) : \
    293 	    flags&SIZEINT ? va_arg(ap, ssize_t) : /* XXX */ \
    294 	    flags&QUADINT ? va_arg(ap, quad_t) : \
    295 	    flags&LONGINT ? va_arg(ap, long) : \
    296 	    flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
    297 	    (long)va_arg(ap, int))
    298 #define	UARG() \
    299 	(flags&MAXINT ? va_arg(ap, uintmax_t) : \
    300 	    flags&PTRINT ? va_arg(ap, uintptr_t) : /* XXX */ \
    301 	    flags&SIZEINT ? va_arg(ap, size_t) : \
    302 	    flags&QUADINT ? va_arg(ap, u_quad_t) : \
    303 	    flags&LONGINT ? va_arg(ap, u_long) : \
    304 	    flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \
    305 	    (u_long)va_arg(ap, u_int))
    306 
    307 	_DIAGASSERT(fp != NULL);
    308 	_DIAGASSERT(fmt0 != NULL);
    309 
    310 	FLOCKFILE(fp);
    311 
    312 	/* sorry, fprintf(read_only_file, "") returns -1, not 0 */
    313 	if (cantwrite(fp)) {
    314 		errno = EBADF;
    315 		FUNLOCKFILE(fp);
    316 		return (-1);
    317 	}
    318 
    319 	/* optimise fprintf(stderr) (and other unbuffered Unix files) */
    320 	if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
    321 	    fp->_file >= 0) {
    322 		ret = __sbprintf(fp, fmt0, ap);
    323 		FUNLOCKFILE(fp);
    324 		return (ret);
    325 	}
    326 
    327 	fmt = fmt0;
    328 	uio.uio_iov = iovp = iov;
    329 	uio.uio_resid = 0;
    330 	uio.uio_iovcnt = 0;
    331 	ret = 0;
    332 
    333 	memset(&ps, 0, sizeof(ps));
    334 
    335 	/*
    336 	 * Scan the format for conversions (`%' character).
    337 	 */
    338 	for (;;) {
    339 		cp = fmt;
    340 		while ((n = mbrtowc(&wc, fmt, MB_CUR_MAX, &ps)) > 0) {
    341 			fmt += n;
    342 			if (wc == '%') {
    343 				fmt--;
    344 				break;
    345 			}
    346 		}
    347 		if ((m = fmt - cp) != 0) {
    348 			PRINT(cp, m);
    349 			ret += m;
    350 		}
    351 		if (n <= 0)
    352 			goto done;
    353 		fmt++;		/* skip over '%' */
    354 
    355 		flags = 0;
    356 		dprec = 0;
    357 		width = 0;
    358 		prec = -1;
    359 		sign = '\0';
    360 
    361 rflag:		ch = *fmt++;
    362 reswitch:	switch (ch) {
    363 		case ' ':
    364 			/*
    365 			 * ``If the space and + flags both appear, the space
    366 			 * flag will be ignored.''
    367 			 *	-- ANSI X3J11
    368 			 */
    369 			if (!sign)
    370 				sign = ' ';
    371 			goto rflag;
    372 		case '#':
    373 			flags |= ALT;
    374 			goto rflag;
    375 		case '*':
    376 			/*
    377 			 * ``A negative field width argument is taken as a
    378 			 * - flag followed by a positive field width.''
    379 			 *	-- ANSI X3J11
    380 			 * They don't exclude field widths read from args.
    381 			 */
    382 			if ((width = va_arg(ap, int)) >= 0)
    383 				goto rflag;
    384 			width = -width;
    385 			/* FALLTHROUGH */
    386 		case '-':
    387 			flags |= LADJUST;
    388 			goto rflag;
    389 		case '+':
    390 			sign = '+';
    391 			goto rflag;
    392 		case '.':
    393 			if ((ch = *fmt++) == '*') {
    394 				n = va_arg(ap, int);
    395 				prec = n < 0 ? -1 : n;
    396 				goto rflag;
    397 			}
    398 			n = 0;
    399 			while (is_digit(ch)) {
    400 				n = 10 * n + to_digit(ch);
    401 				ch = *fmt++;
    402 			}
    403 			prec = n < 0 ? -1 : n;
    404 			goto reswitch;
    405 		case '0':
    406 			/*
    407 			 * ``Note that 0 is taken as a flag, not as the
    408 			 * beginning of a field width.''
    409 			 *	-- ANSI X3J11
    410 			 */
    411 			flags |= ZEROPAD;
    412 			goto rflag;
    413 		case '1': case '2': case '3': case '4':
    414 		case '5': case '6': case '7': case '8': case '9':
    415 			n = 0;
    416 			do {
    417 				n = 10 * n + to_digit(ch);
    418 				ch = *fmt++;
    419 			} while (is_digit(ch));
    420 			width = n;
    421 			goto reswitch;
    422 #ifdef FLOATING_POINT
    423 		case 'L':
    424 			flags |= LONGDBL;
    425 			goto rflag;
    426 #endif
    427 		case 'h':
    428 			flags |= SHORTINT;
    429 			goto rflag;
    430 		case 'j':
    431 			flags |= MAXINT;
    432 			goto rflag;
    433 		case 'l':
    434 			if (*fmt == 'l') {
    435 				fmt++;
    436 				flags |= QUADINT;
    437 			} else {
    438 				flags |= LONGINT;
    439 			}
    440 			goto rflag;
    441 		case 'q':
    442 			flags |= QUADINT;
    443 			goto rflag;
    444 		case 't':
    445 			flags |= PTRINT;
    446 			goto rflag;
    447 		case 'z':
    448 			flags |= SIZEINT;
    449 			goto rflag;
    450 		case 'c':
    451 			*buf = va_arg(ap, int);
    452 			cp = buf;
    453 			size = 1;
    454 			sign = '\0';
    455 			break;
    456 		case 'D':
    457 			flags |= LONGINT;
    458 			/*FALLTHROUGH*/
    459 		case 'd':
    460 		case 'i':
    461 			_uintmax = SARG();
    462 			if ((intmax_t)_uintmax < 0) {
    463 				_uintmax = -_uintmax;
    464 				sign = '-';
    465 			}
    466 			base = DEC;
    467 			goto number;
    468 #ifdef FLOATING_POINT
    469 		case 'e':
    470 		case 'E':
    471 		case 'f':
    472 		case 'g':
    473 		case 'G':
    474 			if (prec == -1) {
    475 				prec = DEFPREC;
    476 			} else if ((ch == 'g' || ch == 'G') && prec == 0) {
    477 				prec = 1;
    478 			}
    479 
    480 			if (flags & LONGDBL) {
    481 				_double = (double) va_arg(ap, long double);
    482 			} else {
    483 				_double = va_arg(ap, double);
    484 			}
    485 
    486 			/* do this before tricky precision changes */
    487 			if (isinf(_double)) {
    488 				if (_double < 0)
    489 					sign = '-';
    490 				cp = "Inf";
    491 				size = 3;
    492 				break;
    493 			}
    494 			if (isnan(_double)) {
    495 				cp = "NaN";
    496 				size = 3;
    497 				break;
    498 			}
    499 
    500 			flags |= FPT;
    501 			cp = cvt(_double, prec, flags, &softsign,
    502 				&expt, ch, &ndig);
    503 			if (ch == 'g' || ch == 'G') {
    504 				if (expt <= -4 || expt > prec)
    505 					ch = (ch == 'g') ? 'e' : 'E';
    506 				else
    507 					ch = 'g';
    508 			}
    509 			if (ch <= 'e') {	/* 'e' or 'E' fmt */
    510 				--expt;
    511 				expsize = exponent(expstr, expt, ch);
    512 				size = expsize + ndig;
    513 				if (ndig > 1 || flags & ALT)
    514 					++size;
    515 			} else if (ch == 'f') {		/* f fmt */
    516 				if (expt > 0) {
    517 					size = expt;
    518 					if (prec || flags & ALT)
    519 						size += prec + 1;
    520 				} else	/* "0.X" */
    521 					size = prec + 2;
    522 			} else if (expt >= ndig) {	/* fixed g fmt */
    523 				size = expt;
    524 				if (flags & ALT)
    525 					++size;
    526 			} else
    527 				size = ndig + (expt > 0 ?
    528 					1 : 2 - expt);
    529 
    530 			if (softsign)
    531 				sign = '-';
    532 			break;
    533 #endif /* FLOATING_POINT */
    534 		case 'n':
    535 			if (flags & MAXINT)
    536 				*va_arg(ap, intmax_t *) = ret;
    537 			else if (flags & PTRINT)
    538 				*va_arg(ap, ptrdiff_t *) = ret;
    539 			else if (flags & SIZEINT)
    540 				*va_arg(ap, ssize_t *) = ret;	/* XXX */
    541 			else if (flags & QUADINT)
    542 				*va_arg(ap, quad_t *) = ret;
    543 			else if (flags & LONGINT)
    544 				*va_arg(ap, long *) = ret;
    545 			else if (flags & SHORTINT)
    546 				*va_arg(ap, short *) = ret;
    547 			else
    548 				*va_arg(ap, int *) = ret;
    549 			continue;	/* no output */
    550 		case 'O':
    551 			flags |= LONGINT;
    552 			/*FALLTHROUGH*/
    553 		case 'o':
    554 			_uintmax = UARG();
    555 			base = OCT;
    556 			goto nosign;
    557 		case 'p':
    558 			/*
    559 			 * ``The argument shall be a pointer to void.  The
    560 			 * value of the pointer is converted to a sequence
    561 			 * of printable characters, in an implementation-
    562 			 * defined manner.''
    563 			 *	-- ANSI X3J11
    564 			 */
    565 			/* NOSTRICT */
    566 			_uintmax = (u_long)va_arg(ap, void *);
    567 			base = HEX;
    568 			xdigs = "0123456789abcdef";
    569 			flags |= HEXPREFIX;
    570 			ch = 'x';
    571 			goto nosign;
    572 		case 's':
    573 			if ((cp = va_arg(ap, char *)) == NULL)
    574 				cp = "(null)";
    575 			if (prec >= 0) {
    576 				/*
    577 				 * can't use strlen; can only look for the
    578 				 * NUL in the first `prec' characters, and
    579 				 * strlen() will go further.
    580 				 */
    581 				char *p = memchr(cp, 0, (size_t)prec);
    582 
    583 				if (p != NULL) {
    584 					size = p - cp;
    585 					if (size > prec)
    586 						size = prec;
    587 				} else
    588 					size = prec;
    589 			} else
    590 				size = strlen(cp);
    591 			sign = '\0';
    592 			break;
    593 		case 'U':
    594 			flags |= LONGINT;
    595 			/*FALLTHROUGH*/
    596 		case 'u':
    597 			_uintmax = UARG();
    598 			base = DEC;
    599 			goto nosign;
    600 		case 'X':
    601 			xdigs = "0123456789ABCDEF";
    602 			goto hex;
    603 		case 'x':
    604 			xdigs = "0123456789abcdef";
    605 hex:			_uintmax = UARG();
    606 			base = HEX;
    607 			/* leading 0x/X only if non-zero */
    608 			if (flags & ALT && _uintmax != 0)
    609 				flags |= HEXPREFIX;
    610 
    611 			/* unsigned conversions */
    612 nosign:			sign = '\0';
    613 			/*
    614 			 * ``... diouXx conversions ... if a precision is
    615 			 * specified, the 0 flag will be ignored.''
    616 			 *	-- ANSI X3J11
    617 			 */
    618 number:			if ((dprec = prec) >= 0)
    619 				flags &= ~ZEROPAD;
    620 
    621 			/*
    622 			 * ``The result of converting a zero value with an
    623 			 * explicit precision of zero is no characters.''
    624 			 *	-- ANSI X3J11
    625 			 */
    626 			bp = buf + BUF;
    627 			if (_uintmax != 0 || prec != 0) {
    628 				/*
    629 				 * Unsigned mod is hard, and unsigned mod
    630 				 * by a constant is easier than that by
    631 				 * a variable; hence this switch.
    632 				 */
    633 				switch (base) {
    634 				case OCT:
    635 					do {
    636 						*--bp = to_char(_uintmax & 7);
    637 						_uintmax >>= 3;
    638 					} while (_uintmax);
    639 					/* handle octal leading 0 */
    640 					if (flags & ALT && *bp != '0')
    641 						*--bp = '0';
    642 					break;
    643 
    644 				case DEC:
    645 					/* many numbers are 1 digit */
    646 					while (_uintmax >= 10) {
    647 						*--bp = to_char(_uintmax % 10);
    648 						_uintmax /= 10;
    649 					}
    650 					*--bp = to_char(_uintmax);
    651 					break;
    652 
    653 				case HEX:
    654 					do {
    655 						*--bp = xdigs[(size_t)
    656 						    (_uintmax & 15)];
    657 						_uintmax >>= 4;
    658 					} while (_uintmax);
    659 					break;
    660 
    661 				default:
    662 					cp = "bug in vfprintf: bad base";
    663 					size = strlen(cp);
    664 					goto skipsize;
    665 				}
    666 			}
    667 			cp = bp;
    668 			size = buf + BUF - bp;
    669 		skipsize:
    670 			break;
    671 		default:	/* "%?" prints ?, unless ? is NUL */
    672 			if (ch == '\0')
    673 				goto done;
    674 			/* pretend it was %c with argument ch */
    675 			*buf = ch;
    676 			cp = buf;
    677 			size = 1;
    678 			sign = '\0';
    679 			break;
    680 		}
    681 
    682 		/*
    683 		 * All reasonable formats wind up here.  At this point, `cp'
    684 		 * points to a string which (if not flags&LADJUST) should be
    685 		 * padded out to `width' places.  If flags&ZEROPAD, it should
    686 		 * first be prefixed by any sign or other prefix; otherwise,
    687 		 * it should be blank padded before the prefix is emitted.
    688 		 * After any left-hand padding and prefixing, emit zeroes
    689 		 * required by a decimal [diouxX] precision, then print the
    690 		 * string proper, then emit zeroes required by any leftover
    691 		 * floating precision; finally, if LADJUST, pad with blanks.
    692 		 *
    693 		 * Compute actual size, so we know how much to pad.
    694 		 * size excludes decimal prec; realsz includes it.
    695 		 */
    696 		realsz = dprec > size ? dprec : size;
    697 		if (sign)
    698 			realsz++;
    699 		else if (flags & HEXPREFIX)
    700 			realsz+= 2;
    701 
    702 		/* right-adjusting blank padding */
    703 		if ((flags & (LADJUST|ZEROPAD)) == 0)
    704 			PAD(width - realsz, blanks);
    705 
    706 		/* prefix */
    707 		if (sign) {
    708 			PRINT(&sign, 1);
    709 		} else if (flags & HEXPREFIX) {
    710 			ox[0] = '0';
    711 			ox[1] = ch;
    712 			PRINT(ox, 2);
    713 		}
    714 
    715 		/* right-adjusting zero padding */
    716 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
    717 			PAD(width - realsz, zeroes);
    718 
    719 		/* leading zeroes from decimal precision */
    720 		PAD(dprec - size, zeroes);
    721 
    722 		/* the string or number proper */
    723 #ifdef FLOATING_POINT
    724 		if ((flags & FPT) == 0) {
    725 			PRINT(cp, size);
    726 		} else {	/* glue together f_p fragments */
    727 			if (ch >= 'f') {	/* 'f' or 'g' */
    728 				if (_double == 0) {
    729 					/* kludge for __dtoa irregularity */
    730 					PRINT("0", 1);
    731 					if (expt < ndig || (flags & ALT) != 0) {
    732 						PRINT(decimal_point, 1);
    733 						PAD(ndig - 1, zeroes);
    734 					}
    735 				} else if (expt <= 0) {
    736 					PRINT("0", 1);
    737 					PRINT(decimal_point, 1);
    738 					PAD(-expt, zeroes);
    739 					PRINT(cp, ndig);
    740 				} else if (expt >= ndig) {
    741 					PRINT(cp, ndig);
    742 					PAD(expt - ndig, zeroes);
    743 					if (flags & ALT)
    744 						PRINT(".", 1);
    745 				} else {
    746 					PRINT(cp, expt);
    747 					cp += expt;
    748 					PRINT(".", 1);
    749 					PRINT(cp, ndig-expt);
    750 				}
    751 			} else {	/* 'e' or 'E' */
    752 				if (ndig > 1 || flags & ALT) {
    753 					ox[0] = *cp++;
    754 					ox[1] = '.';
    755 					PRINT(ox, 2);
    756 					if (_double) {
    757 						PRINT(cp, ndig-1);
    758 					} else	/* 0.[0..] */
    759 						/* __dtoa irregularity */
    760 						PAD(ndig - 1, zeroes);
    761 				} else	/* XeYYY */
    762 					PRINT(cp, 1);
    763 				PRINT(expstr, expsize);
    764 			}
    765 		}
    766 #else
    767 		PRINT(cp, size);
    768 #endif
    769 		/* left-adjusting padding (always blank) */
    770 		if (flags & LADJUST)
    771 			PAD(width - realsz, blanks);
    772 
    773 		/* finally, adjust ret */
    774 		ret += width > realsz ? width : realsz;
    775 
    776 		FLUSH();	/* copy out the I/O vectors */
    777 	}
    778 done:
    779 	FLUSH();
    780 error:
    781 	if (__sferror(fp))
    782 		ret = -1;
    783 	FUNLOCKFILE(fp);
    784 	return (ret);
    785 }
    786 
    787 #ifdef FLOATING_POINT
    788 
    789 static char *
    790 cvt(value, ndigits, flags, sign, decpt, ch, length)
    791 	double value;
    792 	int ndigits, flags, *decpt, ch, *length;
    793 	char *sign;
    794 {
    795 	int mode, dsgn;
    796 	char *digits, *bp, *rve;
    797 
    798 	_DIAGASSERT(decpt != NULL);
    799 	_DIAGASSERT(length != NULL);
    800 	_DIAGASSERT(sign != NULL);
    801 
    802 	if (ch == 'f') {
    803 		mode = 3;		/* ndigits after the decimal point */
    804 	} else {
    805 		/* To obtain ndigits after the decimal point for the 'e'
    806 		 * and 'E' formats, round to ndigits + 1 significant
    807 		 * figures.
    808 		 */
    809 		if (ch == 'e' || ch == 'E') {
    810 			ndigits++;
    811 		}
    812 		mode = 2;		/* ndigits significant digits */
    813 	}
    814 
    815 	if (value < 0) {
    816 		value = -value;
    817 		*sign = '-';
    818 	} else
    819 		*sign = '\000';
    820 	digits = __dtoa(value, mode, ndigits, decpt, &dsgn, &rve);
    821 	if ((ch != 'g' && ch != 'G') || flags & ALT) {	/* Print trailing zeros */
    822 		bp = digits + ndigits;
    823 		if (ch == 'f') {
    824 			if (*digits == '0' && value)
    825 				*decpt = -ndigits + 1;
    826 			bp += *decpt;
    827 		}
    828 		if (value == 0)	/* kludge for __dtoa irregularity */
    829 			rve = bp;
    830 		while (rve < bp)
    831 			*rve++ = '0';
    832 	}
    833 	*length = rve - digits;
    834 	return (digits);
    835 }
    836 
    837 static int
    838 exponent(p0, expon, fmtch)
    839 	char *p0;
    840 	int expon, fmtch;
    841 {
    842 	char *p, *t;
    843 	char expbuf[MAXEXP];
    844 
    845 	_DIAGASSERT(p0 != NULL);
    846 
    847 	p = p0;
    848 	*p++ = fmtch;
    849 	if (expon < 0) {
    850 		expon = -expon;
    851 		*p++ = '-';
    852 	}
    853 	else
    854 		*p++ = '+';
    855 	t = expbuf + MAXEXP;
    856 	if (expon > 9) {
    857 		do {
    858 			*--t = to_char(expon % 10);
    859 		} while ((expon /= 10) > 9);
    860 		*--t = to_char(expon);
    861 		for (; t < expbuf + MAXEXP; *p++ = *t++);
    862 	}
    863 	else {
    864 		*p++ = '0';
    865 		*p++ = to_char(expon);
    866 	}
    867 	return (p - p0);
    868 }
    869 #endif /* FLOATING_POINT */
    870