1/*	$OpenBSD: vfwprintf.c,v 1.11 2014/06/04 07:45:25 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 <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
57union 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
87static int __find_arguments(const wchar_t *fmt0, va_list ap, union arg **argtable,
88    size_t *argtablesiz);
89static 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 */
96static 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 */
129static 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 */
165static 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
240static 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
278int
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
490rflag:		ch = *fmt++;
491reswitch:	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			if (convbuf) {
671				free(convbuf);
672				convbuf = NULL;
673			}
674			cp = convbuf = __mbsconv(dtoaresult, -1);
675			if (cp == NULL)
676				goto error;
677			ndig = dtoaend - dtoaresult;
678			goto fp_common;
679		case 'e':
680		case 'E':
681			expchar = ch;
682			if (prec < 0)	/* account for digit before decpt */
683				prec = DEFPREC + 1;
684			else
685				prec++;
686			goto fp_begin;
687		case 'f':
688		case 'F':
689			expchar = '\0';
690			goto fp_begin;
691		case 'g':
692		case 'G':
693			expchar = ch - ('g' - 'e');
694 			if (prec == 0)
695 				prec = 1;
696fp_begin:
697			if (prec < 0)
698				prec = DEFPREC;
699			if (dtoaresult)
700				__freedtoa(dtoaresult);
701			if (flags & LONGDBL) {
702				fparg.ldbl = GETARG(long double);
703				dtoaresult =
704				    __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
705				    &expt, &signflag, &dtoaend);
706				if (dtoaresult == NULL) {
707					errno = ENOMEM;
708					goto error;
709				}
710			} else {
711				fparg.dbl = GETARG(double);
712				dtoaresult =
713				    __dtoa(fparg.dbl, expchar ? 2 : 3, prec,
714				    &expt, &signflag, &dtoaend);
715				if (dtoaresult == NULL) {
716					errno = ENOMEM;
717					goto error;
718				}
719				if (expt == 9999)
720					expt = INT_MAX;
721 			}
722			if (convbuf) {
723				free(convbuf);
724				convbuf = NULL;
725			}
726			cp = convbuf = __mbsconv(dtoaresult, -1);
727			if (cp == NULL)
728				goto error;
729			ndig = dtoaend - dtoaresult;
730fp_common:
731			if (signflag)
732				sign = '-';
733			if (expt == INT_MAX) {	/* inf or nan */
734				if (*cp == 'N') {
735					cp = (ch >= 'a') ? L"nan" : L"NAN";
736					sign = '\0';
737				} else
738					cp = (ch >= 'a') ? L"inf" : L"INF";
739 				size = 3;
740				flags &= ~ZEROPAD;
741 				break;
742 			}
743			flags |= FPT;
744 			if (ch == 'g' || ch == 'G') {
745				if (expt > -4 && expt <= prec) {
746					/* Make %[gG] smell like %[fF] */
747					expchar = '\0';
748					if (flags & ALT)
749						prec -= expt;
750					else
751						prec = ndig - expt;
752					if (prec < 0)
753						prec = 0;
754				} else {
755					/*
756					 * Make %[gG] smell like %[eE], but
757					 * trim trailing zeroes if no # flag.
758					 */
759					if (!(flags & ALT))
760						prec = ndig;
761				}
762 			}
763			if (expchar) {
764				expsize = exponent(expstr, expt - 1, expchar);
765				size = expsize + prec;
766				if (prec > 1 || flags & ALT)
767 					++size;
768			} else {
769				/* space for digits before decimal point */
770				if (expt > 0)
771					size = expt;
772				else	/* "0" */
773					size = 1;
774				/* space for decimal pt and following digits */
775				if (prec || flags & ALT)
776					size += prec + 1;
777				lead = expt;
778			}
779			break;
780#endif /* FLOATING_POINT */
781#ifndef NO_PRINTF_PERCENT_N
782		case 'n':
783			if (flags & LLONGINT)
784				*GETARG(long long *) = ret;
785			else if (flags & LONGINT)
786				*GETARG(long *) = ret;
787			else if (flags & SHORTINT)
788				*GETARG(short *) = ret;
789			else if (flags & CHARINT)
790				*GETARG(signed char *) = ret;
791			else if (flags & PTRINT)
792				*GETARG(ptrdiff_t *) = ret;
793			else if (flags & SIZEINT)
794				*GETARG(ssize_t *) = ret;
795			else if (flags & MAXINT)
796				*GETARG(intmax_t *) = ret;
797			else
798				*GETARG(int *) = ret;
799			continue;	/* no output */
800#endif /* NO_PRINTF_PERCENT_N */
801		case 'O':
802			flags |= LONGINT;
803			/*FALLTHROUGH*/
804		case 'o':
805			_umax = UARG();
806			base = OCT;
807			goto nosign;
808		case 'p':
809			/*
810			 * ``The argument shall be a pointer to void.  The
811			 * value of the pointer is converted to a sequence
812			 * of printable characters, in an implementation-
813			 * defined manner.''
814			 *	-- ANSI X3J11
815			 */
816			/* NOSTRICT */
817			_umax = (u_long)GETARG(void *);
818			base = HEX;
819			xdigs = xdigs_lower;
820			ox[1] = 'x';
821			goto nosign;
822		case 'S':
823			flags |= LONGINT;
824			/*FALLTHROUGH*/
825		case 's':
826			if (flags & LONGINT) {
827				if ((cp = GETARG(wchar_t *)) == NULL)
828					cp = L"(null)";
829			} else {
830				char *mbsarg;
831				if ((mbsarg = GETARG(char *)) == NULL)
832					mbsarg = "(null)";
833				if (convbuf) {
834					free(convbuf);
835					convbuf = NULL;
836				}
837				convbuf = __mbsconv(mbsarg, prec);
838				if (convbuf == NULL) {
839					fp->_flags |= __SERR;
840					goto error;
841				} else
842					cp = convbuf;
843			}
844			if (prec >= 0) {
845				/*
846				 * can't use wcslen; can only look for the
847				 * NUL in the first `prec' characters, and
848				 * wcslen() will go further.
849				 */
850				wchar_t *p = wmemchr(cp, 0, prec);
851
852				size = p ? (p - cp) : prec;
853			} else {
854				size_t len;
855
856				if ((len = wcslen(cp)) > INT_MAX)
857					goto overflow;
858				size = (int)len;
859			}
860			sign = '\0';
861			break;
862		case 'U':
863			flags |= LONGINT;
864			/*FALLTHROUGH*/
865		case 'u':
866			_umax = UARG();
867			base = DEC;
868			goto nosign;
869		case 'X':
870			xdigs = xdigs_upper;
871			goto hex;
872		case 'x':
873			xdigs = xdigs_lower;
874hex:			_umax = UARG();
875			base = HEX;
876			/* leading 0x/X only if non-zero */
877			if (flags & ALT && _umax != 0)
878				ox[1] = ch;
879
880			/* unsigned conversions */
881nosign:			sign = '\0';
882			/*
883			 * ``... diouXx conversions ... if a precision is
884			 * specified, the 0 flag will be ignored.''
885			 *	-- ANSI X3J11
886			 */
887number:			if ((dprec = prec) >= 0)
888				flags &= ~ZEROPAD;
889
890			/*
891			 * ``The result of converting a zero value with an
892			 * explicit precision of zero is no characters.''
893			 *	-- ANSI X3J11
894			 */
895			cp = buf + BUF;
896			if (_umax != 0 || prec != 0) {
897				/*
898				 * Unsigned mod is hard, and unsigned mod
899				 * by a constant is easier than that by
900				 * a variable; hence this switch.
901				 */
902				switch (base) {
903				case OCT:
904					do {
905						*--cp = to_char(_umax & 7);
906						_umax >>= 3;
907					} while (_umax);
908					/* handle octal leading 0 */
909					if (flags & ALT && *cp != '0')
910						*--cp = '0';
911					break;
912
913				case DEC:
914					/* many numbers are 1 digit */
915					while (_umax >= 10) {
916						*--cp = to_char(_umax % 10);
917						_umax /= 10;
918					}
919					*--cp = to_char(_umax);
920					break;
921
922				case HEX:
923					do {
924						*--cp = xdigs[_umax & 15];
925						_umax >>= 4;
926					} while (_umax);
927					break;
928
929				default:
930					cp = L"bug in vfwprintf: bad base";
931					size = wcslen(cp);
932					goto skipsize;
933				}
934			}
935			size = buf + BUF - cp;
936			if (size > BUF)	/* should never happen */
937				abort();
938		skipsize:
939			break;
940		default:	/* "%?" prints ?, unless ? is NUL */
941			if (ch == '\0')
942				goto done;
943			/* pretend it was %c with argument ch */
944			cp = buf;
945			*cp = ch;
946			size = 1;
947			sign = '\0';
948			break;
949		}
950
951		/*
952		 * All reasonable formats wind up here.  At this point, `cp'
953		 * points to a string which (if not flags&LADJUST) should be
954		 * padded out to `width' places.  If flags&ZEROPAD, it should
955		 * first be prefixed by any sign or other prefix; otherwise,
956		 * it should be blank padded before the prefix is emitted.
957		 * After any left-hand padding and prefixing, emit zeroes
958		 * required by a decimal %[diouxX] precision, then print the
959		 * string proper, then emit zeroes required by any leftover
960		 * floating precision; finally, if LADJUST, pad with blanks.
961		 *
962		 * Compute actual size, so we know how much to pad.
963		 * size excludes decimal prec; realsz includes it.
964		 */
965		realsz = dprec > size ? dprec : size;
966		if (sign)
967			realsz++;
968		if (ox[1])
969			realsz+= 2;
970
971		/* right-adjusting blank padding */
972		if ((flags & (LADJUST|ZEROPAD)) == 0)
973			PAD(width - realsz, blanks);
974
975		/* prefix */
976		if (sign)
977			PRINT(&sign, 1);
978		if (ox[1]) {	/* ox[1] is either x, X, or \0 */
979			ox[0] = '0';
980			PRINT(ox, 2);
981		}
982
983		/* right-adjusting zero padding */
984		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
985			PAD(width - realsz, zeroes);
986
987		/* leading zeroes from decimal precision */
988		PAD(dprec - size, zeroes);
989
990		/* the string or number proper */
991#ifdef FLOATING_POINT
992		if ((flags & FPT) == 0) {
993			PRINT(cp, size);
994		} else {	/* glue together f_p fragments */
995			if (decimal_point == NULL)
996				decimal_point = nl_langinfo(RADIXCHAR);
997			if (!expchar) {	/* %[fF] or sufficiently short %[gG] */
998				if (expt <= 0) {
999					PRINT(zeroes, 1);
1000					if (prec || flags & ALT)
1001						PRINT(decimal_point, 1);
1002					PAD(-expt, zeroes);
1003					/* already handled initial 0's */
1004					prec += expt;
1005 				} else {
1006					PRINTANDPAD(cp, convbuf + ndig,
1007					    lead, zeroes);
1008					cp += lead;
1009					if (prec || flags & ALT)
1010						PRINT(decimal_point, 1);
1011				}
1012				PRINTANDPAD(cp, convbuf + ndig, prec, zeroes);
1013			} else {	/* %[eE] or sufficiently long %[gG] */
1014				if (prec > 1 || flags & ALT) {
1015					buf[0] = *cp++;
1016					buf[1] = *decimal_point;
1017					PRINT(buf, 2);
1018					PRINT(cp, ndig-1);
1019					PAD(prec - ndig, zeroes);
1020				} else { /* XeYYY */
1021					PRINT(cp, 1);
1022				}
1023				PRINT(expstr, expsize);
1024			}
1025		}
1026#else
1027		PRINT(cp, size);
1028#endif
1029		/* left-adjusting padding (always blank) */
1030		if (flags & LADJUST)
1031			PAD(width - realsz, blanks);
1032
1033		/* finally, adjust ret */
1034		if (width < realsz)
1035			width = realsz;
1036		if (width > INT_MAX - ret)
1037			goto overflow;
1038		ret += width;
1039	}
1040done:
1041error:
1042	va_end(orgap);
1043	if (__sferror(fp))
1044		ret = -1;
1045	goto finish;
1046
1047overflow:
1048	errno = ENOMEM;
1049	ret = -1;
1050
1051finish:
1052	if (convbuf)
1053		free(convbuf);
1054#ifdef FLOATING_POINT
1055	if (dtoaresult)
1056		__freedtoa(dtoaresult);
1057#endif
1058	if (argtable != NULL && argtable != statargtable) {
1059		munmap(argtable, argtablesiz);
1060		argtable = NULL;
1061	}
1062	return (ret);
1063}
1064
1065int
1066vfwprintf(FILE * __restrict fp, const wchar_t * __restrict fmt0, __va_list ap)
1067{
1068	int r;
1069
1070	FLOCKFILE(fp);
1071	r = __vfwprintf(fp, fmt0, ap);
1072	FUNLOCKFILE(fp);
1073
1074	return (r);
1075}
1076
1077/*
1078 * Type ids for argument type table.
1079 */
1080#define T_UNUSED	0
1081#define T_SHORT		1
1082#define T_U_SHORT	2
1083#define TP_SHORT	3
1084#define T_INT		4
1085#define T_U_INT		5
1086#define TP_INT		6
1087#define T_LONG		7
1088#define T_U_LONG	8
1089#define TP_LONG		9
1090#define T_LLONG		10
1091#define T_U_LLONG	11
1092#define TP_LLONG	12
1093#define T_DOUBLE	13
1094#define T_LONG_DOUBLE	14
1095#define TP_CHAR		15
1096#define TP_VOID		16
1097#define T_PTRINT	17
1098#define TP_PTRINT	18
1099#define T_SIZEINT	19
1100#define T_SSIZEINT	20
1101#define TP_SSIZEINT	21
1102#define T_MAXINT	22
1103#define T_MAXUINT	23
1104#define TP_MAXINT	24
1105#define T_CHAR		25
1106#define T_U_CHAR	26
1107#define T_WINT		27
1108#define TP_WCHAR	28
1109
1110/*
1111 * Find all arguments when a positional parameter is encountered.  Returns a
1112 * table, indexed by argument number, of pointers to each arguments.  The
1113 * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1114 * It will be replaced with a mmap-ed one if it overflows (malloc cannot be
1115 * used since we are attempting to make snprintf thread safe, and alloca is
1116 * problematic since we have nested functions..)
1117 */
1118static int
1119__find_arguments(const wchar_t *fmt0, va_list ap, union arg **argtable,
1120    size_t *argtablesiz)
1121{
1122	wchar_t *fmt;		/* format string */
1123	int ch;			/* character from fmt */
1124	int n, n2;		/* handy integer (short term usage) */
1125	wchar_t *cp;		/* handy char pointer (short term usage) */
1126	int flags;		/* flags as above */
1127	unsigned char *typetable; /* table of types */
1128	unsigned char stattypetable[STATIC_ARG_TBL_SIZE];
1129	int tablesize;		/* current size of type table */
1130	int tablemax;		/* largest used index in table */
1131	int nextarg;		/* 1-based argument index */
1132	int ret = 0;		/* return value */
1133
1134	/*
1135	 * Add an argument type to the table, expanding if necessary.
1136	 */
1137#define ADDTYPE(type) \
1138	((nextarg >= tablesize) ? \
1139		__grow_type_table(&typetable, &tablesize) : 0, \
1140	(nextarg > tablemax) ? tablemax = nextarg : 0, \
1141	typetable[nextarg++] = type)
1142
1143#define	ADDSARG() \
1144        ((flags&MAXINT) ? ADDTYPE(T_MAXINT) : \
1145	    ((flags&PTRINT) ? ADDTYPE(T_PTRINT) : \
1146	    ((flags&SIZEINT) ? ADDTYPE(T_SSIZEINT) : \
1147	    ((flags&LLONGINT) ? ADDTYPE(T_LLONG) : \
1148	    ((flags&LONGINT) ? ADDTYPE(T_LONG) : \
1149	    ((flags&SHORTINT) ? ADDTYPE(T_SHORT) : \
1150	    ((flags&CHARINT) ? ADDTYPE(T_CHAR) : ADDTYPE(T_INT))))))))
1151
1152#define	ADDUARG() \
1153        ((flags&MAXINT) ? ADDTYPE(T_MAXUINT) : \
1154	    ((flags&PTRINT) ? ADDTYPE(T_PTRINT) : \
1155	    ((flags&SIZEINT) ? ADDTYPE(T_SIZEINT) : \
1156	    ((flags&LLONGINT) ? ADDTYPE(T_U_LLONG) : \
1157	    ((flags&LONGINT) ? ADDTYPE(T_U_LONG) : \
1158	    ((flags&SHORTINT) ? ADDTYPE(T_U_SHORT) : \
1159	    ((flags&CHARINT) ? ADDTYPE(T_U_CHAR) : ADDTYPE(T_U_INT))))))))
1160
1161	/*
1162	 * Add * arguments to the type array.
1163	 */
1164#define ADDASTER() \
1165	n2 = 0; \
1166	cp = fmt; \
1167	while (is_digit(*cp)) { \
1168		APPEND_DIGIT(n2, *cp); \
1169		cp++; \
1170	} \
1171	if (*cp == '$') { \
1172		int hold = nextarg; \
1173		nextarg = n2; \
1174		ADDTYPE(T_INT); \
1175		nextarg = hold; \
1176		fmt = ++cp; \
1177	} else { \
1178		ADDTYPE(T_INT); \
1179	}
1180	fmt = (wchar_t *)fmt0;
1181	typetable = stattypetable;
1182	tablesize = STATIC_ARG_TBL_SIZE;
1183	tablemax = 0;
1184	nextarg = 1;
1185	memset(typetable, T_UNUSED, STATIC_ARG_TBL_SIZE);
1186
1187	/*
1188	 * Scan the format for conversions (`%' character).
1189	 */
1190	for (;;) {
1191		for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
1192			continue;
1193		if (ch == '\0')
1194			goto done;
1195		fmt++;		/* skip over '%' */
1196
1197		flags = 0;
1198
1199rflag:		ch = *fmt++;
1200reswitch:	switch (ch) {
1201		case ' ':
1202		case '#':
1203		case '\'':
1204			goto rflag;
1205		case '*':
1206			ADDASTER();
1207			goto rflag;
1208		case '-':
1209		case '+':
1210			goto rflag;
1211		case '.':
1212			if ((ch = *fmt++) == '*') {
1213				ADDASTER();
1214				goto rflag;
1215			}
1216			while (is_digit(ch)) {
1217				ch = *fmt++;
1218			}
1219			goto reswitch;
1220		case '0':
1221			goto rflag;
1222		case '1': case '2': case '3': case '4':
1223		case '5': case '6': case '7': case '8': case '9':
1224			n = 0;
1225			do {
1226				APPEND_DIGIT(n ,ch);
1227				ch = *fmt++;
1228			} while (is_digit(ch));
1229			if (ch == '$') {
1230				nextarg = n;
1231				goto rflag;
1232			}
1233			goto reswitch;
1234#ifdef FLOATING_POINT
1235		case 'L':
1236			flags |= LONGDBL;
1237			goto rflag;
1238#endif
1239		case 'h':
1240			if (*fmt == 'h') {
1241				fmt++;
1242				flags |= CHARINT;
1243			} else {
1244				flags |= SHORTINT;
1245			}
1246			goto rflag;
1247		case 'l':
1248			if (*fmt == 'l') {
1249				fmt++;
1250				flags |= LLONGINT;
1251			} else {
1252				flags |= LONGINT;
1253			}
1254			goto rflag;
1255		case 'q':
1256			flags |= LLONGINT;
1257			goto rflag;
1258		case 't':
1259			flags |= PTRINT;
1260			goto rflag;
1261		case 'z':
1262			flags |= SIZEINT;
1263			goto rflag;
1264		case 'C':
1265			flags |= LONGINT;
1266			/*FALLTHROUGH*/
1267		case 'c':
1268			if (flags & LONGINT)
1269				ADDTYPE(T_WINT);
1270			else
1271				ADDTYPE(T_INT);
1272			break;
1273		case 'D':
1274			flags |= LONGINT;
1275			/*FALLTHROUGH*/
1276		case 'd':
1277		case 'i':
1278			ADDSARG();
1279			break;
1280#ifdef FLOATING_POINT
1281		case 'a':
1282		case 'A':
1283		case 'e':
1284		case 'E':
1285		case 'f':
1286		case 'F':
1287		case 'g':
1288		case 'G':
1289			if (flags & LONGDBL)
1290				ADDTYPE(T_LONG_DOUBLE);
1291			else
1292				ADDTYPE(T_DOUBLE);
1293			break;
1294#endif /* FLOATING_POINT */
1295#ifndef NO_PRINTF_PERCENT_N
1296		case 'n':
1297			if (flags & LLONGINT)
1298				ADDTYPE(TP_LLONG);
1299			else if (flags & LONGINT)
1300				ADDTYPE(TP_LONG);
1301			else if (flags & SHORTINT)
1302				ADDTYPE(TP_SHORT);
1303			else if (flags & PTRINT)
1304				ADDTYPE(TP_PTRINT);
1305			else if (flags & SIZEINT)
1306				ADDTYPE(TP_SSIZEINT);
1307			else if (flags & MAXINT)
1308				ADDTYPE(TP_MAXINT);
1309			else
1310				ADDTYPE(TP_INT);
1311			continue;	/* no output */
1312#endif /* NO_PRINTF_PERCENT_N */
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	}
1345done:
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
1440overflow:
1441	errno = ENOMEM;
1442	ret = -1;
1443
1444finish:
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 */
1455static 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
1487static int
1488exponent(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