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