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(size_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";
915 if (ch == 'g' || ch == 'G') {
916 if (expt > -4 && expt <= prec) {
917 /* Make %[gG] smell like %[fF] */
927 * Make %[gG] smell like %[eE], but
928 * trim trailing zeroes if no # flag.
935 expsize = exponent(expstr, expt - 1, expchar);
936 size = expsize + prec;
937 if (prec > 1 || flags & ALT)
940 /* space for digits before decimal point */
945 /* space for decimal pt and following digits */
946 if (prec || flags & ALT)
948 if (grouping && expt > 0) {
949 /* space for thousands' grouping */
950 nseps = nrepeats = 0;
952 while (*grouping != CHAR_MAX) {
953 if (lead <= *grouping)
962 size += nseps + nrepeats;
967 #endif /* !NO_FLOATING_POINT */
970 * Assignment-like behavior is specified if the
971 * value overflows or is otherwise unrepresentable.
972 * C99 says to use `signed char' for %hhn conversions.
974 if (flags & LLONGINT)
975 *GETARG(long long *) = ret;
976 else if (flags & SIZET)
977 *GETARG(ssize_t *) = (ssize_t)ret;
978 else if (flags & PTRDIFFT)
979 *GETARG(ptrdiff_t *) = ret;
980 else if (flags & INTMAXT)
981 *GETARG(intmax_t *) = ret;
982 else if (flags & LONGINT)
983 *GETARG(long *) = ret;
984 else if (flags & SHORTINT)
985 *GETARG(short *) = ret;
986 else if (flags & CHARINT)
987 *GETARG(signed char *) = ret;
989 *GETARG(int *) = ret;
990 continue; /* no output */
995 if (flags & INTMAX_SIZE)
1003 * ``The argument shall be a pointer to void. The
1004 * value of the pointer is converted to a sequence
1005 * of printable characters, in an implementation-
1009 ujval = (uintmax_t)(uintptr_t)GETARG(void *);
1011 xdigs = xdigs_lower;
1012 flags = flags | INTMAXT;
1019 if (flags & LONGINT) {
1022 if (convbuf != NULL)
1024 if ((wcp = GETARG(wchar_t *)) == NULL)
1027 convbuf = __wcsconv(wcp, prec);
1028 if (convbuf == NULL) {
1029 fp->_flags |= __SERR;
1034 } else if ((cp = GETARG(char *)) == NULL)
1038 * can't use strlen; can only look for the
1039 * NUL in the first `prec' characters, and
1040 * strlen() will go further.
1042 char *p = memchr(cp, 0, (size_t)prec);
1058 if (flags & INTMAX_SIZE)
1065 xdigs = xdigs_upper;
1068 xdigs = xdigs_lower;
1070 if (flags & INTMAX_SIZE)
1075 /* leading 0x/X only if non-zero */
1077 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
1081 /* unsigned conversions */
1082 nosign: sign = '\0';
1084 * ``... diouXx conversions ... if a precision is
1085 * specified, the 0 flag will be ignored.''
1088 number: if ((dprec = prec) >= 0)
1092 * ``The result of converting a zero value with an
1093 * explicit precision of zero is no characters.''
1096 * ``The C Standard is clear enough as is. The call
1097 * printf("%#.0o", 0) should print 0.''
1098 * -- Defect Report #151
1101 if (flags & INTMAX_SIZE) {
1102 if (ujval != 0 || prec != 0 ||
1103 (flags & ALT && base == 8))
1104 cp = __ujtoa(ujval, cp, base,
1106 flags & GROUPING, thousands_sep,
1109 if (ulval != 0 || prec != 0 ||
1110 (flags & ALT && base == 8))
1111 cp = __ultoa(ulval, cp, base,
1113 flags & GROUPING, thousands_sep,
1116 size = buf + BUF - cp;
1117 if (size > BUF) /* should never happen */
1120 default: /* "%?" prints ?, unless ? is NUL */
1123 /* pretend it was %c with argument ch */
1132 * All reasonable formats wind up here. At this point, `cp'
1133 * points to a string which (if not flags&LADJUST) should be
1134 * padded out to `width' places. If flags&ZEROPAD, it should
1135 * first be prefixed by any sign or other prefix; otherwise,
1136 * it should be blank padded before the prefix is emitted.
1137 * After any left-hand padding and prefixing, emit zeroes
1138 * required by a decimal [diouxX] precision, then print the
1139 * string proper, then emit zeroes required by any leftover
1140 * floating precision; finally, if LADJUST, pad with blanks.
1142 * Compute actual size, so we know how much to pad.
1143 * size excludes decimal prec; realsz includes it.
1145 realsz = dprec > size ? dprec : size;
1151 prsize = width > realsz ? width : realsz;
1152 if ((unsigned)ret + prsize > INT_MAX) {
1157 /* right-adjusting blank padding */
1158 if ((flags & (LADJUST|ZEROPAD)) == 0)
1159 PAD(width - realsz, blanks);
1165 if (ox[1]) { /* ox[1] is either x, X, or \0 */
1170 /* right-adjusting zero padding */
1171 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1172 PAD(width - realsz, zeroes);
1174 /* leading zeroes from decimal precision */
1175 PAD(dprec - size, zeroes);
1177 /* the string or number proper */
1178 #ifndef NO_FLOATING_POINT
1179 if ((flags & FPT) == 0) {
1181 } else { /* glue together f_p fragments */
1182 if (!expchar) { /* %[fF] or sufficiently short %[gG] */
1185 if (prec || flags & ALT)
1186 PRINT(decimal_point, 1);
1188 /* already handled initial 0's */
1191 PRINTANDPAD(cp, dtoaend, lead, zeroes);
1194 while (nseps>0 || nrepeats>0) {
1201 PRINT(&thousands_sep,
1203 PRINTANDPAD(cp,dtoaend,
1210 if (prec || flags & ALT)
1211 PRINT(decimal_point,1);
1213 PRINTANDPAD(cp, dtoaend, prec, zeroes);
1214 } else { /* %[eE] or sufficiently long %[gG] */
1215 if (prec > 1 || flags & ALT) {
1217 buf[1] = *decimal_point;
1220 PAD(prec - ndig, zeroes);
1223 PRINT(expstr, expsize);
1229 /* left-adjusting padding (always blank) */
1230 if (flags & LADJUST)
1231 PAD(width - realsz, blanks);
1233 /* finally, adjust ret */
1236 FLUSH(); /* copy out the I/O vectors */
1242 #ifndef NO_FLOATING_POINT
1243 if (dtoaresult != NULL)
1244 freedtoa(dtoaresult);
1246 if (convbuf != NULL)
1250 if ((argtable != NULL) && (argtable != statargtable))
1257 * Find all arguments when a positional parameter is encountered. Returns a
1258 * table, indexed by argument number, of pointers to each arguments. The
1259 * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1260 * It will be replaces with a malloc-ed one if it overflows.
1263 __find_arguments (const char *fmt0, va_list ap, union arg **argtable)
1265 char *fmt; /* format string */
1266 int ch; /* character from fmt */
1267 int n, n2; /* handy integer (short term usage) */
1268 char *cp; /* handy char pointer (short term usage) */
1269 int flags; /* flags as above */
1270 int width; /* width from format (%8d), or 0 */
1271 enum typeid *typetable; /* table of types */
1272 enum typeid stattypetable [STATIC_ARG_TBL_SIZE];
1273 int tablesize; /* current size of type table */
1274 int tablemax; /* largest used index in table */
1275 int nextarg; /* 1-based argument index */
1278 * Add an argument type to the table, expanding if necessary.
1280 #define ADDTYPE(type) \
1281 ((nextarg >= tablesize) ? \
1282 __grow_type_table(nextarg, &typetable, &tablesize) : (void)0, \
1283 (nextarg > tablemax) ? tablemax = nextarg : 0, \
1284 typetable[nextarg++] = type)
1287 ((flags&INTMAXT) ? ADDTYPE(T_INTMAXT) : \
1288 ((flags&SIZET) ? ADDTYPE(T_SIZET) : \
1289 ((flags&PTRDIFFT) ? ADDTYPE(T_PTRDIFFT) : \
1290 ((flags&LLONGINT) ? ADDTYPE(T_LLONG) : \
1291 ((flags&LONGINT) ? ADDTYPE(T_LONG) : ADDTYPE(T_INT))))))
1294 ((flags&INTMAXT) ? ADDTYPE(T_UINTMAXT) : \
1295 ((flags&SIZET) ? ADDTYPE(T_SIZET) : \
1296 ((flags&PTRDIFFT) ? ADDTYPE(T_PTRDIFFT) : \
1297 ((flags&LLONGINT) ? ADDTYPE(T_U_LLONG) : \
1298 ((flags&LONGINT) ? ADDTYPE(T_U_LONG) : ADDTYPE(T_U_INT))))))
1301 * Add * arguments to the type array.
1303 #define ADDASTER() \
1306 while (is_digit(*cp)) { \
1307 n2 = 10 * n2 + to_digit(*cp); \
1311 int hold = nextarg; \
1320 typetable = stattypetable;
1321 tablesize = STATIC_ARG_TBL_SIZE;
1324 for (n = 0; n < STATIC_ARG_TBL_SIZE; n++)
1325 typetable[n] = T_UNUSED;
1328 * Scan the format for conversions (`%' character).
1331 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
1335 fmt++; /* skip over '%' */
1341 reswitch: switch (ch) {
1353 if ((ch = *fmt++) == '*') {
1357 while (is_digit(ch)) {
1363 case '1': case '2': case '3': case '4':
1364 case '5': case '6': case '7': case '8': case '9':
1367 n = 10 * n + to_digit(ch);
1369 } while (is_digit(ch));
1376 #ifndef NO_FLOATING_POINT
1382 if (flags & SHORTINT) {
1392 if (flags & LONGINT) {
1399 flags |= LLONGINT; /* not necessarily */
1411 if (flags & LONGINT)
1423 #ifndef NO_FLOATING_POINT
1431 if (flags & LONGDBL)
1432 ADDTYPE(T_LONG_DOUBLE);
1436 #endif /* !NO_FLOATING_POINT */
1438 if (flags & INTMAXT)
1439 ADDTYPE(TP_INTMAXT);
1440 else if (flags & PTRDIFFT)
1441 ADDTYPE(TP_PTRDIFFT);
1442 else if (flags & SIZET)
1444 else if (flags & LLONGINT)
1446 else if (flags & LONGINT)
1448 else if (flags & SHORTINT)
1450 else if (flags & CHARINT)
1454 continue; /* no output */
1468 if (flags & LONGINT)
1481 default: /* "%?" prints ?, unless ? is NUL */
1489 * Build the argument table.
1491 if (tablemax >= STATIC_ARG_TBL_SIZE) {
1492 *argtable = (union arg *)
1493 malloc (sizeof (union arg) * (tablemax + 1));
1496 (*argtable) [0].intarg = 0;
1497 for (n = 1; n <= tablemax; n++) {
1498 switch (typetable [n]) {
1499 case T_UNUSED: /* whoops! */
1500 (*argtable) [n].intarg = va_arg (ap, int);
1503 (*argtable) [n].pschararg = va_arg (ap, signed char *);
1506 (*argtable) [n].pshortarg = va_arg (ap, short *);
1509 (*argtable) [n].intarg = va_arg (ap, int);
1512 (*argtable) [n].uintarg = va_arg (ap, unsigned int);
1515 (*argtable) [n].pintarg = va_arg (ap, int *);
1518 (*argtable) [n].longarg = va_arg (ap, long);
1521 (*argtable) [n].ulongarg = va_arg (ap, unsigned long);
1524 (*argtable) [n].plongarg = va_arg (ap, long *);
1527 (*argtable) [n].longlongarg = va_arg (ap, long long);
1530 (*argtable) [n].ulonglongarg = va_arg (ap, unsigned long long);
1533 (*argtable) [n].plonglongarg = va_arg (ap, long long *);
1536 (*argtable) [n].ptrdiffarg = va_arg (ap, ptrdiff_t);
1539 (*argtable) [n].pptrdiffarg = va_arg (ap, ptrdiff_t *);
1542 (*argtable) [n].sizearg = va_arg (ap, size_t);
1545 (*argtable) [n].psizearg = va_arg (ap, size_t *);
1548 (*argtable) [n].intmaxarg = va_arg (ap, intmax_t);
1551 (*argtable) [n].uintmaxarg = va_arg (ap, uintmax_t);
1554 (*argtable) [n].pintmaxarg = va_arg (ap, intmax_t *);
1557 #ifndef NO_FLOATING_POINT
1558 (*argtable) [n].doublearg = va_arg (ap, double);
1562 #ifndef NO_FLOATING_POINT
1563 (*argtable) [n].longdoublearg = va_arg (ap, long double);
1567 (*argtable) [n].pchararg = va_arg (ap, char *);
1570 (*argtable) [n].pvoidarg = va_arg (ap, void *);
1573 (*argtable) [n].wintarg = va_arg (ap, wint_t);
1576 (*argtable) [n].pwchararg = va_arg (ap, wchar_t *);
1581 if ((typetable != NULL) && (typetable != stattypetable))
1586 * Increase the size of the type table.
1589 __grow_type_table (int nextarg, enum typeid **typetable, int *tablesize)
1591 enum typeid *const oldtable = *typetable;
1592 const int oldsize = *tablesize;
1593 enum typeid *newtable;
1594 int n, newsize = oldsize * 2;
1596 if (newsize < nextarg + 1)
1597 newsize = nextarg + 1;
1598 if (oldsize == STATIC_ARG_TBL_SIZE) {
1599 if ((newtable = malloc(newsize * sizeof(enum typeid))) == NULL)
1600 abort(); /* XXX handle better */
1601 bcopy(oldtable, newtable, oldsize * sizeof(enum typeid));
1603 newtable = reallocf(oldtable, newsize * sizeof(enum typeid));
1604 if (newtable == NULL)
1605 abort(); /* XXX handle better */
1607 for (n = oldsize; n < newsize; n++)
1608 newtable[n] = T_UNUSED;
1610 *typetable = newtable;
1611 *tablesize = newsize;
1615 #ifndef NO_FLOATING_POINT
1618 exponent(char *p0, int exp, int fmtch)
1621 char expbuf[MAXEXPDIG];
1631 t = expbuf + MAXEXPDIG;
1634 *--t = to_char(exp % 10);
1635 } while ((exp /= 10) > 9);
1636 *--t = to_char(exp);
1637 for (; t < expbuf + MAXEXPDIG; *p++ = *t++);
1641 * Exponents for decimal floating point conversions
1642 * (%[eEgG]) must be at least two characters long,
1643 * whereas exponents for hexadecimal conversions can
1644 * be only one character long.
1646 if (fmtch == 'e' || fmtch == 'E')
1648 *p++ = to_char(exp);
1652 #endif /* !NO_FLOATING_POINT */