xref: /netbsd-src/lib/libc/stdio/vfwprintf.c (revision d48f14661dda8638fee055ba15d35bdfb29b9fa8)
1 /*	$NetBSD: vfwprintf.c,v 1.8 2006/05/10 21:53:15 mrg 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.8 2006/05/10 21:53:15 mrg 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 #include <float.h>
441 #include <math.h>
442 #include "floatio.h"
443 
444 #define	DEFPREC		6
445 
446 #ifndef WIDE_DOUBLE
447 static int exponent(wchar_t *, int, wchar_t);
448 static char *cvt(double, int, int, char *, int *, int, int *);
449 #endif
450 
451 #endif /* !NO_FLOATING_POINT */
452 
453 /*
454  * The size of the buffer we use as scratch space for integer
455  * conversions, among other things.  Technically, we would need the
456  * most space for base 10 conversions with thousands' grouping
457  * characters between each pair of digits.  100 bytes is a
458  * conservative overestimate even for a 128-bit uintmax_t.
459  */
460 #define	BUF	100
461 
462 #define STATIC_ARG_TBL_SIZE 8           /* Size of static argument table. */
463 
464 /*
465  * Flags used during conversion.
466  */
467 #define	ALT		0x001		/* alternate form */
468 #define	LADJUST		0x004		/* left adjustment */
469 #define	LONGDBL		0x008		/* long double */
470 #define	LONGINT		0x010		/* long integer */
471 #define	LLONGINT	0x020		/* quad_t integer */
472 #define	SHORTINT	0x040		/* short integer */
473 #define	ZEROPAD		0x080		/* zero (as opposed to blank) pad */
474 #define	FPT		0x100		/* Floating point number */
475 #define	GROUPING	0x200		/* use grouping ("'" flag) */
476 					/* C99 additional size modifiers: */
477 #define	SIZET		0x400		/* size_t */
478 #define	PTRDIFFT	0x800		/* ptrdiff_t */
479 #define	INTMAXT		0x1000		/* intmax_t */
480 #define	CHARINT		0x2000		/* print char using int format */
481 
482 /*
483  * Non-MT-safe version
484  */
485 int
486 __vfwprintf_unlocked(FILE *fp, const wchar_t *fmt0, va_list ap)
487 {
488 	wchar_t *fmt;		/* format string */
489 	wchar_t ch;		/* character from fmt */
490 	int n, n2, n3;		/* handy integer (short term usage) */
491 	wchar_t *cp;		/* handy char pointer (short term usage) */
492 	int flags;		/* flags as above */
493 	int ret;		/* return value accumulator */
494 	int width;		/* width from format (%8d), or 0 */
495 	int prec;		/* precision from format; <0 for N/A */
496 	wchar_t sign;		/* sign prefix (' ', '+', '-', or \0) */
497 	char thousands_sep;	/* locale specific thousands separator */
498 	const char *grouping;	/* locale specific numeric grouping rules */
499 #ifndef NO_FLOATING_POINT
500 	/*
501 	 * We can decompose the printed representation of floating
502 	 * point numbers into several parts, some of which may be empty:
503 	 *
504 	 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
505 	 *    A       B     ---C---      D       E   F
506 	 *
507 	 * A:	'sign' holds this value if present; '\0' otherwise
508 	 * B:	ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
509 	 * C:	cp points to the string MMMNNN.  Leading and trailing
510 	 *	zeros are not in the string and must be added.
511 	 * D:	expchar holds this character; '\0' if no exponent, e.g. %f
512 	 * F:	at least two digits for decimal, at least one digit for hex
513 	 */
514 	char *decimal_point;	/* locale specific decimal point */
515 #ifdef WIDE_DOUBLE
516 	int signflag;		/* true if float is negative */
517 	union {			/* floating point arguments %[aAeEfFgG] */
518 		double dbl;
519 		long double ldbl;
520 	} fparg;
521 	char *dtoaend;		/* pointer to end of converted digits */
522 #else
523 	double _double;		/* double precision arguments %[eEfgG] */
524 	char softsign;		/* temporary negative sign for floats */
525 #endif
526 	char *dtoaresult = NULL;/* buffer allocated by dtoa */
527 	int expt;		/* integer value of exponent */
528 	char expchar;		/* exponent character: [eEpP\0] */
529 	int expsize;		/* character count for expstr */
530 	int lead;		/* sig figs before decimal or group sep */
531 	int ndig;		/* actual number of digits returned by dtoa */
532 	wchar_t expstr[MAXEXPDIG+2];	/* buffer for exponent string: e+ZZZ */
533 	int nseps;		/* number of group separators with ' */
534 	int nrepeats;		/* number of repeats of the last group */
535 #endif
536 	u_long	ulval;		/* integer arguments %[diouxX] */
537 	uintmax_t ujval;	/* %j, %ll, %q, %t, %z integers */
538 	int base;		/* base for [diouxX] conversion */
539 	int dprec;		/* a copy of prec if [diouxX], 0 otherwise */
540 	int realsz;		/* field size expanded by dprec, sign, etc */
541 	int size;		/* size of converted field or string */
542 	int prsize;             /* max size of printed field */
543 	const char *xdigs;	/* digits for [xX] conversion */
544 	wchar_t buf[BUF];	/* buffer with space for digits of uintmax_t */
545 	wchar_t ox[2];		/* space for 0x hex-prefix */
546 	union arg *argtable;	/* args, built due to positional arg */
547 	union arg statargtable [STATIC_ARG_TBL_SIZE];
548 	int nextarg;		/* 1-based argument index */
549 	va_list orgap;		/* original argument pointer */
550 	wchar_t *convbuf;	/* multibyte to wide conversion result */
551 
552 	/*
553 	 * Choose PADSIZE to trade efficiency vs. size.  If larger printf
554 	 * fields occur frequently, increase PADSIZE and make the initialisers
555 	 * below longer.
556 	 */
557 #define	PADSIZE	16		/* pad chunk size */
558 	static wchar_t blanks[PADSIZE] =
559 	 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
560 	static wchar_t zeroes[PADSIZE] =
561 	 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
562 
563 	static const char xdigs_lower[16] = "0123456789abcdef";
564 	static const char xdigs_upper[16] = "0123456789ABCDEF";
565 
566 	/*
567 	 * BEWARE, these `goto error' on error, PRINT uses `n2' and
568 	 * PAD uses `n'.
569 	 */
570 #define	PRINT(ptr, len)	do {			\
571 	for (n3 = 0; n3 < (len); n3++)		\
572 		__xfputwc((ptr)[n3], fp);	\
573 } while (/*CONSTCOND*/0)
574 #define	PAD(howmany, with)	do {		\
575 	if ((n = (howmany)) > 0) {		\
576 		while (n > PADSIZE) {		\
577 			PRINT(with, PADSIZE);	\
578 			n -= PADSIZE;		\
579 		}				\
580 		PRINT(with, n);			\
581 	}					\
582 } while (/*CONSTCOND*/0)
583 #define	PRINTANDPAD(p, ep, len, with) do {	\
584 	n2 = (ep) - (p);       			\
585 	if (n2 > (len))				\
586 		n2 = (len);			\
587 	if (n2 > 0)				\
588 		PRINT((p), n2);			\
589 	PAD((len) - (n2 > 0 ? n2 : 0), (with));	\
590 } while(/*CONSTCOND*/0)
591 
592 	/*
593 	 * Get the argument indexed by nextarg.   If the argument table is
594 	 * built, use it to get the argument.  If its not, get the next
595 	 * argument (and arguments must be gotten sequentially).
596 	 */
597 #define GETARG(type) \
598 	((/*CONSTCOND*/argtable != NULL) ? *((type*)(void*)(&argtable[nextarg++])) : \
599 	    (nextarg++, va_arg(ap, type)))
600 
601 	/*
602 	 * To extend shorts properly, we need both signed and unsigned
603 	 * argument extraction methods.
604 	 */
605 #define	SARG() \
606 	(flags&LONGINT ? GETARG(long) : \
607 	    flags&SHORTINT ? (long)(short)GETARG(int) : \
608 	    flags&CHARINT ? (long)(signed char)GETARG(int) : \
609 	    (long)GETARG(int))
610 #define	UARG() \
611 	(flags&LONGINT ? GETARG(u_long) : \
612 	    flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
613 	    flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
614 	    (u_long)GETARG(u_int))
615 #define	INTMAX_SIZE	(INTMAXT|SIZET|PTRDIFFT|LLONGINT)
616 #define SJARG() \
617 	(flags&INTMAXT ? GETARG(intmax_t) : \
618 	    flags&SIZET ? (intmax_t)GETARG(size_t) : \
619 	    flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
620 	    (intmax_t)GETARG(quad_t))
621 #define	UJARG() \
622 	(flags&INTMAXT ? GETARG(uintmax_t) : \
623 	    flags&SIZET ? (uintmax_t)GETARG(size_t) : \
624 	    flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
625 	    (uintmax_t)GETARG(u_quad_t))
626 
627 	/*
628 	 * Get * arguments, including the form *nn$.  Preserve the nextarg
629 	 * that the argument can be gotten once the type is determined.
630 	 */
631 #define GETASTER(val) \
632 	n2 = 0; \
633 	cp = fmt; \
634 	while (is_digit(*cp)) { \
635 		n2 = 10 * n2 + to_digit(*cp); \
636 		cp++; \
637 	} \
638 	if (*cp == '$') { \
639 		int hold = nextarg; \
640 		if (argtable == NULL) { \
641 			argtable = statargtable; \
642 			__find_arguments (fmt0, orgap, &argtable); \
643 		} \
644 		nextarg = n2; \
645 		val = GETARG (int); \
646 		nextarg = hold; \
647 		fmt = ++cp; \
648 	} else { \
649 		val = GETARG (int); \
650 	}
651 
652 	ndig = -1;	/* XXX gcc */
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 WIDE_DOUBLE
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 			dtoaresult = cvt(_double, prec, flags, &softsign,
976 			    &expt, ch, &ndig);
977 			result = convbuf = __mbsconv(dtoaresult, -1);
978 			__freedtoa(dtoaresult);
979 			if (softsign)
980 				sign = '-';
981 #endif
982 			flags |= FPT;
983 			if (ch == 'g' || ch == 'G') {
984 				if (expt > -4 && expt <= prec) {
985 					/* Make %[gG] smell like %[fF] */
986 					expchar = '\0';
987 					if (flags & ALT)
988 						prec -= expt;
989 					else
990 						prec = ndig - expt;
991 					if (prec < 0)
992 						prec = 0;
993 				} else {
994 					/*
995 					 * Make %[gG] smell like %[eE], but
996 					 * trim trailing zeroes if no # flag.
997 					 */
998 					if (!(flags & ALT))
999 						prec = ndig;
1000 				}
1001 			}
1002 			if (expchar) {
1003 				expsize = exponent(expstr, expt - 1, expchar);
1004 				size = expsize + prec;
1005 				if (prec > 1 || flags & ALT)
1006 					++size;
1007 			} else {
1008 				/* space for digits before decimal point */
1009 				if (expt > 0)
1010 					size = expt;
1011 				else	/* "0" */
1012 					size = 1;
1013 				/* space for decimal pt and following digits */
1014 				if (prec || flags & ALT)
1015 					size += prec + 1;
1016 				if (grouping && expt > 0) {
1017 					/* space for thousands' grouping */
1018 					nseps = nrepeats = 0;
1019 					lead = expt;
1020 					while (*grouping != CHAR_MAX) {
1021 						if (lead <= *grouping)
1022 							break;
1023 						lead -= *grouping;
1024 						if (*(grouping+1)) {
1025 							nseps++;
1026 							grouping++;
1027 						} else
1028 							nrepeats++;
1029 					}
1030 					size += nseps + nrepeats;
1031 				} else
1032 					lead = expt;
1033 			}
1034 			break;
1035 #endif /* !NO_FLOATING_POINT */
1036 		case 'n':
1037 			/*
1038 			 * Assignment-like behavior is specified if the
1039 			 * value overflows or is otherwise unrepresentable.
1040 			 * C99 says to use `signed char' for %hhn conversions.
1041 			 */
1042 			if (flags & LLONGINT)
1043 				*GETARG(quad_t *) = ret;
1044 			else if (flags & SIZET)
1045 				*GETARG(ssize_t *) = (ssize_t)ret;
1046 			else if (flags & PTRDIFFT)
1047 				*GETARG(ptrdiff_t *) = ret;
1048 			else if (flags & INTMAXT)
1049 				*GETARG(intmax_t *) = ret;
1050 			else if (flags & LONGINT)
1051 				*GETARG(long *) = ret;
1052 			else if (flags & SHORTINT)
1053 				*GETARG(short *) = ret;
1054 			else if (flags & CHARINT)
1055 				*GETARG(signed char *) = ret;
1056 			else
1057 				*GETARG(int *) = ret;
1058 			continue;	/* no output */
1059 		case 'O':
1060 			flags |= LONGINT;
1061 			/*FALLTHROUGH*/
1062 		case 'o':
1063 			if (flags & INTMAX_SIZE)
1064 				ujval = UJARG();
1065 			else
1066 				ulval = UARG();
1067 			base = 8;
1068 			goto nosign;
1069 		case 'p':
1070 			/*-
1071 			 * ``The argument shall be a pointer to void.  The
1072 			 * value of the pointer is converted to a sequence
1073 			 * of printable characters, in an implementation-
1074 			 * defined manner.''
1075 			 *	-- ANSI X3J11
1076 			 */
1077 			ujval = (uintmax_t)(uintptr_t)GETARG(void *);
1078 			base = 16;
1079 			xdigs = xdigs_lower;
1080 			flags = flags | INTMAXT;
1081 			ox[1] = 'x';
1082 			goto nosign;
1083 		case 'S':
1084 			flags |= LONGINT;
1085 			/*FALLTHROUGH*/
1086 		case 's':
1087 			if (flags & LONGINT) {
1088 				if ((result = GETARG(wchar_t *)) == NULL)
1089 					result = L"(null)";
1090 			} else {
1091 				char *mbp;
1092 
1093 				if (convbuf != NULL)
1094 					free(convbuf);
1095 				if ((mbp = GETARG(char *)) == NULL)
1096 					result = L"(null)";
1097 				else {
1098 					convbuf = __mbsconv(mbp, prec);
1099 					if (convbuf == NULL) {
1100 						fp->_flags |= __SERR;
1101 						goto error;
1102 					}
1103 					result = convbuf;
1104 				}
1105 			}
1106 
1107 			if (prec >= 0) {
1108 				/*
1109 				 * can't use wcslen; can only look for the
1110 				 * NUL in the first `prec' characters, and
1111 				 * wcslen() will go further.
1112 				 */
1113 				wchar_t *p = wmemchr(result, 0, (size_t)prec);
1114 
1115 				if (p != NULL) {
1116 					size = p - result;
1117 					if (size > prec)
1118 						size = prec;
1119 				} else
1120 					size = prec;
1121 			} else
1122 				size = wcslen(result);
1123 			sign = '\0';
1124 			break;
1125 		case 'U':
1126 			flags |= LONGINT;
1127 			/*FALLTHROUGH*/
1128 		case 'u':
1129 			if (flags & INTMAX_SIZE)
1130 				ujval = UJARG();
1131 			else
1132 				ulval = UARG();
1133 			base = 10;
1134 			goto nosign;
1135 		case 'X':
1136 			xdigs = xdigs_upper;
1137 			goto hex;
1138 		case 'x':
1139 			xdigs = xdigs_lower;
1140 hex:
1141 			if (flags & INTMAX_SIZE)
1142 				ujval = UJARG();
1143 			else
1144 				ulval = UARG();
1145 			base = 16;
1146 			/* leading 0x/X only if non-zero */
1147 			if (flags & ALT &&
1148 			    (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
1149 				ox[1] = ch;
1150 
1151 			flags &= ~GROUPING;
1152 			/* unsigned conversions */
1153 nosign:			sign = '\0';
1154 			/*-
1155 			 * ``... diouXx conversions ... if a precision is
1156 			 * specified, the 0 flag will be ignored.''
1157 			 *	-- ANSI X3J11
1158 			 */
1159 number:			if ((dprec = prec) >= 0)
1160 				flags &= ~ZEROPAD;
1161 
1162 			/*-
1163 			 * ``The result of converting a zero value with an
1164 			 * explicit precision of zero is no characters.''
1165 			 *	-- ANSI X3J11
1166 			 *
1167 			 * ``The C Standard is clear enough as is.  The call
1168 			 * printf("%#.0o", 0) should print 0.''
1169 			 *	-- Defect Report #151
1170 			 */
1171 			result = cp = buf + BUF;
1172 			if (flags & INTMAX_SIZE) {
1173 				if (ujval != 0 || prec != 0 ||
1174 				    (flags & ALT && base == 8))
1175 					result = __ujtoa(ujval, cp, base,
1176 					    flags & ALT, xdigs,
1177 					    flags & GROUPING, thousands_sep,
1178 					    grouping);
1179 			} else {
1180 				if (ulval != 0 || prec != 0 ||
1181 				    (flags & ALT && base == 8))
1182 					result = __ultoa(ulval, cp, base,
1183 					    flags & ALT, xdigs,
1184 					    flags & GROUPING, thousands_sep,
1185 					    grouping);
1186 			}
1187 			size = buf + BUF - result;
1188 			if (size > BUF)	/* should never happen */
1189 				abort();
1190 			break;
1191 		default:	/* "%?" prints ?, unless ? is NUL */
1192 			if (ch == '\0')
1193 				goto done;
1194 			/* pretend it was %c with argument ch */
1195 			*buf = ch;
1196 			result = buf;
1197 			size = 1;
1198 			sign = '\0';
1199 			break;
1200 		}
1201 
1202 		/*
1203 		 * All reasonable formats wind up here.  At this point, `result'
1204 		 * points to a string which (if not flags&LADJUST) should be
1205 		 * padded out to `width' places.  If flags&ZEROPAD, it should
1206 		 * first be prefixed by any sign or other prefix; otherwise,
1207 		 * it should be blank padded before the prefix is emitted.
1208 		 * After any left-hand padding and prefixing, emit zeroes
1209 		 * required by a decimal [diouxX] precision, then print the
1210 		 * string proper, then emit zeroes required by any leftover
1211 		 * floating precision; finally, if LADJUST, pad with blanks.
1212 		 *
1213 		 * Compute actual size, so we know how much to pad.
1214 		 * size excludes decimal prec; realsz includes it.
1215 		 */
1216 		realsz = dprec > size ? dprec : size;
1217 		if (sign)
1218 			realsz++;
1219 		if (ox[1])
1220 			realsz += 2;
1221 
1222 		prsize = width > realsz ? width : realsz;
1223 		if ((unsigned)ret + prsize > INT_MAX) {
1224 			ret = EOF;
1225 			goto error;
1226 		}
1227 
1228 		/* right-adjusting blank padding */
1229 		if ((flags & (LADJUST|ZEROPAD)) == 0)
1230 			PAD(width - realsz, blanks);
1231 
1232 		/* prefix */
1233 		if (sign)
1234 			PRINT(&sign, 1);
1235 
1236 		if (ox[1]) {	/* ox[1] is either x, X, or \0 */
1237 			ox[0] = '0';
1238 			PRINT(ox, 2);
1239 		}
1240 
1241 		/* right-adjusting zero padding */
1242 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1243 			PAD(width - realsz, zeroes);
1244 
1245 		/* leading zeroes from decimal precision */
1246 		PAD(dprec - size, zeroes);
1247 
1248 		/* the string or number proper */
1249 #ifndef NO_FLOATING_POINT
1250 		if ((flags & FPT) == 0) {
1251 			PRINT(result, size);
1252 		} else {	/* glue together f_p fragments */
1253 			if (!expchar) {	/* %[fF] or sufficiently short %[gG] */
1254 				if (expt <= 0) {
1255 					PRINT(zeroes, 1);
1256 					if (prec || flags & ALT)
1257 						PRINT(decimal_point, 1);
1258 					PAD(-expt, zeroes);
1259 					/* already handled initial 0's */
1260 					prec += expt;
1261 				} else {
1262 					PRINTANDPAD(result, convbuf + ndig,
1263 					    lead, zeroes);
1264 					result += lead;
1265 					if (grouping) {
1266 						while (nseps>0 || nrepeats>0) {
1267 							if (nrepeats > 0)
1268 								nrepeats--;
1269 							else {
1270 								grouping--;
1271 								nseps--;
1272 							}
1273 							PRINT(&thousands_sep,
1274 							    1);
1275 							PRINTANDPAD(result,
1276 							    convbuf + ndig,
1277 							    *grouping, zeroes);
1278 							result += *grouping;
1279 						}
1280 						if (result > convbuf + ndig)
1281 							result = convbuf + ndig;
1282 					}
1283 					if (prec || flags & ALT) {
1284 						buf[0] = *decimal_point;
1285 						PRINT(buf, 1);
1286 					}
1287 				}
1288 				PRINTANDPAD(result, convbuf + ndig, prec,
1289 				    zeroes);
1290 			} else {	/* %[eE] or sufficiently long %[gG] */
1291 				if (prec > 1 || flags & ALT) {
1292 					buf[0] = *result++;
1293 					buf[1] = *decimal_point;
1294 					PRINT(buf, 2);
1295 					PRINT(result, ndig-1);
1296 					PAD(prec - ndig, zeroes);
1297 				} else	/* XeYYY */
1298 					PRINT(result, 1);
1299 				PRINT(expstr, expsize);
1300 			}
1301 		}
1302 #else
1303 		PRINT(result, size);
1304 #endif
1305 		/* left-adjusting padding (always blank) */
1306 		if (flags & LADJUST)
1307 			PAD(width - realsz, blanks);
1308 
1309 		/* finally, adjust ret */
1310 		ret += prsize;
1311 	}
1312 done:
1313 error:
1314 	va_end(orgap);
1315 	if (convbuf != NULL)
1316 		free(convbuf);
1317 	if (__sferror(fp))
1318 		ret = EOF;
1319 	if ((argtable != NULL) && (argtable != statargtable))
1320 		free (argtable);
1321 	return (ret);
1322 	/* NOTREACHED */
1323 }
1324 
1325 /*
1326  * Find all arguments when a positional parameter is encountered.  Returns a
1327  * table, indexed by argument number, of pointers to each arguments.  The
1328  * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1329  * It will be replaces with a malloc-ed one if it overflows.
1330  */
1331 static void
1332 __find_arguments (const wchar_t *fmt0, va_list ap, union arg **argtable)
1333 {
1334 	wchar_t *fmt;		/* format string */
1335 	wchar_t ch;		/* character from fmt */
1336 	int n, n2;		/* handy integer (short term usage) */
1337 	wchar_t *cp;		/* handy char pointer (short term usage) */
1338 	int flags;		/* flags as above */
1339 	enum typeid *typetable; /* table of types */
1340 	enum typeid stattypetable [STATIC_ARG_TBL_SIZE];
1341 	int tablesize;		/* current size of type table */
1342 	int tablemax;		/* largest used index in table */
1343 	int nextarg;		/* 1-based argument index */
1344 
1345 	/*
1346 	 * Add an argument type to the table, expanding if necessary.
1347 	 */
1348 #define ADDTYPE(type) \
1349 	/*LINTED null effect*/ \
1350 	(void)((nextarg >= tablesize) ? \
1351 		__grow_type_table(nextarg, &typetable, &tablesize) : (void)0, \
1352 	(nextarg > tablemax) ? tablemax = nextarg : 0, \
1353 	typetable[nextarg++] = type)
1354 
1355 #define	ADDSARG() \
1356 	(void)((flags&INTMAXT) ? ADDTYPE(T_INTMAXT) : \
1357 		((flags&SIZET) ? ADDTYPE(T_SIZET) : \
1358 		((flags&PTRDIFFT) ? ADDTYPE(T_PTRDIFFT) : \
1359 		((flags&LLONGINT) ? ADDTYPE(T_LLONG) : \
1360 		((flags&LONGINT) ? ADDTYPE(T_LONG) : ADDTYPE(T_INT))))))
1361 
1362 #define	ADDUARG() \
1363 	(void)((flags&INTMAXT) ? ADDTYPE(T_UINTMAXT) : \
1364 		((flags&SIZET) ? ADDTYPE(T_SIZET) : \
1365 		((flags&PTRDIFFT) ? ADDTYPE(T_PTRDIFFT) : \
1366 		((flags&LLONGINT) ? ADDTYPE(T_U_LLONG) : \
1367 		((flags&LONGINT) ? ADDTYPE(T_U_LONG) : ADDTYPE(T_U_INT))))))
1368 
1369 	/*
1370 	 * Add * arguments to the type array.
1371 	 */
1372 #define ADDASTER() \
1373 	n2 = 0; \
1374 	cp = fmt; \
1375 	while (is_digit(*cp)) { \
1376 		n2 = 10 * n2 + to_digit(*cp); \
1377 		cp++; \
1378 	} \
1379 	if (*cp == '$') { \
1380 		int hold = nextarg; \
1381 		nextarg = n2; \
1382 		ADDTYPE (T_INT); \
1383 		nextarg = hold; \
1384 		fmt = ++cp; \
1385 	} else { \
1386 		ADDTYPE (T_INT); \
1387 	}
1388 	fmt = (wchar_t *)__UNCONST(fmt0);
1389 	typetable = stattypetable;
1390 	tablesize = STATIC_ARG_TBL_SIZE;
1391 	tablemax = 0;
1392 	nextarg = 1;
1393 	for (n = 0; n < STATIC_ARG_TBL_SIZE; n++)
1394 		typetable[n] = T_UNUSED;
1395 
1396 	/*
1397 	 * Scan the format for conversions (`%' character).
1398 	 */
1399 	for (;;) {
1400 		for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
1401 			/* void */;
1402 		if (ch == '\0')
1403 			goto done;
1404 		fmt++;		/* skip over '%' */
1405 
1406 		flags = 0;
1407 
1408 rflag:		ch = *fmt++;
1409 reswitch:	switch (ch) {
1410 		case ' ':
1411 		case '#':
1412 			goto rflag;
1413 		case '*':
1414 			ADDASTER ();
1415 			goto rflag;
1416 		case '-':
1417 		case '+':
1418 		case '\'':
1419 			goto rflag;
1420 		case '.':
1421 			if ((ch = *fmt++) == '*') {
1422 				ADDASTER ();
1423 				goto rflag;
1424 			}
1425 			while (is_digit(ch)) {
1426 				ch = *fmt++;
1427 			}
1428 			goto reswitch;
1429 		case '0':
1430 			goto rflag;
1431 		case '1': case '2': case '3': case '4':
1432 		case '5': case '6': case '7': case '8': case '9':
1433 			n = 0;
1434 			do {
1435 				n = 10 * n + to_digit(ch);
1436 				ch = *fmt++;
1437 			} while (is_digit(ch));
1438 			if (ch == '$') {
1439 				nextarg = n;
1440 				goto rflag;
1441 			}
1442 			goto reswitch;
1443 #ifndef NO_FLOATING_POINT
1444 		case 'L':
1445 			flags |= LONGDBL;
1446 			goto rflag;
1447 #endif
1448 		case 'h':
1449 			if (flags & SHORTINT) {
1450 				flags &= ~SHORTINT;
1451 				flags |= CHARINT;
1452 			} else
1453 				flags |= SHORTINT;
1454 			goto rflag;
1455 		case 'j':
1456 			flags |= INTMAXT;
1457 			goto rflag;
1458 		case 'l':
1459 			if (flags & LONGINT) {
1460 				flags &= ~LONGINT;
1461 				flags |= LLONGINT;
1462 			} else
1463 				flags |= LONGINT;
1464 			goto rflag;
1465 		case 'q':
1466 			flags |= LLONGINT;	/* not necessarily */
1467 			goto rflag;
1468 		case 't':
1469 			flags |= PTRDIFFT;
1470 			goto rflag;
1471 		case 'z':
1472 			flags |= SIZET;
1473 			goto rflag;
1474 		case 'C':
1475 			flags |= LONGINT;
1476 			/*FALLTHROUGH*/
1477 		case 'c':
1478 			if (flags & LONGINT)
1479 				ADDTYPE(T_WINT);
1480 			else
1481 				ADDTYPE(T_INT);
1482 			break;
1483 		case 'D':
1484 			flags |= LONGINT;
1485 			/*FALLTHROUGH*/
1486 		case 'd':
1487 		case 'i':
1488 			ADDSARG();
1489 			break;
1490 #ifndef NO_FLOATING_POINT
1491 		case 'a':
1492 		case 'A':
1493 		case 'e':
1494 		case 'E':
1495 		case 'f':
1496 		case 'g':
1497 		case 'G':
1498 			if (flags & LONGDBL)
1499 				ADDTYPE(T_LONG_DOUBLE);
1500 			else
1501 				ADDTYPE(T_DOUBLE);
1502 			break;
1503 #endif /* !NO_FLOATING_POINT */
1504 		case 'n':
1505 			if (flags & INTMAXT)
1506 				ADDTYPE(TP_INTMAXT);
1507 			else if (flags & PTRDIFFT)
1508 				ADDTYPE(TP_PTRDIFFT);
1509 			else if (flags & SIZET)
1510 				ADDTYPE(TP_SIZET);
1511 			else if (flags & LLONGINT)
1512 				ADDTYPE(TP_LLONG);
1513 			else if (flags & LONGINT)
1514 				ADDTYPE(TP_LONG);
1515 			else if (flags & SHORTINT)
1516 				ADDTYPE(TP_SHORT);
1517 			else if (flags & CHARINT)
1518 				ADDTYPE(TP_SCHAR);
1519 			else
1520 				ADDTYPE(TP_INT);
1521 			continue;	/* no output */
1522 		case 'O':
1523 			flags |= LONGINT;
1524 			/*FALLTHROUGH*/
1525 		case 'o':
1526 			ADDUARG();
1527 			break;
1528 		case 'p':
1529 			ADDTYPE(TP_VOID);
1530 			break;
1531 		case 'S':
1532 			flags |= LONGINT;
1533 			/*FALLTHROUGH*/
1534 		case 's':
1535 			if (flags & LONGINT)
1536 				ADDTYPE(TP_WCHAR);
1537 			else
1538 				ADDTYPE(TP_CHAR);
1539 			break;
1540 		case 'U':
1541 			flags |= LONGINT;
1542 			/*FALLTHROUGH*/
1543 		case 'u':
1544 		case 'X':
1545 		case 'x':
1546 			ADDUARG();
1547 			break;
1548 		default:	/* "%?" prints ?, unless ? is NUL */
1549 			if (ch == '\0')
1550 				goto done;
1551 			break;
1552 		}
1553 	}
1554 done:
1555 	/*
1556 	 * Build the argument table.
1557 	 */
1558 	if (tablemax >= STATIC_ARG_TBL_SIZE) {
1559 		*argtable = (union arg *)
1560 		    malloc (sizeof (union arg) * (tablemax + 1));
1561 	}
1562 
1563 	(*argtable) [0].intarg = 0;
1564 	for (n = 1; n <= tablemax; n++) {
1565 		switch (typetable [n]) {
1566 		    case T_UNUSED: /* whoops! */
1567 			(*argtable) [n].intarg = va_arg (ap, int);
1568 			break;
1569 		    case TP_SCHAR:
1570 			(*argtable) [n].pschararg = va_arg (ap, signed char *);
1571 			break;
1572 		    case TP_SHORT:
1573 			(*argtable) [n].pshortarg = va_arg (ap, short *);
1574 			break;
1575 		    case T_INT:
1576 			(*argtable) [n].intarg = va_arg (ap, int);
1577 			break;
1578 		    case T_U_INT:
1579 			(*argtable) [n].uintarg = va_arg (ap, unsigned int);
1580 			break;
1581 		    case TP_INT:
1582 			(*argtable) [n].pintarg = va_arg (ap, int *);
1583 			break;
1584 		    case T_LONG:
1585 			(*argtable) [n].longarg = va_arg (ap, long);
1586 			break;
1587 		    case T_U_LONG:
1588 			(*argtable) [n].ulongarg = va_arg (ap, unsigned long);
1589 			break;
1590 		    case TP_LONG:
1591 			(*argtable) [n].plongarg = va_arg (ap, long *);
1592 			break;
1593 		    case T_LLONG:
1594 			(*argtable) [n].longlongarg = va_arg (ap, quad_t);
1595 			break;
1596 		    case T_U_LLONG:
1597 			(*argtable) [n].ulonglongarg = va_arg (ap, u_quad_t);
1598 			break;
1599 		    case TP_LLONG:
1600 			(*argtable) [n].plonglongarg = va_arg (ap, quad_t *);
1601 			break;
1602 		    case T_PTRDIFFT:
1603 			(*argtable) [n].ptrdiffarg = va_arg (ap, ptrdiff_t);
1604 			break;
1605 		    case TP_PTRDIFFT:
1606 			(*argtable) [n].pptrdiffarg = va_arg (ap, ptrdiff_t *);
1607 			break;
1608 		    case T_SIZET:
1609 			(*argtable) [n].sizearg = va_arg (ap, size_t);
1610 			break;
1611 		    case TP_SIZET:
1612 			(*argtable) [n].psizearg = va_arg (ap, size_t *);
1613 			break;
1614 		    case T_INTMAXT:
1615 			(*argtable) [n].intmaxarg = va_arg (ap, intmax_t);
1616 			break;
1617 		    case T_UINTMAXT:
1618 			(*argtable) [n].uintmaxarg = va_arg (ap, uintmax_t);
1619 			break;
1620 		    case TP_INTMAXT:
1621 			(*argtable) [n].pintmaxarg = va_arg (ap, intmax_t *);
1622 			break;
1623 #ifndef NO_FLOATING_POINT
1624 		    case T_DOUBLE:
1625 			(*argtable) [n].doublearg = va_arg (ap, double);
1626 			break;
1627 		    case T_LONG_DOUBLE:
1628 			(*argtable) [n].longdoublearg = va_arg (ap, long double);
1629 			break;
1630 #endif
1631 		    case TP_CHAR:
1632 			(*argtable) [n].pchararg = va_arg (ap, char *);
1633 			break;
1634 		    case TP_VOID:
1635 			(*argtable) [n].pvoidarg = va_arg (ap, void *);
1636 			break;
1637 		    case T_WINT:
1638 			(*argtable) [n].wintarg = va_arg (ap, wint_t);
1639 			break;
1640 		    case TP_WCHAR:
1641 			(*argtable) [n].pwchararg = va_arg (ap, wchar_t *);
1642 			break;
1643 		}
1644 	}
1645 
1646 	if ((typetable != NULL) && (typetable != stattypetable))
1647 		free (typetable);
1648 }
1649 
1650 /*
1651  * Increase the size of the type table.
1652  */
1653 static void
1654 __grow_type_table (int nextarg, enum typeid **typetable, int *tablesize)
1655 {
1656 	enum typeid *const oldtable = *typetable;
1657 	const int oldsize = *tablesize;
1658 	enum typeid *newtable;
1659 	int n, newsize = oldsize * 2;
1660 
1661 	if (newsize < nextarg + 1)
1662 		newsize = nextarg + 1;
1663 	if (oldsize == STATIC_ARG_TBL_SIZE) {
1664 		if ((newtable = malloc(newsize * sizeof(enum typeid))) == NULL)
1665 			abort();			/* XXX handle better */
1666 		memcpy(newtable, oldtable, oldsize * sizeof(enum typeid));
1667 	} else {
1668 		newtable = realloc(oldtable, newsize * sizeof(enum typeid));
1669 		if (newtable == NULL)
1670 			abort();			/* XXX handle better */
1671 	}
1672 	for (n = oldsize; n < newsize; n++)
1673 		newtable[n] = T_UNUSED;
1674 
1675 	*typetable = newtable;
1676 	*tablesize = newsize;
1677 }
1678 
1679 
1680 #ifndef NO_FLOATING_POINT
1681 #ifndef WIDE_DOUBLE
1682 static char *
1683 cvt(double value, int ndigits, int flags, char *sign, int *decpt, int ch,
1684     int *length)
1685 {
1686 	int mode, dsgn;
1687 	char *digits, *bp, *rve;
1688 
1689 	_DIAGASSERT(decpt != NULL);
1690 	_DIAGASSERT(length != NULL);
1691 	_DIAGASSERT(sign != NULL);
1692 
1693 	if (ch == 'f') {
1694 		mode = 3;		/* ndigits after the decimal point */
1695 	} else {
1696 		/* To obtain ndigits after the decimal point for the 'e'
1697 		 * and 'E' formats, round to ndigits + 1 significant
1698 		 * figures.
1699 		 */
1700 		if (ch == 'e' || ch == 'E') {
1701 			ndigits++;
1702 		}
1703 		mode = 2;		/* ndigits significant digits */
1704 	}
1705 
1706 	digits = __dtoa(value, mode, ndigits, decpt, &dsgn, &rve);
1707 	if (dsgn) {
1708 		value = -value;
1709 		*sign = '-';
1710 	} else
1711 		*sign = '\000';
1712 	if ((ch != 'g' && ch != 'G') || flags & ALT) {	/* Print trailing zeros */
1713 		bp = digits + ndigits;
1714 		if (ch == 'f') {
1715 			if (*digits == '0' && value)
1716 				*decpt = -ndigits + 1;
1717 			bp += *decpt;
1718 		}
1719 		if (value == 0)	/* kludge for __dtoa irregularity */
1720 			rve = bp;
1721 		while (rve < bp)
1722 			*rve++ = '0';
1723 	}
1724 	*length = rve - digits;
1725 	return digits;
1726 }
1727 
1728 static int
1729 exponent(wchar_t *p0, int expo, wchar_t fmtch)
1730 {
1731 	wchar_t *p, *t;
1732 	wchar_t expbuf[MAXEXPDIG];
1733 
1734 	p = p0;
1735 	*p++ = fmtch;
1736 	if (expo < 0) {
1737 		expo = -expo;
1738 		*p++ = '-';
1739 	}
1740 	else
1741 		*p++ = '+';
1742 	t = expbuf + MAXEXPDIG;
1743 	if (expo > 9) {
1744 		do {
1745 			*--t = to_char(expo % 10);
1746 		} while ((expo /= 10) > 9);
1747 		*--t = to_char(expo);
1748 		for (; t < expbuf + MAXEXPDIG; *p++ = *t++);
1749 	}
1750 	else {
1751 		/*
1752 		 * Exponents for decimal floating point conversions
1753 		 * (%[eEgG]) must be at least two characters long,
1754 		 * whereas exponents for hexadecimal conversions can
1755 		 * be only one character long.
1756 		 */
1757 		if (fmtch == 'e' || fmtch == 'E')
1758 			*p++ = '0';
1759 		*p++ = to_char(expo);
1760 	}
1761 	return (p - p0);
1762 }
1763 #endif
1764 #endif /* !NO_FLOATING_POINT */
1765