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