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
36 * @(#)vfprintf.c 8.1 (Berkeley) 6/4/93
37 * $FreeBSD: src/lib/libc/stdio/vfprintf.c,v 1.34 2001/12/13 19:45:41 phantom Exp $
38 * $DragonFly: src/lib/libc/stdio/vfprintf.c,v 1.16 2006/07/05 15:04:54 joerg Exp $
42 * Actual printf innards.
44 * This code is large and complicated...
47 #include "namespace.h"
48 #include <sys/types.h>
61 #include "un-namespace.h"
63 #include "libc_private.h"
65 #include "priv_stdio.h"
67 /* Borrowed from sys/systm.h, which is _KERNEL-only: */
68 #define CTASSERT(x) _CTASSERT(x, __LINE__)
69 #define _CTASSERT(x, y) __CTASSERT(x, y)
70 #define __CTASSERT(x, y) typedef char __assert ## y[(x) ? 1 : -1]
72 /* This code assumes that a quad_t can fit in a long long: */
73 CTASSERT(sizeof(quad_t) == sizeof(long long));
79 unsigned long ulongarg;
80 long long longlongarg;
81 unsigned long long ulonglongarg;
88 signed char *pschararg;
92 long long *plonglongarg;
93 ptrdiff_t *pptrdiffarg;
96 #ifndef NO_FLOATING_POINT
98 long double longdoublearg;
105 * Type ids for argument type table.
108 T_UNUSED, TP_SHORT, T_INT, T_U_INT, TP_INT,
109 T_LONG, T_U_LONG, TP_LONG, T_LLONG, T_U_LLONG, TP_LLONG,
110 T_PTRDIFFT, TP_PTRDIFFT, T_SIZET, TP_SIZET,
111 T_INTMAXT, T_UINTMAXT, TP_INTMAXT, TP_VOID, TP_CHAR, TP_SCHAR,
112 T_DOUBLE, T_LONG_DOUBLE, T_WINT, TP_WCHAR
115 static int __sprint(FILE *, struct __suio *);
116 static int __sbprintf(FILE *, const char *, va_list) __printflike(2, 0);
117 static char * __ujtoa(uintmax_t, char *, int, int, const char *, int,
119 static char * __ultoa(u_long, char *, int, int, const char *, int,
121 static void __find_arguments(const char *, va_list, union arg **);
122 static void __grow_type_table(int, enum typeid **, int *);
125 * Flush out all the vectors defined by the given uio,
126 * then reset it so that it can be reused.
129 __sprint(FILE *fp, struct __suio *uio)
133 if (uio->uio_resid == 0) {
137 err = __sfvwrite(fp, uio);
144 * Helper function for `fprintf to unbuffered unix file': creates a
145 * temporary buffer. We only work on write-only files; this avoids
146 * worries about ungetc buffers and so forth.
149 __sbprintf(FILE *fp, const char *fmt, va_list ap)
153 unsigned char buf[BUFSIZ];
155 /* copy the important variables */
156 fake.pub._flags = fp->pub._flags & ~__SNBF;
157 fake.pub._fileno = fp->pub._fileno;
158 fake._cookie = fp->_cookie;
159 fake._write = fp->_write;
162 fake.fl_mutex = fp->fl_mutex;
163 fake.fl_owner = fp->fl_owner;
164 fake.fl_count = fp->fl_count;
165 memset(WCIO_GET(&fake), 0, sizeof(struct wchar_io_data));
167 /* set up the buffer */
168 fake._bf._base = fake.pub._p = buf;
169 fake._bf._size = fake.pub._w = sizeof(buf);
170 fake.pub._lbfsize = 0; /* not actually used, but Just In Case */
172 /* do the work, then copy any error status */
173 ret = __vfprintf(&fake, fmt, ap);
174 if (ret >= 0 && __fflush(&fake))
176 if (fake.pub._flags & __SERR)
177 fp->pub._flags |= __SERR;
182 * Macros for converting digits to letters and vice versa
184 #define to_digit(c) ((c) - '0')
185 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
186 #define to_char(n) ((n) + '0')
189 * Convert an unsigned long to ASCII for printf purposes, returning
190 * a pointer to the first character of the string representation.
191 * Octal numbers can be forced to have a leading zero; hex numbers
192 * use the given digits.
195 __ultoa(u_long val, char *endp, int base, int octzero, const char *xdigs,
196 int needgrp, char thousep, const char *grp)
203 * Handle the three cases separately, in the hope of getting
204 * better/faster code.
208 if (val < 10) { /* many numbers are 1 digit */
209 *--cp = to_char(val);
214 * On many machines, unsigned arithmetic is harder than
215 * signed arithmetic, so we do at most one unsigned mod and
216 * divide; this is sufficient to reduce the range of
217 * the incoming value to where signed arithmetic works.
219 if (val > LONG_MAX) {
220 *--cp = to_char(val % 10);
226 *--cp = to_char(sval % 10);
229 * If (*grp == CHAR_MAX) then no more grouping
230 * should be performed.
232 if (needgrp && ndig == *grp && *grp != CHAR_MAX &&
237 * If (*(grp+1) == '\0') then we have to
238 * use *grp character (last grouping rule)
241 if (*(grp + 1) != '\0')
250 *--cp = to_char(val & 7);
253 if (octzero && *cp != '0')
259 *--cp = xdigs[(size_t)val & 15];
270 /* Identical to __ultoa, but for intmax_t. */
272 __ujtoa(uintmax_t val, char *endp, int base, int octzero, const char *xdigs,
273 int needgrp, char thousep, const char *grp)
279 /* quick test for small values; __ultoa is typically much faster */
280 /* (perhaps instead we should run until small, then call __ultoa?) */
281 if (val <= ULONG_MAX)
282 return (__ultoa((u_long)val, endp, base, octzero, xdigs,
283 needgrp, thousep, grp));
287 *--cp = to_char(val % 10);
291 if (val > INTMAX_MAX) {
292 *--cp = to_char(val % 10);
298 *--cp = to_char(sval % 10);
301 * If (*grp == CHAR_MAX) then no more grouping
302 * should be performed.
304 if (needgrp && *grp != CHAR_MAX && ndig == *grp &&
309 * If (*(grp+1) == '\0') then we have to
310 * use *grp character (last grouping rule)
313 if (*(grp + 1) != '\0')
322 *--cp = to_char(val & 7);
325 if (octzero && *cp != '0')
331 *--cp = xdigs[(size_t)val & 15];
343 * Convert a wide character string argument for the %ls format to a multibyte
344 * string representation. If not -1, prec specifies the maximum number of
345 * bytes to output, and also means that we can't assume that the wide char.
346 * string ends is null-terminated.
349 __wcsconv(wchar_t *wcsarg, int prec)
351 static const mbstate_t initial;
353 char buf[MB_LEN_MAX];
358 /* Allocate space for the maximum number of bytes we could output. */
362 nbytes = wcsrtombs(NULL, (const wchar_t **)&p, 0, &mbs);
363 if (nbytes == (size_t)-1)
367 * Optimisation: if the output precision is small enough,
368 * just allocate enough memory for the maximum instead of
369 * scanning the string.
378 clen = wcrtomb(buf, *p++, &mbs);
379 if (clen == 0 || clen == (size_t)-1 ||
380 nbytes + clen > prec)
386 if ((convbuf = malloc(nbytes + 1)) == NULL)
389 /* Fill the output buffer. */
392 if ((nbytes = wcsrtombs(convbuf, (const wchar_t **)&p,
393 nbytes, &mbs)) == (size_t)-1) {
397 convbuf[nbytes] = '\0';
405 vfprintf(FILE *fp, const char *fmt0, va_list ap)
410 ret = __vfprintf(fp, fmt0, ap);
415 #ifndef NO_FLOATING_POINT
419 #define BUF ((MAXEXPDIG * 2) + MAXFRACT + 1) /* + decimal point */
422 extern char *__dtoa(double, int, int, int *, int *, char **);
423 extern void __freedtoa(char *s);
425 static char *cvt(double, int, int, char *, int *, int, int *);
426 static int exponent (char *, int, int);
428 #else /* no NO_FLOATING_POINT */
432 #endif /* NO_FLOATING_POINT */
434 #define STATIC_ARG_TBL_SIZE 8 /* Size of static argument table. */
437 * Flags used during conversion.
439 #define ALT 0x001 /* alternate form */
440 #define HEXPREFIX 0x002 /* add 0x or 0X prefix */
441 #define LADJUST 0x004 /* left adjustment */
442 #define LONGDBL 0x008 /* long double */
443 #define LONGINT 0x010 /* long integer */
444 #define LLONGINT 0x020 /* long long integer */
445 #define SHORTINT 0x040 /* short integer */
446 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
447 #define FPT 0x100 /* Floating point number */
448 #define GROUPING 0x200 /* use grouping ("'" flag) */
449 /* C99 additional size modifiers: */
450 #define SIZET 0x400 /* size_t */
451 #define PTRDIFFT 0x800 /* ptrdiff_t */
452 #define INTMAXT 0x1000 /* intmax_t */
453 #define CHARINT 0x2000 /* print char using int format */
455 * Non-MT-safe version
458 __vfprintf(FILE *fp, const char *fmt0, va_list ap)
460 char *fmt; /* format string */
461 int ch; /* character from fmt */
462 int n, n2; /* handy integer (short term usage) */
463 char *cp; /* handy char pointer (short term usage) */
464 struct __siov *iovp; /* for PRINT macro */
465 int flags; /* flags as above */
466 int ret; /* return value accumulator */
467 int width; /* width from format (%8d), or 0 */
468 int prec; /* precision from format (%.3d), or -1 */
469 char sign; /* sign prefix (' ', '+', '-', or \0) */
470 char thousands_sep; /* locale specific thousands separator */
471 const char *grouping; /* locale specific numeric grouping rules */
472 #ifndef NO_FLOATING_POINT
473 const char *decimal_point; /* locale specific decimal point */
474 char softsign; /* temporary negative sign for floats */
475 double _double; /* double precision arguments %[eEfgG] */
476 int expt; /* integer value of exponent */
477 int expsize; /* character count for expstr */
478 int ndig; /* actual number of digits returned by cvt */
479 char expstr[7]; /* buffer for exponent string */
480 char *dtoaresult; /* buffer allocated by dtoa */
482 u_long ulval; /* integer arguments %[diouxX] */
483 uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */
484 int base; /* base for [diouxX] conversion */
485 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
486 int realsz; /* field size expanded by dprec, sign, etc */
487 int size; /* size of converted field or string */
488 int prsize; /* max size of printed field */
489 const char *xdigs; /* digits for [xX] conversion */
491 struct __suio uio; /* output information: summary */
492 struct __siov iov[NIOV];/* ... and individual io vectors */
493 char buf[BUF]; /* space for %c, %[diouxX], %[eEfFgG] */
494 char ox[2]; /* space for 0x hex-prefix */
495 union arg *argtable; /* args, built due to positional arg */
496 union arg statargtable[STATIC_ARG_TBL_SIZE];
497 int nextarg; /* 1-based argument index */
498 va_list orgap; /* original argument pointer */
499 char *convbuf; /* wide to multibyte conversion result */
508 * Choose PADSIZE to trade efficiency vs. size. If larger printf
509 * fields occur frequently, increase PADSIZE and make the initialisers
512 #define PADSIZE 16 /* pad chunk size */
513 static char blanks[PADSIZE] =
514 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
515 static char zeroes[PADSIZE] =
516 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
519 * BEWARE, these `goto error' on error, and PAD uses `n'.
521 #define PRINT(ptr, len) { \
522 iovp->iov_base = __DECONST(void *, ptr); \
523 iovp->iov_len = (len); \
524 uio.uio_resid += (len); \
526 if (++uio.uio_iovcnt >= NIOV) { \
527 if (__sprint(fp, &uio)) \
532 #define PAD(howmany, with) { \
533 if ((n = (howmany)) > 0) { \
534 while (n > PADSIZE) { \
535 PRINT(with, PADSIZE); \
542 if (uio.uio_resid && __sprint(fp, &uio)) \
544 uio.uio_iovcnt = 0; \
549 * Get the argument indexed by nextarg. If the argument table is
550 * built, use it to get the argument. If its not, get the next
551 * argument (and arguments must be gotten sequentially).
553 #define GETARG(type) \
554 ((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
555 (nextarg++, va_arg(ap, type)))
558 * To extend shorts properly, we need both signed and unsigned
559 * argument extraction methods.
562 (flags&LONGINT ? GETARG(long) : \
563 flags&SHORTINT ? (long)(short)GETARG(int) : \
564 flags&CHARINT ? (long)(signed char)GETARG(int) : \
567 (flags&LONGINT ? GETARG(u_long) : \
568 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
569 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
570 (u_long)GETARG(u_int))
571 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
573 (flags&INTMAXT ? GETARG(intmax_t) : \
574 flags&SIZET ? (intmax_t)GETARG(size_t) : \
575 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
576 (intmax_t)GETARG(long long))
578 (flags&INTMAXT ? GETARG(uintmax_t) : \
579 flags&SIZET ? (uintmax_t)GETARG(size_t) : \
580 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
581 (uintmax_t)GETARG(unsigned long long))
584 * Get * arguments, including the form *nn$. Preserve the nextarg
585 * that the argument can be gotten once the type is determined.
587 #define GETASTER(val) \
590 while (is_digit(*cp)) { \
591 n2 = 10 * n2 + to_digit(*cp); \
595 int hold = nextarg; \
596 if (argtable == NULL) { \
597 argtable = statargtable; \
598 __find_arguments (fmt0, orgap, &argtable); \
601 val = GETARG (int); \
605 val = GETARG (int); \
609 thousands_sep = '\0';
612 #ifndef NO_FLOATING_POINT
614 decimal_point = localeconv()->decimal_point;
616 /* sorry, fprintf(read_only_file, "") returns EOF, not 0 */
621 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
622 if ((fp->pub._flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
623 fp->pub._fileno >= 0) {
624 return (__sbprintf(fp, fmt0, ap));
631 uio.uio_iov = iovp = iov;
637 * Scan the format for conversions (`%' character).
640 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
642 if ((n = fmt - cp) != 0) {
643 if ((unsigned)ret + n > INT_MAX) {
652 fmt++; /* skip over '%' */
661 reswitch: switch (ch) {
664 * ``If the space and + flags both appear, the space
665 * flag will be ignored.''
676 * ``A negative field width argument is taken as a
677 * - flag followed by a positive field width.''
679 * They don't exclude field widths read from args.
694 thousands_sep = *(localeconv()->thousands_sep);
695 grouping = localeconv()->grouping;
698 if ((ch = *fmt++) == '*') {
700 prec = n < 0 ? -1 : n;
704 while (is_digit(ch)) {
705 n = 10 * n + to_digit(ch);
708 prec = n < 0 ? -1 : n;
712 * ``Note that 0 is taken as a flag, not as the
713 * beginning of a field width.''
718 case '1': case '2': case '3': case '4':
719 case '5': case '6': case '7': case '8': case '9':
722 n = 10 * n + to_digit(ch);
724 } while (is_digit(ch));
727 if (argtable == NULL) {
728 argtable = statargtable;
729 __find_arguments (fmt0, orgap,
736 #ifndef NO_FLOATING_POINT
742 if (flags & SHORTINT) {
752 if (flags & LONGINT) {
771 if (flags & LONGINT) {
772 static const mbstate_t initial;
777 mbseqlen = wcrtomb(cp = buf,
778 (wchar_t)GETARG(wint_t), &mbs);
779 if (mbseqlen == (size_t)-1) {
780 fp->pub._flags |= __SERR;
783 size = (int)mbseqlen;
785 *(cp = buf) = GETARG(int);
795 if (flags & INTMAX_SIZE) {
797 if ((intmax_t)ujval < 0) {
803 if ((long)ulval < 0) {
810 #ifndef NO_FLOATING_POINT
818 * Grouping apply to %i, %d, %u, %f, %F, %g, %G
819 * conversion specifiers only. For other conversions
820 * behavior is undefined.
832 fp_begin: if (prec == -1)
835 /* XXX this loses precision. */
836 _double = (double)GETARG(long double);
838 _double = GETARG(double);
839 /* do this before tricky precision changes */
840 if (isinf(_double)) {
850 if (isnan(_double)) {
859 if (dtoaresult != NULL) {
860 __freedtoa(dtoaresult);
863 dtoaresult = cp = cvt(_double, prec, flags, &softsign,
865 if (ch == 'g' || ch == 'G') {
866 if (expt <= -4 || expt > prec)
867 ch = (ch == 'g') ? 'e' : 'E';
871 if (ch == 'e' || ch == 'E') {
873 expsize = exponent(expstr, expt, ch);
874 size = expsize + ndig;
875 if (ndig > 1 || flags & ALT)
877 } else if (ch == 'f' || ch == 'F') {
880 if (prec || flags & ALT)
884 } else if (expt >= ndig) { /* fixed g fmt */
889 size = ndig + (expt > 0 ?
895 #endif /* NO_FLOATING_POINT */
898 * Assignment-like behavior is specified if the
899 * value overflows or is otherwise unrepresentable.
900 * C99 says to use `signed char' for %hhn conversions.
902 if (flags & LLONGINT)
903 *GETARG(long long *) = ret;
904 else if (flags & SIZET)
905 *GETARG(ssize_t *) = (ssize_t)ret;
906 else if (flags & PTRDIFFT)
907 *GETARG(ptrdiff_t *) = ret;
908 else if (flags & INTMAXT)
909 *GETARG(intmax_t *) = ret;
910 else if (flags & LONGINT)
911 *GETARG(long *) = ret;
912 else if (flags & SHORTINT)
913 *GETARG(short *) = ret;
914 else if (flags & CHARINT)
915 *GETARG(signed char *) = ret;
917 *GETARG(int *) = ret;
918 continue; /* no output */
923 if (flags & INTMAX_SIZE)
931 * ``The argument shall be a pointer to void. The
932 * value of the pointer is converted to a sequence
933 * of printable characters, in an implementation-
937 ujval = (uintmax_t)(uintptr_t)GETARG(void *);
939 xdigs = "0123456789abcdef";
940 flags = flags | INTMAXT | HEXPREFIX;
947 if (flags & LONGINT) {
952 if ((wcp = GETARG(wchar_t *)) == NULL)
955 convbuf = __wcsconv(wcp, prec);
956 if (convbuf == NULL) {
957 fp->pub._flags |= __SERR;
962 } else if ((cp = GETARG(char *)) == NULL)
966 * can't use strlen; can only look for the
967 * NUL in the first `prec' characters, and
968 * strlen() will go further.
970 char *p = memchr(cp, 0, (size_t)prec);
986 if (flags & INTMAX_SIZE)
993 xdigs = "0123456789ABCDEF";
996 xdigs = "0123456789abcdef";
998 if (flags & INTMAX_SIZE)
1003 /* leading 0x/X only if non-zero */
1005 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
1009 /* unsigned conversions */
1010 nosign: sign = '\0';
1012 * ``... diouXx conversions ... if a precision is
1013 * specified, the 0 flag will be ignored.''
1016 number: if ((dprec = prec) >= 0)
1020 * ``The result of converting a zero value with an
1021 * explicit precision of zero is no characters.''
1025 if (flags & INTMAX_SIZE) {
1026 if (ujval != 0 || prec != 0)
1027 cp = __ujtoa(ujval, cp, base,
1029 flags & GROUPING, thousands_sep,
1032 if (ulval != 0 || prec != 0)
1033 cp = __ultoa(ulval, cp, base,
1035 flags & GROUPING, thousands_sep,
1038 size = buf + BUF - cp;
1040 default: /* "%?" prints ?, unless ? is NUL */
1043 /* pretend it was %c with argument ch */
1052 * All reasonable formats wind up here. At this point, `cp'
1053 * points to a string which (if not flags&LADJUST) should be
1054 * padded out to `width' places. If flags&ZEROPAD, it should
1055 * first be prefixed by any sign or other prefix; otherwise,
1056 * it should be blank padded before the prefix is emitted.
1057 * After any left-hand padding and prefixing, emit zeroes
1058 * required by a decimal [diouxX] precision, then print the
1059 * string proper, then emit zeroes required by any leftover
1060 * floating precision; finally, if LADJUST, pad with blanks.
1062 * Compute actual size, so we know how much to pad.
1063 * size excludes decimal prec; realsz includes it.
1065 realsz = dprec > size ? dprec : size;
1068 else if (flags & HEXPREFIX)
1071 prsize = width > realsz ? width : realsz;
1072 if ((unsigned)ret + prsize > INT_MAX) {
1077 /* right-adjusting blank padding */
1078 if ((flags & (LADJUST|ZEROPAD)) == 0)
1079 PAD(width - realsz, blanks);
1084 } else if (flags & HEXPREFIX) {
1090 /* right-adjusting zero padding */
1091 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1092 PAD(width - realsz, zeroes);
1094 /* leading zeroes from decimal precision */
1095 PAD(dprec - size, zeroes);
1097 /* the string or number proper */
1098 #ifndef NO_FLOATING_POINT
1099 if ((flags & FPT) == 0) {
1101 } else { /* glue together f_p fragments */
1102 if (ch >= 'f') { /* 'f' or 'g' */
1104 /* kludge for __dtoa irregularity */
1106 if (expt < ndig || (flags & ALT) != 0) {
1107 PRINT(decimal_point, 1);
1108 PAD(ndig - 1, zeroes);
1110 } else if (expt <= 0) {
1112 PRINT(decimal_point, 1);
1115 } else if (expt >= ndig) {
1117 PAD(expt - ndig, zeroes);
1119 PRINT(decimal_point, 1);
1123 PRINT(decimal_point, 1);
1124 PRINT(cp, ndig-expt);
1126 } else { /* 'e' or 'E' */
1127 if (ndig > 1 || flags & ALT) {
1129 ox[1] = *decimal_point;
1133 } else /* 0.[0..] */
1134 /* __dtoa irregularity */
1135 PAD(ndig - 1, zeroes);
1138 PRINT(expstr, expsize);
1144 /* left-adjusting padding (always blank) */
1145 if (flags & LADJUST)
1146 PAD(width - realsz, blanks);
1148 /* finally, adjust ret */
1151 FLUSH(); /* copy out the I/O vectors */
1156 #ifndef NO_FLOATING_POINT
1157 if (dtoaresult != NULL)
1158 __freedtoa(dtoaresult);
1160 if (convbuf != NULL)
1164 if ((argtable != NULL) && (argtable != statargtable))
1171 * Find all arguments when a positional parameter is encountered. Returns a
1172 * table, indexed by argument number, of pointers to each arguments. The
1173 * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1174 * It will be replaces with a malloc-ed one if it overflows.
1177 __find_arguments (const char *fmt0, va_list ap, union arg **argtable)
1179 char *fmt; /* format string */
1180 int ch; /* character from fmt */
1181 int n, n2; /* handy integer (short term usage) */
1182 char *cp; /* handy char pointer (short term usage) */
1183 int flags; /* flags as above */
1184 int width; /* width from format (%8d), or 0 */
1185 enum typeid *typetable; /* table of types */
1186 enum typeid stattypetable[STATIC_ARG_TBL_SIZE];
1187 int tablesize; /* current size of type table */
1188 int tablemax; /* largest used index in table */
1189 int nextarg; /* 1-based argument index */
1192 * Add an argument type to the table, expanding if necessary.
1194 #define ADDTYPE(type) \
1195 ((nextarg >= tablesize) ? \
1196 __grow_type_table(nextarg, &typetable, &tablesize) : 0, \
1197 (nextarg > tablemax) ? tablemax = nextarg : 0, \
1198 typetable[nextarg++] = type)
1201 ((flags&INTMAXT) ? ADDTYPE(T_INTMAXT) : \
1202 ((flags&SIZET) ? ADDTYPE(T_SIZET) : \
1203 ((flags&PTRDIFFT) ? ADDTYPE(T_PTRDIFFT) : \
1204 ((flags&LLONGINT) ? ADDTYPE(T_LLONG) : \
1205 ((flags&LONGINT) ? ADDTYPE(T_LONG) : ADDTYPE(T_INT))))))
1208 ((flags&INTMAXT) ? ADDTYPE(T_UINTMAXT) : \
1209 ((flags&SIZET) ? ADDTYPE(T_SIZET) : \
1210 ((flags&PTRDIFFT) ? ADDTYPE(T_PTRDIFFT) : \
1211 ((flags&LLONGINT) ? ADDTYPE(T_U_LLONG) : \
1212 ((flags&LONGINT) ? ADDTYPE(T_U_LONG) : ADDTYPE(T_U_INT))))))
1215 * Add * arguments to the type array.
1217 #define ADDASTER() \
1220 while (is_digit(*cp)) { \
1221 n2 = 10 * n2 + to_digit(*cp); \
1225 int hold = nextarg; \
1234 typetable = stattypetable;
1235 tablesize = STATIC_ARG_TBL_SIZE;
1238 memset (typetable, T_UNUSED, STATIC_ARG_TBL_SIZE);
1241 * Scan the format for conversions (`%' character).
1244 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
1248 fmt++; /* skip over '%' */
1254 reswitch: switch (ch) {
1266 if ((ch = *fmt++) == '*') {
1270 while (is_digit(ch)) {
1276 case '1': case '2': case '3': case '4':
1277 case '5': case '6': case '7': case '8': case '9':
1280 n = 10 * n + to_digit(ch);
1282 } while (is_digit(ch));
1289 #ifndef NO_FLOATING_POINT
1295 if (flags & SHORTINT) {
1305 if (flags & LONGINT) {
1324 if (flags & LONGINT)
1336 #ifndef NO_FLOATING_POINT
1346 if (flags & LONGDBL)
1347 ADDTYPE(T_LONG_DOUBLE);
1351 #endif /* NO_FLOATING_POINT */
1353 if (flags & INTMAXT)
1354 ADDTYPE(TP_INTMAXT);
1355 else if (flags & PTRDIFFT)
1356 ADDTYPE(TP_PTRDIFFT);
1357 else if (flags & SIZET)
1359 else if (flags & LLONGINT)
1361 else if (flags & LONGINT)
1363 else if (flags & SHORTINT)
1365 else if (flags & CHARINT)
1369 continue; /* no output */
1383 if (flags & LONGINT)
1396 default: /* "%?" prints ?, unless ? is NUL */
1404 * Build the argument table.
1406 if (tablemax >= STATIC_ARG_TBL_SIZE) {
1407 *argtable = (union arg *)
1408 malloc(sizeof(union arg) * (tablemax + 1));
1410 (*argtable)[0].intarg = 0;
1411 for (n = 1; n <= tablemax; n++) {
1412 switch (typetable [n]) {
1413 case T_UNUSED: /* "whoops" */
1415 (*argtable)[n].intarg = va_arg(ap, int);
1418 (*argtable) [n].pschararg = va_arg (ap, signed char *);
1421 (*argtable)[n].pshortarg = va_arg(ap, short *);
1424 (*argtable)[n].uintarg = va_arg(ap, unsigned int);
1427 (*argtable)[n].pintarg = va_arg(ap, int *);
1430 (*argtable)[n].longarg = va_arg(ap, long);
1433 (*argtable)[n].ulongarg = va_arg(ap, unsigned long);
1436 (*argtable)[n].plongarg = va_arg(ap, long *);
1439 (*argtable)[n].longlongarg = va_arg(ap, long long);
1442 (*argtable)[n].ulonglongarg = va_arg(ap, unsigned long long);
1445 (*argtable)[n].plonglongarg = va_arg(ap, long long *);
1448 (*argtable)[n].ptrdiffarg = va_arg(ap, ptrdiff_t);
1451 (*argtable)[n].pptrdiffarg = va_arg(ap, ptrdiff_t *);
1454 (*argtable)[n].sizearg = va_arg(ap, size_t);
1457 (*argtable)[n].psizearg = va_arg(ap, ssize_t *);
1460 (*argtable)[n].intmaxarg = va_arg(ap, intmax_t);
1463 (*argtable)[n].uintmaxarg = va_arg(ap, uintmax_t);
1466 (*argtable)[n].pintmaxarg = va_arg (ap, intmax_t *);
1469 (*argtable)[n].doublearg = va_arg(ap, double);
1472 (*argtable)[n].longdoublearg = va_arg(ap, long double);
1475 (*argtable)[n].pchararg = va_arg(ap, char *);
1478 (*argtable)[n].pvoidarg = va_arg(ap, void *);
1481 (*argtable)[n].wintarg = va_arg(ap, wint_t);
1484 (*argtable)[n].pwchararg = va_arg(ap, wchar_t *);
1489 if ((typetable != NULL) && (typetable != stattypetable))
1494 * Increase the size of the type table.
1497 __grow_type_table(int nextarg, enum typeid **typetable, int *tablesize)
1499 enum typeid * const oldtable = *typetable;
1500 const int oldsize = *tablesize;
1501 enum typeid *newtable;
1502 int n, newsize = oldsize * 2;
1504 if (newsize < nextarg + 1)
1505 newsize = nextarg + 1;
1506 if (oldsize == STATIC_ARG_TBL_SIZE) {
1507 if ((newtable = malloc(newsize * sizeof(enum typeid))) == NULL)
1508 abort(); /* XXX handle better */
1509 bcopy(oldtable, newtable, oldsize * sizeof(enum typeid));
1511 if ((newtable = reallocf(oldtable, newsize * sizeof(enum typeid))) == NULL)
1512 abort(); /* XXX handle better */
1514 for (n = oldsize; n < newsize; n++)
1515 newtable[n] = T_UNUSED;
1517 *typetable = newtable;
1518 *tablesize = newsize;
1522 #ifndef NO_FLOATING_POINT
1525 cvt(double value, int ndigits, int flags, char *sign, int *decpt,
1526 int ch, int *length)
1529 char *digits, *bp, *rve;
1532 mode = 3; /* ndigits after the decimal point */
1535 * To obtain ndigits after the decimal point for the 'e'
1536 * and 'E' formats, round to ndigits + 1 significant
1539 if (ch == 'e' || ch == 'E')
1541 mode = 2; /* ndigits significant digits */
1543 digits = __dtoa(value, mode, ndigits, decpt, &dsgn, &rve);
1545 if ((ch != 'g' && ch != 'G') || flags & ALT) {
1546 /* print trailing zeros */
1547 bp = digits + ndigits;
1549 if (*digits == '0' && value)
1550 *decpt = -ndigits + 1;
1553 if (value == 0) /* kludge for __dtoa irregularity */
1558 *length = rve - digits;
1563 exponent(char *p0, int expo, int fmtch)
1566 char expbuf[MAXEXPDIG];
1576 t = expbuf + MAXEXPDIG;
1579 *--t = to_char(expo % 10);
1580 } while ((expo /= 10) > 9);
1581 *--t = to_char(expo);
1582 for (; t < expbuf + MAXEXPDIG; *p++ = *t++);
1586 *p++ = to_char(expo);
1590 #endif /* NO_FLOATING_POINT */