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 * 4. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 #if defined(LIBC_SCCS) && !defined(lint)
34 static char sccsid[] = "@(#)vfprintf.c 8.1 (Berkeley) 6/4/93";
35 #endif /* LIBC_SCCS and not lint */
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
40 * Actual printf innards.
42 * This code is large and complicated...
45 #include "namespace.h"
46 #include <sys/types.h>
60 #include "un-namespace.h"
62 #include "libc_private.h"
71 long long longlongarg;
72 unsigned long long ulonglongarg;
79 signed char *pschararg;
83 long long *plonglongarg;
84 ptrdiff_t *pptrdiffarg;
87 #ifndef NO_FLOATING_POINT
89 long double longdoublearg;
96 * Type ids for argument type table.
99 T_UNUSED, TP_SHORT, T_INT, T_U_INT, TP_INT,
100 T_LONG, T_U_LONG, TP_LONG, T_LLONG, T_U_LLONG, TP_LLONG,
101 T_PTRDIFFT, TP_PTRDIFFT, T_SIZET, TP_SIZET,
102 T_INTMAXT, T_UINTMAXT, TP_INTMAXT, TP_VOID, TP_CHAR, TP_SCHAR,
103 T_DOUBLE, T_LONG_DOUBLE, T_WINT, TP_WCHAR
106 static int __sprint(FILE *, struct __suio *);
107 static int __sbprintf(FILE *, const char *, va_list) __printflike(2, 0);
108 static char *__ujtoa(uintmax_t, char *, int, int, const char *, int, char,
110 static char *__ultoa(u_long, char *, int, int, const char *, int, char,
112 static char *__wcsconv(wchar_t *, int);
113 static void __find_arguments(const char *, va_list, union arg **);
114 static void __grow_type_table(int, enum typeid **, int *);
117 * Flush out all the vectors defined by the given uio,
118 * then reset it so that it can be reused.
121 __sprint(FILE *fp, struct __suio *uio)
125 if (uio->uio_resid == 0) {
129 err = __sfvwrite(fp, uio);
136 * Helper function for `fprintf to unbuffered unix file': creates a
137 * temporary buffer. We only work on write-only files; this avoids
138 * worries about ungetc buffers and so forth.
141 __sbprintf(FILE *fp, const char *fmt, va_list ap)
145 unsigned char buf[BUFSIZ];
147 /* copy the important variables */
148 fake._flags = fp->_flags & ~__SNBF;
149 fake._file = fp->_file;
150 fake._cookie = fp->_cookie;
151 fake._write = fp->_write;
152 fake._extra = fp->_extra;
154 /* set up the buffer */
155 fake._bf._base = fake._p = buf;
156 fake._bf._size = fake._w = sizeof(buf);
157 fake._lbfsize = 0; /* not actually used, but Just In Case */
159 /* do the work, then copy any error status */
160 ret = __vfprintf(&fake, fmt, ap);
161 if (ret >= 0 && __fflush(&fake))
163 if (fake._flags & __SERR)
164 fp->_flags |= __SERR;
169 * Macros for converting digits to letters and vice versa
171 #define to_digit(c) ((c) - '0')
172 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
173 #define to_char(n) ((n) + '0')
176 * Convert an unsigned long to ASCII for printf purposes, returning
177 * a pointer to the first character of the string representation.
178 * Octal numbers can be forced to have a leading zero; hex numbers
179 * use the given digits.
182 __ultoa(u_long val, char *endp, int base, int octzero, const char *xdigs,
183 int needgrp, char thousep, const char *grp)
190 * Handle the three cases separately, in the hope of getting
191 * better/faster code.
195 if (val < 10) { /* many numbers are 1 digit */
196 *--cp = to_char(val);
201 * On many machines, unsigned arithmetic is harder than
202 * signed arithmetic, so we do at most one unsigned mod and
203 * divide; this is sufficient to reduce the range of
204 * the incoming value to where signed arithmetic works.
206 if (val > LONG_MAX) {
207 *--cp = to_char(val % 10);
213 *--cp = to_char(sval % 10);
216 * If (*grp == CHAR_MAX) then no more grouping
217 * should be performed.
219 if (needgrp && ndig == *grp && *grp != CHAR_MAX
224 * If (*(grp+1) == '\0') then we have to
225 * use *grp character (last grouping rule)
228 if (*(grp+1) != '\0')
237 *--cp = to_char(val & 7);
240 if (octzero && *cp != '0')
246 *--cp = xdigs[val & 15];
257 /* Identical to __ultoa, but for intmax_t. */
259 __ujtoa(uintmax_t val, char *endp, int base, int octzero, const char *xdigs,
260 int needgrp, char thousep, const char *grp)
266 /* quick test for small values; __ultoa is typically much faster */
267 /* (perhaps instead we should run until small, then call __ultoa?) */
268 if (val <= ULONG_MAX)
269 return (__ultoa((u_long)val, endp, base, octzero, xdigs,
270 needgrp, thousep, grp));
274 *--cp = to_char(val % 10);
278 if (val > INTMAX_MAX) {
279 *--cp = to_char(val % 10);
285 *--cp = to_char(sval % 10);
288 * If (*grp == CHAR_MAX) then no more grouping
289 * should be performed.
291 if (needgrp && *grp != CHAR_MAX && ndig == *grp
296 * If (*(grp+1) == '\0') then we have to
297 * use *grp character (last grouping rule)
300 if (*(grp+1) != '\0')
309 *--cp = to_char(val & 7);
312 if (octzero && *cp != '0')
318 *--cp = xdigs[val & 15];
330 * Convert a wide character string argument for the %ls format to a multibyte
331 * string representation. If not -1, prec specifies the maximum number of
332 * bytes to output, and also means that we can't assume that the wide char.
333 * string ends is null-terminated.
336 __wcsconv(wchar_t *wcsarg, int prec)
338 static const mbstate_t initial;
340 char buf[MB_LEN_MAX];
345 /* Allocate space for the maximum number of bytes we could output. */
349 nbytes = wcsrtombs(NULL, (const wchar_t **)&p, 0, &mbs);
350 if (nbytes == (size_t)-1)
354 * Optimisation: if the output precision is small enough,
355 * just allocate enough memory for the maximum instead of
356 * scanning the string.
365 clen = wcrtomb(buf, *p++, &mbs);
366 if (clen == 0 || clen == (size_t)-1 ||
367 nbytes + clen > prec)
373 if ((convbuf = malloc(nbytes + 1)) == NULL)
376 /* Fill the output buffer. */
379 if ((nbytes = wcsrtombs(convbuf, (const wchar_t **)&p,
380 nbytes, &mbs)) == (size_t)-1) {
384 convbuf[nbytes] = '\0';
392 vfprintf(FILE * __restrict fp, const char * __restrict fmt0, va_list ap)
398 ret = __vfprintf(fp, fmt0, ap);
403 #ifndef NO_FLOATING_POINT
406 #define freedtoa __freedtoa
415 static int exponent(char *, int, int);
417 #endif /* !NO_FLOATING_POINT */
420 * The size of the buffer we use as scratch space for integer
421 * conversions, among other things. Technically, we would need the
422 * most space for base 10 conversions with thousands' grouping
423 * characters between each pair of digits. 100 bytes is a
424 * conservative overestimate even for a 128-bit uintmax_t.
428 #define STATIC_ARG_TBL_SIZE 8 /* Size of static argument table. */
431 * Flags used during conversion.
433 #define ALT 0x001 /* alternate form */
434 #define LADJUST 0x004 /* left adjustment */
435 #define LONGDBL 0x008 /* long double */
436 #define LONGINT 0x010 /* long integer */
437 #define LLONGINT 0x020 /* long long integer */
438 #define SHORTINT 0x040 /* short integer */
439 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
440 #define FPT 0x100 /* Floating point number */
441 #define GROUPING 0x200 /* use grouping ("'" flag) */
442 /* C99 additional size modifiers: */
443 #define SIZET 0x400 /* size_t */
444 #define PTRDIFFT 0x800 /* ptrdiff_t */
445 #define INTMAXT 0x1000 /* intmax_t */
446 #define CHARINT 0x2000 /* print char using int format */
449 * Non-MT-safe version
452 __vfprintf(FILE *fp, const char *fmt0, va_list ap)
454 char *fmt; /* format string */
455 int ch; /* character from fmt */
456 int n, n2; /* handy integer (short term usage) */
457 char *cp; /* handy char pointer (short term usage) */
458 struct __siov *iovp; /* for PRINT macro */
459 int flags; /* flags as above */
460 int ret; /* return value accumulator */
461 int width; /* width from format (%8d), or 0 */
462 int prec; /* precision from format; <0 for N/A */
463 char sign; /* sign prefix (' ', '+', '-', or \0) */
464 char thousands_sep; /* locale specific thousands separator */
465 const char *grouping; /* locale specific numeric grouping rules */
467 if (__use_xprintf == 0 && getenv("USE_XPRINTF"))
469 if (__use_xprintf > 0)
470 return (__xvprintf(fp, fmt0, ap));
472 #ifndef NO_FLOATING_POINT
474 * We can decompose the printed representation of floating
475 * point numbers into several parts, some of which may be empty:
477 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
480 * A: 'sign' holds this value if present; '\0' otherwise
481 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
482 * C: cp points to the string MMMNNN. Leading and trailing
483 * zeros are not in the string and must be added.
484 * D: expchar holds this character; '\0' if no exponent, e.g. %f
485 * F: at least two digits for decimal, at least one digit for hex
487 char *decimal_point; /* locale specific decimal point */
488 int signflag; /* true if float is negative */
489 union { /* floating point arguments %[aAeEfFgG] */
493 int expt; /* integer value of exponent */
494 char expchar; /* exponent character: [eEpP\0] */
495 char *dtoaend; /* pointer to end of converted digits */
496 int expsize; /* character count for expstr */
497 int lead; /* sig figs before decimal or group sep */
498 int ndig; /* actual number of digits returned by dtoa */
499 char expstr[MAXEXPDIG+2]; /* buffer for exponent string: e+ZZZ */
500 char *dtoaresult; /* buffer allocated by dtoa */
501 int nseps; /* number of group separators with ' */
502 int nrepeats; /* number of repeats of the last group */
504 u_long ulval; /* integer arguments %[diouxX] */
505 uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */
506 int base; /* base for [diouxX] conversion */
507 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
508 int realsz; /* field size expanded by dprec, sign, etc */
509 int size; /* size of converted field or string */
510 int prsize; /* max size of printed field */
511 const char *xdigs; /* digits for %[xX] conversion */
513 struct __suio uio; /* output information: summary */
514 struct __siov iov[NIOV];/* ... and individual io vectors */
515 char buf[BUF]; /* buffer with space for digits of uintmax_t */
516 char ox[2]; /* space for 0x; ox[1] is either x, X, or \0 */
517 union arg *argtable; /* args, built due to positional arg */
518 union arg statargtable [STATIC_ARG_TBL_SIZE];
519 int nextarg; /* 1-based argument index */
520 va_list orgap; /* original argument pointer */
521 char *convbuf; /* wide to multibyte conversion result */
524 * Choose PADSIZE to trade efficiency vs. size. If larger printf
525 * fields occur frequently, increase PADSIZE and make the initialisers
528 #define PADSIZE 16 /* pad chunk size */
529 static char blanks[PADSIZE] =
530 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
531 static char zeroes[PADSIZE] =
532 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
534 static const char xdigs_lower[16] = "0123456789abcdef";
535 static const char xdigs_upper[16] = "0123456789ABCDEF";
538 * BEWARE, these `goto error' on error, and PAD uses `n'.
540 #define PRINT(ptr, len) { \
541 iovp->iov_base = (ptr); \
542 iovp->iov_len = (len); \
543 uio.uio_resid += (len); \
545 if (++uio.uio_iovcnt >= NIOV) { \
546 if (__sprint(fp, &uio)) \
551 #define PAD(howmany, with) { \
552 if ((n = (howmany)) > 0) { \
553 while (n > PADSIZE) { \
554 PRINT(with, PADSIZE); \
560 #define PRINTANDPAD(p, ep, len, with) do { \
566 PAD((len) - (n2 > 0 ? n2 : 0), (with)); \
569 if (uio.uio_resid && __sprint(fp, &uio)) \
571 uio.uio_iovcnt = 0; \
576 * Get the argument indexed by nextarg. If the argument table is
577 * built, use it to get the argument. If its not, get the next
578 * argument (and arguments must be gotten sequentially).
580 #define GETARG(type) \
581 ((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
582 (nextarg++, va_arg(ap, type)))
585 * To extend shorts properly, we need both signed and unsigned
586 * argument extraction methods.
589 (flags&LONGINT ? GETARG(long) : \
590 flags&SHORTINT ? (long)(short)GETARG(int) : \
591 flags&CHARINT ? (long)(signed char)GETARG(int) : \
594 (flags&LONGINT ? GETARG(u_long) : \
595 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
596 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
597 (u_long)GETARG(u_int))
598 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
600 (flags&INTMAXT ? GETARG(intmax_t) : \
601 flags&SIZET ? (intmax_t)GETARG(ssize_t) : \
602 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
603 (intmax_t)GETARG(long long))
605 (flags&INTMAXT ? GETARG(uintmax_t) : \
606 flags&SIZET ? (uintmax_t)GETARG(size_t) : \
607 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
608 (uintmax_t)GETARG(unsigned long long))
611 * Get * arguments, including the form *nn$. Preserve the nextarg
612 * that the argument can be gotten once the type is determined.
614 #define GETASTER(val) \
617 while (is_digit(*cp)) { \
618 n2 = 10 * n2 + to_digit(*cp); \
622 int hold = nextarg; \
623 if (argtable == NULL) { \
624 argtable = statargtable; \
625 __find_arguments (fmt0, orgap, &argtable); \
628 val = GETARG (int); \
632 val = GETARG (int); \
636 thousands_sep = '\0';
639 #ifndef NO_FLOATING_POINT
641 decimal_point = localeconv()->decimal_point;
643 /* sorry, fprintf(read_only_file, "") returns EOF, not 0 */
644 if (prepwrite(fp) != 0)
647 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
648 if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
650 return (__sbprintf(fp, fmt0, ap));
656 uio.uio_iov = iovp = iov;
662 * Scan the format for conversions (`%' character).
665 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
667 if ((n = fmt - cp) != 0) {
668 if ((unsigned)ret + n > INT_MAX) {
677 fmt++; /* skip over '%' */
687 reswitch: switch (ch) {
690 * ``If the space and + flags both appear, the space
691 * flag will be ignored.''
702 * ``A negative field width argument is taken as a
703 * - flag followed by a positive field width.''
705 * They don't exclude field widths read from args.
720 thousands_sep = *(localeconv()->thousands_sep);
721 grouping = localeconv()->grouping;
724 if ((ch = *fmt++) == '*') {
729 while (is_digit(ch)) {
730 prec = 10 * prec + to_digit(ch);
736 * ``Note that 0 is taken as a flag, not as the
737 * beginning of a field width.''
742 case '1': case '2': case '3': case '4':
743 case '5': case '6': case '7': case '8': case '9':
746 n = 10 * n + to_digit(ch);
748 } while (is_digit(ch));
751 if (argtable == NULL) {
752 argtable = statargtable;
753 __find_arguments (fmt0, orgap,
760 #ifndef NO_FLOATING_POINT
766 if (flags & SHORTINT) {
776 if (flags & LONGINT) {
783 flags |= LLONGINT; /* not necessarily */
795 if (flags & LONGINT) {
796 static const mbstate_t initial;
801 mbseqlen = wcrtomb(cp = buf,
802 (wchar_t)GETARG(wint_t), &mbs);
803 if (mbseqlen == (size_t)-1) {
804 fp->_flags |= __SERR;
807 size = (int)mbseqlen;
809 *(cp = buf) = GETARG(int);
819 if (flags & INTMAX_SIZE) {
821 if ((intmax_t)ujval < 0) {
827 if ((long)ulval < 0) {
834 #ifndef NO_FLOATING_POINT
848 if (dtoaresult != NULL)
849 freedtoa(dtoaresult);
850 if (flags & LONGDBL) {
851 fparg.ldbl = GETARG(long double);
853 __hldtoa(fparg.ldbl, xdigs, prec,
854 &expt, &signflag, &dtoaend);
856 fparg.dbl = GETARG(double);
858 __hdtoa(fparg.dbl, xdigs, prec,
859 &expt, &signflag, &dtoaend);
869 if (prec < 0) /* account for digit before decpt */
880 expchar = ch - ('g' - 'e');
886 if (dtoaresult != NULL)
887 freedtoa(dtoaresult);
888 if (flags & LONGDBL) {
889 fparg.ldbl = GETARG(long double);
891 __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
892 &expt, &signflag, &dtoaend);
894 fparg.dbl = GETARG(double);
896 dtoa(fparg.dbl, expchar ? 2 : 3, prec,
897 &expt, &signflag, &dtoaend);
904 if (expt == INT_MAX) { /* inf or nan */
906 cp = (ch >= 'a') ? "nan" : "NAN";
909 cp = (ch >= 'a') ? "inf" : "INF";
916 if (ch == 'g' || ch == 'G') {
917 if (expt > -4 && expt <= prec) {
918 /* Make %[gG] smell like %[fF] */
928 * Make %[gG] smell like %[eE], but
929 * trim trailing zeroes if no # flag.
936 expsize = exponent(expstr, expt - 1, expchar);
937 size = expsize + prec;
938 if (prec > 1 || flags & ALT)
941 /* space for digits before decimal point */
946 /* space for decimal pt and following digits */
947 if (prec || flags & ALT)
949 if (grouping && expt > 0) {
950 /* space for thousands' grouping */
951 nseps = nrepeats = 0;
953 while (*grouping != CHAR_MAX) {
954 if (lead <= *grouping)
963 size += nseps + nrepeats;
968 #endif /* !NO_FLOATING_POINT */
971 * Assignment-like behavior is specified if the
972 * value overflows or is otherwise unrepresentable.
973 * C99 says to use `signed char' for %hhn conversions.
975 if (flags & LLONGINT)
976 *GETARG(long long *) = ret;
977 else if (flags & SIZET)
978 *GETARG(ssize_t *) = (ssize_t)ret;
979 else if (flags & PTRDIFFT)
980 *GETARG(ptrdiff_t *) = ret;
981 else if (flags & INTMAXT)
982 *GETARG(intmax_t *) = ret;
983 else if (flags & LONGINT)
984 *GETARG(long *) = ret;
985 else if (flags & SHORTINT)
986 *GETARG(short *) = ret;
987 else if (flags & CHARINT)
988 *GETARG(signed char *) = ret;
990 *GETARG(int *) = ret;
991 continue; /* no output */
996 if (flags & INTMAX_SIZE)
1004 * ``The argument shall be a pointer to void. The
1005 * value of the pointer is converted to a sequence
1006 * of printable characters, in an implementation-
1010 ujval = (uintmax_t)(uintptr_t)GETARG(void *);
1012 xdigs = xdigs_lower;
1013 flags = flags | INTMAXT;
1020 if (flags & LONGINT) {
1023 if (convbuf != NULL)
1025 if ((wcp = GETARG(wchar_t *)) == NULL)
1028 convbuf = __wcsconv(wcp, prec);
1029 if (convbuf == NULL) {
1030 fp->_flags |= __SERR;
1035 } else if ((cp = GETARG(char *)) == NULL)
1039 * can't use strlen; can only look for the
1040 * NUL in the first `prec' characters, and
1041 * strlen() will go further.
1043 char *p = memchr(cp, 0, (size_t)prec);
1059 if (flags & INTMAX_SIZE)
1066 xdigs = xdigs_upper;
1069 xdigs = xdigs_lower;
1071 if (flags & INTMAX_SIZE)
1076 /* leading 0x/X only if non-zero */
1078 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
1082 /* unsigned conversions */
1083 nosign: sign = '\0';
1085 * ``... diouXx conversions ... if a precision is
1086 * specified, the 0 flag will be ignored.''
1089 number: if ((dprec = prec) >= 0)
1093 * ``The result of converting a zero value with an
1094 * explicit precision of zero is no characters.''
1097 * ``The C Standard is clear enough as is. The call
1098 * printf("%#.0o", 0) should print 0.''
1099 * -- Defect Report #151
1102 if (flags & INTMAX_SIZE) {
1103 if (ujval != 0 || prec != 0 ||
1104 (flags & ALT && base == 8))
1105 cp = __ujtoa(ujval, cp, base,
1107 flags & GROUPING, thousands_sep,
1110 if (ulval != 0 || prec != 0 ||
1111 (flags & ALT && base == 8))
1112 cp = __ultoa(ulval, cp, base,
1114 flags & GROUPING, thousands_sep,
1117 size = buf + BUF - cp;
1118 if (size > BUF) /* should never happen */
1121 default: /* "%?" prints ?, unless ? is NUL */
1124 /* pretend it was %c with argument ch */
1133 * All reasonable formats wind up here. At this point, `cp'
1134 * points to a string which (if not flags&LADJUST) should be
1135 * padded out to `width' places. If flags&ZEROPAD, it should
1136 * first be prefixed by any sign or other prefix; otherwise,
1137 * it should be blank padded before the prefix is emitted.
1138 * After any left-hand padding and prefixing, emit zeroes
1139 * required by a decimal [diouxX] precision, then print the
1140 * string proper, then emit zeroes required by any leftover
1141 * floating precision; finally, if LADJUST, pad with blanks.
1143 * Compute actual size, so we know how much to pad.
1144 * size excludes decimal prec; realsz includes it.
1146 realsz = dprec > size ? dprec : size;
1152 prsize = width > realsz ? width : realsz;
1153 if ((unsigned)ret + prsize > INT_MAX) {
1158 /* right-adjusting blank padding */
1159 if ((flags & (LADJUST|ZEROPAD)) == 0)
1160 PAD(width - realsz, blanks);
1166 if (ox[1]) { /* ox[1] is either x, X, or \0 */
1171 /* right-adjusting zero padding */
1172 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1173 PAD(width - realsz, zeroes);
1175 /* leading zeroes from decimal precision */
1176 PAD(dprec - size, zeroes);
1178 /* the string or number proper */
1179 #ifndef NO_FLOATING_POINT
1180 if ((flags & FPT) == 0) {
1182 } else { /* glue together f_p fragments */
1183 if (!expchar) { /* %[fF] or sufficiently short %[gG] */
1186 if (prec || flags & ALT)
1187 PRINT(decimal_point, 1);
1189 /* already handled initial 0's */
1192 PRINTANDPAD(cp, dtoaend, lead, zeroes);
1195 while (nseps>0 || nrepeats>0) {
1202 PRINT(&thousands_sep,
1204 PRINTANDPAD(cp,dtoaend,
1211 if (prec || flags & ALT)
1212 PRINT(decimal_point,1);
1214 PRINTANDPAD(cp, dtoaend, prec, zeroes);
1215 } else { /* %[eE] or sufficiently long %[gG] */
1216 if (prec > 1 || flags & ALT) {
1218 buf[1] = *decimal_point;
1221 PAD(prec - ndig, zeroes);
1224 PRINT(expstr, expsize);
1230 /* left-adjusting padding (always blank) */
1231 if (flags & LADJUST)
1232 PAD(width - realsz, blanks);
1234 /* finally, adjust ret */
1237 FLUSH(); /* copy out the I/O vectors */
1243 #ifndef NO_FLOATING_POINT
1244 if (dtoaresult != NULL)
1245 freedtoa(dtoaresult);
1247 if (convbuf != NULL)
1251 if ((argtable != NULL) && (argtable != statargtable))
1258 * Find all arguments when a positional parameter is encountered. Returns a
1259 * table, indexed by argument number, of pointers to each arguments. The
1260 * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1261 * It will be replaces with a malloc-ed one if it overflows.
1264 __find_arguments (const char *fmt0, va_list ap, union arg **argtable)
1266 char *fmt; /* format string */
1267 int ch; /* character from fmt */
1268 int n, n2; /* handy integer (short term usage) */
1269 char *cp; /* handy char pointer (short term usage) */
1270 int flags; /* flags as above */
1271 int width; /* width from format (%8d), or 0 */
1272 enum typeid *typetable; /* table of types */
1273 enum typeid stattypetable [STATIC_ARG_TBL_SIZE];
1274 int tablesize; /* current size of type table */
1275 int tablemax; /* largest used index in table */
1276 int nextarg; /* 1-based argument index */
1279 * Add an argument type to the table, expanding if necessary.
1281 #define ADDTYPE(type) \
1282 ((nextarg >= tablesize) ? \
1283 __grow_type_table(nextarg, &typetable, &tablesize) : (void)0, \
1284 (nextarg > tablemax) ? tablemax = nextarg : 0, \
1285 typetable[nextarg++] = type)
1288 ((flags&INTMAXT) ? ADDTYPE(T_INTMAXT) : \
1289 ((flags&SIZET) ? ADDTYPE(T_SIZET) : \
1290 ((flags&PTRDIFFT) ? ADDTYPE(T_PTRDIFFT) : \
1291 ((flags&LLONGINT) ? ADDTYPE(T_LLONG) : \
1292 ((flags&LONGINT) ? ADDTYPE(T_LONG) : ADDTYPE(T_INT))))))
1295 ((flags&INTMAXT) ? ADDTYPE(T_UINTMAXT) : \
1296 ((flags&SIZET) ? ADDTYPE(T_SIZET) : \
1297 ((flags&PTRDIFFT) ? ADDTYPE(T_PTRDIFFT) : \
1298 ((flags&LLONGINT) ? ADDTYPE(T_U_LLONG) : \
1299 ((flags&LONGINT) ? ADDTYPE(T_U_LONG) : ADDTYPE(T_U_INT))))))
1302 * Add * arguments to the type array.
1304 #define ADDASTER() \
1307 while (is_digit(*cp)) { \
1308 n2 = 10 * n2 + to_digit(*cp); \
1312 int hold = nextarg; \
1321 typetable = stattypetable;
1322 tablesize = STATIC_ARG_TBL_SIZE;
1325 for (n = 0; n < STATIC_ARG_TBL_SIZE; n++)
1326 typetable[n] = T_UNUSED;
1329 * Scan the format for conversions (`%' character).
1332 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
1336 fmt++; /* skip over '%' */
1342 reswitch: switch (ch) {
1354 if ((ch = *fmt++) == '*') {
1358 while (is_digit(ch)) {
1364 case '1': case '2': case '3': case '4':
1365 case '5': case '6': case '7': case '8': case '9':
1368 n = 10 * n + to_digit(ch);
1370 } while (is_digit(ch));
1377 #ifndef NO_FLOATING_POINT
1383 if (flags & SHORTINT) {
1393 if (flags & LONGINT) {
1400 flags |= LLONGINT; /* not necessarily */
1412 if (flags & LONGINT)
1424 #ifndef NO_FLOATING_POINT
1432 if (flags & LONGDBL)
1433 ADDTYPE(T_LONG_DOUBLE);
1437 #endif /* !NO_FLOATING_POINT */
1439 if (flags & INTMAXT)
1440 ADDTYPE(TP_INTMAXT);
1441 else if (flags & PTRDIFFT)
1442 ADDTYPE(TP_PTRDIFFT);
1443 else if (flags & SIZET)
1445 else if (flags & LLONGINT)
1447 else if (flags & LONGINT)
1449 else if (flags & SHORTINT)
1451 else if (flags & CHARINT)
1455 continue; /* no output */
1469 if (flags & LONGINT)
1482 default: /* "%?" prints ?, unless ? is NUL */
1490 * Build the argument table.
1492 if (tablemax >= STATIC_ARG_TBL_SIZE) {
1493 *argtable = (union arg *)
1494 malloc (sizeof (union arg) * (tablemax + 1));
1497 (*argtable) [0].intarg = 0;
1498 for (n = 1; n <= tablemax; n++) {
1499 switch (typetable [n]) {
1500 case T_UNUSED: /* whoops! */
1501 (*argtable) [n].intarg = va_arg (ap, int);
1504 (*argtable) [n].pschararg = va_arg (ap, signed char *);
1507 (*argtable) [n].pshortarg = va_arg (ap, short *);
1510 (*argtable) [n].intarg = va_arg (ap, int);
1513 (*argtable) [n].uintarg = va_arg (ap, unsigned int);
1516 (*argtable) [n].pintarg = va_arg (ap, int *);
1519 (*argtable) [n].longarg = va_arg (ap, long);
1522 (*argtable) [n].ulongarg = va_arg (ap, unsigned long);
1525 (*argtable) [n].plongarg = va_arg (ap, long *);
1528 (*argtable) [n].longlongarg = va_arg (ap, long long);
1531 (*argtable) [n].ulonglongarg = va_arg (ap, unsigned long long);
1534 (*argtable) [n].plonglongarg = va_arg (ap, long long *);
1537 (*argtable) [n].ptrdiffarg = va_arg (ap, ptrdiff_t);
1540 (*argtable) [n].pptrdiffarg = va_arg (ap, ptrdiff_t *);
1543 (*argtable) [n].sizearg = va_arg (ap, size_t);
1546 (*argtable) [n].psizearg = va_arg (ap, size_t *);
1549 (*argtable) [n].intmaxarg = va_arg (ap, intmax_t);
1552 (*argtable) [n].uintmaxarg = va_arg (ap, uintmax_t);
1555 (*argtable) [n].pintmaxarg = va_arg (ap, intmax_t *);
1558 #ifndef NO_FLOATING_POINT
1559 (*argtable) [n].doublearg = va_arg (ap, double);
1563 #ifndef NO_FLOATING_POINT
1564 (*argtable) [n].longdoublearg = va_arg (ap, long double);
1568 (*argtable) [n].pchararg = va_arg (ap, char *);
1571 (*argtable) [n].pvoidarg = va_arg (ap, void *);
1574 (*argtable) [n].wintarg = va_arg (ap, wint_t);
1577 (*argtable) [n].pwchararg = va_arg (ap, wchar_t *);
1582 if ((typetable != NULL) && (typetable != stattypetable))
1587 * Increase the size of the type table.
1590 __grow_type_table (int nextarg, enum typeid **typetable, int *tablesize)
1592 enum typeid *const oldtable = *typetable;
1593 const int oldsize = *tablesize;
1594 enum typeid *newtable;
1595 int n, newsize = oldsize * 2;
1597 if (newsize < nextarg + 1)
1598 newsize = nextarg + 1;
1599 if (oldsize == STATIC_ARG_TBL_SIZE) {
1600 if ((newtable = malloc(newsize * sizeof(enum typeid))) == NULL)
1601 abort(); /* XXX handle better */
1602 bcopy(oldtable, newtable, oldsize * sizeof(enum typeid));
1604 newtable = reallocf(oldtable, newsize * sizeof(enum typeid));
1605 if (newtable == NULL)
1606 abort(); /* XXX handle better */
1608 for (n = oldsize; n < newsize; n++)
1609 newtable[n] = T_UNUSED;
1611 *typetable = newtable;
1612 *tablesize = newsize;
1616 #ifndef NO_FLOATING_POINT
1619 exponent(char *p0, int exp, int fmtch)
1622 char expbuf[MAXEXPDIG];
1632 t = expbuf + MAXEXPDIG;
1635 *--t = to_char(exp % 10);
1636 } while ((exp /= 10) > 9);
1637 *--t = to_char(exp);
1638 for (; t < expbuf + MAXEXPDIG; *p++ = *t++);
1642 * Exponents for decimal floating point conversions
1643 * (%[eEgG]) must be at least two characters long,
1644 * whereas exponents for hexadecimal conversions can
1645 * be only one character long.
1647 if (fmtch == 'e' || fmtch == 'E')
1649 *p++ = to_char(exp);
1653 #endif /* !NO_FLOATING_POINT */