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"
65 #include "printflocal.h"
67 static int __sprint(FILE *, struct __suio *);
68 static int __sbprintf(FILE *, const char *, va_list) __printflike(2, 0);
69 static char *__wcsconv(wchar_t *, int);
72 #include "printfcommon.h"
75 * Flush out all the vectors defined by the given uio,
76 * then reset it so that it can be reused.
79 __sprint(FILE *fp, struct __suio *uio)
83 if (uio->uio_resid == 0) {
87 err = __sfvwrite(fp, uio);
94 * Helper function for `fprintf to unbuffered unix file': creates a
95 * temporary buffer. We only work on write-only files; this avoids
96 * worries about ungetc buffers and so forth.
99 __sbprintf(FILE *fp, const char *fmt, va_list ap)
103 unsigned char buf[BUFSIZ];
105 /* copy the important variables */
106 fake._flags = fp->_flags & ~__SNBF;
107 fake._file = fp->_file;
108 fake._cookie = fp->_cookie;
109 fake._write = fp->_write;
110 fake._orientation = fp->_orientation;
111 fake._mbstate = fp->_mbstate;
113 /* set up the buffer */
114 fake._bf._base = fake._p = buf;
115 fake._bf._size = fake._w = sizeof(buf);
116 fake._lbfsize = 0; /* not actually used, but Just In Case */
118 /* do the work, then copy any error status */
119 ret = __vfprintf(&fake, fmt, ap);
120 if (ret >= 0 && __fflush(&fake))
122 if (fake._flags & __SERR)
123 fp->_flags |= __SERR;
128 * Convert a wide character string argument for the %ls format to a multibyte
129 * string representation. If not -1, prec specifies the maximum number of
130 * bytes to output, and also means that we can't assume that the wide char.
131 * string ends is null-terminated.
134 __wcsconv(wchar_t *wcsarg, int prec)
136 static const mbstate_t initial;
138 char buf[MB_LEN_MAX];
143 /* Allocate space for the maximum number of bytes we could output. */
147 nbytes = wcsrtombs(NULL, (const wchar_t **)&p, 0, &mbs);
148 if (nbytes == (size_t)-1)
152 * Optimisation: if the output precision is small enough,
153 * just allocate enough memory for the maximum instead of
154 * scanning the string.
163 clen = wcrtomb(buf, *p++, &mbs);
164 if (clen == 0 || clen == (size_t)-1 ||
165 nbytes + clen > prec)
171 if ((convbuf = malloc(nbytes + 1)) == NULL)
174 /* Fill the output buffer. */
177 if ((nbytes = wcsrtombs(convbuf, (const wchar_t **)&p,
178 nbytes, &mbs)) == (size_t)-1) {
182 convbuf[nbytes] = '\0';
190 vfprintf(FILE * __restrict fp, const char * __restrict fmt0, va_list ap)
196 ret = __vfprintf(fp, fmt0, ap);
202 * The size of the buffer we use as scratch space for integer
203 * conversions, among other things. Technically, we would need the
204 * most space for base 10 conversions with thousands' grouping
205 * characters between each pair of digits. 100 bytes is a
206 * conservative overestimate even for a 128-bit uintmax_t.
211 * Non-MT-safe version
214 __vfprintf(FILE *fp, const char *fmt0, va_list ap)
216 char *fmt; /* format string */
217 int ch; /* character from fmt */
218 int n, n2; /* handy integer (short term usage) */
219 char *cp; /* handy char pointer (short term usage) */
220 int flags; /* flags as above */
221 int ret; /* return value accumulator */
222 int width; /* width from format (%8d), or 0 */
223 int prec; /* precision from format; <0 for N/A */
224 char sign; /* sign prefix (' ', '+', '-', or \0) */
225 char thousands_sep; /* locale specific thousands separator */
226 const char *grouping; /* locale specific numeric grouping rules */
228 #ifndef NO_FLOATING_POINT
230 * We can decompose the printed representation of floating
231 * point numbers into several parts, some of which may be empty:
233 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
236 * A: 'sign' holds this value if present; '\0' otherwise
237 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
238 * C: cp points to the string MMMNNN. Leading and trailing
239 * zeros are not in the string and must be added.
240 * D: expchar holds this character; '\0' if no exponent, e.g. %f
241 * F: at least two digits for decimal, at least one digit for hex
243 char *decimal_point; /* locale specific decimal point */
244 int signflag; /* true if float is negative */
245 union { /* floating point arguments %[aAeEfFgG] */
249 int expt; /* integer value of exponent */
250 char expchar; /* exponent character: [eEpP\0] */
251 char *dtoaend; /* pointer to end of converted digits */
252 int expsize; /* character count for expstr */
253 int lead; /* sig figs before decimal or group sep */
254 int ndig; /* actual number of digits returned by dtoa */
255 char expstr[MAXEXPDIG+2]; /* buffer for exponent string: e+ZZZ */
256 char *dtoaresult; /* buffer allocated by dtoa */
257 int nseps; /* number of group separators with ' */
258 int nrepeats; /* number of repeats of the last group */
260 u_long ulval; /* integer arguments %[diouxX] */
261 uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */
262 int base; /* base for [diouxX] conversion */
263 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
264 int realsz; /* field size expanded by dprec, sign, etc */
265 int size; /* size of converted field or string */
266 int prsize; /* max size of printed field */
267 const char *xdigs; /* digits for %[xX] conversion */
268 struct io_state io; /* I/O buffering state */
269 char buf[BUF]; /* buffer with space for digits of uintmax_t */
270 char ox[2]; /* space for 0x; ox[1] is either x, X, or \0 */
271 union arg *argtable; /* args, built due to positional arg */
272 union arg statargtable [STATIC_ARG_TBL_SIZE];
273 int nextarg; /* 1-based argument index */
274 va_list orgap; /* original argument pointer */
275 char *convbuf; /* wide to multibyte conversion result */
277 static const char xdigs_lower[16] = "0123456789abcdef";
278 static const char xdigs_upper[16] = "0123456789ABCDEF";
280 /* BEWARE, these `goto error' on error. */
281 #define PRINT(ptr, len) { \
282 if (io_print(&io, (ptr), (len))) \
285 #define PAD(howmany, with) { \
286 if (io_pad(&io, (howmany), (with))) \
289 #define PRINTANDPAD(p, ep, len, with) { \
290 if (io_printandpad(&io, (p), (ep), (len), (with))) \
299 * Get the argument indexed by nextarg. If the argument table is
300 * built, use it to get the argument. If its not, get the next
301 * argument (and arguments must be gotten sequentially).
303 #define GETARG(type) \
304 ((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
305 (nextarg++, va_arg(ap, type)))
308 * To extend shorts properly, we need both signed and unsigned
309 * argument extraction methods.
312 (flags&LONGINT ? GETARG(long) : \
313 flags&SHORTINT ? (long)(short)GETARG(int) : \
314 flags&CHARINT ? (long)(signed char)GETARG(int) : \
317 (flags&LONGINT ? GETARG(u_long) : \
318 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
319 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
320 (u_long)GETARG(u_int))
321 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
323 (flags&INTMAXT ? GETARG(intmax_t) : \
324 flags&SIZET ? (intmax_t)GETARG(size_t) : \
325 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
326 (intmax_t)GETARG(long long))
328 (flags&INTMAXT ? GETARG(uintmax_t) : \
329 flags&SIZET ? (uintmax_t)GETARG(size_t) : \
330 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
331 (uintmax_t)GETARG(unsigned long long))
334 * Get * arguments, including the form *nn$. Preserve the nextarg
335 * that the argument can be gotten once the type is determined.
337 #define GETASTER(val) \
340 while (is_digit(*cp)) { \
341 n2 = 10 * n2 + to_digit(*cp); \
345 int hold = nextarg; \
346 if (argtable == NULL) { \
347 argtable = statargtable; \
348 if (__find_arguments (fmt0, orgap, &argtable)) { \
354 val = GETARG (int); \
358 val = GETARG (int); \
361 if (__use_xprintf == 0 && getenv("USE_XPRINTF"))
363 if (__use_xprintf > 0)
364 return (__xvprintf(fp, fmt0, ap));
366 /* sorry, fprintf(read_only_file, "") returns EOF, not 0 */
367 if (prepwrite(fp) != 0)
370 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
371 if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
373 return (__sbprintf(fp, fmt0, ap));
375 thousands_sep = '\0';
384 #ifndef NO_FLOATING_POINT
386 decimal_point = localeconv()->decimal_point;
390 * Scan the format for conversions (`%' character).
393 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
395 if ((n = fmt - cp) != 0) {
396 if ((unsigned)ret + n > INT_MAX) {
405 fmt++; /* skip over '%' */
415 reswitch: switch (ch) {
418 * ``If the space and + flags both appear, the space
419 * flag will be ignored.''
430 * ``A negative field width argument is taken as a
431 * - flag followed by a positive field width.''
433 * They don't exclude field widths read from args.
448 thousands_sep = *(localeconv()->thousands_sep);
449 grouping = localeconv()->grouping;
452 if ((ch = *fmt++) == '*') {
457 while (is_digit(ch)) {
458 prec = 10 * prec + to_digit(ch);
464 * ``Note that 0 is taken as a flag, not as the
465 * beginning of a field width.''
470 case '1': case '2': case '3': case '4':
471 case '5': case '6': case '7': case '8': case '9':
474 n = 10 * n + to_digit(ch);
476 } while (is_digit(ch));
479 if (argtable == NULL) {
480 argtable = statargtable;
481 if (__find_arguments (fmt0, orgap,
491 #ifndef NO_FLOATING_POINT
497 if (flags & SHORTINT) {
507 if (flags & LONGINT) {
514 flags |= LLONGINT; /* not necessarily */
526 if (flags & LONGINT) {
527 static const mbstate_t initial;
532 mbseqlen = wcrtomb(cp = buf,
533 (wchar_t)GETARG(wint_t), &mbs);
534 if (mbseqlen == (size_t)-1) {
535 fp->_flags |= __SERR;
538 size = (int)mbseqlen;
540 *(cp = buf) = GETARG(int);
550 if (flags & INTMAX_SIZE) {
552 if ((intmax_t)ujval < 0) {
558 if ((long)ulval < 0) {
565 #ifndef NO_FLOATING_POINT
579 if (dtoaresult != NULL)
580 freedtoa(dtoaresult);
581 if (flags & LONGDBL) {
582 fparg.ldbl = GETARG(long double);
584 __hldtoa(fparg.ldbl, xdigs, prec,
585 &expt, &signflag, &dtoaend);
587 fparg.dbl = GETARG(double);
589 __hdtoa(fparg.dbl, xdigs, prec,
590 &expt, &signflag, &dtoaend);
600 if (prec < 0) /* account for digit before decpt */
611 expchar = ch - ('g' - 'e');
617 if (dtoaresult != NULL)
618 freedtoa(dtoaresult);
619 if (flags & LONGDBL) {
620 fparg.ldbl = GETARG(long double);
622 __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
623 &expt, &signflag, &dtoaend);
625 fparg.dbl = GETARG(double);
627 dtoa(fparg.dbl, expchar ? 2 : 3, prec,
628 &expt, &signflag, &dtoaend);
635 if (expt == INT_MAX) { /* inf or nan */
637 cp = (ch >= 'a') ? "nan" : "NAN";
640 cp = (ch >= 'a') ? "inf" : "INF";
647 if (ch == 'g' || ch == 'G') {
648 if (expt > -4 && expt <= prec) {
649 /* Make %[gG] smell like %[fF] */
659 * Make %[gG] smell like %[eE], but
660 * trim trailing zeroes if no # flag.
667 expsize = exponent(expstr, expt - 1, expchar);
668 size = expsize + prec;
669 if (prec > 1 || flags & ALT)
672 /* space for digits before decimal point */
677 /* space for decimal pt and following digits */
678 if (prec || flags & ALT)
680 if (grouping && expt > 0) {
681 /* space for thousands' grouping */
682 nseps = nrepeats = 0;
684 while (*grouping != CHAR_MAX) {
685 if (lead <= *grouping)
694 size += nseps + nrepeats;
699 #endif /* !NO_FLOATING_POINT */
702 * Assignment-like behavior is specified if the
703 * value overflows or is otherwise unrepresentable.
704 * C99 says to use `signed char' for %hhn conversions.
706 if (flags & LLONGINT)
707 *GETARG(long long *) = ret;
708 else if (flags & SIZET)
709 *GETARG(ssize_t *) = (ssize_t)ret;
710 else if (flags & PTRDIFFT)
711 *GETARG(ptrdiff_t *) = ret;
712 else if (flags & INTMAXT)
713 *GETARG(intmax_t *) = ret;
714 else if (flags & LONGINT)
715 *GETARG(long *) = ret;
716 else if (flags & SHORTINT)
717 *GETARG(short *) = ret;
718 else if (flags & CHARINT)
719 *GETARG(signed char *) = ret;
721 *GETARG(int *) = ret;
722 continue; /* no output */
727 if (flags & INTMAX_SIZE)
735 * ``The argument shall be a pointer to void. The
736 * value of the pointer is converted to a sequence
737 * of printable characters, in an implementation-
741 ujval = (uintmax_t)(uintptr_t)GETARG(void *);
744 flags = flags | INTMAXT;
751 if (flags & LONGINT) {
756 if ((wcp = GETARG(wchar_t *)) == NULL)
759 convbuf = __wcsconv(wcp, prec);
760 if (convbuf == NULL) {
761 fp->_flags |= __SERR;
766 } else if ((cp = GETARG(char *)) == NULL)
770 * can't use strlen; can only look for the
771 * NUL in the first `prec' characters, and
772 * strlen() will go further.
774 char *p = memchr(cp, 0, (size_t)prec);
790 if (flags & INTMAX_SIZE)
802 if (flags & INTMAX_SIZE)
807 /* leading 0x/X only if non-zero */
809 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
813 /* unsigned conversions */
816 * ``... diouXx conversions ... if a precision is
817 * specified, the 0 flag will be ignored.''
820 number: if ((dprec = prec) >= 0)
824 * ``The result of converting a zero value with an
825 * explicit precision of zero is no characters.''
828 * ``The C Standard is clear enough as is. The call
829 * printf("%#.0o", 0) should print 0.''
830 * -- Defect Report #151
833 if (flags & INTMAX_SIZE) {
834 if (ujval != 0 || prec != 0 ||
835 (flags & ALT && base == 8))
836 cp = __ujtoa(ujval, cp, base,
838 flags & GROUPING, thousands_sep,
841 if (ulval != 0 || prec != 0 ||
842 (flags & ALT && base == 8))
843 cp = __ultoa(ulval, cp, base,
845 flags & GROUPING, thousands_sep,
848 size = buf + BUF - cp;
849 if (size > BUF) /* should never happen */
852 default: /* "%?" prints ?, unless ? is NUL */
855 /* pretend it was %c with argument ch */
864 * All reasonable formats wind up here. At this point, `cp'
865 * points to a string which (if not flags&LADJUST) should be
866 * padded out to `width' places. If flags&ZEROPAD, it should
867 * first be prefixed by any sign or other prefix; otherwise,
868 * it should be blank padded before the prefix is emitted.
869 * After any left-hand padding and prefixing, emit zeroes
870 * required by a decimal [diouxX] precision, then print the
871 * string proper, then emit zeroes required by any leftover
872 * floating precision; finally, if LADJUST, pad with blanks.
874 * Compute actual size, so we know how much to pad.
875 * size excludes decimal prec; realsz includes it.
877 realsz = dprec > size ? dprec : size;
883 prsize = width > realsz ? width : realsz;
884 if ((unsigned)ret + prsize > INT_MAX) {
889 /* right-adjusting blank padding */
890 if ((flags & (LADJUST|ZEROPAD)) == 0)
891 PAD(width - realsz, blanks);
897 if (ox[1]) { /* ox[1] is either x, X, or \0 */
902 /* right-adjusting zero padding */
903 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
904 PAD(width - realsz, zeroes);
906 /* leading zeroes from decimal precision */
907 PAD(dprec - size, zeroes);
909 /* the string or number proper */
910 #ifndef NO_FLOATING_POINT
911 if ((flags & FPT) == 0) {
913 } else { /* glue together f_p fragments */
914 if (!expchar) { /* %[fF] or sufficiently short %[gG] */
917 if (prec || flags & ALT)
918 PRINT(decimal_point, 1);
920 /* already handled initial 0's */
923 PRINTANDPAD(cp, dtoaend, lead, zeroes);
926 while (nseps>0 || nrepeats>0) {
933 PRINT(&thousands_sep,
935 PRINTANDPAD(cp,dtoaend,
942 if (prec || flags & ALT)
943 PRINT(decimal_point,1);
945 PRINTANDPAD(cp, dtoaend, prec, zeroes);
946 } else { /* %[eE] or sufficiently long %[gG] */
947 if (prec > 1 || flags & ALT) {
949 buf[1] = *decimal_point;
952 PAD(prec - ndig, zeroes);
955 PRINT(expstr, expsize);
961 /* left-adjusting padding (always blank) */
963 PAD(width - realsz, blanks);
965 /* finally, adjust ret */
968 FLUSH(); /* copy out the I/O vectors */
974 #ifndef NO_FLOATING_POINT
975 if (dtoaresult != NULL)
976 freedtoa(dtoaresult);
982 if ((argtable != NULL) && (argtable != statargtable))