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