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