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