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