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