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