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