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