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