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