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