xref: /freebsd/lib/libc/stdio/vfwprintf.c (revision a3e8fd0b7f663db7eafff527d5c3ca3bcfa8a537)
1 /*-
2  * Copyright (c) 1990, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Chris Torek.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #include <sys/cdefs.h>
38 #if 0
39 #if defined(LIBC_SCCS) && !defined(lint)
40 static char sccsid[] = "@(#)vfprintf.c	8.1 (Berkeley) 6/4/93";
41 #endif /* LIBC_SCCS and not lint */
42 __FBSDID("FreeBSD: src/lib/libc/stdio/vfprintf.c,v 1.45 2002/09/06 11:23:55 tjr Exp ");
43 #endif
44 __FBSDID("$FreeBSD$");
45 
46 /*
47  * Actual wprintf innards.
48  *
49  * Avoid making gratuitous changes to this source file; it should be kept
50  * as close as possible to vfprintf.c for ease of maintenance.
51  */
52 
53 #include "namespace.h"
54 #include <sys/types.h>
55 
56 #include <ctype.h>
57 #include <limits.h>
58 #include <locale.h>
59 #include <stdarg.h>
60 #include <stddef.h>
61 #include <stdint.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <wchar.h>
66 #include <wctype.h>
67 #include "un-namespace.h"
68 
69 #include "libc_private.h"
70 #include "local.h"
71 #include "fvwrite.h"
72 
73 /* Define FLOATING_POINT to get floating point. */
74 #define	FLOATING_POINT
75 
76 union arg {
77 	int	intarg;
78 	u_int	uintarg;
79 	long	longarg;
80 	u_long	ulongarg;
81 	long long longlongarg;
82 	unsigned long long ulonglongarg;
83 	ptrdiff_t ptrdiffarg;
84 	size_t	sizearg;
85 	intmax_t intmaxarg;
86 	uintmax_t uintmaxarg;
87 	void	*pvoidarg;
88 	char	*pchararg;
89 	signed char *pschararg;
90 	short	*pshortarg;
91 	int	*pintarg;
92 	long	*plongarg;
93 	long long *plonglongarg;
94 	ptrdiff_t *pptrdiffarg;
95 	size_t	*psizearg;
96 	intmax_t *pintmaxarg;
97 #ifdef FLOATING_POINT
98 	double	doublearg;
99 	long double longdoublearg;
100 #endif
101 	wint_t	wintarg;
102 	wchar_t	*pwchararg;
103 };
104 
105 /*
106  * Type ids for argument type table.
107  */
108 enum typeid {
109 	T_UNUSED, TP_SHORT, T_INT, T_U_INT, TP_INT,
110 	T_LONG, T_U_LONG, TP_LONG, T_LLONG, T_U_LLONG, TP_LLONG,
111 	T_PTRDIFFT, TP_PTRDIFFT, T_SIZET, TP_SIZET,
112 	T_INTMAXT, T_UINTMAXT, TP_INTMAXT, TP_VOID, TP_CHAR, TP_SCHAR,
113 	T_DOUBLE, T_LONG_DOUBLE, T_WINT, TP_WCHAR
114 };
115 
116 static int	__sbprintf(FILE *, const wchar_t *, va_list);
117 static wchar_t	*__ujtoa(uintmax_t, wchar_t *, int, int, wchar_t *, int, char,
118 		    const char *);
119 static wchar_t	*__ultoa(u_long, wchar_t *, int, int, wchar_t *, int, char,
120 		    const char *);
121 static wchar_t	*__mbsconv(char *, int);
122 static void	__find_arguments(const wchar_t *, va_list, union arg **);
123 static void	__grow_type_table(int, enum typeid **, int *);
124 
125 /*
126  * Helper function for `fprintf to unbuffered unix file': creates a
127  * temporary buffer.  We only work on write-only files; this avoids
128  * worries about ungetc buffers and so forth.
129  */
130 static int
131 __sbprintf(FILE *fp, const wchar_t *fmt, va_list ap)
132 {
133 	int ret;
134 	FILE fake;
135 	unsigned char buf[BUFSIZ];
136 
137 	/* copy the important variables */
138 	fake._flags = fp->_flags & ~__SNBF;
139 	fake._file = fp->_file;
140 	fake._cookie = fp->_cookie;
141 	fake._write = fp->_write;
142 	fake._extra = fp->_extra;
143 
144 	/* set up the buffer */
145 	fake._bf._base = fake._p = buf;
146 	fake._bf._size = fake._w = sizeof(buf);
147 	fake._lbfsize = 0;	/* not actually used, but Just In Case */
148 
149 	/* do the work, then copy any error status */
150 	ret = __vfwprintf(&fake, fmt, ap);
151 	if (ret >= 0 && __fflush(&fake))
152 		ret = WEOF;
153 	if (fake._flags & __SERR)
154 		fp->_flags |= __SERR;
155 	return (ret);
156 }
157 
158 /*
159  * Macros for converting digits to letters and vice versa
160  */
161 #define	to_digit(c)	((c) - '0')
162 #define is_digit(c)	((unsigned)to_digit(c) <= 9)
163 #define	to_char(n)	((n) + '0')
164 
165 /*
166  * Convert an unsigned long to ASCII for printf purposes, returning
167  * a pointer to the first character of the string representation.
168  * Octal numbers can be forced to have a leading zero; hex numbers
169  * use the given digits.
170  */
171 static wchar_t *
172 __ultoa(u_long val, wchar_t *endp, int base, int octzero, wchar_t *xdigs,
173 	int needgrp, char thousep, const char *grp)
174 {
175 	wchar_t *cp = endp;
176 	long sval;
177 	int ndig;
178 
179 	/*
180 	 * Handle the three cases separately, in the hope of getting
181 	 * better/faster code.
182 	 */
183 	switch (base) {
184 	case 10:
185 		if (val < 10) {	/* many numbers are 1 digit */
186 			*--cp = to_char(val);
187 			return (cp);
188 		}
189 		ndig = 0;
190 		/*
191 		 * On many machines, unsigned arithmetic is harder than
192 		 * signed arithmetic, so we do at most one unsigned mod and
193 		 * divide; this is sufficient to reduce the range of
194 		 * the incoming value to where signed arithmetic works.
195 		 */
196 		if (val > LONG_MAX) {
197 			*--cp = to_char(val % 10);
198 			ndig++;
199 			sval = val / 10;
200 		} else
201 			sval = val;
202 		do {
203 			*--cp = to_char(sval % 10);
204 			ndig++;
205 			/*
206 			 * If (*grp == CHAR_MAX) then no more grouping
207 			 * should be performed.
208 			 */
209 			if (needgrp && ndig == *grp && *grp != CHAR_MAX
210 					&& sval > 9) {
211 				*--cp = thousep;
212 				ndig = 0;
213 				/*
214 				 * If (*(grp+1) == '\0') then we have to
215 				 * use *grp character (last grouping rule)
216 				 * for all next cases
217 				 */
218 				if (*(grp+1) != '\0')
219 					grp++;
220 			}
221 			sval /= 10;
222 		} while (sval != 0);
223 		break;
224 
225 	case 8:
226 		do {
227 			*--cp = to_char(val & 7);
228 			val >>= 3;
229 		} while (val);
230 		if (octzero && *cp != '0')
231 			*--cp = '0';
232 		break;
233 
234 	case 16:
235 		do {
236 			*--cp = xdigs[val & 15];
237 			val >>= 4;
238 		} while (val);
239 		break;
240 
241 	default:			/* oops */
242 		abort();
243 	}
244 	return (cp);
245 }
246 
247 /* Identical to __ultoa, but for intmax_t. */
248 static wchar_t *
249 __ujtoa(uintmax_t val, wchar_t *endp, int base, int octzero, wchar_t *xdigs,
250 	int needgrp, char thousep, const char *grp)
251 {
252 	wchar_t *cp = endp;
253 	intmax_t sval;
254 	int ndig;
255 
256 	/* quick test for small values; __ultoa is typically much faster */
257 	/* (perhaps instead we should run until small, then call __ultoa?) */
258 	if (val <= ULONG_MAX)
259 		return (__ultoa((u_long)val, endp, base, octzero, xdigs,
260 		    needgrp, thousep, grp));
261 	switch (base) {
262 	case 10:
263 		if (val < 10) {
264 			*--cp = to_char(val % 10);
265 			return (cp);
266 		}
267 		ndig = 0;
268 		if (val > INTMAX_MAX) {
269 			*--cp = to_char(val % 10);
270 			ndig++;
271 			sval = val / 10;
272 		} else
273 			sval = val;
274 		do {
275 			*--cp = to_char(sval % 10);
276 			ndig++;
277 			/*
278 			 * If (*grp == CHAR_MAX) then no more grouping
279 			 * should be performed.
280 			 */
281 			if (needgrp && *grp != CHAR_MAX && ndig == *grp
282 					&& sval > 9) {
283 				*--cp = thousep;
284 				ndig = 0;
285 				/*
286 				 * If (*(grp+1) == '\0') then we have to
287 				 * use *grp character (last grouping rule)
288 				 * for all next cases
289 				 */
290 				if (*(grp+1) != '\0')
291 					grp++;
292 			}
293 			sval /= 10;
294 		} while (sval != 0);
295 		break;
296 
297 	case 8:
298 		do {
299 			*--cp = to_char(val & 7);
300 			val >>= 3;
301 		} while (val);
302 		if (octzero && *cp != '0')
303 			*--cp = '0';
304 		break;
305 
306 	case 16:
307 		do {
308 			*--cp = xdigs[val & 15];
309 			val >>= 4;
310 		} while (val);
311 		break;
312 
313 	default:
314 		abort();
315 	}
316 	return (cp);
317 }
318 
319 /*
320  * Convert a multibyte character string argument for the %s format to a wide
321  * string representation. ``prec'' specifies the maximum number of bytes
322  * to output. If ``prec'' is greater than or equal to zero, we can't assume
323  * that the multibyte char. string ends in a null character.
324  */
325 static wchar_t *
326 __mbsconv(char *mbsarg, int prec)
327 {
328 	wchar_t *convbuf, *wcp;
329 	const char *p;
330 	size_t insize, nchars, nconv;
331 	mbstate_t mbs;
332 
333 	/*
334 	 * Supplied argument is a multibyte string; convert it to wide
335 	 * characters first.
336 	 */
337 	if (prec >= 0) {
338 		/*
339 		 * String is not guaranteed to be NUL-terminated. Find the
340 		 * number of characters to print.
341 		 */
342 		memset(&mbs, 0, sizeof(mbs));
343 		p = mbsarg;
344 		insize = nchars = 0;
345 		while (nchars != (size_t)prec) {
346 			nconv = mbrlen(p, MB_CUR_MAX, &mbs);
347 			if (nconv == 0 || nconv == (size_t)-1 ||
348 			    nconv == (size_t)-2)
349 				break;
350 			p += nconv;
351 			nchars++;
352 			insize += nconv;
353 		}
354 		if (nconv == (size_t)-1 || nconv == (size_t)-2)
355 			return (NULL);
356 	} else
357 		insize = strlen(mbsarg);
358 
359 	/*
360 	 * Allocate buffer for the result and perform the conversion,
361 	 * converting at most `size' bytes of the input multibyte string to
362 	 * wide characters for printing.
363 	 */
364 	convbuf = malloc((insize + 1) * sizeof(*convbuf));
365 	if (convbuf == NULL)
366 		return (NULL);
367 	wcp = convbuf;
368 	p = mbsarg;
369 	memset(&mbs, 0, sizeof(mbs));
370 	while (insize != 0) {
371 		nconv = mbrtowc(wcp, p, insize, &mbs);
372 		if (nconv == 0 || nconv == (size_t)-1 || nconv == (size_t)-2)
373 			break;
374 		wcp++;
375 		p += nconv;
376 		insize -= nconv;
377 	}
378 	if (nconv == (size_t)-1 || nconv == (size_t)-2) {
379 		free(convbuf);
380 		return (NULL);
381 	}
382 	*wcp = L'\0';
383 
384 	return (convbuf);
385 }
386 
387 /*
388  * MT-safe version
389  */
390 int
391 vfwprintf(FILE * __restrict fp, const wchar_t * __restrict fmt0, va_list ap)
392 
393 {
394 	int ret;
395 
396 	FLOCKFILE(fp);
397 	ret = __vfwprintf(fp, fmt0, ap);
398 	FUNLOCKFILE(fp);
399 	return (ret);
400 }
401 
402 #ifdef FLOATING_POINT
403 #include <math.h>
404 #include "floatio.h"
405 
406 #define	BUF		((MAXEXP*2)+MAXFRACT+1)		/* + decimal point */
407 #define	DEFPREC		6
408 
409 static wchar_t *cvt(double, int, int, char *, int *, wchar_t, int *,
410 	    wchar_t **);
411 static int exponent(wchar_t *, int, wchar_t);
412 
413 #else /* no FLOATING_POINT */
414 
415 #define	BUF		136
416 
417 #endif /* FLOATING_POINT */
418 
419 #define STATIC_ARG_TBL_SIZE 8           /* Size of static argument table. */
420 
421 /*
422  * Flags used during conversion.
423  */
424 #define	ALT		0x001		/* alternate form */
425 #define	HEXPREFIX	0x002		/* add 0x or 0X prefix */
426 #define	LADJUST		0x004		/* left adjustment */
427 #define	LONGDBL		0x008		/* long double */
428 #define	LONGINT		0x010		/* long integer */
429 #define	LLONGINT	0x020		/* long long integer */
430 #define	SHORTINT	0x040		/* short integer */
431 #define	ZEROPAD		0x080		/* zero (as opposed to blank) pad */
432 #define	FPT		0x100		/* Floating point number */
433 #define	GROUPING	0x200		/* use grouping ("'" flag) */
434 					/* C99 additional size modifiers: */
435 #define	SIZET		0x400		/* size_t */
436 #define	PTRDIFFT	0x800		/* ptrdiff_t */
437 #define	INTMAXT		0x1000		/* intmax_t */
438 #define	CHARINT		0x2000		/* print char using int format */
439 
440 /*
441  * Non-MT-safe version
442  */
443 int
444 __vfwprintf(FILE *fp, const wchar_t *fmt0, va_list ap)
445 {
446 	wchar_t *fmt;		/* format string */
447 	wchar_t ch;		/* character from fmt */
448 	int n, n2;		/* handy integer (short term usage) */
449 	wchar_t *cp;		/* handy char pointer (short term usage) */
450 	int flags;		/* flags as above */
451 	int ret;		/* return value accumulator */
452 	int width;		/* width from format (%8d), or 0 */
453 	int prec;		/* precision from format (%.3d), or -1 */
454 	wchar_t sign;		/* sign prefix (' ', '+', '-', or \0) */
455 	char thousands_sep;	/* locale specific thousands separator */
456 	const char *grouping;	/* locale specific numeric grouping rules */
457 #ifdef FLOATING_POINT
458 	char *decimal_point;	/* locale specific decimal point */
459 	char softsign;		/* temporary negative sign for floats */
460 	double _double;		/* double precision arguments %[eEfgG] */
461 	int expt;		/* integer value of exponent */
462 	int expsize;		/* character count for expstr */
463 	int ndig;		/* actual number of digits returned by cvt */
464 	wchar_t expstr[7];	/* buffer for exponent string */
465 	wchar_t *dtoaresult;	/* buffer allocated by dtoa */
466 #endif
467 	u_long	ulval;		/* integer arguments %[diouxX] */
468 	uintmax_t ujval;	/* %j, %ll, %q, %t, %z integers */
469 	int base;		/* base for [diouxX] conversion */
470 	int dprec;		/* a copy of prec if [diouxX], 0 otherwise */
471 	int realsz;		/* field size expanded by dprec, sign, etc */
472 	int size;		/* size of converted field or string */
473 	int prsize;             /* max size of printed field */
474 	wchar_t *xdigs;		/* digits for [xX] conversion */
475 	wchar_t buf[BUF];	/* space for %c, %[diouxX], %[eEfFgG] */
476 	wchar_t ox[2];		/* space for 0x hex-prefix */
477 	union arg *argtable;	/* args, built due to positional arg */
478 	union arg statargtable [STATIC_ARG_TBL_SIZE];
479 	int nextarg;		/* 1-based argument index */
480 	va_list orgap;		/* original argument pointer */
481 	wchar_t *convbuf;	/* multibyte to wide conversion result */
482 
483 	/*
484 	 * Choose PADSIZE to trade efficiency vs. size.  If larger printf
485 	 * fields occur frequently, increase PADSIZE and make the initialisers
486 	 * below longer.
487 	 */
488 #define	PADSIZE	16		/* pad chunk size */
489 	static wchar_t blanks[PADSIZE] =
490 	 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
491 	static wchar_t zeroes[PADSIZE] =
492 	 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
493 
494 	/*
495 	 * BEWARE, these `goto error' on error, PRINT uses `n2' and
496 	 * PAD uses `n'.
497 	 */
498 #define	PRINT(ptr, len)	do {			\
499 	for (n2 = 0; n2 < (len); n2++)		\
500 		__fputwc((ptr)[n2], fp);	\
501 } while (0)
502 #define	PAD(howmany, with)	do {		\
503 	if ((n = (howmany)) > 0) {		\
504 		while (n > PADSIZE) {		\
505 			PRINT(with, PADSIZE);	\
506 			n -= PADSIZE;		\
507 		}				\
508 		PRINT(with, n);			\
509 	}					\
510 } while (0)
511 
512 	/*
513 	 * Get the argument indexed by nextarg.   If the argument table is
514 	 * built, use it to get the argument.  If its not, get the next
515 	 * argument (and arguments must be gotten sequentially).
516 	 */
517 #define GETARG(type) \
518 	((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
519 	    (nextarg++, va_arg(ap, type)))
520 
521 	/*
522 	 * To extend shorts properly, we need both signed and unsigned
523 	 * argument extraction methods.
524 	 */
525 #define	SARG() \
526 	(flags&LONGINT ? GETARG(long) : \
527 	    flags&SHORTINT ? (long)(short)GETARG(int) : \
528 	    flags&CHARINT ? (long)(signed char)GETARG(int) : \
529 	    (long)GETARG(int))
530 #define	UARG() \
531 	(flags&LONGINT ? GETARG(u_long) : \
532 	    flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
533 	    flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
534 	    (u_long)GETARG(u_int))
535 #define	INTMAX_SIZE	(INTMAXT|SIZET|PTRDIFFT|LLONGINT)
536 #define SJARG() \
537 	(flags&INTMAXT ? GETARG(intmax_t) : \
538 	    flags&SIZET ? (intmax_t)GETARG(size_t) : \
539 	    flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
540 	    (intmax_t)GETARG(long long))
541 #define	UJARG() \
542 	(flags&INTMAXT ? GETARG(uintmax_t) : \
543 	    flags&SIZET ? (uintmax_t)GETARG(size_t) : \
544 	    flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
545 	    (uintmax_t)GETARG(unsigned long long))
546 
547 	/*
548 	 * Get * arguments, including the form *nn$.  Preserve the nextarg
549 	 * that the argument can be gotten once the type is determined.
550 	 */
551 #define GETASTER(val) \
552 	n2 = 0; \
553 	cp = fmt; \
554 	while (is_digit(*cp)) { \
555 		n2 = 10 * n2 + to_digit(*cp); \
556 		cp++; \
557 	} \
558 	if (*cp == '$') { \
559 		int hold = nextarg; \
560 		if (argtable == NULL) { \
561 			argtable = statargtable; \
562 			__find_arguments (fmt0, orgap, &argtable); \
563 		} \
564 		nextarg = n2; \
565 		val = GETARG (int); \
566 		nextarg = hold; \
567 		fmt = ++cp; \
568 	} else { \
569 		val = GETARG (int); \
570 	}
571 
572 
573 	thousands_sep = '\0';
574 	grouping = NULL;
575 #ifdef FLOATING_POINT
576 	dtoaresult = NULL;
577 	decimal_point = localeconv()->decimal_point;
578 #endif
579 	convbuf = NULL;
580 	/* sorry, fwprintf(read_only_file, L"") returns WEOF, not 0 */
581 	if (cantwrite(fp))
582 		return (EOF);
583 
584 	/* optimise fprintf(stderr) (and other unbuffered Unix files) */
585 	if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
586 	    fp->_file >= 0)
587 		return (__sbprintf(fp, fmt0, ap));
588 
589 	fmt = (wchar_t *)fmt0;
590 	argtable = NULL;
591 	nextarg = 1;
592 	va_copy(orgap, ap);
593 	ret = 0;
594 
595 	/*
596 	 * Scan the format for conversions (`%' character).
597 	 */
598 	for (;;) {
599 		for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
600 			/* void */;
601 		if ((n = fmt - cp) != 0) {
602 			if ((unsigned)ret + n > INT_MAX) {
603 				ret = EOF;
604 				goto error;
605 			}
606 			PRINT(cp, n);
607 			ret += n;
608 		}
609 		if (ch == '\0')
610 			goto done;
611 		fmt++;		/* skip over '%' */
612 
613 		flags = 0;
614 		dprec = 0;
615 		width = 0;
616 		prec = -1;
617 		sign = '\0';
618 
619 rflag:		ch = *fmt++;
620 reswitch:	switch (ch) {
621 		case ' ':
622 			/*-
623 			 * ``If the space and + flags both appear, the space
624 			 * flag will be ignored.''
625 			 *	-- ANSI X3J11
626 			 */
627 			if (!sign)
628 				sign = ' ';
629 			goto rflag;
630 		case '#':
631 			flags |= ALT;
632 			goto rflag;
633 		case '*':
634 			/*-
635 			 * ``A negative field width argument is taken as a
636 			 * - flag followed by a positive field width.''
637 			 *	-- ANSI X3J11
638 			 * They don't exclude field widths read from args.
639 			 */
640 			GETASTER (width);
641 			if (width >= 0)
642 				goto rflag;
643 			width = -width;
644 			/* FALLTHROUGH */
645 		case '-':
646 			flags |= LADJUST;
647 			goto rflag;
648 		case '+':
649 			sign = '+';
650 			goto rflag;
651 		case '\'':
652 			flags |= GROUPING;
653 			thousands_sep = *(localeconv()->thousands_sep);
654 			grouping = localeconv()->grouping;
655 			goto rflag;
656 		case '.':
657 			if ((ch = *fmt++) == '*') {
658 				GETASTER (n);
659 				prec = n < 0 ? -1 : n;
660 				goto rflag;
661 			}
662 			n = 0;
663 			while (is_digit(ch)) {
664 				n = 10 * n + to_digit(ch);
665 				ch = *fmt++;
666 			}
667 			prec = n < 0 ? -1 : n;
668 			goto reswitch;
669 		case '0':
670 			/*-
671 			 * ``Note that 0 is taken as a flag, not as the
672 			 * beginning of a field width.''
673 			 *	-- ANSI X3J11
674 			 */
675 			flags |= ZEROPAD;
676 			goto rflag;
677 		case '1': case '2': case '3': case '4':
678 		case '5': case '6': case '7': case '8': case '9':
679 			n = 0;
680 			do {
681 				n = 10 * n + to_digit(ch);
682 				ch = *fmt++;
683 			} while (is_digit(ch));
684 			if (ch == '$') {
685 				nextarg = n;
686 				if (argtable == NULL) {
687 					argtable = statargtable;
688 					__find_arguments (fmt0, orgap,
689 					    &argtable);
690 				}
691 				goto rflag;
692 			}
693 			width = n;
694 			goto reswitch;
695 #ifdef FLOATING_POINT
696 		case 'L':
697 			flags |= LONGDBL;
698 			goto rflag;
699 #endif
700 		case 'h':
701 			if (flags & SHORTINT) {
702 				flags &= ~SHORTINT;
703 				flags |= CHARINT;
704 			} else
705 				flags |= SHORTINT;
706 			goto rflag;
707 		case 'j':
708 			flags |= INTMAXT;
709 			goto rflag;
710 		case 'l':
711 			if (flags & LONGINT) {
712 				flags &= ~LONGINT;
713 				flags |= LLONGINT;
714 			} else
715 				flags |= LONGINT;
716 			goto rflag;
717 		case 'q':
718 			flags |= LLONGINT;	/* not necessarily */
719 			goto rflag;
720 		case 't':
721 			flags |= PTRDIFFT;
722 			goto rflag;
723 		case 'z':
724 			flags |= SIZET;
725 			goto rflag;
726 		case 'C':
727 			flags |= LONGINT;
728 			/*FALLTHROUGH*/
729 		case 'c':
730 			if (flags & LONGINT)
731 				*(cp = buf) = (wchar_t)GETARG(wint_t);
732 			else
733 				*(cp = buf) = (wchar_t)btowc(GETARG(int));
734 			size = 1;
735 			sign = '\0';
736 			break;
737 		case 'D':
738 			flags |= LONGINT;
739 			/*FALLTHROUGH*/
740 		case 'd':
741 		case 'i':
742 			if (flags & INTMAX_SIZE) {
743 				ujval = SJARG();
744 				if ((intmax_t)ujval < 0) {
745 					ujval = -ujval;
746 					sign = '-';
747 				}
748 			} else {
749 				ulval = SARG();
750 				if ((long)ulval < 0) {
751 					ulval = -ulval;
752 					sign = '-';
753 				}
754 			}
755 			base = 10;
756 			goto number;
757 #ifdef FLOATING_POINT
758 #ifdef HEXFLOAT
759 		case 'a':
760 		case 'A':
761 #endif
762 		case 'e':
763 		case 'E':
764 			/*-
765 			 * Grouping apply to %i, %d, %u, %f, %F, %g, %G
766 			 * conversion specifiers only. For other conversions
767 			 * behavior is undefined.
768 			 *	-- POSIX
769 			 */
770 			flags &= ~GROUPING;
771 			/*FALLTHROUGH*/
772 		case 'f':
773 		case 'F':
774 			goto fp_begin;
775 		case 'g':
776 		case 'G':
777 			if (prec == 0)
778 				prec = 1;
779 fp_begin:		if (prec == -1)
780 				prec = DEFPREC;
781 			if (flags & LONGDBL)
782 				/* XXX this loses precision. */
783 				_double = (double)GETARG(long double);
784 			else
785 				_double = GETARG(double);
786 			/* do this before tricky precision changes */
787 			if (isinf(_double)) {
788 				if (_double < 0)
789 					sign = '-';
790 				if (iswupper(ch))
791 					cp = L"INF";
792 				else
793 					cp = L"inf";
794 				size = 3;
795 				break;
796 			}
797 			if (isnan(_double)) {
798 				if (iswupper(ch))
799 					cp = L"NAN";
800 				else
801 					cp = L"nan";
802 				size = 3;
803 				break;
804 			}
805 			flags |= FPT;
806 			if (dtoaresult != NULL) {
807 				free(dtoaresult);
808 				dtoaresult = NULL;
809 			}
810 			cp = cvt(_double, prec, flags, &softsign,
811 				&expt, ch, &ndig, &dtoaresult);
812 			if (ch == 'g' || ch == 'G') {
813 				if (expt <= -4 || expt > prec)
814 					ch = (ch == 'g') ? 'e' : 'E';
815 				else
816 					ch = 'g';
817 			}
818 			if (ch == 'e' || ch == 'E') {
819 				--expt;
820 				expsize = exponent(expstr, expt, ch);
821 				size = expsize + ndig;
822 				if (ndig > 1 || flags & ALT)
823 					++size;
824 			} else if (ch == 'f' || ch == 'F') {
825 				if (expt > 0) {
826 					size = expt;
827 					if (prec || flags & ALT)
828 						size += prec + 1;
829 				} else	/* "0.X" */
830 					size = prec + 2;
831 			} else if (expt >= ndig) {	/* fixed g fmt */
832 				size = expt;
833 				if (flags & ALT)
834 					++size;
835 			} else
836 				size = ndig + (expt > 0 ?
837 					1 : 2 - expt);
838 
839 			if (softsign)
840 				sign = '-';
841 			break;
842 #endif /* FLOATING_POINT */
843 		case 'n':
844 			/*
845 			 * Assignment-like behavior is specified if the
846 			 * value overflows or is otherwise unrepresentable.
847 			 * C99 says to use `signed char' for %hhn conversions.
848 			 */
849 			if (flags & LLONGINT)
850 				*GETARG(long long *) = ret;
851 			else if (flags & SIZET)
852 				*GETARG(ssize_t *) = (ssize_t)ret;
853 			else if (flags & PTRDIFFT)
854 				*GETARG(ptrdiff_t *) = ret;
855 			else if (flags & INTMAXT)
856 				*GETARG(intmax_t *) = ret;
857 			else if (flags & LONGINT)
858 				*GETARG(long *) = ret;
859 			else if (flags & SHORTINT)
860 				*GETARG(short *) = ret;
861 			else if (flags & CHARINT)
862 				*GETARG(signed char *) = ret;
863 			else
864 				*GETARG(int *) = ret;
865 			continue;	/* no output */
866 		case 'O':
867 			flags |= LONGINT;
868 			/*FALLTHROUGH*/
869 		case 'o':
870 			if (flags & INTMAX_SIZE)
871 				ujval = UJARG();
872 			else
873 				ulval = UARG();
874 			base = 8;
875 			goto nosign;
876 		case 'p':
877 			/*-
878 			 * ``The argument shall be a pointer to void.  The
879 			 * value of the pointer is converted to a sequence
880 			 * of printable characters, in an implementation-
881 			 * defined manner.''
882 			 *	-- ANSI X3J11
883 			 */
884 			ujval = (uintmax_t)(uintptr_t)GETARG(void *);
885 			base = 16;
886 			xdigs = L"0123456789abcdef";
887 			flags = flags | INTMAXT | HEXPREFIX;
888 			ch = 'x';
889 			goto nosign;
890 		case 'S':
891 			flags |= LONGINT;
892 			/*FALLTHROUGH*/
893 		case 's':
894 			if (flags & LONGINT) {
895 				if ((cp = GETARG(wchar_t *)) == NULL)
896 					cp = L"(null)";
897 			} else {
898 				char *mbp;
899 
900 				if (convbuf != NULL)
901 					free(convbuf);
902 				if ((mbp = GETARG(char *)) == NULL)
903 					cp = L"(null)";
904 				else {
905 					convbuf = __mbsconv(mbp, prec);
906 					if (convbuf == NULL) {
907 						fp->_flags |= __SERR;
908 						goto error;
909 					}
910 					cp = convbuf;
911 				}
912 			}
913 
914 			if (prec >= 0) {
915 				/*
916 				 * can't use wcslen; can only look for the
917 				 * NUL in the first `prec' characters, and
918 				 * wcslen() will go further.
919 				 */
920 				wchar_t *p = wmemchr(cp, 0, (size_t)prec);
921 
922 				if (p != NULL) {
923 					size = p - cp;
924 					if (size > prec)
925 						size = prec;
926 				} else
927 					size = prec;
928 			} else
929 				size = wcslen(cp);
930 			sign = '\0';
931 			break;
932 		case 'U':
933 			flags |= LONGINT;
934 			/*FALLTHROUGH*/
935 		case 'u':
936 			if (flags & INTMAX_SIZE)
937 				ujval = UJARG();
938 			else
939 				ulval = UARG();
940 			base = 10;
941 			goto nosign;
942 		case 'X':
943 			xdigs = L"0123456789ABCDEF";
944 			goto hex;
945 		case 'x':
946 			xdigs = L"0123456789abcdef";
947 hex:
948 			if (flags & INTMAX_SIZE)
949 				ujval = UJARG();
950 			else
951 				ulval = UARG();
952 			base = 16;
953 			/* leading 0x/X only if non-zero */
954 			if (flags & ALT &&
955 			    (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
956 				flags |= HEXPREFIX;
957 
958 			flags &= ~GROUPING;
959 			/* unsigned conversions */
960 nosign:			sign = '\0';
961 			/*-
962 			 * ``... diouXx conversions ... if a precision is
963 			 * specified, the 0 flag will be ignored.''
964 			 *	-- ANSI X3J11
965 			 */
966 number:			if ((dprec = prec) >= 0)
967 				flags &= ~ZEROPAD;
968 
969 			/*-
970 			 * ``The result of converting a zero value with an
971 			 * explicit precision of zero is no characters.''
972 			 *	-- ANSI X3J11
973 			 */
974 			cp = buf + BUF;
975 			if (flags & INTMAX_SIZE) {
976 				if (ujval != 0 || prec != 0)
977 					cp = __ujtoa(ujval, cp, base,
978 					    flags & ALT, xdigs,
979 					    flags & GROUPING, thousands_sep,
980 					    grouping);
981 			} else {
982 				if (ulval != 0 || prec != 0)
983 					cp = __ultoa(ulval, cp, base,
984 					    flags & ALT, xdigs,
985 					    flags & GROUPING, thousands_sep,
986 					    grouping);
987 			}
988 			size = buf + BUF - cp;
989 			break;
990 		default:	/* "%?" prints ?, unless ? is NUL */
991 			if (ch == '\0')
992 				goto done;
993 			/* pretend it was %c with argument ch */
994 			cp = buf;
995 			*cp = ch;
996 			size = 1;
997 			sign = '\0';
998 			break;
999 		}
1000 
1001 		/*
1002 		 * All reasonable formats wind up here.  At this point, `cp'
1003 		 * points to a string which (if not flags&LADJUST) should be
1004 		 * padded out to `width' places.  If flags&ZEROPAD, it should
1005 		 * first be prefixed by any sign or other prefix; otherwise,
1006 		 * it should be blank padded before the prefix is emitted.
1007 		 * After any left-hand padding and prefixing, emit zeroes
1008 		 * required by a decimal [diouxX] precision, then print the
1009 		 * string proper, then emit zeroes required by any leftover
1010 		 * floating precision; finally, if LADJUST, pad with blanks.
1011 		 *
1012 		 * Compute actual size, so we know how much to pad.
1013 		 * size excludes decimal prec; realsz includes it.
1014 		 */
1015 		realsz = dprec > size ? dprec : size;
1016 		if (sign)
1017 			realsz++;
1018 		else if (flags & HEXPREFIX)
1019 			realsz += 2;
1020 
1021 		prsize = width > realsz ? width : realsz;
1022 		if ((unsigned)ret + prsize > INT_MAX) {
1023 			ret = EOF;
1024 			goto error;
1025 		}
1026 
1027 		/* right-adjusting blank padding */
1028 		if ((flags & (LADJUST|ZEROPAD)) == 0)
1029 			PAD(width - realsz, blanks);
1030 
1031 		/* prefix */
1032 		if (sign) {
1033 			PRINT(&sign, 1);
1034 		} else if (flags & HEXPREFIX) {
1035 			ox[0] = '0';
1036 			ox[1] = ch;
1037 			PRINT(ox, 2);
1038 		}
1039 
1040 		/* right-adjusting zero padding */
1041 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1042 			PAD(width - realsz, zeroes);
1043 
1044 		/* leading zeroes from decimal precision */
1045 		PAD(dprec - size, zeroes);
1046 
1047 		/* the string or number proper */
1048 #ifdef FLOATING_POINT
1049 		if ((flags & FPT) == 0) {
1050 			PRINT(cp, size);
1051 		} else {	/* glue together f_p fragments */
1052 			if (ch >= 'f') {	/* 'f' or 'g' */
1053 				if (_double == 0) {
1054 					/* kludge for __dtoa irregularity */
1055 					PRINT(L"0", 1);
1056 					if (expt < ndig || (flags & ALT) != 0) {
1057 						PRINT(decimal_point, 1);
1058 						PAD(ndig - 1, zeroes);
1059 					}
1060 				} else if (expt <= 0) {
1061 					PRINT(L"0", 1);
1062 					PRINT(decimal_point, 1);
1063 					PAD(-expt, zeroes);
1064 					PRINT(cp, ndig);
1065 				} else if (expt >= ndig) {
1066 					PRINT(cp, ndig);
1067 					PAD(expt - ndig, zeroes);
1068 					if (flags & ALT)
1069 						PRINT(decimal_point, 1);
1070 				} else {
1071 					PRINT(cp, expt);
1072 					cp += expt;
1073 					PRINT(decimal_point, 1);
1074 					PRINT(cp, ndig-expt);
1075 				}
1076 			} else {	/* 'e' or 'E' */
1077 				if (ndig > 1 || flags & ALT) {
1078 					ox[0] = *cp++;
1079 					ox[1] = *decimal_point;
1080 					PRINT(ox, 2);
1081 					if (_double) {
1082 						PRINT(cp, ndig-1);
1083 					} else	/* 0.[0..] */
1084 						/* __dtoa irregularity */
1085 						PAD(ndig - 1, zeroes);
1086 				} else	/* XeYYY */
1087 					PRINT(cp, 1);
1088 				PRINT(expstr, expsize);
1089 			}
1090 		}
1091 #else
1092 		PRINT(cp, size);
1093 #endif
1094 		/* left-adjusting padding (always blank) */
1095 		if (flags & LADJUST)
1096 			PAD(width - realsz, blanks);
1097 
1098 		/* finally, adjust ret */
1099 		ret += prsize;
1100 	}
1101 done:
1102 error:
1103 #ifdef FLOATING_POINT
1104 	if (dtoaresult != NULL)
1105 		free(dtoaresult);
1106 #endif
1107 	if (convbuf != NULL)
1108 		free(convbuf);
1109 	if (__sferror(fp))
1110 		ret = EOF;
1111 	if ((argtable != NULL) && (argtable != statargtable))
1112 		free (argtable);
1113 	return (ret);
1114 	/* NOTREACHED */
1115 }
1116 
1117 /*
1118  * Find all arguments when a positional parameter is encountered.  Returns a
1119  * table, indexed by argument number, of pointers to each arguments.  The
1120  * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1121  * It will be replaces with a malloc-ed one if it overflows.
1122  */
1123 static void
1124 __find_arguments (const wchar_t *fmt0, va_list ap, union arg **argtable)
1125 {
1126 	wchar_t *fmt;		/* format string */
1127 	wchar_t ch;		/* character from fmt */
1128 	int n, n2;		/* handy integer (short term usage) */
1129 	wchar_t *cp;		/* handy char pointer (short term usage) */
1130 	int flags;		/* flags as above */
1131 	int width;		/* width from format (%8d), or 0 */
1132 	enum typeid *typetable; /* table of types */
1133 	enum typeid stattypetable [STATIC_ARG_TBL_SIZE];
1134 	int tablesize;		/* current size of type table */
1135 	int tablemax;		/* largest used index in table */
1136 	int nextarg;		/* 1-based argument index */
1137 
1138 	/*
1139 	 * Add an argument type to the table, expanding if necessary.
1140 	 */
1141 #define ADDTYPE(type) \
1142 	((nextarg >= tablesize) ? \
1143 		__grow_type_table(nextarg, &typetable, &tablesize) : 0, \
1144 	(nextarg > tablemax) ? tablemax = nextarg : 0, \
1145 	typetable[nextarg++] = type)
1146 
1147 #define	ADDSARG() \
1148 	((flags&INTMAXT) ? ADDTYPE(T_INTMAXT) : \
1149 		((flags&SIZET) ? ADDTYPE(T_SIZET) : \
1150 		((flags&PTRDIFFT) ? ADDTYPE(T_PTRDIFFT) : \
1151 		((flags&LLONGINT) ? ADDTYPE(T_LLONG) : \
1152 		((flags&LONGINT) ? ADDTYPE(T_LONG) : ADDTYPE(T_INT))))))
1153 
1154 #define	ADDUARG() \
1155 	((flags&INTMAXT) ? ADDTYPE(T_UINTMAXT) : \
1156 		((flags&SIZET) ? ADDTYPE(T_SIZET) : \
1157 		((flags&PTRDIFFT) ? ADDTYPE(T_PTRDIFFT) : \
1158 		((flags&LLONGINT) ? ADDTYPE(T_U_LLONG) : \
1159 		((flags&LONGINT) ? ADDTYPE(T_U_LONG) : 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 		n2 = 10 * n2 + to_digit(*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 			/* void */;
1193 		if (ch == '\0')
1194 			goto done;
1195 		fmt++;		/* skip over '%' */
1196 
1197 		flags = 0;
1198 		width = 0;
1199 
1200 rflag:		ch = *fmt++;
1201 reswitch:	switch (ch) {
1202 		case ' ':
1203 		case '#':
1204 			goto rflag;
1205 		case '*':
1206 			ADDASTER ();
1207 			goto rflag;
1208 		case '-':
1209 		case '+':
1210 		case '\'':
1211 			goto rflag;
1212 		case '.':
1213 			if ((ch = *fmt++) == '*') {
1214 				ADDASTER ();
1215 				goto rflag;
1216 			}
1217 			while (is_digit(ch)) {
1218 				ch = *fmt++;
1219 			}
1220 			goto reswitch;
1221 		case '0':
1222 			goto rflag;
1223 		case '1': case '2': case '3': case '4':
1224 		case '5': case '6': case '7': case '8': case '9':
1225 			n = 0;
1226 			do {
1227 				n = 10 * n + to_digit(ch);
1228 				ch = *fmt++;
1229 			} while (is_digit(ch));
1230 			if (ch == '$') {
1231 				nextarg = n;
1232 				goto rflag;
1233 			}
1234 			width = n;
1235 			goto reswitch;
1236 #ifdef FLOATING_POINT
1237 		case 'L':
1238 			flags |= LONGDBL;
1239 			goto rflag;
1240 #endif
1241 		case 'h':
1242 			if (flags & SHORTINT) {
1243 				flags &= ~SHORTINT;
1244 				flags |= CHARINT;
1245 			} else
1246 				flags |= SHORTINT;
1247 			goto rflag;
1248 		case 'j':
1249 			flags |= INTMAXT;
1250 			goto rflag;
1251 		case 'l':
1252 			if (flags & LONGINT) {
1253 				flags &= ~LONGINT;
1254 				flags |= LLONGINT;
1255 			} else
1256 				flags |= LONGINT;
1257 			goto rflag;
1258 		case 'q':
1259 			flags |= LLONGINT;	/* not necessarily */
1260 			goto rflag;
1261 		case 't':
1262 			flags |= PTRDIFFT;
1263 			goto rflag;
1264 		case 'z':
1265 			flags |= SIZET;
1266 			goto rflag;
1267 		case 'C':
1268 			flags |= LONGINT;
1269 			/*FALLTHROUGH*/
1270 		case 'c':
1271 			if (flags & LONGINT)
1272 				ADDTYPE(T_WINT);
1273 			else
1274 				ADDTYPE(T_INT);
1275 			break;
1276 		case 'D':
1277 			flags |= LONGINT;
1278 			/*FALLTHROUGH*/
1279 		case 'd':
1280 		case 'i':
1281 			ADDSARG();
1282 			break;
1283 #ifdef FLOATING_POINT
1284 #ifdef HEXFLOAT
1285 		case 'a':
1286 		case 'A':
1287 #endif
1288 		case 'e':
1289 		case 'E':
1290 		case 'f':
1291 		case 'g':
1292 		case 'G':
1293 			if (flags & LONGDBL)
1294 				ADDTYPE(T_LONG_DOUBLE);
1295 			else
1296 				ADDTYPE(T_DOUBLE);
1297 			break;
1298 #endif /* FLOATING_POINT */
1299 		case 'n':
1300 			if (flags & INTMAXT)
1301 				ADDTYPE(TP_INTMAXT);
1302 			else if (flags & PTRDIFFT)
1303 				ADDTYPE(TP_PTRDIFFT);
1304 			else if (flags & SIZET)
1305 				ADDTYPE(TP_SIZET);
1306 			else if (flags & LLONGINT)
1307 				ADDTYPE(TP_LLONG);
1308 			else if (flags & LONGINT)
1309 				ADDTYPE(TP_LONG);
1310 			else if (flags & SHORTINT)
1311 				ADDTYPE(TP_SHORT);
1312 			else if (flags & CHARINT)
1313 				ADDTYPE(TP_SCHAR);
1314 			else
1315 				ADDTYPE(TP_INT);
1316 			continue;	/* no output */
1317 		case 'O':
1318 			flags |= LONGINT;
1319 			/*FALLTHROUGH*/
1320 		case 'o':
1321 			ADDUARG();
1322 			break;
1323 		case 'p':
1324 			ADDTYPE(TP_VOID);
1325 			break;
1326 		case 'S':
1327 			flags |= LONGINT;
1328 			/*FALLTHROUGH*/
1329 		case 's':
1330 			if (flags & LONGINT)
1331 				ADDTYPE(TP_WCHAR);
1332 			else
1333 				ADDTYPE(TP_CHAR);
1334 			break;
1335 		case 'U':
1336 			flags |= LONGINT;
1337 			/*FALLTHROUGH*/
1338 		case 'u':
1339 		case 'X':
1340 		case 'x':
1341 			ADDUARG();
1342 			break;
1343 		default:	/* "%?" prints ?, unless ? is NUL */
1344 			if (ch == '\0')
1345 				goto done;
1346 			break;
1347 		}
1348 	}
1349 done:
1350 	/*
1351 	 * Build the argument table.
1352 	 */
1353 	if (tablemax >= STATIC_ARG_TBL_SIZE) {
1354 		*argtable = (union arg *)
1355 		    malloc (sizeof (union arg) * (tablemax + 1));
1356 	}
1357 
1358 	(*argtable) [0].intarg = 0;
1359 	for (n = 1; n <= tablemax; n++) {
1360 		switch (typetable [n]) {
1361 		    case T_UNUSED: /* whoops! */
1362 			(*argtable) [n].intarg = va_arg (ap, int);
1363 			break;
1364 		    case TP_SCHAR:
1365 			(*argtable) [n].pschararg = va_arg (ap, signed char *);
1366 			break;
1367 		    case TP_SHORT:
1368 			(*argtable) [n].pshortarg = va_arg (ap, short *);
1369 			break;
1370 		    case T_INT:
1371 			(*argtable) [n].intarg = va_arg (ap, int);
1372 			break;
1373 		    case T_U_INT:
1374 			(*argtable) [n].uintarg = va_arg (ap, unsigned int);
1375 			break;
1376 		    case TP_INT:
1377 			(*argtable) [n].pintarg = va_arg (ap, int *);
1378 			break;
1379 		    case T_LONG:
1380 			(*argtable) [n].longarg = va_arg (ap, long);
1381 			break;
1382 		    case T_U_LONG:
1383 			(*argtable) [n].ulongarg = va_arg (ap, unsigned long);
1384 			break;
1385 		    case TP_LONG:
1386 			(*argtable) [n].plongarg = va_arg (ap, long *);
1387 			break;
1388 		    case T_LLONG:
1389 			(*argtable) [n].longlongarg = va_arg (ap, long long);
1390 			break;
1391 		    case T_U_LLONG:
1392 			(*argtable) [n].ulonglongarg = va_arg (ap, unsigned long long);
1393 			break;
1394 		    case TP_LLONG:
1395 			(*argtable) [n].plonglongarg = va_arg (ap, long long *);
1396 			break;
1397 		    case T_PTRDIFFT:
1398 			(*argtable) [n].ptrdiffarg = va_arg (ap, ptrdiff_t);
1399 			break;
1400 		    case TP_PTRDIFFT:
1401 			(*argtable) [n].pptrdiffarg = va_arg (ap, ptrdiff_t *);
1402 			break;
1403 		    case T_SIZET:
1404 			(*argtable) [n].sizearg = va_arg (ap, size_t);
1405 			break;
1406 		    case TP_SIZET:
1407 			(*argtable) [n].psizearg = va_arg (ap, ssize_t *);
1408 			break;
1409 		    case T_INTMAXT:
1410 			(*argtable) [n].intmaxarg = va_arg (ap, intmax_t);
1411 			break;
1412 		    case T_UINTMAXT:
1413 			(*argtable) [n].uintmaxarg = va_arg (ap, uintmax_t);
1414 			break;
1415 		    case TP_INTMAXT:
1416 			(*argtable) [n].pintmaxarg = va_arg (ap, intmax_t *);
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_WINT:
1433 			(*argtable) [n].wintarg = va_arg (ap, wint_t);
1434 			break;
1435 		    case TP_WCHAR:
1436 			(*argtable) [n].pwchararg = va_arg (ap, wchar_t *);
1437 			break;
1438 		}
1439 	}
1440 
1441 	if ((typetable != NULL) && (typetable != stattypetable))
1442 		free (typetable);
1443 }
1444 
1445 /*
1446  * Increase the size of the type table.
1447  */
1448 static void
1449 __grow_type_table (int nextarg, enum typeid **typetable, int *tablesize)
1450 {
1451 	enum typeid *const oldtable = *typetable;
1452 	const int oldsize = *tablesize;
1453 	enum typeid *newtable;
1454 	int newsize = oldsize * 2;
1455 
1456 	if (newsize < nextarg + 1)
1457 		newsize = nextarg + 1;
1458 	if (oldsize == STATIC_ARG_TBL_SIZE) {
1459 		if ((newtable = malloc(newsize)) == NULL)
1460 			abort();			/* XXX handle better */
1461 		bcopy(oldtable, newtable, oldsize);
1462 	} else {
1463 		if ((newtable = reallocf(oldtable, newsize)) == NULL)
1464 			abort();			/* XXX handle better */
1465 	}
1466 	memset(&newtable[oldsize], T_UNUSED, newsize - oldsize);
1467 
1468 	*typetable = newtable;
1469 	*tablesize = newsize;
1470 }
1471 
1472 
1473 #ifdef FLOATING_POINT
1474 
1475 extern char *__dtoa(double, int, int, int *, int *, char **, char **);
1476 
1477 static wchar_t *
1478 cvt(double value, int ndigits, int flags, char *sign, int *decpt,
1479     wchar_t ch, int *length, wchar_t **dtoaresultp)
1480 {
1481 	int i, mode, dsgn;
1482 	wchar_t *digits, *bp, *result, *rve;
1483 	char *tresult, *trve;
1484 
1485 	if (ch == 'f')
1486 		mode = 3;		/* ndigits after the decimal point */
1487 	else {
1488 		/*
1489 		 * To obtain ndigits after the decimal point for the 'e'
1490 		 * and 'E' formats, round to ndigits + 1 significant
1491 		 * figures.
1492 		 */
1493 		if (ch == 'e' || ch == 'E')
1494 			ndigits++;
1495 		mode = 2;		/* ndigits significant digits */
1496 	}
1497 	__dtoa(value, mode, ndigits, decpt, &dsgn, &trve, &tresult);
1498 	if ((result = malloc((trve - tresult + 1) * sizeof(*result))) == NULL)
1499 		abort();		/* XXX handle better */
1500 	for (i = 0; i < trve - tresult + 1; i++)
1501 		result[i] = (wchar_t)(unsigned char)tresult[i];
1502 	rve = result + (trve - tresult);
1503 	free(tresult);
1504 	*dtoaresultp = result;
1505 	digits = result;
1506 	*sign = dsgn != 0;
1507 	if ((ch != 'g' && ch != 'G') || flags & ALT) {
1508 		/* print trailing zeros */
1509 		bp = digits + ndigits;
1510 		if (ch == 'f') {
1511 			if (*digits == '0' && value)
1512 				*decpt = -ndigits + 1;
1513 			bp += *decpt;
1514 		}
1515 		if (value == 0)	/* kludge for __dtoa irregularity */
1516 			rve = bp;
1517 		while (rve < bp)
1518 			*rve++ = '0';
1519 	}
1520 	*length = rve - digits;
1521 	return (digits);
1522 }
1523 
1524 static int
1525 exponent(wchar_t *p0, int exp, wchar_t fmtch)
1526 {
1527 	wchar_t *p, *t;
1528 	wchar_t expbuf[MAXEXP];
1529 
1530 	p = p0;
1531 	*p++ = fmtch;
1532 	if (exp < 0) {
1533 		exp = -exp;
1534 		*p++ = '-';
1535 	}
1536 	else
1537 		*p++ = '+';
1538 	t = expbuf + MAXEXP;
1539 	if (exp > 9) {
1540 		do {
1541 			*--t = to_char(exp % 10);
1542 		} while ((exp /= 10) > 9);
1543 		*--t = to_char(exp);
1544 		for (; t < expbuf + MAXEXP; *p++ = *t++);
1545 	}
1546 	else {
1547 		*p++ = '0';
1548 		*p++ = to_char(exp);
1549 	}
1550 	return (p - p0);
1551 }
1552 #endif /* FLOATING_POINT */
1553