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