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