Home | History | Annotate | Download | only in stdio
      1 /*	$OpenBSD: vfwprintf.c,v 1.15 2015/12/28 22:08:18 mmcc Exp $ */
      2 /*-
      3  * Copyright (c) 1990 The Regents of the University of California.
      4  * All rights reserved.
      5  *
      6  * This code is derived from software contributed to Berkeley by
      7  * Chris Torek.
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *    notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  * 3. Neither the name of the University nor the names of its contributors
     18  *    may be used to endorse or promote products derived from this software
     19  *    without specific prior written permission.
     20  *
     21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     31  * SUCH DAMAGE.
     32  */
     33 
     34 /*
     35  * Actual wprintf innards.
     36  *
     37  * This code is large and complicated...
     38  */
     39 
     40 #include <sys/types.h>
     41 #include <sys/mman.h>
     42 
     43 #include <errno.h>
     44 #include <langinfo.h>
     45 #include <limits.h>
     46 #include <stdarg.h>
     47 #include <stddef.h>
     48 #include <stdio.h>
     49 #include <stdint.h>
     50 #include <stdlib.h>
     51 #include <string.h>
     52 #include <unistd.h>
     53 
     54 #include "local.h"
     55 #include "fvwrite.h"
     56 
     57 union arg {
     58 	int			intarg;
     59 	unsigned int		uintarg;
     60 	long			longarg;
     61 	unsigned long		ulongarg;
     62 	long long		longlongarg;
     63 	unsigned long long	ulonglongarg;
     64 	ptrdiff_t		ptrdiffarg;
     65 	size_t			sizearg;
     66 	ssize_t			ssizearg;
     67 	intmax_t		intmaxarg;
     68 	uintmax_t		uintmaxarg;
     69 	void			*pvoidarg;
     70 	char			*pchararg;
     71 	signed char		*pschararg;
     72 	short			*pshortarg;
     73 	int			*pintarg;
     74 	long			*plongarg;
     75 	long long		*plonglongarg;
     76 	ptrdiff_t		*pptrdiffarg;
     77 	ssize_t			*pssizearg;
     78 	intmax_t		*pintmaxarg;
     79 #ifdef FLOATING_POINT
     80 	double			doublearg;
     81 	long double		longdoublearg;
     82 #endif
     83 	wint_t			wintarg;
     84 	wchar_t			*pwchararg;
     85 };
     86 
     87 static int __find_arguments(const wchar_t *fmt0, va_list ap, union arg **argtable,
     88     size_t *argtablesiz);
     89 static int __grow_type_table(unsigned char **typetable, int *tablesize);
     90 
     91 /*
     92  * Helper function for `fprintf to unbuffered unix file': creates a
     93  * temporary buffer.  We only work on write-only files; this avoids
     94  * worries about ungetc buffers and so forth.
     95  */
     96 static int
     97 __sbprintf(FILE *fp, const wchar_t *fmt, va_list ap)
     98 {
     99 	int ret;
    100 	FILE fake;
    101 	struct __sfileext fakeext;
    102 	unsigned char buf[BUFSIZ];
    103 
    104 	_FILEEXT_SETUP(&fake, &fakeext);
    105 	/* copy the important variables */
    106 	fake._flags = fp->_flags & ~__SNBF;
    107 	fake._file = fp->_file;
    108 	fake._cookie = fp->_cookie;
    109 	fake._write = fp->_write;
    110 
    111 	/* set up the buffer */
    112 	fake._bf._base = fake._p = buf;
    113 	fake._bf._size = fake._w = sizeof(buf);
    114 	fake._lbfsize = 0;	/* not actually used, but Just In Case */
    115 
    116 	/* do the work, then copy any error status */
    117 	ret = __vfwprintf(&fake, fmt, ap);
    118 	if (ret >= 0 && __sflush(&fake))
    119 		ret = EOF;
    120 	if (fake._flags & __SERR)
    121 		fp->_flags |= __SERR;
    122 	return (ret);
    123 }
    124 
    125 /*
    126  * Like __fputwc_unlock, but handles fake string (__SSTR) files properly.
    127  * File must already be locked.
    128  */
    129 static wint_t
    130 __xfputwc(wchar_t wc, FILE *fp)
    131 {
    132 	mbstate_t mbs;
    133 	char buf[MB_LEN_MAX];
    134 	struct __suio uio;
    135 	struct __siov iov;
    136 	size_t len;
    137 
    138 	if ((fp->_flags & __SSTR) == 0)
    139 		return (__fputwc_unlock(wc, fp));
    140 
    141 	bzero(&mbs, sizeof(mbs));
    142 	len = wcrtomb(buf, wc, &mbs);
    143 	if (len == (size_t)-1) {
    144 		fp->_flags |= __SERR;
    145 		errno = EILSEQ;
    146 		return (WEOF);
    147 	}
    148 	uio.uio_iov = &iov;
    149 	uio.uio_resid = len;
    150 	uio.uio_iovcnt = 1;
    151 	iov.iov_base = buf;
    152 	iov.iov_len = len;
    153 	return (__sfvwrite(fp, &uio) != EOF ? (wint_t)wc : WEOF);
    154 }
    155 
    156 /*
    157  * Convert a multibyte character string argument for the %s format to a wide
    158  * string representation. ``prec'' specifies the maximum number of bytes
    159  * to output. If ``prec'' is greater than or equal to zero, we can't assume
    160  * that the multibyte character string ends in a null character.
    161  *
    162  * Returns NULL on failure.
    163  * To find out what happened check errno for ENOMEM, EILSEQ and EINVAL.
    164  */
    165 static wchar_t *
    166 __mbsconv(char *mbsarg, int prec)
    167 {
    168 	mbstate_t mbs;
    169 	wchar_t *convbuf, *wcp;
    170 	const char *p;
    171 	size_t insize, nchars, nconv;
    172 
    173 	if (mbsarg == NULL)
    174 		return (NULL);
    175 
    176 	/*
    177 	 * Supplied argument is a multibyte string; convert it to wide
    178 	 * characters first.
    179 	 */
    180 	if (prec >= 0) {
    181 		/*
    182 		 * String is not guaranteed to be NUL-terminated. Find the
    183 		 * number of characters to print.
    184 		 */
    185 		p = mbsarg;
    186 		insize = nchars = nconv = 0;
    187 		bzero(&mbs, sizeof(mbs));
    188 		while (nchars != (size_t)prec) {
    189 			nconv = mbrlen(p, MB_CUR_MAX, &mbs);
    190 			if (nconv == (size_t)0 || nconv == (size_t)-1 ||
    191 			    nconv == (size_t)-2)
    192 				break;
    193 			p += nconv;
    194 			nchars++;
    195 			insize += nconv;
    196 		}
    197 		if (nconv == (size_t)-1 || nconv == (size_t)-2)
    198 			return (NULL);
    199 	} else
    200 		insize = strlen(mbsarg);
    201 
    202 	/*
    203 	 * Allocate buffer for the result and perform the conversion,
    204 	 * converting at most `size' bytes of the input multibyte string to
    205 	 * wide characters for printing.
    206 	 */
    207 	convbuf = calloc(insize + 1, sizeof(*convbuf));
    208 	if (convbuf == NULL)
    209 		return (NULL);
    210 	wcp = convbuf;
    211 	p = mbsarg;
    212 	bzero(&mbs, sizeof(mbs));
    213 	nconv = 0;
    214 	while (insize != 0) {
    215 		nconv = mbrtowc(wcp, p, insize, &mbs);
    216 		if (nconv == 0 || nconv == (size_t)-1 || nconv == (size_t)-2)
    217 			break;
    218 		wcp++;
    219 		p += nconv;
    220 		insize -= nconv;
    221 	}
    222 	if (nconv == (size_t)-1 || nconv == (size_t)-2) {
    223 		free(convbuf);
    224 		return (NULL);
    225 	}
    226 	*wcp = '\0';
    227 
    228 	return (convbuf);
    229 }
    230 
    231 #ifdef FLOATING_POINT
    232 #include <float.h>
    233 #include <locale.h>
    234 #include <math.h>
    235 #include "floatio.h"
    236 #include "gdtoa.h"
    237 
    238 #define	DEFPREC		6
    239 
    240 static int exponent(wchar_t *, int, int);
    241 #endif /* FLOATING_POINT */
    242 
    243 /*
    244  * The size of the buffer we use as scratch space for integer
    245  * conversions, among other things.  Technically, we would need the
    246  * most space for base 10 conversions with thousands' grouping
    247  * characters between each pair of digits.  100 bytes is a
    248  * conservative overestimate even for a 128-bit uintmax_t.
    249  */
    250 #define BUF	100
    251 
    252 #define STATIC_ARG_TBL_SIZE 8	/* Size of static argument table. */
    253 
    254 
    255 /*
    256  * Macros for converting digits to letters and vice versa
    257  */
    258 #define	to_digit(c)	((c) - '0')
    259 #define is_digit(c)	((unsigned)to_digit(c) <= 9)
    260 #define	to_char(n)	((wchar_t)((n) + '0'))
    261 
    262 /*
    263  * Flags used during conversion.
    264  */
    265 #define	ALT		0x0001		/* alternate form */
    266 #define	LADJUST		0x0004		/* left adjustment */
    267 #define	LONGDBL		0x0008		/* long double */
    268 #define	LONGINT		0x0010		/* long integer */
    269 #define	LLONGINT	0x0020		/* long long integer */
    270 #define	SHORTINT	0x0040		/* short integer */
    271 #define	ZEROPAD		0x0080		/* zero (as opposed to blank) pad */
    272 #define FPT		0x0100		/* Floating point number */
    273 #define PTRINT		0x0200		/* (unsigned) ptrdiff_t */
    274 #define SIZEINT		0x0400		/* (signed) size_t */
    275 #define CHARINT		0x0800		/* 8 bit integer */
    276 #define MAXINT		0x1000		/* largest integer size (intmax_t) */
    277 
    278 int
    279 __vfwprintf(FILE * __restrict fp, const wchar_t * __restrict fmt0, __va_list ap)
    280 {
    281 	wchar_t *fmt;		/* format string */
    282 	wchar_t ch;		/* character from fmt */
    283 	int n, n2, n3;		/* handy integers (short term usage) */
    284 	wchar_t *cp;		/* handy char pointer (short term usage) */
    285 	int flags;		/* flags as above */
    286 	int ret;		/* return value accumulator */
    287 	int width;		/* width from format (%8d), or 0 */
    288 	int prec;		/* precision from format; <0 for N/A */
    289 	wchar_t sign;		/* sign prefix (' ', '+', '-', or \0) */
    290 #ifdef FLOATING_POINT
    291 	/*
    292 	 * We can decompose the printed representation of floating
    293 	 * point numbers into several parts, some of which may be empty:
    294 	 *
    295 	 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
    296 	 *    A       B     ---C---      D       E   F
    297 	 *
    298 	 * A:	'sign' holds this value if present; '\0' otherwise
    299 	 * B:	ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
    300 	 * C:	cp points to the string MMMNNN.  Leading and trailing
    301 	 *	zeros are not in the string and must be added.
    302 	 * D:	expchar holds this character; '\0' if no exponent, e.g. %f
    303 	 * F:	at least two digits for decimal, at least one digit for hex
    304 	 */
    305 	char *decimal_point = NULL;
    306 	int signflag;		/* true if float is negative */
    307 	union {			/* floating point arguments %[aAeEfFgG] */
    308 		double dbl;
    309 		long double ldbl;
    310 	} fparg;
    311 	int expt;		/* integer value of exponent */
    312 	char expchar;		/* exponent character: [eEpP\0] */
    313 	char *dtoaend;		/* pointer to end of converted digits */
    314 	int expsize;		/* character count for expstr */
    315 	int lead;		/* sig figs before decimal or group sep */
    316 	int ndig;		/* actual number of digits returned by dtoa */
    317 	wchar_t expstr[MAXEXPDIG+2];	/* buffer for exponent string: e+ZZZ */
    318 	char *dtoaresult = NULL;
    319 #endif
    320 
    321 	uintmax_t _umax;	/* integer arguments %[diouxX] */
    322 	enum { OCT, DEC, HEX } base;	/* base for %[diouxX] conversion */
    323 	int dprec;		/* a copy of prec if %[diouxX], 0 otherwise */
    324 	int realsz;		/* field size expanded by dprec */
    325 	int size;		/* size of converted field or string */
    326 	const char *xdigs;	/* digits for %[xX] conversion */
    327 	wchar_t buf[BUF];	/* buffer with space for digits of uintmax_t */
    328 	wchar_t ox[2];		/* space for 0x; ox[1] is either x, X, or \0 */
    329 	union arg *argtable;	/* args, built due to positional arg */
    330 	union arg statargtable[STATIC_ARG_TBL_SIZE];
    331 	size_t argtablesiz;
    332 	int nextarg;		/* 1-based argument index */
    333 	va_list orgap;		/* original argument pointer */
    334 	wchar_t *convbuf;	/* buffer for multibyte to wide conversion */
    335 
    336 	/*
    337 	 * Choose PADSIZE to trade efficiency vs. size.  If larger printf
    338 	 * fields occur frequently, increase PADSIZE and make the initialisers
    339 	 * below longer.
    340 	 */
    341 #define	PADSIZE	16		/* pad chunk size */
    342 	static wchar_t blanks[PADSIZE] =
    343 	 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
    344 	static wchar_t zeroes[PADSIZE] =
    345 	 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
    346 
    347 	static const char xdigs_lower[16] = "0123456789abcdef";
    348 	static const char xdigs_upper[16] = "0123456789ABCDEF";
    349 
    350 	/*
    351 	 * BEWARE, these `goto error' on error, PRINT uses 'n3',
    352 	 * PAD uses `n' and 'n3', and PRINTANDPAD uses 'n', 'n2', and 'n3'.
    353 	 */
    354 #define	PRINT(ptr, len)	do {	\
    355 	for (n3 = 0; n3 < (len); n3++) {	\
    356 		if ((__xfputwc((ptr)[n3], fp)) == WEOF)	\
    357 			goto error; \
    358 	} \
    359 } while (0)
    360 #define	PAD(howmany, with) do { \
    361 	if ((n = (howmany)) > 0) { \
    362 		while (n > PADSIZE) { \
    363 			PRINT(with, PADSIZE); \
    364 			n -= PADSIZE; \
    365 		} \
    366 		PRINT(with, n); \
    367 	} \
    368 } while (0)
    369 #define	PRINTANDPAD(p, ep, len, with) do {	\
    370 	n2 = (ep) - (p);       			\
    371 	if (n2 > (len))				\
    372 		n2 = (len);			\
    373 	if (n2 > 0)				\
    374 		PRINT((p), n2);			\
    375 	PAD((len) - (n2 > 0 ? n2 : 0), (with));	\
    376 } while(0)
    377 
    378 	/*
    379 	 * To extend shorts properly, we need both signed and unsigned
    380 	 * argument extraction methods.
    381 	 */
    382 #define	SARG() \
    383 	((intmax_t)(flags&MAXINT ? GETARG(intmax_t) : \
    384 	    flags&LLONGINT ? GETARG(long long) : \
    385 	    flags&LONGINT ? GETARG(long) : \
    386 	    flags&PTRINT ? GETARG(ptrdiff_t) : \
    387 	    flags&SIZEINT ? GETARG(ssize_t) : \
    388 	    flags&SHORTINT ? (short)GETARG(int) : \
    389 	    flags&CHARINT ? (signed char)GETARG(int) : \
    390 	    GETARG(int)))
    391 #define	UARG() \
    392 	((uintmax_t)(flags&MAXINT ? GETARG(uintmax_t) : \
    393 	    flags&LLONGINT ? GETARG(unsigned long long) : \
    394 	    flags&LONGINT ? GETARG(unsigned long) : \
    395 	    flags&PTRINT ? (uintptr_t)GETARG(ptrdiff_t) : /* XXX */ \
    396 	    flags&SIZEINT ? GETARG(size_t) : \
    397 	    flags&SHORTINT ? (unsigned short)GETARG(int) : \
    398 	    flags&CHARINT ? (unsigned char)GETARG(int) : \
    399 	    GETARG(unsigned int)))
    400 
    401 	/*
    402 	 * Append a digit to a value and check for overflow.
    403 	 */
    404 #define APPEND_DIGIT(val, dig) do { \
    405 	if ((val) > INT_MAX / 10) \
    406 		goto overflow; \
    407 	(val) *= 10; \
    408 	if ((val) > INT_MAX - to_digit((dig))) \
    409 		goto overflow; \
    410 	(val) += to_digit((dig)); \
    411 } while (0)
    412 
    413 	 /*
    414 	  * Get * arguments, including the form *nn$.  Preserve the nextarg
    415 	  * that the argument can be gotten once the type is determined.
    416 	  */
    417 #define GETASTER(val) \
    418 	n2 = 0; \
    419 	cp = fmt; \
    420 	while (is_digit(*cp)) { \
    421 		APPEND_DIGIT(n2, *cp); \
    422 		cp++; \
    423 	} \
    424 	if (*cp == '$') { \
    425 		int hold = nextarg; \
    426 		if (argtable == NULL) { \
    427 			argtable = statargtable; \
    428 			__find_arguments(fmt0, orgap, &argtable, &argtablesiz); \
    429 		} \
    430 		nextarg = n2; \
    431 		val = GETARG(int); \
    432 		nextarg = hold; \
    433 		fmt = ++cp; \
    434 	} else { \
    435 		val = GETARG(int); \
    436 	}
    437 
    438 /*
    439 * Get the argument indexed by nextarg.   If the argument table is
    440 * built, use it to get the argument.  If its not, get the next
    441 * argument (and arguments must be gotten sequentially).
    442 */
    443 #define GETARG(type) \
    444 	((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
    445 		(nextarg++, va_arg(ap, type)))
    446 
    447 	_SET_ORIENTATION(fp, 1);
    448 	/* sorry, fwprintf(read_only_file, "") returns EOF, not 0 */
    449 	if (cantwrite(fp)) {
    450 		errno = EBADF;
    451 		return (EOF);
    452 	}
    453 
    454 	/* optimise fwprintf(stderr) (and other unbuffered Unix files) */
    455 	if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
    456 	    fp->_file >= 0)
    457 		return (__sbprintf(fp, fmt0, ap));
    458 
    459 	fmt = (wchar_t *)fmt0;
    460 	argtable = NULL;
    461 	nextarg = 1;
    462 	va_copy(orgap, ap);
    463 	ret = 0;
    464 	convbuf = NULL;
    465 
    466 	/*
    467 	 * Scan the format for conversions (`%' character).
    468 	 */
    469 	for (;;) {
    470 		for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
    471 			continue;
    472 		if (fmt != cp) {
    473 			ptrdiff_t m = fmt - cp;
    474 			if (m < 0 || m > INT_MAX - ret)
    475 				goto overflow;
    476 			PRINT(cp, m);
    477 			ret += m;
    478 		}
    479 		if (ch == '\0')
    480 			goto done;
    481 		fmt++;		/* skip over '%' */
    482 
    483 		flags = 0;
    484 		dprec = 0;
    485 		width = 0;
    486 		prec = -1;
    487 		sign = '\0';
    488 		ox[1] = '\0';
    489 
    490 rflag:		ch = *fmt++;
    491 reswitch:	switch (ch) {
    492 		case ' ':
    493 			/*
    494 			 * ``If the space and + flags both appear, the space
    495 			 * flag will be ignored.''
    496 			 *	-- ANSI X3J11
    497 			 */
    498 			if (!sign)
    499 				sign = ' ';
    500 			goto rflag;
    501 		case '#':
    502 			flags |= ALT;
    503 			goto rflag;
    504 		case '\'':
    505 			/* grouping not implemented */
    506 			goto rflag;
    507 		case '*':
    508 			/*
    509 			 * ``A negative field width argument is taken as a
    510 			 * - flag followed by a positive field width.''
    511 			 *	-- ANSI X3J11
    512 			 * They don't exclude field widths read from args.
    513 			 */
    514 			GETASTER(width);
    515 			if (width >= 0)
    516 				goto rflag;
    517 			if (width == INT_MIN)
    518 				goto overflow;
    519 			width = -width;
    520 			/* FALLTHROUGH */
    521 		case '-':
    522 			flags |= LADJUST;
    523 			goto rflag;
    524 		case '+':
    525 			sign = '+';
    526 			goto rflag;
    527 		case '.':
    528 			if ((ch = *fmt++) == '*') {
    529 				GETASTER(n);
    530 				prec = n < 0 ? -1 : n;
    531 				goto rflag;
    532 			}
    533 			n = 0;
    534 			while (is_digit(ch)) {
    535 				APPEND_DIGIT(n, ch);
    536 				ch = *fmt++;
    537 			}
    538 			if (ch == '$') {
    539 				nextarg = n;
    540 				if (argtable == NULL) {
    541 					argtable = statargtable;
    542 					__find_arguments(fmt0, orgap,
    543 					    &argtable, &argtablesiz);
    544 				}
    545 				goto rflag;
    546 			}
    547 			prec = n;
    548 			goto reswitch;
    549 		case '0':
    550 			/*
    551 			 * ``Note that 0 is taken as a flag, not as the
    552 			 * beginning of a field width.''
    553 			 *	-- ANSI X3J11
    554 			 */
    555 			flags |= ZEROPAD;
    556 			goto rflag;
    557 		case '1': case '2': case '3': case '4':
    558 		case '5': case '6': case '7': case '8': case '9':
    559 			n = 0;
    560 			do {
    561 				APPEND_DIGIT(n, ch);
    562 				ch = *fmt++;
    563 			} while (is_digit(ch));
    564 			if (ch == '$') {
    565 				nextarg = n;
    566 				if (argtable == NULL) {
    567 					argtable = statargtable;
    568 					__find_arguments(fmt0, orgap,
    569 					    &argtable, &argtablesiz);
    570 				}
    571 				goto rflag;
    572 			}
    573 			width = n;
    574 			goto reswitch;
    575 #ifdef FLOATING_POINT
    576 		case 'L':
    577 			flags |= LONGDBL;
    578 			goto rflag;
    579 #endif
    580 		case 'h':
    581 			if (*fmt == 'h') {
    582 				fmt++;
    583 				flags |= CHARINT;
    584 			} else {
    585 				flags |= SHORTINT;
    586 			}
    587 			goto rflag;
    588 		case 'j':
    589 			flags |= MAXINT;
    590 			goto rflag;
    591 		case 'l':
    592 			if (*fmt == 'l') {
    593 				fmt++;
    594 				flags |= LLONGINT;
    595 			} else {
    596 				flags |= LONGINT;
    597 			}
    598 			goto rflag;
    599 		case 'q':
    600 			flags |= LLONGINT;
    601 			goto rflag;
    602 		case 't':
    603 			flags |= PTRINT;
    604 			goto rflag;
    605 		case 'z':
    606 			flags |= SIZEINT;
    607 			goto rflag;
    608 		case 'C':
    609 			flags |= LONGINT;
    610 			/*FALLTHROUGH*/
    611 		case 'c':
    612 			if (flags & LONGINT)
    613 				*(cp = buf) = (wchar_t)GETARG(wint_t);
    614 			else
    615 				*(cp = buf) = (wchar_t)btowc(GETARG(int));
    616 			size = 1;
    617 			sign = '\0';
    618 			break;
    619 		case 'D':
    620 			flags |= LONGINT;
    621 			/*FALLTHROUGH*/
    622 		case 'd':
    623 		case 'i':
    624 			_umax = SARG();
    625 			if ((intmax_t)_umax < 0) {
    626 				_umax = -_umax;
    627 				sign = '-';
    628 			}
    629 			base = DEC;
    630 			goto number;
    631 #ifdef FLOATING_POINT
    632 		case 'a':
    633 		case 'A':
    634 			if (ch == 'a') {
    635 				ox[1] = 'x';
    636 				xdigs = xdigs_lower;
    637 				expchar = 'p';
    638 			} else {
    639 				ox[1] = 'X';
    640 				xdigs = xdigs_upper;
    641 				expchar = 'P';
    642 			}
    643 			if (prec >= 0)
    644 				prec++;
    645 			if (dtoaresult)
    646 				__freedtoa(dtoaresult);
    647 			if (flags & LONGDBL) {
    648 				fparg.ldbl = GETARG(long double);
    649 				dtoaresult =
    650 				    __hldtoa(fparg.ldbl, xdigs, prec,
    651 				    &expt, &signflag, &dtoaend);
    652 				if (dtoaresult == NULL) {
    653 					errno = ENOMEM;
    654 					goto error;
    655 				}
    656 			} else {
    657 				fparg.dbl = GETARG(double);
    658 				dtoaresult =
    659 				    __hdtoa(fparg.dbl, xdigs, prec,
    660 				    &expt, &signflag, &dtoaend);
    661 				if (dtoaresult == NULL) {
    662 					errno = ENOMEM;
    663 					goto error;
    664 				}
    665 			}
    666 			if (prec < 0)
    667 				prec = dtoaend - dtoaresult;
    668 			if (expt == INT_MAX)
    669 				ox[1] = '\0';
    670 			free(convbuf);
    671 			cp = convbuf = __mbsconv(dtoaresult, -1);
    672 			if (cp == NULL)
    673 				goto error;
    674 			ndig = dtoaend - dtoaresult;
    675 			goto fp_common;
    676 		case 'e':
    677 		case 'E':
    678 			expchar = ch;
    679 			if (prec < 0)	/* account for digit before decpt */
    680 				prec = DEFPREC + 1;
    681 			else
    682 				prec++;
    683 			goto fp_begin;
    684 		case 'f':
    685 		case 'F':
    686 			expchar = '\0';
    687 			goto fp_begin;
    688 		case 'g':
    689 		case 'G':
    690 			expchar = ch - ('g' - 'e');
    691  			if (prec == 0)
    692  				prec = 1;
    693 fp_begin:
    694 			if (prec < 0)
    695 				prec = DEFPREC;
    696 			if (dtoaresult)
    697 				__freedtoa(dtoaresult);
    698 			if (flags & LONGDBL) {
    699 				fparg.ldbl = GETARG(long double);
    700 				dtoaresult =
    701 				    __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
    702 				    &expt, &signflag, &dtoaend);
    703 				if (dtoaresult == NULL) {
    704 					errno = ENOMEM;
    705 					goto error;
    706 				}
    707 			} else {
    708 				fparg.dbl = GETARG(double);
    709 				dtoaresult =
    710 				    __dtoa(fparg.dbl, expchar ? 2 : 3, prec,
    711 				    &expt, &signflag, &dtoaend);
    712 				if (dtoaresult == NULL) {
    713 					errno = ENOMEM;
    714 					goto error;
    715 				}
    716 				if (expt == 9999)
    717 					expt = INT_MAX;
    718  			}
    719 			free(convbuf);
    720 			cp = convbuf = __mbsconv(dtoaresult, -1);
    721 			if (cp == NULL)
    722 				goto error;
    723 			ndig = dtoaend - dtoaresult;
    724 fp_common:
    725 			if (signflag)
    726 				sign = '-';
    727 			if (expt == INT_MAX) {	/* inf or nan */
    728 				if (*cp == 'N')
    729 					cp = (ch >= 'a') ? L"nan" : L"NAN";
    730 				else
    731 					cp = (ch >= 'a') ? L"inf" : L"INF";
    732  				size = 3;
    733 				flags &= ~ZEROPAD;
    734  				break;
    735  			}
    736 			flags |= FPT;
    737  			if (ch == 'g' || ch == 'G') {
    738 				if (expt > -4 && expt <= prec) {
    739 					/* Make %[gG] smell like %[fF] */
    740 					expchar = '\0';
    741 					if (flags & ALT)
    742 						prec -= expt;
    743 					else
    744 						prec = ndig - expt;
    745 					if (prec < 0)
    746 						prec = 0;
    747 				} else {
    748 					/*
    749 					 * Make %[gG] smell like %[eE], but
    750 					 * trim trailing zeroes if no # flag.
    751 					 */
    752 					if (!(flags & ALT))
    753 						prec = ndig;
    754 				}
    755  			}
    756 			if (expchar) {
    757 				expsize = exponent(expstr, expt - 1, expchar);
    758 				size = expsize + prec;
    759 				if (prec > 1 || flags & ALT)
    760  					++size;
    761 			} else {
    762 				/* space for digits before decimal point */
    763 				if (expt > 0)
    764 					size = expt;
    765 				else	/* "0" */
    766 					size = 1;
    767 				/* space for decimal pt and following digits */
    768 				if (prec || flags & ALT)
    769 					size += prec + 1;
    770 				lead = expt;
    771 			}
    772 			break;
    773 #endif /* FLOATING_POINT */
    774 #ifndef NO_PRINTF_PERCENT_N
    775 		case 'n':
    776 			if (flags & LLONGINT)
    777 				*GETARG(long long *) = ret;
    778 			else if (flags & LONGINT)
    779 				*GETARG(long *) = ret;
    780 			else if (flags & SHORTINT)
    781 				*GETARG(short *) = ret;
    782 			else if (flags & CHARINT)
    783 				*GETARG(signed char *) = ret;
    784 			else if (flags & PTRINT)
    785 				*GETARG(ptrdiff_t *) = ret;
    786 			else if (flags & SIZEINT)
    787 				*GETARG(ssize_t *) = ret;
    788 			else if (flags & MAXINT)
    789 				*GETARG(intmax_t *) = ret;
    790 			else
    791 				*GETARG(int *) = ret;
    792 			continue;	/* no output */
    793 #endif /* NO_PRINTF_PERCENT_N */
    794 		case 'O':
    795 			flags |= LONGINT;
    796 			/*FALLTHROUGH*/
    797 		case 'o':
    798 			_umax = UARG();
    799 			base = OCT;
    800 			goto nosign;
    801 		case 'p':
    802 			/*
    803 			 * ``The argument shall be a pointer to void.  The
    804 			 * value of the pointer is converted to a sequence
    805 			 * of printable characters, in an implementation-
    806 			 * defined manner.''
    807 			 *	-- ANSI X3J11
    808 			 */
    809 			_umax = (u_long)GETARG(void *);
    810 			base = HEX;
    811 			xdigs = xdigs_lower;
    812 			ox[1] = 'x';
    813 			goto nosign;
    814 		case 'S':
    815 			flags |= LONGINT;
    816 			/*FALLTHROUGH*/
    817 		case 's':
    818 			if (flags & LONGINT) {
    819 				if ((cp = GETARG(wchar_t *)) == NULL)
    820 					cp = L"(null)";
    821 			} else {
    822 				char *mbsarg;
    823 				if ((mbsarg = GETARG(char *)) == NULL)
    824 					mbsarg = "(null)";
    825 				free(convbuf);
    826 				convbuf = __mbsconv(mbsarg, prec);
    827 				if (convbuf == NULL) {
    828 					fp->_flags |= __SERR;
    829 					goto error;
    830 				} else
    831 					cp = convbuf;
    832 			}
    833 			if (prec >= 0) {
    834 				/*
    835 				 * can't use wcslen; can only look for the
    836 				 * NUL in the first `prec' characters, and
    837 				 * wcslen() will go further.
    838 				 */
    839 				wchar_t *p = wmemchr(cp, 0, prec);
    840 
    841 				size = p ? (p - cp) : prec;
    842 			} else {
    843 				size_t len;
    844 
    845 				if ((len = wcslen(cp)) > INT_MAX)
    846 					goto overflow;
    847 				size = (int)len;
    848 			}
    849 			sign = '\0';
    850 			break;
    851 		case 'U':
    852 			flags |= LONGINT;
    853 			/*FALLTHROUGH*/
    854 		case 'u':
    855 			_umax = UARG();
    856 			base = DEC;
    857 			goto nosign;
    858 		case 'X':
    859 			xdigs = xdigs_upper;
    860 			goto hex;
    861 		case 'x':
    862 			xdigs = xdigs_lower;
    863 hex:			_umax = UARG();
    864 			base = HEX;
    865 			/* leading 0x/X only if non-zero */
    866 			if (flags & ALT && _umax != 0)
    867 				ox[1] = ch;
    868 
    869 			/* unsigned conversions */
    870 nosign:			sign = '\0';
    871 			/*
    872 			 * ``... diouXx conversions ... if a precision is
    873 			 * specified, the 0 flag will be ignored.''
    874 			 *	-- ANSI X3J11
    875 			 */
    876 number:			if ((dprec = prec) >= 0)
    877 				flags &= ~ZEROPAD;
    878 
    879 			/*
    880 			 * ``The result of converting a zero value with an
    881 			 * explicit precision of zero is no characters.''
    882 			 *	-- ANSI X3J11
    883 			 */
    884 			cp = buf + BUF;
    885 			if (_umax != 0 || prec != 0) {
    886 				/*
    887 				 * Unsigned mod is hard, and unsigned mod
    888 				 * by a constant is easier than that by
    889 				 * a variable; hence this switch.
    890 				 */
    891 				switch (base) {
    892 				case OCT:
    893 					do {
    894 						*--cp = to_char(_umax & 7);
    895 						_umax >>= 3;
    896 					} while (_umax);
    897 					/* handle octal leading 0 */
    898 					if (flags & ALT && *cp != '0')
    899 						*--cp = '0';
    900 					break;
    901 
    902 				case DEC:
    903 					/* many numbers are 1 digit */
    904 					while (_umax >= 10) {
    905 						*--cp = to_char(_umax % 10);
    906 						_umax /= 10;
    907 					}
    908 					*--cp = to_char(_umax);
    909 					break;
    910 
    911 				case HEX:
    912 					do {
    913 						*--cp = xdigs[_umax & 15];
    914 						_umax >>= 4;
    915 					} while (_umax);
    916 					break;
    917 
    918 				default:
    919 					cp = L"bug in vfwprintf: bad base";
    920 					size = wcslen(cp);
    921 					goto skipsize;
    922 				}
    923 			}
    924 			size = buf + BUF - cp;
    925 			if (size > BUF)	/* should never happen */
    926 				abort();
    927 		skipsize:
    928 			break;
    929 		default:	/* "%?" prints ?, unless ? is NUL */
    930 			if (ch == '\0')
    931 				goto done;
    932 			/* pretend it was %c with argument ch */
    933 			cp = buf;
    934 			*cp = ch;
    935 			size = 1;
    936 			sign = '\0';
    937 			break;
    938 		}
    939 
    940 		/*
    941 		 * All reasonable formats wind up here.  At this point, `cp'
    942 		 * points to a string which (if not flags&LADJUST) should be
    943 		 * padded out to `width' places.  If flags&ZEROPAD, it should
    944 		 * first be prefixed by any sign or other prefix; otherwise,
    945 		 * it should be blank padded before the prefix is emitted.
    946 		 * After any left-hand padding and prefixing, emit zeroes
    947 		 * required by a decimal %[diouxX] precision, then print the
    948 		 * string proper, then emit zeroes required by any leftover
    949 		 * floating precision; finally, if LADJUST, pad with blanks.
    950 		 *
    951 		 * Compute actual size, so we know how much to pad.
    952 		 * size excludes decimal prec; realsz includes it.
    953 		 */
    954 		realsz = dprec > size ? dprec : size;
    955 		if (sign)
    956 			realsz++;
    957 		if (ox[1])
    958 			realsz+= 2;
    959 
    960 		/* right-adjusting blank padding */
    961 		if ((flags & (LADJUST|ZEROPAD)) == 0)
    962 			PAD(width - realsz, blanks);
    963 
    964 		/* prefix */
    965 		if (sign)
    966 			PRINT(&sign, 1);
    967 		if (ox[1]) {	/* ox[1] is either x, X, or \0 */
    968 			ox[0] = '0';
    969 			PRINT(ox, 2);
    970 		}
    971 
    972 		/* right-adjusting zero padding */
    973 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
    974 			PAD(width - realsz, zeroes);
    975 
    976 		/* leading zeroes from decimal precision */
    977 		PAD(dprec - size, zeroes);
    978 
    979 		/* the string or number proper */
    980 #ifdef FLOATING_POINT
    981 		if ((flags & FPT) == 0) {
    982 			PRINT(cp, size);
    983 		} else {	/* glue together f_p fragments */
    984 			if (decimal_point == NULL)
    985 				decimal_point = nl_langinfo(RADIXCHAR);
    986 			if (!expchar) {	/* %[fF] or sufficiently short %[gG] */
    987 				if (expt <= 0) {
    988 					PRINT(zeroes, 1);
    989 					if (prec || flags & ALT)
    990 						PRINT(decimal_point, 1);
    991 					PAD(-expt, zeroes);
    992 					/* already handled initial 0's */
    993 					prec += expt;
    994  				} else {
    995 					PRINTANDPAD(cp, convbuf + ndig,
    996 					    lead, zeroes);
    997 					cp += lead;
    998 					if (prec || flags & ALT)
    999 						PRINT(decimal_point, 1);
   1000 				}
   1001 				PRINTANDPAD(cp, convbuf + ndig, prec, zeroes);
   1002 			} else {	/* %[eE] or sufficiently long %[gG] */
   1003 				if (prec > 1 || flags & ALT) {
   1004 					buf[0] = *cp++;
   1005 					buf[1] = *decimal_point;
   1006 					PRINT(buf, 2);
   1007 					PRINT(cp, ndig-1);
   1008 					PAD(prec - ndig, zeroes);
   1009 				} else { /* XeYYY */
   1010 					PRINT(cp, 1);
   1011 				}
   1012 				PRINT(expstr, expsize);
   1013 			}
   1014 		}
   1015 #else
   1016 		PRINT(cp, size);
   1017 #endif
   1018 		/* left-adjusting padding (always blank) */
   1019 		if (flags & LADJUST)
   1020 			PAD(width - realsz, blanks);
   1021 
   1022 		/* finally, adjust ret */
   1023 		if (width < realsz)
   1024 			width = realsz;
   1025 		if (width > INT_MAX - ret)
   1026 			goto overflow;
   1027 		ret += width;
   1028 	}
   1029 done:
   1030 error:
   1031 	va_end(orgap);
   1032 	if (__sferror(fp))
   1033 		ret = -1;
   1034 	goto finish;
   1035 
   1036 overflow:
   1037 	errno = ENOMEM;
   1038 	ret = -1;
   1039 
   1040 finish:
   1041 	free(convbuf);
   1042 #ifdef FLOATING_POINT
   1043 	if (dtoaresult)
   1044 		__freedtoa(dtoaresult);
   1045 #endif
   1046 	if (argtable != NULL && argtable != statargtable) {
   1047 		munmap(argtable, argtablesiz);
   1048 		argtable = NULL;
   1049 	}
   1050 	return (ret);
   1051 }
   1052 
   1053 int
   1054 vfwprintf(FILE * __restrict fp, const wchar_t * __restrict fmt0, __va_list ap)
   1055 {
   1056 	int r;
   1057 
   1058 	FLOCKFILE(fp);
   1059 	r = __vfwprintf(fp, fmt0, ap);
   1060 	FUNLOCKFILE(fp);
   1061 
   1062 	return (r);
   1063 }
   1064 DEF_STRONG(vfwprintf);
   1065 
   1066 /*
   1067  * Type ids for argument type table.
   1068  */
   1069 #define T_UNUSED	0
   1070 #define T_SHORT		1
   1071 #define T_U_SHORT	2
   1072 #define TP_SHORT	3
   1073 #define T_INT		4
   1074 #define T_U_INT		5
   1075 #define TP_INT		6
   1076 #define T_LONG		7
   1077 #define T_U_LONG	8
   1078 #define TP_LONG		9
   1079 #define T_LLONG		10
   1080 #define T_U_LLONG	11
   1081 #define TP_LLONG	12
   1082 #define T_DOUBLE	13
   1083 #define T_LONG_DOUBLE	14
   1084 #define TP_CHAR		15
   1085 #define TP_VOID		16
   1086 #define T_PTRINT	17
   1087 #define TP_PTRINT	18
   1088 #define T_SIZEINT	19
   1089 #define T_SSIZEINT	20
   1090 #define TP_SSIZEINT	21
   1091 #define T_MAXINT	22
   1092 #define T_MAXUINT	23
   1093 #define TP_MAXINT	24
   1094 #define T_CHAR		25
   1095 #define T_U_CHAR	26
   1096 #define T_WINT		27
   1097 #define TP_WCHAR	28
   1098 
   1099 /*
   1100  * Find all arguments when a positional parameter is encountered.  Returns a
   1101  * table, indexed by argument number, of pointers to each arguments.  The
   1102  * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
   1103  * It will be replaced with a mmap-ed one if it overflows (malloc cannot be
   1104  * used since we are attempting to make snprintf thread safe, and alloca is
   1105  * problematic since we have nested functions..)
   1106  */
   1107 static int
   1108 __find_arguments(const wchar_t *fmt0, va_list ap, union arg **argtable,
   1109     size_t *argtablesiz)
   1110 {
   1111 	wchar_t *fmt;		/* format string */
   1112 	int ch;			/* character from fmt */
   1113 	int n, n2;		/* handy integer (short term usage) */
   1114 	wchar_t *cp;		/* handy char pointer (short term usage) */
   1115 	int flags;		/* flags as above */
   1116 	unsigned char *typetable; /* table of types */
   1117 	unsigned char stattypetable[STATIC_ARG_TBL_SIZE];
   1118 	int tablesize;		/* current size of type table */
   1119 	int tablemax;		/* largest used index in table */
   1120 	int nextarg;		/* 1-based argument index */
   1121 	int ret = 0;		/* return value */
   1122 
   1123 	/*
   1124 	 * Add an argument type to the table, expanding if necessary.
   1125 	 */
   1126 #define ADDTYPE(type) \
   1127 	((nextarg >= tablesize) ? \
   1128 		__grow_type_table(&typetable, &tablesize) : 0, \
   1129 	(nextarg > tablemax) ? tablemax = nextarg : 0, \
   1130 	typetable[nextarg++] = type)
   1131 
   1132 #define	ADDSARG() \
   1133         ((flags&MAXINT) ? ADDTYPE(T_MAXINT) : \
   1134 	    ((flags&PTRINT) ? ADDTYPE(T_PTRINT) : \
   1135 	    ((flags&SIZEINT) ? ADDTYPE(T_SSIZEINT) : \
   1136 	    ((flags&LLONGINT) ? ADDTYPE(T_LLONG) : \
   1137 	    ((flags&LONGINT) ? ADDTYPE(T_LONG) : \
   1138 	    ((flags&SHORTINT) ? ADDTYPE(T_SHORT) : \
   1139 	    ((flags&CHARINT) ? ADDTYPE(T_CHAR) : ADDTYPE(T_INT))))))))
   1140 
   1141 #define	ADDUARG() \
   1142         ((flags&MAXINT) ? ADDTYPE(T_MAXUINT) : \
   1143 	    ((flags&PTRINT) ? ADDTYPE(T_PTRINT) : \
   1144 	    ((flags&SIZEINT) ? ADDTYPE(T_SIZEINT) : \
   1145 	    ((flags&LLONGINT) ? ADDTYPE(T_U_LLONG) : \
   1146 	    ((flags&LONGINT) ? ADDTYPE(T_U_LONG) : \
   1147 	    ((flags&SHORTINT) ? ADDTYPE(T_U_SHORT) : \
   1148 	    ((flags&CHARINT) ? ADDTYPE(T_U_CHAR) : ADDTYPE(T_U_INT))))))))
   1149 
   1150 	/*
   1151 	 * Add * arguments to the type array.
   1152 	 */
   1153 #define ADDASTER() \
   1154 	n2 = 0; \
   1155 	cp = fmt; \
   1156 	while (is_digit(*cp)) { \
   1157 		APPEND_DIGIT(n2, *cp); \
   1158 		cp++; \
   1159 	} \
   1160 	if (*cp == '$') { \
   1161 		int hold = nextarg; \
   1162 		nextarg = n2; \
   1163 		ADDTYPE(T_INT); \
   1164 		nextarg = hold; \
   1165 		fmt = ++cp; \
   1166 	} else { \
   1167 		ADDTYPE(T_INT); \
   1168 	}
   1169 	fmt = (wchar_t *)fmt0;
   1170 	typetable = stattypetable;
   1171 	tablesize = STATIC_ARG_TBL_SIZE;
   1172 	tablemax = 0;
   1173 	nextarg = 1;
   1174 	memset(typetable, T_UNUSED, STATIC_ARG_TBL_SIZE);
   1175 
   1176 	/*
   1177 	 * Scan the format for conversions (`%' character).
   1178 	 */
   1179 	for (;;) {
   1180 		for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
   1181 			continue;
   1182 		if (ch == '\0')
   1183 			goto done;
   1184 		fmt++;		/* skip over '%' */
   1185 
   1186 		flags = 0;
   1187 
   1188 rflag:		ch = *fmt++;
   1189 reswitch:	switch (ch) {
   1190 		case ' ':
   1191 		case '#':
   1192 		case '\'':
   1193 			goto rflag;
   1194 		case '*':
   1195 			ADDASTER();
   1196 			goto rflag;
   1197 		case '-':
   1198 		case '+':
   1199 			goto rflag;
   1200 		case '.':
   1201 			if ((ch = *fmt++) == '*') {
   1202 				ADDASTER();
   1203 				goto rflag;
   1204 			}
   1205 			while (is_digit(ch)) {
   1206 				ch = *fmt++;
   1207 			}
   1208 			goto reswitch;
   1209 		case '0':
   1210 			goto rflag;
   1211 		case '1': case '2': case '3': case '4':
   1212 		case '5': case '6': case '7': case '8': case '9':
   1213 			n = 0;
   1214 			do {
   1215 				APPEND_DIGIT(n ,ch);
   1216 				ch = *fmt++;
   1217 			} while (is_digit(ch));
   1218 			if (ch == '$') {
   1219 				nextarg = n;
   1220 				goto rflag;
   1221 			}
   1222 			goto reswitch;
   1223 #ifdef FLOATING_POINT
   1224 		case 'L':
   1225 			flags |= LONGDBL;
   1226 			goto rflag;
   1227 #endif
   1228 		case 'h':
   1229 			if (*fmt == 'h') {
   1230 				fmt++;
   1231 				flags |= CHARINT;
   1232 			} else {
   1233 				flags |= SHORTINT;
   1234 			}
   1235 			goto rflag;
   1236 		case 'l':
   1237 			if (*fmt == 'l') {
   1238 				fmt++;
   1239 				flags |= LLONGINT;
   1240 			} else {
   1241 				flags |= LONGINT;
   1242 			}
   1243 			goto rflag;
   1244 		case 'q':
   1245 			flags |= LLONGINT;
   1246 			goto rflag;
   1247 		case 't':
   1248 			flags |= PTRINT;
   1249 			goto rflag;
   1250 		case 'z':
   1251 			flags |= SIZEINT;
   1252 			goto rflag;
   1253 		case 'C':
   1254 			flags |= LONGINT;
   1255 			/*FALLTHROUGH*/
   1256 		case 'c':
   1257 			if (flags & LONGINT)
   1258 				ADDTYPE(T_WINT);
   1259 			else
   1260 				ADDTYPE(T_INT);
   1261 			break;
   1262 		case 'D':
   1263 			flags |= LONGINT;
   1264 			/*FALLTHROUGH*/
   1265 		case 'd':
   1266 		case 'i':
   1267 			ADDSARG();
   1268 			break;
   1269 #ifdef FLOATING_POINT
   1270 		case 'a':
   1271 		case 'A':
   1272 		case 'e':
   1273 		case 'E':
   1274 		case 'f':
   1275 		case 'F':
   1276 		case 'g':
   1277 		case 'G':
   1278 			if (flags & LONGDBL)
   1279 				ADDTYPE(T_LONG_DOUBLE);
   1280 			else
   1281 				ADDTYPE(T_DOUBLE);
   1282 			break;
   1283 #endif /* FLOATING_POINT */
   1284 #ifndef NO_PRINTF_PERCENT_N
   1285 		case 'n':
   1286 			if (flags & LLONGINT)
   1287 				ADDTYPE(TP_LLONG);
   1288 			else if (flags & LONGINT)
   1289 				ADDTYPE(TP_LONG);
   1290 			else if (flags & SHORTINT)
   1291 				ADDTYPE(TP_SHORT);
   1292 			else if (flags & PTRINT)
   1293 				ADDTYPE(TP_PTRINT);
   1294 			else if (flags & SIZEINT)
   1295 				ADDTYPE(TP_SSIZEINT);
   1296 			else if (flags & MAXINT)
   1297 				ADDTYPE(TP_MAXINT);
   1298 			else
   1299 				ADDTYPE(TP_INT);
   1300 			continue;	/* no output */
   1301 #endif /* NO_PRINTF_PERCENT_N */
   1302 		case 'O':
   1303 			flags |= LONGINT;
   1304 			/*FALLTHROUGH*/
   1305 		case 'o':
   1306 			ADDUARG();
   1307 			break;
   1308 		case 'p':
   1309 			ADDTYPE(TP_VOID);
   1310 			break;
   1311 		case 'S':
   1312 			flags |= LONGINT;
   1313 			/*FALLTHROUGH*/
   1314 		case 's':
   1315 			if (flags & LONGINT)
   1316 				ADDTYPE(TP_CHAR);
   1317 			else
   1318 				ADDTYPE(TP_WCHAR);
   1319 			break;
   1320 		case 'U':
   1321 			flags |= LONGINT;
   1322 			/*FALLTHROUGH*/
   1323 		case 'u':
   1324 		case 'X':
   1325 		case 'x':
   1326 			ADDUARG();
   1327 			break;
   1328 		default:	/* "%?" prints ?, unless ? is NUL */
   1329 			if (ch == '\0')
   1330 				goto done;
   1331 			break;
   1332 		}
   1333 	}
   1334 done:
   1335 	/*
   1336 	 * Build the argument table.
   1337 	 */
   1338 	if (tablemax >= STATIC_ARG_TBL_SIZE) {
   1339 		*argtablesiz = sizeof(union arg) * (tablemax + 1);
   1340 		*argtable = mmap(NULL, *argtablesiz,
   1341 		    PROT_WRITE|PROT_READ, MAP_ANON|MAP_PRIVATE, -1, 0);
   1342 		if (*argtable == MAP_FAILED)
   1343 			return (-1);
   1344 	}
   1345 
   1346 #if 0
   1347 	/* XXX is this required? */
   1348 	(*argtable)[0].intarg = 0;
   1349 #endif
   1350 	for (n = 1; n <= tablemax; n++) {
   1351 		switch (typetable[n]) {
   1352 		case T_UNUSED:
   1353 		case T_CHAR:
   1354 		case T_U_CHAR:
   1355 		case T_SHORT:
   1356 		case T_U_SHORT:
   1357 		case T_INT:
   1358 			(*argtable)[n].intarg = va_arg(ap, int);
   1359 			break;
   1360 		case TP_SHORT:
   1361 			(*argtable)[n].pshortarg = va_arg(ap, short *);
   1362 			break;
   1363 		case T_U_INT:
   1364 			(*argtable)[n].uintarg = va_arg(ap, unsigned int);
   1365 			break;
   1366 		case TP_INT:
   1367 			(*argtable)[n].pintarg = va_arg(ap, int *);
   1368 			break;
   1369 		case T_LONG:
   1370 			(*argtable)[n].longarg = va_arg(ap, long);
   1371 			break;
   1372 		case T_U_LONG:
   1373 			(*argtable)[n].ulongarg = va_arg(ap, unsigned long);
   1374 			break;
   1375 		case TP_LONG:
   1376 			(*argtable)[n].plongarg = va_arg(ap, long *);
   1377 			break;
   1378 		case T_LLONG:
   1379 			(*argtable)[n].longlongarg = va_arg(ap, long long);
   1380 			break;
   1381 		case T_U_LLONG:
   1382 			(*argtable)[n].ulonglongarg = va_arg(ap, unsigned long long);
   1383 			break;
   1384 		case TP_LLONG:
   1385 			(*argtable)[n].plonglongarg = va_arg(ap, long long *);
   1386 			break;
   1387 #ifdef FLOATING_POINT
   1388 		case T_DOUBLE:
   1389 			(*argtable)[n].doublearg = va_arg(ap, double);
   1390 			break;
   1391 		case T_LONG_DOUBLE:
   1392 			(*argtable)[n].longdoublearg = va_arg(ap, long double);
   1393 			break;
   1394 #endif
   1395 		case TP_CHAR:
   1396 			(*argtable)[n].pchararg = va_arg(ap, char *);
   1397 			break;
   1398 		case TP_VOID:
   1399 			(*argtable)[n].pvoidarg = va_arg(ap, void *);
   1400 			break;
   1401 		case T_PTRINT:
   1402 			(*argtable)[n].ptrdiffarg = va_arg(ap, ptrdiff_t);
   1403 			break;
   1404 		case TP_PTRINT:
   1405 			(*argtable)[n].pptrdiffarg = va_arg(ap, ptrdiff_t *);
   1406 			break;
   1407 		case T_SIZEINT:
   1408 			(*argtable)[n].sizearg = va_arg(ap, size_t);
   1409 			break;
   1410 		case T_SSIZEINT:
   1411 			(*argtable)[n].ssizearg = va_arg(ap, ssize_t);
   1412 			break;
   1413 		case TP_SSIZEINT:
   1414 			(*argtable)[n].pssizearg = va_arg(ap, ssize_t *);
   1415 			break;
   1416 		case TP_MAXINT:
   1417 			(*argtable)[n].intmaxarg = va_arg(ap, intmax_t);
   1418 			break;
   1419 		case T_WINT:
   1420 			(*argtable)[n].wintarg = va_arg(ap, wint_t);
   1421 			break;
   1422 		case TP_WCHAR:
   1423 			(*argtable)[n].pwchararg = va_arg(ap, wchar_t *);
   1424 			break;
   1425 		}
   1426 	}
   1427 	goto finish;
   1428 
   1429 overflow:
   1430 	errno = ENOMEM;
   1431 	ret = -1;
   1432 
   1433 finish:
   1434 	if (typetable != NULL && typetable != stattypetable) {
   1435 		munmap(typetable, *argtablesiz);
   1436 		typetable = NULL;
   1437 	}
   1438 	return (ret);
   1439 }
   1440 
   1441 /*
   1442  * Increase the size of the type table.
   1443  */
   1444 static int
   1445 __grow_type_table(unsigned char **typetable, int *tablesize)
   1446 {
   1447 	unsigned char *oldtable = *typetable;
   1448 	int newsize = *tablesize * 2;
   1449 
   1450 	if (newsize < getpagesize())
   1451 		newsize = getpagesize();
   1452 
   1453 	if (*tablesize == STATIC_ARG_TBL_SIZE) {
   1454 		*typetable = mmap(NULL, newsize, PROT_WRITE|PROT_READ,
   1455 		    MAP_ANON|MAP_PRIVATE, -1, 0);
   1456 		if (*typetable == MAP_FAILED)
   1457 			return (-1);
   1458 		bcopy(oldtable, *typetable, *tablesize);
   1459 	} else {
   1460 		unsigned char *new = mmap(NULL, newsize, PROT_WRITE|PROT_READ,
   1461 		    MAP_ANON|MAP_PRIVATE, -1, 0);
   1462 		if (new == MAP_FAILED)
   1463 			return (-1);
   1464 		memmove(new, *typetable, *tablesize);
   1465 		munmap(*typetable, *tablesize);
   1466 		*typetable = new;
   1467 	}
   1468 	memset(*typetable + *tablesize, T_UNUSED, (newsize - *tablesize));
   1469 
   1470 	*tablesize = newsize;
   1471 	return (0);
   1472 }
   1473 
   1474 
   1475 #ifdef FLOATING_POINT
   1476 static int
   1477 exponent(wchar_t *p0, int exp, int fmtch)
   1478 {
   1479 	wchar_t *p, *t;
   1480 	wchar_t expbuf[MAXEXPDIG];
   1481 
   1482 	p = p0;
   1483 	*p++ = fmtch;
   1484 	if (exp < 0) {
   1485 		exp = -exp;
   1486 		*p++ = '-';
   1487 	} else
   1488 		*p++ = '+';
   1489 	t = expbuf + MAXEXPDIG;
   1490 	if (exp > 9) {
   1491 		do {
   1492 			*--t = to_char(exp % 10);
   1493 		} while ((exp /= 10) > 9);
   1494 		*--t = to_char(exp);
   1495 		for (; t < expbuf + MAXEXPDIG; *p++ = *t++)
   1496 			/* nothing */;
   1497 	} else {
   1498 		/*
   1499 		 * Exponents for decimal floating point conversions
   1500 		 * (%[eEgG]) must be at least two characters long,
   1501 		 * whereas exponents for hexadecimal conversions can
   1502 		 * be only one character long.
   1503 		 */
   1504 		if (fmtch == 'e' || fmtch == 'E')
   1505 			*p++ = '0';
   1506 		*p++ = to_char(exp);
   1507 	}
   1508 	return (p - p0);
   1509 }
   1510 #endif /* FLOATING_POINT */
   1511