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