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