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