xref: /netbsd-src/lib/libc/stdio/vfwprintf.c (revision aaf4ece63a859a04e37cf3a7229b5fab0157cc06)
1 /*	$NetBSD: vfwprintf.c,v 1.5 2005/12/02 14:45:24 yamt 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.5 2005/12/02 14:45:24 yamt 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 		const wchar_t *result;
683 
684 		for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
685 			/* void */;
686 		if ((n = fmt - cp) != 0) {
687 			if ((unsigned)ret + n > INT_MAX) {
688 				ret = EOF;
689 				goto error;
690 			}
691 			PRINT(cp, n);
692 			ret += n;
693 		}
694 		if (ch == '\0')
695 			goto done;
696 		fmt++;		/* skip over '%' */
697 
698 		flags = 0;
699 		dprec = 0;
700 		width = 0;
701 		prec = -1;
702 		sign = '\0';
703 		ox[1] = '\0';
704 		expchar = '\0';
705 		lead = 0;
706 		nseps = nrepeats = 0;
707 		ulval = 0;
708 		ujval = 0;
709 		xdigs = NULL;
710 
711 rflag:		ch = *fmt++;
712 reswitch:	switch (ch) {
713 		case ' ':
714 			/*-
715 			 * ``If the space and + flags both appear, the space
716 			 * flag will be ignored.''
717 			 *	-- ANSI X3J11
718 			 */
719 			if (!sign)
720 				sign = ' ';
721 			goto rflag;
722 		case '#':
723 			flags |= ALT;
724 			goto rflag;
725 		case '*':
726 			/*-
727 			 * ``A negative field width argument is taken as a
728 			 * - flag followed by a positive field width.''
729 			 *	-- ANSI X3J11
730 			 * They don't exclude field widths read from args.
731 			 */
732 			GETASTER (width);
733 			if (width >= 0)
734 				goto rflag;
735 			width = -width;
736 			/* FALLTHROUGH */
737 		case '-':
738 			flags |= LADJUST;
739 			goto rflag;
740 		case '+':
741 			sign = '+';
742 			goto rflag;
743 		case '\'':
744 			flags |= GROUPING;
745 			thousands_sep = *(localeconv()->thousands_sep);
746 			grouping = localeconv()->grouping;
747 			goto rflag;
748 		case '.':
749 			if ((ch = *fmt++) == '*') {
750 				GETASTER (prec);
751 				goto rflag;
752 			}
753 			prec = 0;
754 			while (is_digit(ch)) {
755 				prec = 10 * prec + to_digit(ch);
756 				ch = *fmt++;
757 			}
758 			goto reswitch;
759 		case '0':
760 			/*-
761 			 * ``Note that 0 is taken as a flag, not as the
762 			 * beginning of a field width.''
763 			 *	-- ANSI X3J11
764 			 */
765 			flags |= ZEROPAD;
766 			goto rflag;
767 		case '1': case '2': case '3': case '4':
768 		case '5': case '6': case '7': case '8': case '9':
769 			n = 0;
770 			do {
771 				n = 10 * n + to_digit(ch);
772 				ch = *fmt++;
773 			} while (is_digit(ch));
774 			if (ch == '$') {
775 				nextarg = n;
776 				if (argtable == NULL) {
777 					argtable = statargtable;
778 					__find_arguments (fmt0, orgap,
779 					    &argtable);
780 				}
781 				goto rflag;
782 			}
783 			width = n;
784 			goto reswitch;
785 #ifndef NO_FLOATING_POINT
786 		case 'L':
787 			flags |= LONGDBL;
788 			goto rflag;
789 #endif
790 		case 'h':
791 			if (flags & SHORTINT) {
792 				flags &= ~SHORTINT;
793 				flags |= CHARINT;
794 			} else
795 				flags |= SHORTINT;
796 			goto rflag;
797 		case 'j':
798 			flags |= INTMAXT;
799 			goto rflag;
800 		case 'l':
801 			if (flags & LONGINT) {
802 				flags &= ~LONGINT;
803 				flags |= LLONGINT;
804 			} else
805 				flags |= LONGINT;
806 			goto rflag;
807 		case 'q':
808 			flags |= LLONGINT;	/* not necessarily */
809 			goto rflag;
810 		case 't':
811 			flags |= PTRDIFFT;
812 			goto rflag;
813 		case 'z':
814 			flags |= SIZET;
815 			goto rflag;
816 		case 'C':
817 			flags |= LONGINT;
818 			/*FALLTHROUGH*/
819 		case 'c':
820 			if (flags & LONGINT)
821 				*buf = (wchar_t)GETARG(wint_t);
822 			else
823 				*buf = (wchar_t)btowc(GETARG(int));
824 			result = buf;
825 			size = 1;
826 			sign = '\0';
827 			break;
828 		case 'D':
829 			flags |= LONGINT;
830 			/*FALLTHROUGH*/
831 		case 'd':
832 		case 'i':
833 			if (flags & INTMAX_SIZE) {
834 				ujval = SJARG();
835 				if ((intmax_t)ujval < 0) {
836 					ujval = -ujval;
837 					sign = '-';
838 				}
839 			} else {
840 				ulval = SARG();
841 				if ((long)ulval < 0) {
842 					ulval = -ulval;
843 					sign = '-';
844 				}
845 			}
846 			base = 10;
847 			goto number;
848 #ifndef NO_FLOATING_POINT
849 #ifdef notyet
850 		case 'a':
851 		case 'A':
852 			if (ch == 'a') {
853 				ox[1] = 'x';
854 				xdigs = xdigs_lower;
855 				expchar = 'p';
856 			} else {
857 				ox[1] = 'X';
858 				xdigs = xdigs_upper;
859 				expchar = 'P';
860 			}
861 			if (prec >= 0)
862 				prec++;
863 			if (flags & LONGDBL) {
864 				fparg.ldbl = GETARG(long double);
865 				dtoaresult =
866 				    __hldtoa(fparg.ldbl, xdigs, prec,
867 				        &expt, &signflag, &dtoaend);
868 			} else {
869 				fparg.dbl = GETARG(double);
870 				dtoaresult =
871 				    __hdtoa(fparg.dbl, xdigs, prec,
872 				        &expt, &signflag, &dtoaend);
873 			}
874 
875 			if (prec < 0)
876 				prec = dtoaend - dtoaresult;
877 			if (expt == INT_MAX)
878 				ox[1] = '\0';
879 			if (convbuf != NULL)
880 				free(convbuf);
881 			ndig = dtoaend - dtoaresult;
882 			result = convbuf = __mbsconv(dtoaresult, -1);
883 			freedtoa(dtoaresult);
884 			goto fp_common;
885 		case 'e':
886 		case 'E':
887 			expchar = ch;
888 			if (prec < 0)	/* account for digit before decpt */
889 				prec = DEFPREC + 1;
890 			else
891 				prec++;
892 			goto fp_begin;
893 		case 'f':
894 		case 'F':
895 			expchar = '\0';
896 			goto fp_begin;
897 		case 'g':
898 		case 'G':
899 			expchar = ch - ('g' - 'e');
900 			if (prec == 0)
901 				prec = 1;
902 fp_begin:
903 			if (prec < 0)
904 				prec = DEFPREC;
905 			if (convbuf != NULL)
906 				free(convbuf);
907 			if (flags & LONGDBL) {
908 				fparg.ldbl = GETARG(long double);
909 				dtoaresult =
910 				    __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
911 				    &expt, &signflag, &dtoaend);
912 			} else {
913 				fparg.dbl = GETARG(double);
914 				dtoaresult =
915 				    dtoa(fparg.dbl, expchar ? 2 : 3, prec,
916 				    &expt, &signflag, &dtoaend);
917 				if (expt == 9999)
918 					expt = INT_MAX;
919 			}
920 			ndig = dtoaend - dtoaresult;
921 			result = convbuf = __mbsconv(dtoaresult, -1);
922 			freedtoa(dtoaresult);
923 fp_common:
924 			if (signflag)
925 				sign = '-';
926 			if (expt == INT_MAX) {	/* inf or nan */
927 				if (*result == 'N') {
928 					result = (ch >= 'a') ? L"nan" : L"NAN";
929 					sign = '\0';
930 				} else
931 					result = (ch >= 'a') ? L"inf" : L"INF";
932 				size = 3;
933 				break;
934 			}
935 #else
936 		case 'e':
937 		case 'E':
938 		case 'f':
939 		case 'F':
940 		case 'g':
941 		case 'G':
942 			if (prec == -1) {
943 				prec = DEFPREC;
944 			} else if ((ch == 'g' || ch == 'G') && prec == 0) {
945 				prec = 1;
946 			}
947 
948 			if (flags & LONGDBL) {
949 				_double = (double) GETARG(long double);
950 			} else {
951 				_double = GETARG(double);
952 			}
953 
954 			/* do this before tricky precision changes */
955 			if (isinf(_double)) {
956 				if (_double < 0)
957 					sign = '-';
958 				if (ch == 'E' || ch == 'F' || ch == 'G')
959 					result = L"INF";
960 				else
961 					result = L"inf";
962 				size = 3;
963 				break;
964 			}
965 			if (isnan(_double)) {
966 				if (ch == 'E' || ch == 'F' || ch == 'G')
967 					result = L"NAN";
968 				else
969 					result = L"nan";
970 				size = 3;
971 				break;
972 			}
973 
974 			flags |= FPT;
975 			result = cvt(_double, prec, flags, &softsign,
976 				&expt, ch, &ndig);
977 			if (softsign)
978 				sign = '-';
979 #endif
980 			flags |= FPT;
981 			if (ch == 'g' || ch == 'G') {
982 				if (expt > -4 && expt <= prec) {
983 					/* Make %[gG] smell like %[fF] */
984 					expchar = '\0';
985 					if (flags & ALT)
986 						prec -= expt;
987 					else
988 						prec = ndig - expt;
989 					if (prec < 0)
990 						prec = 0;
991 				} else {
992 					/*
993 					 * Make %[gG] smell like %[eE], but
994 					 * trim trailing zeroes if no # flag.
995 					 */
996 					if (!(flags & ALT))
997 						prec = ndig;
998 				}
999 			}
1000 			if (expchar) {
1001 				expsize = exponent(expstr, expt - 1, expchar);
1002 				size = expsize + prec;
1003 				if (prec > 1 || flags & ALT)
1004 					++size;
1005 			} else {
1006 				/* space for digits before decimal point */
1007 				if (expt > 0)
1008 					size = expt;
1009 				else	/* "0" */
1010 					size = 1;
1011 				/* space for decimal pt and following digits */
1012 				if (prec || flags & ALT)
1013 					size += prec + 1;
1014 				if (grouping && expt > 0) {
1015 					/* space for thousands' grouping */
1016 					nseps = nrepeats = 0;
1017 					lead = expt;
1018 					while (*grouping != CHAR_MAX) {
1019 						if (lead <= *grouping)
1020 							break;
1021 						lead -= *grouping;
1022 						if (*(grouping+1)) {
1023 							nseps++;
1024 							grouping++;
1025 						} else
1026 							nrepeats++;
1027 					}
1028 					size += nseps + nrepeats;
1029 				} else
1030 					lead = expt;
1031 			}
1032 			break;
1033 #endif /* !NO_FLOATING_POINT */
1034 		case 'n':
1035 			/*
1036 			 * Assignment-like behavior is specified if the
1037 			 * value overflows or is otherwise unrepresentable.
1038 			 * C99 says to use `signed char' for %hhn conversions.
1039 			 */
1040 			if (flags & LLONGINT)
1041 				*GETARG(quad_t *) = ret;
1042 			else if (flags & SIZET)
1043 				*GETARG(ssize_t *) = (ssize_t)ret;
1044 			else if (flags & PTRDIFFT)
1045 				*GETARG(ptrdiff_t *) = ret;
1046 			else if (flags & INTMAXT)
1047 				*GETARG(intmax_t *) = ret;
1048 			else if (flags & LONGINT)
1049 				*GETARG(long *) = ret;
1050 			else if (flags & SHORTINT)
1051 				*GETARG(short *) = ret;
1052 			else if (flags & CHARINT)
1053 				*GETARG(signed char *) = ret;
1054 			else
1055 				*GETARG(int *) = ret;
1056 			continue;	/* no output */
1057 		case 'O':
1058 			flags |= LONGINT;
1059 			/*FALLTHROUGH*/
1060 		case 'o':
1061 			if (flags & INTMAX_SIZE)
1062 				ujval = UJARG();
1063 			else
1064 				ulval = UARG();
1065 			base = 8;
1066 			goto nosign;
1067 		case 'p':
1068 			/*-
1069 			 * ``The argument shall be a pointer to void.  The
1070 			 * value of the pointer is converted to a sequence
1071 			 * of printable characters, in an implementation-
1072 			 * defined manner.''
1073 			 *	-- ANSI X3J11
1074 			 */
1075 			ujval = (uintmax_t)(uintptr_t)GETARG(void *);
1076 			base = 16;
1077 			xdigs = xdigs_lower;
1078 			flags = flags | INTMAXT;
1079 			ox[1] = 'x';
1080 			goto nosign;
1081 		case 'S':
1082 			flags |= LONGINT;
1083 			/*FALLTHROUGH*/
1084 		case 's':
1085 			if (flags & LONGINT) {
1086 				if ((result = GETARG(wchar_t *)) == NULL)
1087 					result = L"(null)";
1088 			} else {
1089 				char *mbp;
1090 
1091 				if (convbuf != NULL)
1092 					free(convbuf);
1093 				if ((mbp = GETARG(char *)) == NULL)
1094 					result = L"(null)";
1095 				else {
1096 					convbuf = __mbsconv(mbp, prec);
1097 					if (convbuf == NULL) {
1098 						fp->_flags |= __SERR;
1099 						goto error;
1100 					}
1101 					result = convbuf;
1102 				}
1103 			}
1104 
1105 			if (prec >= 0) {
1106 				/*
1107 				 * can't use wcslen; can only look for the
1108 				 * NUL in the first `prec' characters, and
1109 				 * wcslen() will go further.
1110 				 */
1111 				wchar_t *p = wmemchr(result, 0, (size_t)prec);
1112 
1113 				if (p != NULL) {
1114 					size = p - result;
1115 					if (size > prec)
1116 						size = prec;
1117 				} else
1118 					size = prec;
1119 			} else
1120 				size = wcslen(result);
1121 			sign = '\0';
1122 			break;
1123 		case 'U':
1124 			flags |= LONGINT;
1125 			/*FALLTHROUGH*/
1126 		case 'u':
1127 			if (flags & INTMAX_SIZE)
1128 				ujval = UJARG();
1129 			else
1130 				ulval = UARG();
1131 			base = 10;
1132 			goto nosign;
1133 		case 'X':
1134 			xdigs = xdigs_upper;
1135 			goto hex;
1136 		case 'x':
1137 			xdigs = xdigs_lower;
1138 hex:
1139 			if (flags & INTMAX_SIZE)
1140 				ujval = UJARG();
1141 			else
1142 				ulval = UARG();
1143 			base = 16;
1144 			/* leading 0x/X only if non-zero */
1145 			if (flags & ALT &&
1146 			    (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
1147 				ox[1] = ch;
1148 
1149 			flags &= ~GROUPING;
1150 			/* unsigned conversions */
1151 nosign:			sign = '\0';
1152 			/*-
1153 			 * ``... diouXx conversions ... if a precision is
1154 			 * specified, the 0 flag will be ignored.''
1155 			 *	-- ANSI X3J11
1156 			 */
1157 number:			if ((dprec = prec) >= 0)
1158 				flags &= ~ZEROPAD;
1159 
1160 			/*-
1161 			 * ``The result of converting a zero value with an
1162 			 * explicit precision of zero is no characters.''
1163 			 *	-- ANSI X3J11
1164 			 *
1165 			 * ``The C Standard is clear enough as is.  The call
1166 			 * printf("%#.0o", 0) should print 0.''
1167 			 *	-- Defect Report #151
1168 			 */
1169 			result = cp = buf + BUF;
1170 			if (flags & INTMAX_SIZE) {
1171 				if (ujval != 0 || prec != 0 ||
1172 				    (flags & ALT && base == 8))
1173 					result = __ujtoa(ujval, cp, base,
1174 					    flags & ALT, xdigs,
1175 					    flags & GROUPING, thousands_sep,
1176 					    grouping);
1177 			} else {
1178 				if (ulval != 0 || prec != 0 ||
1179 				    (flags & ALT && base == 8))
1180 					result = __ultoa(ulval, cp, base,
1181 					    flags & ALT, xdigs,
1182 					    flags & GROUPING, thousands_sep,
1183 					    grouping);
1184 			}
1185 			size = buf + BUF - result;
1186 			if (size > BUF)	/* should never happen */
1187 				abort();
1188 			break;
1189 		default:	/* "%?" prints ?, unless ? is NUL */
1190 			if (ch == '\0')
1191 				goto done;
1192 			/* pretend it was %c with argument ch */
1193 			*buf = ch;
1194 			result = buf;
1195 			size = 1;
1196 			sign = '\0';
1197 			break;
1198 		}
1199 
1200 		/*
1201 		 * All reasonable formats wind up here.  At this point, `result'
1202 		 * points to a string which (if not flags&LADJUST) should be
1203 		 * padded out to `width' places.  If flags&ZEROPAD, it should
1204 		 * first be prefixed by any sign or other prefix; otherwise,
1205 		 * it should be blank padded before the prefix is emitted.
1206 		 * After any left-hand padding and prefixing, emit zeroes
1207 		 * required by a decimal [diouxX] precision, then print the
1208 		 * string proper, then emit zeroes required by any leftover
1209 		 * floating precision; finally, if LADJUST, pad with blanks.
1210 		 *
1211 		 * Compute actual size, so we know how much to pad.
1212 		 * size excludes decimal prec; realsz includes it.
1213 		 */
1214 		realsz = dprec > size ? dprec : size;
1215 		if (sign)
1216 			realsz++;
1217 		if (ox[1])
1218 			realsz += 2;
1219 
1220 		prsize = width > realsz ? width : realsz;
1221 		if ((unsigned)ret + prsize > INT_MAX) {
1222 			ret = EOF;
1223 			goto error;
1224 		}
1225 
1226 		/* right-adjusting blank padding */
1227 		if ((flags & (LADJUST|ZEROPAD)) == 0)
1228 			PAD(width - realsz, blanks);
1229 
1230 		/* prefix */
1231 		if (sign)
1232 			PRINT(&sign, 1);
1233 
1234 		if (ox[1]) {	/* ox[1] is either x, X, or \0 */
1235 			ox[0] = '0';
1236 			PRINT(ox, 2);
1237 		}
1238 
1239 		/* right-adjusting zero padding */
1240 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1241 			PAD(width - realsz, zeroes);
1242 
1243 		/* leading zeroes from decimal precision */
1244 		PAD(dprec - size, zeroes);
1245 
1246 		/* the string or number proper */
1247 #ifndef NO_FLOATING_POINT
1248 		if ((flags & FPT) == 0) {
1249 			PRINT(result, size);
1250 		} else {	/* glue together f_p fragments */
1251 			if (!expchar) {	/* %[fF] or sufficiently short %[gG] */
1252 				if (expt <= 0) {
1253 					PRINT(zeroes, 1);
1254 					if (prec || flags & ALT)
1255 						PRINT(decimal_point, 1);
1256 					PAD(-expt, zeroes);
1257 					/* already handled initial 0's */
1258 					prec += expt;
1259 				} else {
1260 					PRINTANDPAD(result, convbuf + ndig,
1261 					    lead, zeroes);
1262 					result += lead;
1263 					if (grouping) {
1264 						while (nseps>0 || nrepeats>0) {
1265 							if (nrepeats > 0)
1266 								nrepeats--;
1267 							else {
1268 								grouping--;
1269 								nseps--;
1270 							}
1271 							PRINT(&thousands_sep,
1272 							    1);
1273 							PRINTANDPAD(result,
1274 							    convbuf + ndig,
1275 							    *grouping, zeroes);
1276 							result += *grouping;
1277 						}
1278 						if (result > convbuf + ndig)
1279 							result = convbuf + ndig;
1280 					}
1281 					if (prec || flags & ALT) {
1282 						buf[0] = *decimal_point;
1283 						PRINT(buf, 1);
1284 					}
1285 				}
1286 				PRINTANDPAD(result, convbuf + ndig, prec,
1287 				    zeroes);
1288 			} else {	/* %[eE] or sufficiently long %[gG] */
1289 				if (prec > 1 || flags & ALT) {
1290 					buf[0] = *result++;
1291 					buf[1] = *decimal_point;
1292 					PRINT(buf, 2);
1293 					PRINT(result, ndig-1);
1294 					PAD(prec - ndig, zeroes);
1295 				} else	/* XeYYY */
1296 					PRINT(result, 1);
1297 				PRINT(expstr, expsize);
1298 			}
1299 		}
1300 #else
1301 		PRINT(result, size);
1302 #endif
1303 		/* left-adjusting padding (always blank) */
1304 		if (flags & LADJUST)
1305 			PAD(width - realsz, blanks);
1306 
1307 		/* finally, adjust ret */
1308 		ret += prsize;
1309 	}
1310 done:
1311 error:
1312 	va_end(orgap);
1313 	if (convbuf != NULL)
1314 		free(convbuf);
1315 	if (__sferror(fp))
1316 		ret = EOF;
1317 	if ((argtable != NULL) && (argtable != statargtable))
1318 		free (argtable);
1319 	return (ret);
1320 	/* NOTREACHED */
1321 }
1322 
1323 /*
1324  * Find all arguments when a positional parameter is encountered.  Returns a
1325  * table, indexed by argument number, of pointers to each arguments.  The
1326  * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1327  * It will be replaces with a malloc-ed one if it overflows.
1328  */
1329 static void
1330 __find_arguments (const wchar_t *fmt0, va_list ap, union arg **argtable)
1331 {
1332 	wchar_t *fmt;		/* format string */
1333 	wchar_t ch;		/* character from fmt */
1334 	int n, n2;		/* handy integer (short term usage) */
1335 	wchar_t *cp;		/* handy char pointer (short term usage) */
1336 	int flags;		/* flags as above */
1337 	enum typeid *typetable; /* table of types */
1338 	enum typeid stattypetable [STATIC_ARG_TBL_SIZE];
1339 	int tablesize;		/* current size of type table */
1340 	int tablemax;		/* largest used index in table */
1341 	int nextarg;		/* 1-based argument index */
1342 
1343 	/*
1344 	 * Add an argument type to the table, expanding if necessary.
1345 	 */
1346 #define ADDTYPE(type) \
1347 	/*LINTED null effect*/ \
1348 	(void)((nextarg >= tablesize) ? \
1349 		__grow_type_table(nextarg, &typetable, &tablesize) : (void)0, \
1350 	(nextarg > tablemax) ? tablemax = nextarg : 0, \
1351 	typetable[nextarg++] = type)
1352 
1353 #define	ADDSARG() \
1354 	(void)((flags&INTMAXT) ? ADDTYPE(T_INTMAXT) : \
1355 		((flags&SIZET) ? ADDTYPE(T_SIZET) : \
1356 		((flags&PTRDIFFT) ? ADDTYPE(T_PTRDIFFT) : \
1357 		((flags&LLONGINT) ? ADDTYPE(T_LLONG) : \
1358 		((flags&LONGINT) ? ADDTYPE(T_LONG) : ADDTYPE(T_INT))))))
1359 
1360 #define	ADDUARG() \
1361 	(void)((flags&INTMAXT) ? ADDTYPE(T_UINTMAXT) : \
1362 		((flags&SIZET) ? ADDTYPE(T_SIZET) : \
1363 		((flags&PTRDIFFT) ? ADDTYPE(T_PTRDIFFT) : \
1364 		((flags&LLONGINT) ? ADDTYPE(T_U_LLONG) : \
1365 		((flags&LONGINT) ? ADDTYPE(T_U_LONG) : ADDTYPE(T_U_INT))))))
1366 
1367 	/*
1368 	 * Add * arguments to the type array.
1369 	 */
1370 #define ADDASTER() \
1371 	n2 = 0; \
1372 	cp = fmt; \
1373 	while (is_digit(*cp)) { \
1374 		n2 = 10 * n2 + to_digit(*cp); \
1375 		cp++; \
1376 	} \
1377 	if (*cp == '$') { \
1378 		int hold = nextarg; \
1379 		nextarg = n2; \
1380 		ADDTYPE (T_INT); \
1381 		nextarg = hold; \
1382 		fmt = ++cp; \
1383 	} else { \
1384 		ADDTYPE (T_INT); \
1385 	}
1386 	fmt = (wchar_t *)__UNCONST(fmt0);
1387 	typetable = stattypetable;
1388 	tablesize = STATIC_ARG_TBL_SIZE;
1389 	tablemax = 0;
1390 	nextarg = 1;
1391 	for (n = 0; n < STATIC_ARG_TBL_SIZE; n++)
1392 		typetable[n] = T_UNUSED;
1393 
1394 	/*
1395 	 * Scan the format for conversions (`%' character).
1396 	 */
1397 	for (;;) {
1398 		for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
1399 			/* void */;
1400 		if (ch == '\0')
1401 			goto done;
1402 		fmt++;		/* skip over '%' */
1403 
1404 		flags = 0;
1405 
1406 rflag:		ch = *fmt++;
1407 reswitch:	switch (ch) {
1408 		case ' ':
1409 		case '#':
1410 			goto rflag;
1411 		case '*':
1412 			ADDASTER ();
1413 			goto rflag;
1414 		case '-':
1415 		case '+':
1416 		case '\'':
1417 			goto rflag;
1418 		case '.':
1419 			if ((ch = *fmt++) == '*') {
1420 				ADDASTER ();
1421 				goto rflag;
1422 			}
1423 			while (is_digit(ch)) {
1424 				ch = *fmt++;
1425 			}
1426 			goto reswitch;
1427 		case '0':
1428 			goto rflag;
1429 		case '1': case '2': case '3': case '4':
1430 		case '5': case '6': case '7': case '8': case '9':
1431 			n = 0;
1432 			do {
1433 				n = 10 * n + to_digit(ch);
1434 				ch = *fmt++;
1435 			} while (is_digit(ch));
1436 			if (ch == '$') {
1437 				nextarg = n;
1438 				goto rflag;
1439 			}
1440 			goto reswitch;
1441 #ifndef NO_FLOATING_POINT
1442 		case 'L':
1443 			flags |= LONGDBL;
1444 			goto rflag;
1445 #endif
1446 		case 'h':
1447 			if (flags & SHORTINT) {
1448 				flags &= ~SHORTINT;
1449 				flags |= CHARINT;
1450 			} else
1451 				flags |= SHORTINT;
1452 			goto rflag;
1453 		case 'j':
1454 			flags |= INTMAXT;
1455 			goto rflag;
1456 		case 'l':
1457 			if (flags & LONGINT) {
1458 				flags &= ~LONGINT;
1459 				flags |= LLONGINT;
1460 			} else
1461 				flags |= LONGINT;
1462 			goto rflag;
1463 		case 'q':
1464 			flags |= LLONGINT;	/* not necessarily */
1465 			goto rflag;
1466 		case 't':
1467 			flags |= PTRDIFFT;
1468 			goto rflag;
1469 		case 'z':
1470 			flags |= SIZET;
1471 			goto rflag;
1472 		case 'C':
1473 			flags |= LONGINT;
1474 			/*FALLTHROUGH*/
1475 		case 'c':
1476 			if (flags & LONGINT)
1477 				ADDTYPE(T_WINT);
1478 			else
1479 				ADDTYPE(T_INT);
1480 			break;
1481 		case 'D':
1482 			flags |= LONGINT;
1483 			/*FALLTHROUGH*/
1484 		case 'd':
1485 		case 'i':
1486 			ADDSARG();
1487 			break;
1488 #ifndef NO_FLOATING_POINT
1489 		case 'a':
1490 		case 'A':
1491 		case 'e':
1492 		case 'E':
1493 		case 'f':
1494 		case 'g':
1495 		case 'G':
1496 			if (flags & LONGDBL)
1497 				ADDTYPE(T_LONG_DOUBLE);
1498 			else
1499 				ADDTYPE(T_DOUBLE);
1500 			break;
1501 #endif /* !NO_FLOATING_POINT */
1502 		case 'n':
1503 			if (flags & INTMAXT)
1504 				ADDTYPE(TP_INTMAXT);
1505 			else if (flags & PTRDIFFT)
1506 				ADDTYPE(TP_PTRDIFFT);
1507 			else if (flags & SIZET)
1508 				ADDTYPE(TP_SIZET);
1509 			else if (flags & LLONGINT)
1510 				ADDTYPE(TP_LLONG);
1511 			else if (flags & LONGINT)
1512 				ADDTYPE(TP_LONG);
1513 			else if (flags & SHORTINT)
1514 				ADDTYPE(TP_SHORT);
1515 			else if (flags & CHARINT)
1516 				ADDTYPE(TP_SCHAR);
1517 			else
1518 				ADDTYPE(TP_INT);
1519 			continue;	/* no output */
1520 		case 'O':
1521 			flags |= LONGINT;
1522 			/*FALLTHROUGH*/
1523 		case 'o':
1524 			ADDUARG();
1525 			break;
1526 		case 'p':
1527 			ADDTYPE(TP_VOID);
1528 			break;
1529 		case 'S':
1530 			flags |= LONGINT;
1531 			/*FALLTHROUGH*/
1532 		case 's':
1533 			if (flags & LONGINT)
1534 				ADDTYPE(TP_WCHAR);
1535 			else
1536 				ADDTYPE(TP_CHAR);
1537 			break;
1538 		case 'U':
1539 			flags |= LONGINT;
1540 			/*FALLTHROUGH*/
1541 		case 'u':
1542 		case 'X':
1543 		case 'x':
1544 			ADDUARG();
1545 			break;
1546 		default:	/* "%?" prints ?, unless ? is NUL */
1547 			if (ch == '\0')
1548 				goto done;
1549 			break;
1550 		}
1551 	}
1552 done:
1553 	/*
1554 	 * Build the argument table.
1555 	 */
1556 	if (tablemax >= STATIC_ARG_TBL_SIZE) {
1557 		*argtable = (union arg *)
1558 		    malloc (sizeof (union arg) * (tablemax + 1));
1559 	}
1560 
1561 	(*argtable) [0].intarg = 0;
1562 	for (n = 1; n <= tablemax; n++) {
1563 		switch (typetable [n]) {
1564 		    case T_UNUSED: /* whoops! */
1565 			(*argtable) [n].intarg = va_arg (ap, int);
1566 			break;
1567 		    case TP_SCHAR:
1568 			(*argtable) [n].pschararg = va_arg (ap, signed char *);
1569 			break;
1570 		    case TP_SHORT:
1571 			(*argtable) [n].pshortarg = va_arg (ap, short *);
1572 			break;
1573 		    case T_INT:
1574 			(*argtable) [n].intarg = va_arg (ap, int);
1575 			break;
1576 		    case T_U_INT:
1577 			(*argtable) [n].uintarg = va_arg (ap, unsigned int);
1578 			break;
1579 		    case TP_INT:
1580 			(*argtable) [n].pintarg = va_arg (ap, int *);
1581 			break;
1582 		    case T_LONG:
1583 			(*argtable) [n].longarg = va_arg (ap, long);
1584 			break;
1585 		    case T_U_LONG:
1586 			(*argtable) [n].ulongarg = va_arg (ap, unsigned long);
1587 			break;
1588 		    case TP_LONG:
1589 			(*argtable) [n].plongarg = va_arg (ap, long *);
1590 			break;
1591 		    case T_LLONG:
1592 			(*argtable) [n].longlongarg = va_arg (ap, quad_t);
1593 			break;
1594 		    case T_U_LLONG:
1595 			(*argtable) [n].ulonglongarg = va_arg (ap, u_quad_t);
1596 			break;
1597 		    case TP_LLONG:
1598 			(*argtable) [n].plonglongarg = va_arg (ap, quad_t *);
1599 			break;
1600 		    case T_PTRDIFFT:
1601 			(*argtable) [n].ptrdiffarg = va_arg (ap, ptrdiff_t);
1602 			break;
1603 		    case TP_PTRDIFFT:
1604 			(*argtable) [n].pptrdiffarg = va_arg (ap, ptrdiff_t *);
1605 			break;
1606 		    case T_SIZET:
1607 			(*argtable) [n].sizearg = va_arg (ap, size_t);
1608 			break;
1609 		    case TP_SIZET:
1610 			(*argtable) [n].psizearg = va_arg (ap, size_t *);
1611 			break;
1612 		    case T_INTMAXT:
1613 			(*argtable) [n].intmaxarg = va_arg (ap, intmax_t);
1614 			break;
1615 		    case T_UINTMAXT:
1616 			(*argtable) [n].uintmaxarg = va_arg (ap, uintmax_t);
1617 			break;
1618 		    case TP_INTMAXT:
1619 			(*argtable) [n].pintmaxarg = va_arg (ap, intmax_t *);
1620 			break;
1621 #ifndef NO_FLOATING_POINT
1622 		    case T_DOUBLE:
1623 			(*argtable) [n].doublearg = va_arg (ap, double);
1624 			break;
1625 		    case T_LONG_DOUBLE:
1626 			(*argtable) [n].longdoublearg = va_arg (ap, long double);
1627 			break;
1628 #endif
1629 		    case TP_CHAR:
1630 			(*argtable) [n].pchararg = va_arg (ap, char *);
1631 			break;
1632 		    case TP_VOID:
1633 			(*argtable) [n].pvoidarg = va_arg (ap, void *);
1634 			break;
1635 		    case T_WINT:
1636 			(*argtable) [n].wintarg = va_arg (ap, wint_t);
1637 			break;
1638 		    case TP_WCHAR:
1639 			(*argtable) [n].pwchararg = va_arg (ap, wchar_t *);
1640 			break;
1641 		}
1642 	}
1643 
1644 	if ((typetable != NULL) && (typetable != stattypetable))
1645 		free (typetable);
1646 }
1647 
1648 /*
1649  * Increase the size of the type table.
1650  */
1651 static void
1652 __grow_type_table (int nextarg, enum typeid **typetable, int *tablesize)
1653 {
1654 	enum typeid *const oldtable = *typetable;
1655 	const int oldsize = *tablesize;
1656 	enum typeid *newtable;
1657 	int n, newsize = oldsize * 2;
1658 
1659 	if (newsize < nextarg + 1)
1660 		newsize = nextarg + 1;
1661 	if (oldsize == STATIC_ARG_TBL_SIZE) {
1662 		if ((newtable = malloc(newsize * sizeof(enum typeid))) == NULL)
1663 			abort();			/* XXX handle better */
1664 		bcopy(oldtable, newtable, oldsize * sizeof(enum typeid));
1665 	} else {
1666 		newtable = realloc(oldtable, newsize * sizeof(enum typeid));
1667 		if (newtable == NULL)
1668 			abort();			/* XXX handle better */
1669 	}
1670 	for (n = oldsize; n < newsize; n++)
1671 		newtable[n] = T_UNUSED;
1672 
1673 	*typetable = newtable;
1674 	*tablesize = newsize;
1675 }
1676 
1677 
1678 #ifndef NO_FLOATING_POINT
1679 static wchar_t *
1680 cvt(double value, int ndigits, int flags, char *sign, int *decpt, int ch,
1681     int *length)
1682 {
1683 	int mode, dsgn;
1684 	char *digits, *bp, *rve;
1685 	static wchar_t buf[512];
1686 
1687 	_DIAGASSERT(decpt != NULL);
1688 	_DIAGASSERT(length != NULL);
1689 	_DIAGASSERT(sign != NULL);
1690 
1691 	if (ch == 'f') {
1692 		mode = 3;		/* ndigits after the decimal point */
1693 	} else {
1694 		/* To obtain ndigits after the decimal point for the 'e'
1695 		 * and 'E' formats, round to ndigits + 1 significant
1696 		 * figures.
1697 		 */
1698 		if (ch == 'e' || ch == 'E') {
1699 			ndigits++;
1700 		}
1701 		mode = 2;		/* ndigits significant digits */
1702 	}
1703 
1704 	digits = __dtoa(value, mode, ndigits, decpt, &dsgn, &rve);
1705 	if (dsgn) {
1706 		value = -value;
1707 		*sign = '-';
1708 	} else
1709 		*sign = '\000';
1710 	if ((ch != 'g' && ch != 'G') || flags & ALT) {	/* Print trailing zeros */
1711 		bp = digits + ndigits;
1712 		if (ch == 'f') {
1713 			if (*digits == '0' && value)
1714 				*decpt = -ndigits + 1;
1715 			bp += *decpt;
1716 		}
1717 		if (value == 0)	/* kludge for __dtoa irregularity */
1718 			rve = bp;
1719 		while (rve < bp)
1720 			*rve++ = '0';
1721 	}
1722 	*length = rve - digits;
1723 	(void)mbstowcs(buf, digits, sizeof(buf)/sizeof(buf[0]));
1724 	return buf;
1725 }
1726 static int
1727 exponent(wchar_t *p0, int expo, wchar_t fmtch)
1728 {
1729 	wchar_t *p, *t;
1730 	wchar_t expbuf[MAXEXPDIG];
1731 
1732 	p = p0;
1733 	*p++ = fmtch;
1734 	if (expo < 0) {
1735 		expo = -expo;
1736 		*p++ = '-';
1737 	}
1738 	else
1739 		*p++ = '+';
1740 	t = expbuf + MAXEXPDIG;
1741 	if (expo > 9) {
1742 		do {
1743 			*--t = to_char(expo % 10);
1744 		} while ((expo /= 10) > 9);
1745 		*--t = to_char(expo);
1746 		for (; t < expbuf + MAXEXPDIG; *p++ = *t++);
1747 	}
1748 	else {
1749 		/*
1750 		 * Exponents for decimal floating point conversions
1751 		 * (%[eEgG]) must be at least two characters long,
1752 		 * whereas exponents for hexadecimal conversions can
1753 		 * be only one character long.
1754 		 */
1755 		if (fmtch == 'e' || fmtch == 'E')
1756 			*p++ = '0';
1757 		*p++ = to_char(expo);
1758 	}
1759 	return (p - p0);
1760 }
1761 #endif /* !NO_FLOATING_POINT */
1762