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)
38 static char sccsid[] = "@(#)vfprintf.c 8.1 (Berkeley) 6/4/93";
39 #endif /* LIBC_SCCS and not lint */
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
44 * Actual printf innards.
46 * This code is large and complicated...
49 #include "namespace.h"
50 #include <sys/types.h>
64 #include "un-namespace.h"
66 #include "libc_private.h"
75 long long longlongarg;
76 unsigned long long ulonglongarg;
83 signed char *pschararg;
87 long long *plonglongarg;
88 ptrdiff_t *pptrdiffarg;
91 #ifndef NO_FLOATING_POINT
93 long double longdoublearg;
100 * Type ids for argument type table.
103 T_UNUSED, TP_SHORT, T_INT, T_U_INT, TP_INT,
104 T_LONG, T_U_LONG, TP_LONG, T_LLONG, T_U_LLONG, TP_LLONG,
105 T_PTRDIFFT, TP_PTRDIFFT, T_SIZET, TP_SIZET,
106 T_INTMAXT, T_UINTMAXT, TP_INTMAXT, TP_VOID, TP_CHAR, TP_SCHAR,
107 T_DOUBLE, T_LONG_DOUBLE, T_WINT, TP_WCHAR
110 static int __sprint(FILE *, struct __suio *);
111 static int __sbprintf(FILE *, const char *, va_list) __printflike(2, 0);
112 static char *__ujtoa(uintmax_t, char *, int, int, const char *, int, char,
114 static char *__ultoa(u_long, char *, int, int, const char *, int, char,
116 static char *__wcsconv(wchar_t *, int);
117 static void __find_arguments(const char *, va_list, union arg **);
118 static void __grow_type_table(int, enum typeid **, int *);
121 * Flush out all the vectors defined by the given uio,
122 * then reset it so that it can be reused.
125 __sprint(FILE *fp, struct __suio *uio)
129 if (uio->uio_resid == 0) {
133 err = __sfvwrite(fp, uio);
140 * Helper function for `fprintf to unbuffered unix file': creates a
141 * temporary buffer. We only work on write-only files; this avoids
142 * worries about ungetc buffers and so forth.
145 __sbprintf(FILE *fp, const char *fmt, va_list ap)
149 unsigned char buf[BUFSIZ];
151 /* copy the important variables */
152 fake._flags = fp->_flags & ~__SNBF;
153 fake._file = fp->_file;
154 fake._cookie = fp->_cookie;
155 fake._write = fp->_write;
156 fake._extra = fp->_extra;
158 /* set up the buffer */
159 fake._bf._base = fake._p = buf;
160 fake._bf._size = fake._w = sizeof(buf);
161 fake._lbfsize = 0; /* not actually used, but Just In Case */
163 /* do the work, then copy any error status */
164 ret = __vfprintf(&fake, fmt, ap);
165 if (ret >= 0 && __fflush(&fake))
167 if (fake._flags & __SERR)
168 fp->_flags |= __SERR;
173 * Macros for converting digits to letters and vice versa
175 #define to_digit(c) ((c) - '0')
176 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
177 #define to_char(n) ((n) + '0')
180 * Convert an unsigned long to ASCII for printf purposes, returning
181 * a pointer to the first character of the string representation.
182 * Octal numbers can be forced to have a leading zero; hex numbers
183 * use the given digits.
186 __ultoa(u_long val, char *endp, int base, int octzero, const char *xdigs,
187 int needgrp, char thousep, const char *grp)
194 * Handle the three cases separately, in the hope of getting
195 * better/faster code.
199 if (val < 10) { /* many numbers are 1 digit */
200 *--cp = to_char(val);
205 * On many machines, unsigned arithmetic is harder than
206 * signed arithmetic, so we do at most one unsigned mod and
207 * divide; this is sufficient to reduce the range of
208 * the incoming value to where signed arithmetic works.
210 if (val > LONG_MAX) {
211 *--cp = to_char(val % 10);
217 *--cp = to_char(sval % 10);
220 * If (*grp == CHAR_MAX) then no more grouping
221 * should be performed.
223 if (needgrp && ndig == *grp && *grp != CHAR_MAX
228 * If (*(grp+1) == '\0') then we have to
229 * use *grp character (last grouping rule)
232 if (*(grp+1) != '\0')
241 *--cp = to_char(val & 7);
244 if (octzero && *cp != '0')
250 *--cp = xdigs[val & 15];
261 /* Identical to __ultoa, but for intmax_t. */
263 __ujtoa(uintmax_t val, char *endp, int base, int octzero, const char *xdigs,
264 int needgrp, char thousep, const char *grp)
270 /* quick test for small values; __ultoa is typically much faster */
271 /* (perhaps instead we should run until small, then call __ultoa?) */
272 if (val <= ULONG_MAX)
273 return (__ultoa((u_long)val, endp, base, octzero, xdigs,
274 needgrp, thousep, grp));
278 *--cp = to_char(val % 10);
282 if (val > INTMAX_MAX) {
283 *--cp = to_char(val % 10);
289 *--cp = to_char(sval % 10);
292 * If (*grp == CHAR_MAX) then no more grouping
293 * should be performed.
295 if (needgrp && *grp != CHAR_MAX && ndig == *grp
300 * If (*(grp+1) == '\0') then we have to
301 * use *grp character (last grouping rule)
304 if (*(grp+1) != '\0')
313 *--cp = to_char(val & 7);
316 if (octzero && *cp != '0')
322 *--cp = xdigs[val & 15];
334 * Convert a wide character string argument for the %ls format to a multibyte
335 * string representation. If not -1, prec specifies the maximum number of
336 * bytes to output, and also means that we can't assume that the wide char.
337 * string ends is null-terminated.
340 __wcsconv(wchar_t *wcsarg, int prec)
342 static const mbstate_t initial;
344 char buf[MB_LEN_MAX];
349 /* Allocate space for the maximum number of bytes we could output. */
353 nbytes = wcsrtombs(NULL, (const wchar_t **)&p, 0, &mbs);
354 if (nbytes == (size_t)-1)
358 * Optimisation: if the output precision is small enough,
359 * just allocate enough memory for the maximum instead of
360 * scanning the string.
369 clen = wcrtomb(buf, *p++, &mbs);
370 if (clen == 0 || clen == (size_t)-1 ||
371 nbytes + clen > prec)
377 if ((convbuf = malloc(nbytes + 1)) == NULL)
380 /* Fill the output buffer. */
383 if ((nbytes = wcsrtombs(convbuf, (const wchar_t **)&p,
384 nbytes, &mbs)) == (size_t)-1) {
388 convbuf[nbytes] = '\0';
396 vfprintf(FILE * __restrict fp, const char * __restrict fmt0, va_list ap)
402 ret = __vfprintf(fp, fmt0, ap);
407 #ifndef NO_FLOATING_POINT
410 #define freedtoa __freedtoa
419 static int exponent(char *, int, int);
421 #endif /* !NO_FLOATING_POINT */
424 * The size of the buffer we use as scratch space for integer
425 * conversions, among other things. Technically, we would need the
426 * most space for base 10 conversions with thousands' grouping
427 * characters between each pair of digits. 100 bytes is a
428 * conservative overestimate even for a 128-bit uintmax_t.
432 #define STATIC_ARG_TBL_SIZE 8 /* Size of static argument table. */
435 * Flags used during conversion.
437 #define ALT 0x001 /* alternate form */
438 #define LADJUST 0x004 /* left adjustment */
439 #define LONGDBL 0x008 /* long double */
440 #define LONGINT 0x010 /* long integer */
441 #define LLONGINT 0x020 /* long long integer */
442 #define SHORTINT 0x040 /* short integer */
443 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
444 #define FPT 0x100 /* Floating point number */
445 #define GROUPING 0x200 /* use grouping ("'" flag) */
446 /* C99 additional size modifiers: */
447 #define SIZET 0x400 /* size_t */
448 #define PTRDIFFT 0x800 /* ptrdiff_t */
449 #define INTMAXT 0x1000 /* intmax_t */
450 #define CHARINT 0x2000 /* print char using int format */
453 * Non-MT-safe version
456 __vfprintf(FILE *fp, const char *fmt0, va_list ap)
458 char *fmt; /* format string */
459 int ch; /* character from fmt */
460 int n, n2; /* handy integer (short term usage) */
461 char *cp; /* handy char pointer (short term usage) */
462 struct __siov *iovp; /* for PRINT macro */
463 int flags; /* flags as above */
464 int ret; /* return value accumulator */
465 int width; /* width from format (%8d), or 0 */
466 int prec; /* precision from format; <0 for N/A */
467 char sign; /* sign prefix (' ', '+', '-', or \0) */
468 char thousands_sep; /* locale specific thousands separator */
469 const char *grouping; /* locale specific numeric grouping rules */
471 if (__use_xprintf == 0 && getenv("USE_XPRINTF"))
473 if (__use_xprintf > 0)
474 return (__xvprintf(fp, fmt0, ap));
476 #ifndef NO_FLOATING_POINT
478 * We can decompose the printed representation of floating
479 * point numbers into several parts, some of which may be empty:
481 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
484 * A: 'sign' holds this value if present; '\0' otherwise
485 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
486 * C: cp points to the string MMMNNN. Leading and trailing
487 * zeros are not in the string and must be added.
488 * D: expchar holds this character; '\0' if no exponent, e.g. %f
489 * F: at least two digits for decimal, at least one digit for hex
491 char *decimal_point; /* locale specific decimal point */
492 int signflag; /* true if float is negative */
493 union { /* floating point arguments %[aAeEfFgG] */
497 int expt; /* integer value of exponent */
498 char expchar; /* exponent character: [eEpP\0] */
499 char *dtoaend; /* pointer to end of converted digits */
500 int expsize; /* character count for expstr */
501 int lead; /* sig figs before decimal or group sep */
502 int ndig; /* actual number of digits returned by dtoa */
503 char expstr[MAXEXPDIG+2]; /* buffer for exponent string: e+ZZZ */
504 char *dtoaresult; /* buffer allocated by dtoa */
505 int nseps; /* number of group separators with ' */
506 int nrepeats; /* number of repeats of the last group */
508 u_long ulval; /* integer arguments %[diouxX] */
509 uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */
510 int base; /* base for [diouxX] conversion */
511 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
512 int realsz; /* field size expanded by dprec, sign, etc */
513 int size; /* size of converted field or string */
514 int prsize; /* max size of printed field */
515 const char *xdigs; /* digits for %[xX] conversion */
517 struct __suio uio; /* output information: summary */
518 struct __siov iov[NIOV];/* ... and individual io vectors */
519 char buf[BUF]; /* buffer with space for digits of uintmax_t */
520 char ox[2]; /* space for 0x; ox[1] is either x, X, or \0 */
521 union arg *argtable; /* args, built due to positional arg */
522 union arg statargtable [STATIC_ARG_TBL_SIZE];
523 int nextarg; /* 1-based argument index */
524 va_list orgap; /* original argument pointer */
525 char *convbuf; /* wide to multibyte conversion result */
528 * Choose PADSIZE to trade efficiency vs. size. If larger printf
529 * fields occur frequently, increase PADSIZE and make the initialisers
532 #define PADSIZE 16 /* pad chunk size */
533 static char blanks[PADSIZE] =
534 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
535 static char zeroes[PADSIZE] =
536 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
538 static const char xdigs_lower[17] = "0123456789abcdef?";
539 static const char xdigs_upper[17] = "0123456789ABCDEF?";
542 * BEWARE, these `goto error' on error, and PAD uses `n'.
544 #define PRINT(ptr, len) { \
545 iovp->iov_base = (ptr); \
546 iovp->iov_len = (len); \
547 uio.uio_resid += (len); \
549 if (++uio.uio_iovcnt >= NIOV) { \
550 if (__sprint(fp, &uio)) \
555 #define PAD(howmany, with) { \
556 if ((n = (howmany)) > 0) { \
557 while (n > PADSIZE) { \
558 PRINT(with, PADSIZE); \
564 #define PRINTANDPAD(p, ep, len, with) do { \
570 PAD((len) - (n2 > 0 ? n2 : 0), (with)); \
573 if (uio.uio_resid && __sprint(fp, &uio)) \
575 uio.uio_iovcnt = 0; \
580 * Get the argument indexed by nextarg. If the argument table is
581 * built, use it to get the argument. If its not, get the next
582 * argument (and arguments must be gotten sequentially).
584 #define GETARG(type) \
585 ((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
586 (nextarg++, va_arg(ap, type)))
589 * To extend shorts properly, we need both signed and unsigned
590 * argument extraction methods.
593 (flags&LONGINT ? GETARG(long) : \
594 flags&SHORTINT ? (long)(short)GETARG(int) : \
595 flags&CHARINT ? (long)(signed char)GETARG(int) : \
598 (flags&LONGINT ? GETARG(u_long) : \
599 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
600 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
601 (u_long)GETARG(u_int))
602 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
604 (flags&INTMAXT ? GETARG(intmax_t) : \
605 flags&SIZET ? (intmax_t)GETARG(size_t) : \
606 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
607 (intmax_t)GETARG(long long))
609 (flags&INTMAXT ? GETARG(uintmax_t) : \
610 flags&SIZET ? (uintmax_t)GETARG(size_t) : \
611 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
612 (uintmax_t)GETARG(unsigned long long))
615 * Get * arguments, including the form *nn$. Preserve the nextarg
616 * that the argument can be gotten once the type is determined.
618 #define GETASTER(val) \
621 while (is_digit(*cp)) { \
622 n2 = 10 * n2 + to_digit(*cp); \
626 int hold = nextarg; \
627 if (argtable == NULL) { \
628 argtable = statargtable; \
629 __find_arguments (fmt0, orgap, &argtable); \
632 val = GETARG (int); \
636 val = GETARG (int); \
640 thousands_sep = '\0';
643 #ifndef NO_FLOATING_POINT
645 decimal_point = localeconv()->decimal_point;
647 /* sorry, fprintf(read_only_file, "") returns EOF, not 0 */
648 if (prepwrite(fp) != 0)
651 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
652 if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
654 return (__sbprintf(fp, fmt0, ap));
660 uio.uio_iov = iovp = iov;
666 * Scan the format for conversions (`%' character).
669 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
671 if ((n = fmt - cp) != 0) {
672 if ((unsigned)ret + n > INT_MAX) {
681 fmt++; /* skip over '%' */
691 reswitch: switch (ch) {
694 * ``If the space and + flags both appear, the space
695 * flag will be ignored.''
706 * ``A negative field width argument is taken as a
707 * - flag followed by a positive field width.''
709 * They don't exclude field widths read from args.
724 thousands_sep = *(localeconv()->thousands_sep);
725 grouping = localeconv()->grouping;
728 if ((ch = *fmt++) == '*') {
733 while (is_digit(ch)) {
734 prec = 10 * prec + to_digit(ch);
740 * ``Note that 0 is taken as a flag, not as the
741 * beginning of a field width.''
746 case '1': case '2': case '3': case '4':
747 case '5': case '6': case '7': case '8': case '9':
750 n = 10 * n + to_digit(ch);
752 } while (is_digit(ch));
755 if (argtable == NULL) {
756 argtable = statargtable;
757 __find_arguments (fmt0, orgap,
764 #ifndef NO_FLOATING_POINT
770 if (flags & SHORTINT) {
780 if (flags & LONGINT) {
787 flags |= LLONGINT; /* not necessarily */
799 if (flags & LONGINT) {
800 static const mbstate_t initial;
805 mbseqlen = wcrtomb(cp = buf,
806 (wchar_t)GETARG(wint_t), &mbs);
807 if (mbseqlen == (size_t)-1) {
808 fp->_flags |= __SERR;
811 size = (int)mbseqlen;
813 *(cp = buf) = GETARG(int);
823 if (flags & INTMAX_SIZE) {
825 if ((intmax_t)ujval < 0) {
831 if ((long)ulval < 0) {
838 #ifndef NO_FLOATING_POINT
852 if (dtoaresult != NULL)
853 freedtoa(dtoaresult);
854 if (flags & LONGDBL) {
855 fparg.ldbl = GETARG(long double);
857 __hldtoa(fparg.ldbl, xdigs, prec,
858 &expt, &signflag, &dtoaend);
860 fparg.dbl = GETARG(double);
862 __hdtoa(fparg.dbl, xdigs, prec,
863 &expt, &signflag, &dtoaend);
873 if (prec < 0) /* account for digit before decpt */
884 expchar = ch - ('g' - 'e');
890 if (dtoaresult != NULL)
891 freedtoa(dtoaresult);
892 if (flags & LONGDBL) {
893 fparg.ldbl = GETARG(long double);
895 __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
896 &expt, &signflag, &dtoaend);
898 fparg.dbl = GETARG(double);
900 dtoa(fparg.dbl, expchar ? 2 : 3, prec,
901 &expt, &signflag, &dtoaend);
908 if (expt == INT_MAX) { /* inf or nan */
910 cp = (ch >= 'a') ? "nan" : "NAN";
913 cp = (ch >= 'a') ? "inf" : "INF";
919 if (ch == 'g' || ch == 'G') {
920 if (expt > -4 && expt <= prec) {
921 /* Make %[gG] smell like %[fF] */
931 * Make %[gG] smell like %[eE], but
932 * trim trailing zeroes if no # flag.
939 expsize = exponent(expstr, expt - 1, expchar);
940 size = expsize + prec;
941 if (prec > 1 || flags & ALT)
944 /* space for digits before decimal point */
949 /* space for decimal pt and following digits */
950 if (prec || flags & ALT)
952 if (grouping && expt > 0) {
953 /* space for thousands' grouping */
954 nseps = nrepeats = 0;
956 while (*grouping != CHAR_MAX) {
957 if (lead <= *grouping)
966 size += nseps + nrepeats;
971 #endif /* !NO_FLOATING_POINT */
974 * Assignment-like behavior is specified if the
975 * value overflows or is otherwise unrepresentable.
976 * C99 says to use `signed char' for %hhn conversions.
978 if (flags & LLONGINT)
979 *GETARG(long long *) = ret;
980 else if (flags & SIZET)
981 *GETARG(ssize_t *) = (ssize_t)ret;
982 else if (flags & PTRDIFFT)
983 *GETARG(ptrdiff_t *) = ret;
984 else if (flags & INTMAXT)
985 *GETARG(intmax_t *) = ret;
986 else if (flags & LONGINT)
987 *GETARG(long *) = ret;
988 else if (flags & SHORTINT)
989 *GETARG(short *) = ret;
990 else if (flags & CHARINT)
991 *GETARG(signed char *) = ret;
993 *GETARG(int *) = ret;
994 continue; /* no output */
999 if (flags & INTMAX_SIZE)
1007 * ``The argument shall be a pointer to void. The
1008 * value of the pointer is converted to a sequence
1009 * of printable characters, in an implementation-
1013 ujval = (uintmax_t)(uintptr_t)GETARG(void *);
1015 xdigs = xdigs_lower;
1016 flags = flags | INTMAXT;
1023 if (flags & LONGINT) {
1026 if (convbuf != NULL)
1028 if ((wcp = GETARG(wchar_t *)) == NULL)
1031 convbuf = __wcsconv(wcp, prec);
1032 if (convbuf == NULL) {
1033 fp->_flags |= __SERR;
1038 } else if ((cp = GETARG(char *)) == NULL)
1042 * can't use strlen; can only look for the
1043 * NUL in the first `prec' characters, and
1044 * strlen() will go further.
1046 char *p = memchr(cp, 0, (size_t)prec);
1062 if (flags & INTMAX_SIZE)
1069 xdigs = xdigs_upper;
1072 xdigs = xdigs_lower;
1074 if (flags & INTMAX_SIZE)
1079 /* leading 0x/X only if non-zero */
1081 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
1085 /* unsigned conversions */
1086 nosign: sign = '\0';
1088 * ``... diouXx conversions ... if a precision is
1089 * specified, the 0 flag will be ignored.''
1092 number: if ((dprec = prec) >= 0)
1096 * ``The result of converting a zero value with an
1097 * explicit precision of zero is no characters.''
1100 * ``The C Standard is clear enough as is. The call
1101 * printf("%#.0o", 0) should print 0.''
1102 * -- Defect Report #151
1105 if (flags & INTMAX_SIZE) {
1106 if (ujval != 0 || prec != 0 ||
1107 (flags & ALT && base == 8))
1108 cp = __ujtoa(ujval, cp, base,
1110 flags & GROUPING, thousands_sep,
1113 if (ulval != 0 || prec != 0 ||
1114 (flags & ALT && base == 8))
1115 cp = __ultoa(ulval, cp, base,
1117 flags & GROUPING, thousands_sep,
1120 size = buf + BUF - cp;
1121 if (size > BUF) /* should never happen */
1124 default: /* "%?" prints ?, unless ? is NUL */
1127 /* pretend it was %c with argument ch */
1136 * All reasonable formats wind up here. At this point, `cp'
1137 * points to a string which (if not flags&LADJUST) should be
1138 * padded out to `width' places. If flags&ZEROPAD, it should
1139 * first be prefixed by any sign or other prefix; otherwise,
1140 * it should be blank padded before the prefix is emitted.
1141 * After any left-hand padding and prefixing, emit zeroes
1142 * required by a decimal [diouxX] precision, then print the
1143 * string proper, then emit zeroes required by any leftover
1144 * floating precision; finally, if LADJUST, pad with blanks.
1146 * Compute actual size, so we know how much to pad.
1147 * size excludes decimal prec; realsz includes it.
1149 realsz = dprec > size ? dprec : size;
1155 prsize = width > realsz ? width : realsz;
1156 if ((unsigned)ret + prsize > INT_MAX) {
1161 /* right-adjusting blank padding */
1162 if ((flags & (LADJUST|ZEROPAD)) == 0)
1163 PAD(width - realsz, blanks);
1169 if (ox[1]) { /* ox[1] is either x, X, or \0 */
1174 /* right-adjusting zero padding */
1175 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1176 PAD(width - realsz, zeroes);
1178 /* leading zeroes from decimal precision */
1179 PAD(dprec - size, zeroes);
1181 /* the string or number proper */
1182 #ifndef NO_FLOATING_POINT
1183 if ((flags & FPT) == 0) {
1185 } else { /* glue together f_p fragments */
1186 if (!expchar) { /* %[fF] or sufficiently short %[gG] */
1189 if (prec || flags & ALT)
1190 PRINT(decimal_point, 1);
1192 /* already handled initial 0's */
1195 PRINTANDPAD(cp, dtoaend, lead, zeroes);
1198 while (nseps>0 || nrepeats>0) {
1205 PRINT(&thousands_sep,
1207 PRINTANDPAD(cp,dtoaend,
1214 if (prec || flags & ALT)
1215 PRINT(decimal_point,1);
1217 PRINTANDPAD(cp, dtoaend, prec, zeroes);
1218 } else { /* %[eE] or sufficiently long %[gG] */
1219 if (prec > 1 || flags & ALT) {
1221 buf[1] = *decimal_point;
1224 PAD(prec - ndig, zeroes);
1227 PRINT(expstr, expsize);
1233 /* left-adjusting padding (always blank) */
1234 if (flags & LADJUST)
1235 PAD(width - realsz, blanks);
1237 /* finally, adjust ret */
1240 FLUSH(); /* copy out the I/O vectors */
1246 #ifndef NO_FLOATING_POINT
1247 if (dtoaresult != NULL)
1248 freedtoa(dtoaresult);
1250 if (convbuf != NULL)
1254 if ((argtable != NULL) && (argtable != statargtable))
1261 * Find all arguments when a positional parameter is encountered. Returns a
1262 * table, indexed by argument number, of pointers to each arguments. The
1263 * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1264 * It will be replaces with a malloc-ed one if it overflows.
1267 __find_arguments (const char *fmt0, va_list ap, union arg **argtable)
1269 char *fmt; /* format string */
1270 int ch; /* character from fmt */
1271 int n, n2; /* handy integer (short term usage) */
1272 char *cp; /* handy char pointer (short term usage) */
1273 int flags; /* flags as above */
1274 int width; /* width from format (%8d), or 0 */
1275 enum typeid *typetable; /* table of types */
1276 enum typeid stattypetable [STATIC_ARG_TBL_SIZE];
1277 int tablesize; /* current size of type table */
1278 int tablemax; /* largest used index in table */
1279 int nextarg; /* 1-based argument index */
1282 * Add an argument type to the table, expanding if necessary.
1284 #define ADDTYPE(type) \
1285 ((nextarg >= tablesize) ? \
1286 __grow_type_table(nextarg, &typetable, &tablesize) : (void)0, \
1287 (nextarg > tablemax) ? tablemax = nextarg : 0, \
1288 typetable[nextarg++] = type)
1291 ((flags&INTMAXT) ? ADDTYPE(T_INTMAXT) : \
1292 ((flags&SIZET) ? ADDTYPE(T_SIZET) : \
1293 ((flags&PTRDIFFT) ? ADDTYPE(T_PTRDIFFT) : \
1294 ((flags&LLONGINT) ? ADDTYPE(T_LLONG) : \
1295 ((flags&LONGINT) ? ADDTYPE(T_LONG) : ADDTYPE(T_INT))))))
1298 ((flags&INTMAXT) ? ADDTYPE(T_UINTMAXT) : \
1299 ((flags&SIZET) ? ADDTYPE(T_SIZET) : \
1300 ((flags&PTRDIFFT) ? ADDTYPE(T_PTRDIFFT) : \
1301 ((flags&LLONGINT) ? ADDTYPE(T_U_LLONG) : \
1302 ((flags&LONGINT) ? ADDTYPE(T_U_LONG) : ADDTYPE(T_U_INT))))))
1305 * Add * arguments to the type array.
1307 #define ADDASTER() \
1310 while (is_digit(*cp)) { \
1311 n2 = 10 * n2 + to_digit(*cp); \
1315 int hold = nextarg; \
1324 typetable = stattypetable;
1325 tablesize = STATIC_ARG_TBL_SIZE;
1328 for (n = 0; n < STATIC_ARG_TBL_SIZE; n++)
1329 typetable[n] = T_UNUSED;
1332 * Scan the format for conversions (`%' character).
1335 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
1339 fmt++; /* skip over '%' */
1345 reswitch: switch (ch) {
1357 if ((ch = *fmt++) == '*') {
1361 while (is_digit(ch)) {
1367 case '1': case '2': case '3': case '4':
1368 case '5': case '6': case '7': case '8': case '9':
1371 n = 10 * n + to_digit(ch);
1373 } while (is_digit(ch));
1380 #ifndef NO_FLOATING_POINT
1386 if (flags & SHORTINT) {
1396 if (flags & LONGINT) {
1403 flags |= LLONGINT; /* not necessarily */
1415 if (flags & LONGINT)
1427 #ifndef NO_FLOATING_POINT
1435 if (flags & LONGDBL)
1436 ADDTYPE(T_LONG_DOUBLE);
1440 #endif /* !NO_FLOATING_POINT */
1442 if (flags & INTMAXT)
1443 ADDTYPE(TP_INTMAXT);
1444 else if (flags & PTRDIFFT)
1445 ADDTYPE(TP_PTRDIFFT);
1446 else if (flags & SIZET)
1448 else if (flags & LLONGINT)
1450 else if (flags & LONGINT)
1452 else if (flags & SHORTINT)
1454 else if (flags & CHARINT)
1458 continue; /* no output */
1472 if (flags & LONGINT)
1485 default: /* "%?" prints ?, unless ? is NUL */
1493 * Build the argument table.
1495 if (tablemax >= STATIC_ARG_TBL_SIZE) {
1496 *argtable = (union arg *)
1497 malloc (sizeof (union arg) * (tablemax + 1));
1500 (*argtable) [0].intarg = 0;
1501 for (n = 1; n <= tablemax; n++) {
1502 switch (typetable [n]) {
1503 case T_UNUSED: /* whoops! */
1504 (*argtable) [n].intarg = va_arg (ap, int);
1507 (*argtable) [n].pschararg = va_arg (ap, signed char *);
1510 (*argtable) [n].pshortarg = va_arg (ap, short *);
1513 (*argtable) [n].intarg = va_arg (ap, int);
1516 (*argtable) [n].uintarg = va_arg (ap, unsigned int);
1519 (*argtable) [n].pintarg = va_arg (ap, int *);
1522 (*argtable) [n].longarg = va_arg (ap, long);
1525 (*argtable) [n].ulongarg = va_arg (ap, unsigned long);
1528 (*argtable) [n].plongarg = va_arg (ap, long *);
1531 (*argtable) [n].longlongarg = va_arg (ap, long long);
1534 (*argtable) [n].ulonglongarg = va_arg (ap, unsigned long long);
1537 (*argtable) [n].plonglongarg = va_arg (ap, long long *);
1540 (*argtable) [n].ptrdiffarg = va_arg (ap, ptrdiff_t);
1543 (*argtable) [n].pptrdiffarg = va_arg (ap, ptrdiff_t *);
1546 (*argtable) [n].sizearg = va_arg (ap, size_t);
1549 (*argtable) [n].psizearg = va_arg (ap, size_t *);
1552 (*argtable) [n].intmaxarg = va_arg (ap, intmax_t);
1555 (*argtable) [n].uintmaxarg = va_arg (ap, uintmax_t);
1558 (*argtable) [n].pintmaxarg = va_arg (ap, intmax_t *);
1561 #ifndef NO_FLOATING_POINT
1562 (*argtable) [n].doublearg = va_arg (ap, double);
1566 #ifndef NO_FLOATING_POINT
1567 (*argtable) [n].longdoublearg = va_arg (ap, long double);
1571 (*argtable) [n].pchararg = va_arg (ap, char *);
1574 (*argtable) [n].pvoidarg = va_arg (ap, void *);
1577 (*argtable) [n].wintarg = va_arg (ap, wint_t);
1580 (*argtable) [n].pwchararg = va_arg (ap, wchar_t *);
1585 if ((typetable != NULL) && (typetable != stattypetable))
1590 * Increase the size of the type table.
1593 __grow_type_table (int nextarg, enum typeid **typetable, int *tablesize)
1595 enum typeid *const oldtable = *typetable;
1596 const int oldsize = *tablesize;
1597 enum typeid *newtable;
1598 int n, newsize = oldsize * 2;
1600 if (newsize < nextarg + 1)
1601 newsize = nextarg + 1;
1602 if (oldsize == STATIC_ARG_TBL_SIZE) {
1603 if ((newtable = malloc(newsize * sizeof(enum typeid))) == NULL)
1604 abort(); /* XXX handle better */
1605 bcopy(oldtable, newtable, oldsize * sizeof(enum typeid));
1607 newtable = reallocf(oldtable, newsize * sizeof(enum typeid));
1608 if (newtable == NULL)
1609 abort(); /* XXX handle better */
1611 for (n = oldsize; n < newsize; n++)
1612 newtable[n] = T_UNUSED;
1614 *typetable = newtable;
1615 *tablesize = newsize;
1619 #ifndef NO_FLOATING_POINT
1622 exponent(char *p0, int exp, int fmtch)
1625 char expbuf[MAXEXPDIG];
1635 t = expbuf + MAXEXPDIG;
1638 *--t = to_char(exp % 10);
1639 } while ((exp /= 10) > 9);
1640 *--t = to_char(exp);
1641 for (; t < expbuf + MAXEXPDIG; *p++ = *t++);
1645 * Exponents for decimal floating point conversions
1646 * (%[eEgG]) must be at least two characters long,
1647 * whereas exponents for hexadecimal conversions can
1648 * be only one character long.
1650 if (fmtch == 'e' || fmtch == 'E')
1652 *p++ = to_char(exp);
1656 #endif /* !NO_FLOATING_POINT */