2 * Copyright (c) 1990, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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.
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
37 #if defined(LIBC_SCCS) && !defined(lint)
39 static char sccsid[] = "@(#)vfprintf.c 8.1 (Berkeley) 6/4/93";
41 static const char rcsid[] =
43 #endif /* LIBC_SCCS and not lint */
46 * Actual printf innards.
48 * This code is large and complicated...
51 #include <sys/types.h>
66 #include "libc_private.h"
68 /* Define FLOATING_POINT to get floating point. */
69 #define FLOATING_POINT
71 static int __sprint __P((FILE *, struct __suio *));
72 static int __sbprintf __P((FILE *, const char *, va_list));
73 static char * __ultoa __P((u_long, char *, int, int, char *));
74 static char * __uqtoa __P((u_quad_t, char *, int, int, char *));
75 static void __find_arguments __P((const char *, va_list, void ***));
76 static void __grow_type_table __P((int, unsigned char **, int *));
79 * Flush out all the vectors defined by the given uio,
80 * then reset it so that it can be reused.
85 register struct __suio *uio;
89 if (uio->uio_resid == 0) {
93 err = __sfvwrite(fp, uio);
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.
105 __sbprintf(fp, fmt, ap)
112 unsigned char buf[BUFSIZ];
114 /* copy the important variables */
115 fake._flags = fp->_flags & ~__SNBF;
116 fake._file = fp->_file;
117 fake._cookie = fp->_cookie;
118 fake._write = fp->_write;
120 /* set up the buffer */
121 fake._bf._base = fake._p = buf;
122 fake._bf._size = fake._w = sizeof(buf);
123 fake._lbfsize = 0; /* not actually used, but Just In Case */
125 /* do the work, then copy any error status */
126 ret = vfprintf(&fake, fmt, ap);
127 if (ret >= 0 && fflush(&fake))
129 if (fake._flags & __SERR)
130 fp->_flags |= __SERR;
135 * Macros for converting digits to letters and vice versa
137 #define to_digit(c) ((c) - '0')
138 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
139 #define to_char(n) ((n) + '0')
142 * Convert an unsigned long to ASCII for printf purposes, returning
143 * a pointer to the first character of the string representation.
144 * Octal numbers can be forced to have a leading zero; hex numbers
145 * use the given digits.
148 __ultoa(val, endp, base, octzero, xdigs)
154 register char *cp = endp;
158 * Handle the three cases separately, in the hope of getting
159 * better/faster code.
163 if (val < 10) { /* many numbers are 1 digit */
164 *--cp = to_char(val);
168 * On many machines, unsigned arithmetic is harder than
169 * signed arithmetic, so we do at most one unsigned mod and
170 * divide; this is sufficient to reduce the range of
171 * the incoming value to where signed arithmetic works.
173 if (val > LONG_MAX) {
174 *--cp = to_char(val % 10);
179 *--cp = to_char(sval % 10);
186 *--cp = to_char(val & 7);
189 if (octzero && *cp != '0')
195 *--cp = xdigs[val & 15];
206 /* Identical to __ultoa, but for quads. */
208 __uqtoa(val, endp, base, octzero, xdigs)
209 register u_quad_t val;
214 register char *cp = endp;
215 register quad_t sval;
217 /* quick test for small values; __ultoa is typically much faster */
218 /* (perhaps instead we should run until small, then call __ultoa?) */
219 if (val <= ULONG_MAX)
220 return (__ultoa((u_long)val, endp, base, octzero, xdigs));
224 *--cp = to_char(val % 10);
227 if (val > QUAD_MAX) {
228 *--cp = to_char(val % 10);
233 *--cp = to_char(sval % 10);
240 *--cp = to_char(val & 7);
243 if (octzero && *cp != '0')
249 *--cp = xdigs[val & 15];
260 #ifdef FLOATING_POINT
264 #define BUF (MAXEXP+MAXFRACT+1) /* + decimal point */
267 static char *cvt __P((double, int, int, char *, int *, int, int *));
268 static int exponent __P((char *, int, int));
270 #else /* no FLOATING_POINT */
274 #endif /* FLOATING_POINT */
276 #define STATIC_ARG_TBL_SIZE 8 /* Size of static argument table. */
279 * Flags used during conversion.
281 #define ALT 0x001 /* alternate form */
282 #define HEXPREFIX 0x002 /* add 0x or 0X prefix */
283 #define LADJUST 0x004 /* left adjustment */
284 #define LONGDBL 0x008 /* long double */
285 #define LONGINT 0x010 /* long integer */
286 #define QUADINT 0x020 /* quad integer */
287 #define SHORTINT 0x040 /* short integer */
288 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
289 #define FPT 0x100 /* Floating point number */
291 vfprintf(fp, fmt0, ap)
296 register char *fmt; /* format string */
297 register int ch; /* character from fmt */
298 register int n, n2; /* handy integer (short term usage) */
299 register char *cp; /* handy char pointer (short term usage) */
300 register struct __siov *iovp;/* for PRINT macro */
301 register int flags; /* flags as above */
302 int ret; /* return value accumulator */
303 int width; /* width from format (%8d), or 0 */
304 int prec; /* precision from format (%.3d), or -1 */
305 char sign; /* sign prefix (' ', '+', '-', or \0) */
306 #ifdef FLOATING_POINT
307 char softsign; /* temporary negative sign for floats */
308 double _double; /* double precision arguments %[eEfgG] */
309 int expt; /* integer value of exponent */
310 int expsize; /* character count for expstr */
311 int ndig; /* actual number of digits returned by cvt */
312 char expstr[7]; /* buffer for exponent string */
314 u_long ulval; /* integer arguments %[diouxX] */
315 u_quad_t uqval; /* %q integers */
316 int base; /* base for [diouxX] conversion */
317 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
318 int realsz; /* field size expanded by dprec, sign, etc */
319 int size; /* size of converted field or string */
320 int prsize; /* max size of printed field */
321 char *xdigs; /* digits for [xX] conversion */
323 struct __suio uio; /* output information: summary */
324 struct __siov iov[NIOV];/* ... and individual io vectors */
325 char buf[BUF]; /* space for %c, %[diouxX], %[eEfgG] */
326 char ox[2]; /* space for 0x hex-prefix */
327 void **argtable; /* args, built due to positional arg */
328 void *statargtable [STATIC_ARG_TBL_SIZE];
329 int nextarg; /* 1-based argument index */
330 va_list orgap; /* original argument pointer */
333 * Choose PADSIZE to trade efficiency vs. size. If larger printf
334 * fields occur frequently, increase PADSIZE and make the initialisers
337 #define PADSIZE 16 /* pad chunk size */
338 static char blanks[PADSIZE] =
339 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
340 static char zeroes[PADSIZE] =
341 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
344 * BEWARE, these `goto error' on error, and PAD uses `n'.
346 #define PRINT(ptr, len) { \
347 iovp->iov_base = (ptr); \
348 iovp->iov_len = (len); \
349 uio.uio_resid += (len); \
351 if (++uio.uio_iovcnt >= NIOV) { \
352 if (__sprint(fp, &uio)) \
357 #define PAD(howmany, with) { \
358 if ((n = (howmany)) > 0) { \
359 while (n > PADSIZE) { \
360 PRINT(with, PADSIZE); \
367 if (uio.uio_resid && __sprint(fp, &uio)) \
369 uio.uio_iovcnt = 0; \
374 * Get the argument indexed by nextarg. If the argument table is
375 * built, use it to get the argument. If its not, get the next
376 * argument (and arguments must be gotten sequentially).
378 #define GETARG(type) \
379 ((argtable != NULL) ? *((type*)(argtable[nextarg++])) : \
380 (nextarg++, va_arg(ap, type)))
383 * To extend shorts properly, we need both signed and unsigned
384 * argument extraction methods.
387 (flags&LONGINT ? GETARG(long) : \
388 flags&SHORTINT ? (long)(short)GETARG(int) : \
391 (flags&LONGINT ? GETARG(u_long) : \
392 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
393 (u_long)GETARG(u_int))
396 * Get * arguments, including the form *nn$. Preserve the nextarg
397 * that the argument can be gotten once the type is determined.
399 #define GETASTER(val) \
402 while (is_digit(*cp)) { \
403 n2 = 10 * n2 + to_digit(*cp); \
407 int hold = nextarg; \
408 if (argtable == NULL) { \
409 argtable = statargtable; \
410 __find_arguments (fmt0, orgap, &argtable); \
413 val = GETARG (int); \
417 val = GETARG (int); \
422 /* sorry, fprintf(read_only_file, "") returns EOF, not 0 */
428 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
429 if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
432 return (__sbprintf(fp, fmt0, ap));
439 uio.uio_iov = iovp = iov;
445 * Scan the format for conversions (`%' character).
448 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
450 if ((n = fmt - cp) != 0) {
451 if ((unsigned)ret + n > INT_MAX) {
460 fmt++; /* skip over '%' */
469 reswitch: switch (ch) {
472 * ``If the space and + flags both appear, the space
473 * flag will be ignored.''
484 * ``A negative field width argument is taken as a
485 * - flag followed by a positive field width.''
487 * They don't exclude field widths read from args.
501 if ((ch = *fmt++) == '*') {
503 prec = n < 0 ? -1 : n;
507 while (is_digit(ch)) {
508 n = 10 * n + to_digit(ch);
511 prec = n < 0 ? -1 : n;
515 * ``Note that 0 is taken as a flag, not as the
516 * beginning of a field width.''
521 case '1': case '2': case '3': case '4':
522 case '5': case '6': case '7': case '8': case '9':
525 n = 10 * n + to_digit(ch);
527 } while (is_digit(ch));
530 if (argtable == NULL) {
531 argtable = statargtable;
532 __find_arguments (fmt0, orgap,
539 #ifdef FLOATING_POINT
557 *(cp = buf) = GETARG(int);
566 if (flags & QUADINT) {
567 uqval = GETARG(quad_t);
568 if ((quad_t)uqval < 0) {
574 if ((long)ulval < 0) {
581 #ifdef FLOATING_POINT
590 fp_begin: if (prec == -1)
593 /* XXX this loses precision. */
594 _double = (double)GETARG(long double);
596 _double = GETARG(double);
597 /* do this before tricky precision changes */
598 if (isinf(_double)) {
605 if (isnan(_double)) {
611 cp = cvt(_double, prec, flags, &softsign,
613 if (ch == 'g' || ch == 'G') {
614 if (expt <= -4 || expt > prec)
615 ch = (ch == 'g') ? 'e' : 'E';
619 if (ch <= 'e') { /* 'e' or 'E' fmt */
621 expsize = exponent(expstr, expt, ch);
622 size = expsize + ndig;
623 if (ndig > 1 || flags & ALT)
625 } else if (ch == 'f') { /* f fmt */
628 if (prec || flags & ALT)
632 } else if (expt >= ndig) { /* fixed g fmt */
637 size = ndig + (expt > 0 ?
643 #endif /* FLOATING_POINT */
646 *GETARG(quad_t *) = ret;
647 else if (flags & LONGINT)
648 *GETARG(long *) = ret;
649 else if (flags & SHORTINT)
650 *GETARG(short *) = ret;
652 *GETARG(int *) = ret;
653 continue; /* no output */
659 uqval = GETARG(u_quad_t);
666 * ``The argument shall be a pointer to void. The
667 * value of the pointer is converted to a sequence
668 * of printable characters, in an implementation-
672 ulval = (u_long)GETARG(void *);
674 xdigs = "0123456789abcdef";
675 flags = (flags & ~QUADINT) | HEXPREFIX;
679 if ((cp = GETARG(char *)) == NULL)
683 * can't use strlen; can only look for the
684 * NUL in the first `prec' characters, and
685 * strlen() will go further.
687 char *p = memchr(cp, 0, (size_t)prec);
704 uqval = GETARG(u_quad_t);
710 xdigs = "0123456789ABCDEF";
713 xdigs = "0123456789abcdef";
714 hex: if (flags & QUADINT)
715 uqval = GETARG(u_quad_t);
719 /* leading 0x/X only if non-zero */
721 (flags & QUADINT ? uqval != 0 : ulval != 0))
724 /* unsigned conversions */
727 * ``... diouXx conversions ... if a precision is
728 * specified, the 0 flag will be ignored.''
731 number: if ((dprec = prec) >= 0)
735 * ``The result of converting a zero value with an
736 * explicit precision of zero is no characters.''
740 if (flags & QUADINT) {
741 if (uqval != 0 || prec != 0)
742 cp = __uqtoa(uqval, cp, base,
745 if (ulval != 0 || prec != 0)
746 cp = __ultoa(ulval, cp, base,
749 size = buf + BUF - cp;
751 default: /* "%?" prints ?, unless ? is NUL */
754 /* pretend it was %c with argument ch */
763 * All reasonable formats wind up here. At this point, `cp'
764 * points to a string which (if not flags&LADJUST) should be
765 * padded out to `width' places. If flags&ZEROPAD, it should
766 * first be prefixed by any sign or other prefix; otherwise,
767 * it should be blank padded before the prefix is emitted.
768 * After any left-hand padding and prefixing, emit zeroes
769 * required by a decimal [diouxX] precision, then print the
770 * string proper, then emit zeroes required by any leftover
771 * floating precision; finally, if LADJUST, pad with blanks.
773 * Compute actual size, so we know how much to pad.
774 * size excludes decimal prec; realsz includes it.
776 realsz = dprec > size ? dprec : size;
779 else if (flags & HEXPREFIX)
782 prsize = width > realsz ? width : realsz;
783 if ((unsigned)ret + prsize > INT_MAX) {
788 /* right-adjusting blank padding */
789 if ((flags & (LADJUST|ZEROPAD)) == 0)
790 PAD(width - realsz, blanks);
795 } else if (flags & HEXPREFIX) {
801 /* right-adjusting zero padding */
802 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
803 PAD(width - realsz, zeroes);
805 /* leading zeroes from decimal precision */
806 PAD(dprec - size, zeroes);
808 /* the string or number proper */
809 #ifdef FLOATING_POINT
810 if ((flags & FPT) == 0) {
812 } else { /* glue together f_p fragments */
813 if (ch >= 'f') { /* 'f' or 'g' */
815 /* kludge for __dtoa irregularity */
817 (flags & ALT) == 0) {
821 PAD(ndig - 1, zeroes);
823 } else if (expt <= 0) {
827 } else if (expt >= ndig) {
829 PAD(expt - ndig, zeroes);
836 PRINT(cp, ndig-expt);
838 } else { /* 'e' or 'E' */
839 if (ndig > 1 || flags & ALT) {
846 /* __dtoa irregularity */
847 PAD(ndig - 1, zeroes);
850 PRINT(expstr, expsize);
856 /* left-adjusting padding (always blank) */
858 PAD(width - realsz, blanks);
860 /* finally, adjust ret */
863 FLUSH(); /* copy out the I/O vectors */
871 if ((argtable != NULL) && (argtable != statargtable))
878 * Type ids for argument type table.
894 #define T_LONG_DOUBLE 14
899 * Find all arguments when a positional parameter is encountered. Returns a
900 * table, indexed by argument number, of pointers to each arguments. The
901 * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
902 * It will be replaces with a malloc-ed on if it overflows.
905 __find_arguments (fmt0, ap, argtable)
910 register char *fmt; /* format string */
911 register int ch; /* character from fmt */
912 register int n, n2; /* handy integer (short term usage) */
913 register char *cp; /* handy char pointer (short term usage) */
914 register int flags; /* flags as above */
915 int width; /* width from format (%8d), or 0 */
916 unsigned char *typetable; /* table of types */
917 unsigned char stattypetable [STATIC_ARG_TBL_SIZE];
918 int tablesize; /* current size of type table */
919 int tablemax; /* largest used index in table */
920 int nextarg; /* 1-based argument index */
923 * Add an argument type to the table, expanding if necessary.
925 #define ADDTYPE(type) \
926 ((nextarg >= tablesize) ? \
927 __grow_type_table(nextarg, &typetable, &tablesize) : 0, \
928 typetable[nextarg++] = type, \
929 (nextarg > tablemax) ? tablemax = nextarg : 0)
932 ((flags&LONGINT) ? ADDTYPE(T_LONG) : \
933 ((flags&SHORTINT) ? ADDTYPE(T_SHORT) : ADDTYPE(T_INT)))
936 ((flags&LONGINT) ? ADDTYPE(T_U_LONG) : \
937 ((flags&SHORTINT) ? ADDTYPE(T_U_SHORT) : ADDTYPE(T_U_INT)))
940 * Add * arguments to the type array.
945 while (is_digit(*cp)) { \
946 n2 = 10 * n2 + to_digit(*cp); \
950 int hold = nextarg; \
959 typetable = stattypetable;
960 tablesize = STATIC_ARG_TBL_SIZE;
963 memset (typetable, T_UNUSED, STATIC_ARG_TBL_SIZE);
966 * Scan the format for conversions (`%' character).
969 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
973 fmt++; /* skip over '%' */
979 reswitch: switch (ch) {
990 if ((ch = *fmt++) == '*') {
994 while (is_digit(ch)) {
1000 case '1': case '2': case '3': case '4':
1001 case '5': case '6': case '7': case '8': case '9':
1004 n = 10 * n + to_digit(ch);
1006 } while (is_digit(ch));
1013 #ifdef FLOATING_POINT
1022 if (flags & LONGINT)
1038 if (flags & QUADINT) {
1044 #ifdef FLOATING_POINT
1050 if (flags & LONGDBL)
1051 ADDTYPE(T_LONG_DOUBLE);
1055 #endif /* FLOATING_POINT */
1057 if (flags & QUADINT)
1059 else if (flags & LONGINT)
1061 else if (flags & SHORTINT)
1065 continue; /* no output */
1070 if (flags & QUADINT)
1085 if (flags & QUADINT)
1092 if (flags & QUADINT)
1097 default: /* "%?" prints ?, unless ? is NUL */
1105 * Build the argument table.
1107 if (tablemax >= STATIC_ARG_TBL_SIZE) {
1108 *argtable = (void **)
1109 malloc (sizeof (void *) * (tablemax + 1));
1112 (*argtable) [0] = NULL;
1113 for (n = 1; n <= tablemax; n++) {
1114 switch (typetable [n]) {
1116 (*argtable) [n] = (void *) &va_arg (ap, int);
1119 (*argtable) [n] = (void *) &va_arg (ap, int);
1122 (*argtable) [n] = (void *) &va_arg (ap, int);
1125 (*argtable) [n] = (void *) &va_arg (ap, short *);
1128 (*argtable) [n] = (void *) &va_arg (ap, int);
1131 (*argtable) [n] = (void *) &va_arg (ap, unsigned int);
1134 (*argtable) [n] = (void *) &va_arg (ap, int *);
1137 (*argtable) [n] = (void *) &va_arg (ap, long);
1140 (*argtable) [n] = (void *) &va_arg (ap, unsigned long);
1143 (*argtable) [n] = (void *) &va_arg (ap, long *);
1146 (*argtable) [n] = (void *) &va_arg (ap, quad_t);
1149 (*argtable) [n] = (void *) &va_arg (ap, u_quad_t);
1152 (*argtable) [n] = (void *) &va_arg (ap, quad_t *);
1155 (*argtable) [n] = (void *) &va_arg (ap, double);
1158 (*argtable) [n] = (void *) &va_arg (ap, long double);
1161 (*argtable) [n] = (void *) &va_arg (ap, char *);
1164 (*argtable) [n] = (void *) &va_arg (ap, void *);
1169 if ((typetable != NULL) && (typetable != stattypetable))
1174 * Increase the size of the type table.
1177 __grow_type_table (nextarg, typetable, tablesize)
1179 unsigned char **typetable;
1182 unsigned char *oldtable = *typetable;
1183 int newsize = *tablesize * 2;
1185 if (*tablesize == STATIC_ARG_TBL_SIZE) {
1186 *typetable = (unsigned char *)
1187 malloc (sizeof (unsigned char) * newsize);
1188 bcopy (oldtable, *typetable, *tablesize);
1190 *typetable = (unsigned char *)
1191 reallocf (typetable, sizeof (unsigned char) * newsize);
1194 memset (&typetable [*tablesize], T_UNUSED, (newsize - *tablesize));
1196 *tablesize = newsize;
1200 #ifdef FLOATING_POINT
1202 extern char *__dtoa __P((double, int, int, int *, int *, char **));
1205 cvt(value, ndigits, flags, sign, decpt, ch, length)
1207 int ndigits, flags, *decpt, ch, *length;
1211 char *digits, *bp, *rve;
1214 mode = 3; /* ndigits after the decimal point */
1217 * To obtain ndigits after the decimal point for the 'e'
1218 * and 'E' formats, round to ndigits + 1 significant
1221 if (ch == 'e' || ch == 'E')
1223 mode = 2; /* ndigits significant digits */
1230 digits = __dtoa(value, mode, ndigits, decpt, &dsgn, &rve);
1231 if ((ch != 'g' && ch != 'G') || flags & ALT) {
1232 /* print trailing zeros */
1233 bp = digits + ndigits;
1235 if (*digits == '0' && value)
1236 *decpt = -ndigits + 1;
1239 if (value == 0) /* kludge for __dtoa irregularity */
1244 *length = rve - digits;
1249 exponent(p0, exp, fmtch)
1253 register char *p, *t;
1254 char expbuf[MAXEXP];
1264 t = expbuf + MAXEXP;
1267 *--t = to_char(exp % 10);
1268 } while ((exp /= 10) > 9);
1269 *--t = to_char(exp);
1270 for (; t < expbuf + MAXEXP; *p++ = *t++);
1274 *p++ = to_char(exp);
1278 #endif /* FLOATING_POINT */