2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1990, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
10 * Copyright (c) 2011 The FreeBSD Foundation
11 * All rights reserved.
12 * Portions of this software were developed by David Chisnall
13 * under sponsorship from the FreeBSD Foundation.
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 * notice, this list of conditions and the following disclaimer in the
22 * documentation and/or other materials provided with the distribution.
23 * 3. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40 #if defined(LIBC_SCCS) && !defined(lint)
41 static char sccsid[] = "@(#)vfprintf.c 8.1 (Berkeley) 6/4/93";
42 #endif /* LIBC_SCCS and not lint */
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
47 * Actual printf innards.
49 * This code is large and complicated...
52 #include "namespace.h"
53 #include <sys/types.h>
68 #include "xlocale_private.h"
69 #include "un-namespace.h"
71 #include "libc_private.h"
74 #include "printflocal.h"
76 static int __sprint(FILE *, struct __suio *, locale_t);
77 static int __sbprintf(FILE *, locale_t, const char *, va_list) __printflike(3, 0)
79 static char *__wcsconv(wchar_t *, int);
82 #include "printfcommon.h"
84 struct grouping_state {
85 char *thousands_sep; /* locale-specific thousands separator */
86 int thousep_len; /* length of thousands_sep */
87 const char *grouping; /* locale-specific numeric grouping rules */
88 int lead; /* sig figs before decimal or group sep */
89 int nseps; /* number of group separators with ' */
90 int nrepeats; /* number of repeats of the last group */
94 * Initialize the thousands' grouping state in preparation to print a
95 * number with ndigits digits. This routine returns the total number
96 * of bytes that will be needed.
99 grouping_init(struct grouping_state *gs, int ndigits, locale_t loc)
101 struct lconv *locale;
103 locale = localeconv_l(loc);
104 gs->grouping = locale->grouping;
105 gs->thousands_sep = locale->thousands_sep;
106 gs->thousep_len = strlen(gs->thousands_sep);
108 gs->nseps = gs->nrepeats = 0;
110 while (*gs->grouping != CHAR_MAX) {
111 if (gs->lead <= *gs->grouping)
113 gs->lead -= *gs->grouping;
114 if (*(gs->grouping+1)) {
120 return ((gs->nseps + gs->nrepeats) * gs->thousep_len);
124 * Print a number with thousands' separators.
127 grouping_print(struct grouping_state *gs, struct io_state *iop,
128 const CHAR *cp, const CHAR *ep, locale_t locale)
130 const CHAR *cp0 = cp;
132 if (io_printandpad(iop, cp, ep, gs->lead, zeroes, locale))
135 while (gs->nseps > 0 || gs->nrepeats > 0) {
136 if (gs->nrepeats > 0)
142 if (io_print(iop, gs->thousands_sep, gs->thousep_len, locale))
144 if (io_printandpad(iop, cp, ep, *gs->grouping, zeroes, locale))
154 * Flush out all the vectors defined by the given uio,
155 * then reset it so that it can be reused.
158 __sprint(FILE *fp, struct __suio *uio, locale_t locale)
162 if (uio->uio_resid == 0) {
166 err = __sfvwrite(fp, uio);
173 * Helper function for `fprintf to unbuffered unix file': creates a
174 * temporary buffer. We only work on write-only files; this avoids
175 * worries about ungetc buffers and so forth.
178 __sbprintf(FILE *fp, locale_t locale, const char *fmt, va_list ap)
181 FILE fake = FAKE_FILE;
182 unsigned char buf[BUFSIZ];
184 /* XXX This is probably not needed. */
185 if (prepwrite(fp) != 0)
188 /* copy the important variables */
189 fake._flags = fp->_flags & ~__SNBF;
190 fake._file = fp->_file;
191 fake._cookie = fp->_cookie;
192 fake._write = fp->_write;
193 fake._orientation = fp->_orientation;
194 fake._mbstate = fp->_mbstate;
196 /* set up the buffer */
197 fake._bf._base = fake._p = buf;
198 fake._bf._size = fake._w = sizeof(buf);
199 fake._lbfsize = 0; /* not actually used, but Just In Case */
201 /* do the work, then copy any error status */
202 ret = __vfprintf(&fake, locale, fmt, ap);
203 if (ret >= 0 && __fflush(&fake))
205 if (fake._flags & __SERR)
206 fp->_flags |= __SERR;
211 * Convert a wide character string argument for the %ls format to a multibyte
212 * string representation. If not -1, prec specifies the maximum number of
213 * bytes to output, and also means that we can't assume that the wide char.
214 * string ends is null-terminated.
217 __wcsconv(wchar_t *wcsarg, int prec)
219 static const mbstate_t initial;
221 char buf[MB_LEN_MAX];
226 /* Allocate space for the maximum number of bytes we could output. */
230 nbytes = wcsrtombs(NULL, (const wchar_t **)&p, 0, &mbs);
231 if (nbytes == (size_t)-1)
235 * Optimisation: if the output precision is small enough,
236 * just allocate enough memory for the maximum instead of
237 * scanning the string.
246 clen = wcrtomb(buf, *p++, &mbs);
247 if (clen == 0 || clen == (size_t)-1 ||
248 nbytes + clen > prec)
254 if ((convbuf = malloc(nbytes + 1)) == NULL)
257 /* Fill the output buffer. */
260 if ((nbytes = wcsrtombs(convbuf, (const wchar_t **)&p,
261 nbytes, &mbs)) == (size_t)-1) {
265 convbuf[nbytes] = '\0';
273 vfprintf_l(FILE * __restrict fp, locale_t locale, const char * __restrict fmt0,
279 FLOCKFILE_CANCELSAFE(fp);
280 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
281 if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
283 ret = __sbprintf(fp, locale, fmt0, ap);
285 ret = __vfprintf(fp, locale, fmt0, ap);
286 FUNLOCKFILE_CANCELSAFE();
290 vfprintf(FILE * __restrict fp, const char * __restrict fmt0, va_list ap)
292 return vfprintf_l(fp, __get_locale(), fmt0, ap);
296 * The size of the buffer we use as scratch space for integer
297 * conversions, among other things. We need enough space to
298 * write a uintmax_t in octal (plus one byte).
300 #if UINTMAX_MAX <= UINT64_MAX
303 #error "BUF must be large enough to format a uintmax_t"
307 * Non-MT-safe version
310 __vfprintf(FILE *fp, locale_t locale, const char *fmt0, va_list ap)
312 char *fmt; /* format string */
313 int ch; /* character from fmt */
314 int n, n2; /* handy integer (short term usage) */
315 char *cp; /* handy char pointer (short term usage) */
316 int flags; /* flags as above */
317 int ret; /* return value accumulator */
318 int width; /* width from format (%8d), or 0 */
319 int prec; /* precision from format; <0 for N/A */
321 char sign; /* sign prefix (' ', '+', '-', or \0) */
322 struct grouping_state gs; /* thousands' grouping info */
324 #ifndef NO_FLOATING_POINT
326 * We can decompose the printed representation of floating
327 * point numbers into several parts, some of which may be empty:
329 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
332 * A: 'sign' holds this value if present; '\0' otherwise
333 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
334 * C: cp points to the string MMMNNN. Leading and trailing
335 * zeros are not in the string and must be added.
336 * D: expchar holds this character; '\0' if no exponent, e.g. %f
337 * F: at least two digits for decimal, at least one digit for hex
339 char *decimal_point; /* locale specific decimal point */
340 int decpt_len; /* length of decimal_point */
341 int signflag; /* true if float is negative */
342 union { /* floating point arguments %[aAeEfFgG] */
346 int expt; /* integer value of exponent */
347 char expchar; /* exponent character: [eEpP\0] */
348 char *dtoaend; /* pointer to end of converted digits */
349 int expsize; /* character count for expstr */
350 int ndig; /* actual number of digits returned by dtoa */
351 char expstr[MAXEXPDIG+2]; /* buffer for exponent string: e+ZZZ */
352 char *dtoaresult; /* buffer allocated by dtoa */
354 u_long ulval; /* integer arguments %[diouxX] */
355 uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */
356 int base; /* base for [diouxX] conversion */
357 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
358 int realsz; /* field size expanded by dprec, sign, etc */
359 int size; /* size of converted field or string */
360 int prsize; /* max size of printed field */
361 const char *xdigs; /* digits for %[xX] conversion */
362 struct io_state io; /* I/O buffering state */
363 char buf[BUF]; /* buffer with space for digits of uintmax_t */
364 char ox[2]; /* space for 0x; ox[1] is either x, X, or \0 */
365 union arg *argtable; /* args, built due to positional arg */
366 union arg statargtable [STATIC_ARG_TBL_SIZE];
367 int nextarg; /* 1-based argument index */
368 va_list orgap; /* original argument pointer */
369 char *convbuf; /* wide to multibyte conversion result */
372 static const char xdigs_lower[16] = "0123456789abcdef";
373 static const char xdigs_upper[16] = "0123456789ABCDEF";
375 /* BEWARE, these `goto error' on error. */
376 #define PRINT(ptr, len) { \
377 if (io_print(&io, (ptr), (len), locale)) \
380 #define PAD(howmany, with) { \
381 if (io_pad(&io, (howmany), (with), locale)) \
384 #define PRINTANDPAD(p, ep, len, with) { \
385 if (io_printandpad(&io, (p), (ep), (len), (with), locale)) \
389 if (io_flush(&io, locale)) \
394 * Get the argument indexed by nextarg. If the argument table is
395 * built, use it to get the argument. If its not, get the next
396 * argument (and arguments must be gotten sequentially).
398 #define GETARG(type) \
399 ((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
400 (nextarg++, va_arg(ap, type)))
403 * To extend shorts properly, we need both signed and unsigned
404 * argument extraction methods.
407 (flags&LONGINT ? GETARG(long) : \
408 flags&SHORTINT ? (long)(short)GETARG(int) : \
409 flags&CHARINT ? (long)(signed char)GETARG(int) : \
412 (flags&LONGINT ? GETARG(u_long) : \
413 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
414 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
415 (u_long)GETARG(u_int))
416 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
418 (flags&INTMAXT ? GETARG(intmax_t) : \
419 flags&SIZET ? (intmax_t)GETARG(ssize_t) : \
420 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
421 (intmax_t)GETARG(long long))
423 (flags&INTMAXT ? GETARG(uintmax_t) : \
424 flags&SIZET ? (uintmax_t)GETARG(size_t) : \
425 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
426 (uintmax_t)GETARG(unsigned long long))
429 * Get * arguments, including the form *nn$. Preserve the nextarg
430 * that the argument can be gotten once the type is determined.
432 #define GETASTER(val) \
435 while (is_digit(*cp)) { \
436 n2 = 10 * n2 + to_digit(*cp); \
440 int hold = nextarg; \
441 if (argtable == NULL) { \
442 argtable = statargtable; \
443 if (__find_arguments (fmt0, orgap, &argtable)) { \
449 val = GETARG (int); \
453 val = GETARG (int); \
456 if (__use_xprintf == 0 && getenv("USE_XPRINTF"))
458 if (__use_xprintf > 0)
459 return (__xvprintf(fp, fmt0, ap));
461 /* sorry, fprintf(read_only_file, "") returns EOF, not 0 */
462 if (prepwrite(fp) != 0) {
467 savserr = fp->_flags & __SERR;
468 fp->_flags &= ~__SERR;
478 #ifndef NO_FLOATING_POINT
480 decimal_point = localeconv_l(locale)->decimal_point;
481 /* The overwhelmingly common case is decpt_len == 1. */
482 decpt_len = (decimal_point[1] == '\0' ? 1 : strlen(decimal_point));
486 * Scan the format for conversions (`%' character).
489 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
491 if ((n = fmt - cp) != 0) {
492 if ((unsigned)ret + n > INT_MAX) {
502 fmt++; /* skip over '%' */
513 reswitch: switch (ch) {
516 * ``If the space and + flags both appear, the space
517 * flag will be ignored.''
528 * ``A negative field width argument is taken as a
529 * - flag followed by a positive field width.''
531 * They don't exclude field widths read from args.
548 if ((ch = *fmt++) == '*') {
553 while (is_digit(ch)) {
554 prec = 10 * prec + to_digit(ch);
560 * ``Note that 0 is taken as a flag, not as the
561 * beginning of a field width.''
566 case '1': case '2': case '3': case '4':
567 case '5': case '6': case '7': case '8': case '9':
570 n = 10 * n + to_digit(ch);
572 } while (is_digit(ch));
575 if (argtable == NULL) {
576 argtable = statargtable;
577 if (__find_arguments (fmt0, orgap,
587 #ifndef NO_FLOATING_POINT
593 if (flags & SHORTINT) {
603 if (flags & LONGINT) {
610 flags |= LLONGINT; /* not necessarily */
622 if (flags & LONGINT) {
623 static const mbstate_t initial;
628 mbseqlen = wcrtomb(cp = buf,
629 (wchar_t)GETARG(wint_t), &mbs);
630 if (mbseqlen == (size_t)-1) {
631 fp->_flags |= __SERR;
634 size = (int)mbseqlen;
636 *(cp = buf) = GETARG(int);
646 if (flags & INTMAX_SIZE) {
648 if ((intmax_t)ujval < 0) {
654 if ((long)ulval < 0) {
661 #ifndef NO_FLOATING_POINT
675 if (dtoaresult != NULL)
676 freedtoa(dtoaresult);
677 if (flags & LONGDBL) {
678 fparg.ldbl = GETARG(long double);
680 __hldtoa(fparg.ldbl, xdigs, prec,
681 &expt, &signflag, &dtoaend);
683 fparg.dbl = GETARG(double);
685 __hdtoa(fparg.dbl, xdigs, prec,
686 &expt, &signflag, &dtoaend);
696 if (prec < 0) /* account for digit before decpt */
707 expchar = ch - ('g' - 'e');
713 if (dtoaresult != NULL)
714 freedtoa(dtoaresult);
715 if (flags & LONGDBL) {
716 fparg.ldbl = GETARG(long double);
718 __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
719 &expt, &signflag, &dtoaend);
721 fparg.dbl = GETARG(double);
723 dtoa(fparg.dbl, expchar ? 2 : 3, prec,
724 &expt, &signflag, &dtoaend);
731 if (expt == INT_MAX) { /* inf or nan */
733 cp = (ch >= 'a') ? "nan" : "NAN";
736 cp = (ch >= 'a') ? "inf" : "INF";
743 if (ch == 'g' || ch == 'G') {
744 if (expt > -4 && expt <= prec) {
745 /* Make %[gG] smell like %[fF] */
755 * Make %[gG] smell like %[eE], but
756 * trim trailing zeroes if no # flag.
763 expsize = exponent(expstr, expt - 1, expchar);
764 size = expsize + prec;
765 if (prec > 1 || flags & ALT)
768 /* space for digits before decimal point */
773 /* space for decimal pt and following digits */
774 if (prec || flags & ALT)
775 size += prec + decpt_len;
776 if ((flags & GROUPING) && expt > 0)
777 size += grouping_init(&gs, expt, locale);
780 #endif /* !NO_FLOATING_POINT */
782 cp = strerror(saved_errno);
783 size = (prec >= 0) ? strnlen(cp, prec) : strlen(cp);
788 * Assignment-like behavior is specified if the
789 * value overflows or is otherwise unrepresentable.
790 * C99 says to use `signed char' for %hhn conversions.
792 if (flags & LLONGINT)
793 *GETARG(long long *) = ret;
794 else if (flags & SIZET)
795 *GETARG(ssize_t *) = (ssize_t)ret;
796 else if (flags & PTRDIFFT)
797 *GETARG(ptrdiff_t *) = ret;
798 else if (flags & INTMAXT)
799 *GETARG(intmax_t *) = ret;
800 else if (flags & LONGINT)
801 *GETARG(long *) = ret;
802 else if (flags & SHORTINT)
803 *GETARG(short *) = ret;
804 else if (flags & CHARINT)
805 *GETARG(signed char *) = ret;
807 *GETARG(int *) = ret;
808 continue; /* no output */
813 if (flags & INTMAX_SIZE)
821 * ``The argument shall be a pointer to void. The
822 * value of the pointer is converted to a sequence
823 * of printable characters, in an implementation-
827 ujval = (uintmax_t)(uintptr_t)GETARG(void *);
830 flags = flags | INTMAXT;
837 if (flags & LONGINT) {
842 if ((wcp = GETARG(wchar_t *)) == NULL)
845 convbuf = __wcsconv(wcp, prec);
846 if (convbuf == NULL) {
847 fp->_flags |= __SERR;
852 } else if ((cp = GETARG(char *)) == NULL)
854 size = (prec >= 0) ? strnlen(cp, prec) : strlen(cp);
861 if (flags & INTMAX_SIZE)
873 if (flags & INTMAX_SIZE)
878 /* leading 0x/X only if non-zero */
880 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
884 /* unsigned conversions */
887 * ``... diouXx conversions ... if a precision is
888 * specified, the 0 flag will be ignored.''
891 number: if ((dprec = prec) >= 0)
895 * ``The result of converting a zero value with an
896 * explicit precision of zero is no characters.''
899 * ``The C Standard is clear enough as is. The call
900 * printf("%#.0o", 0) should print 0.''
901 * -- Defect Report #151
904 if (flags & INTMAX_SIZE) {
905 if (ujval != 0 || prec != 0 ||
906 (flags & ALT && base == 8))
907 cp = __ujtoa(ujval, cp, base,
910 if (ulval != 0 || prec != 0 ||
911 (flags & ALT && base == 8))
912 cp = __ultoa(ulval, cp, base,
915 size = buf + BUF - cp;
916 if (size > BUF) /* should never happen */
918 if ((flags & GROUPING) && size != 0)
919 size += grouping_init(&gs, size, locale);
921 default: /* "%?" prints ?, unless ? is NUL */
924 /* pretend it was %c with argument ch */
933 * All reasonable formats wind up here. At this point, `cp'
934 * points to a string which (if not flags&LADJUST) should be
935 * padded out to `width' places. If flags&ZEROPAD, it should
936 * first be prefixed by any sign or other prefix; otherwise,
937 * it should be blank padded before the prefix is emitted.
938 * After any left-hand padding and prefixing, emit zeroes
939 * required by a decimal [diouxX] precision, then print the
940 * string proper, then emit zeroes required by any leftover
941 * floating precision; finally, if LADJUST, pad with blanks.
943 * Compute actual size, so we know how much to pad.
944 * size excludes decimal prec; realsz includes it.
946 realsz = dprec > size ? dprec : size;
952 prsize = width > realsz ? width : realsz;
953 if ((unsigned)ret + prsize > INT_MAX) {
959 /* right-adjusting blank padding */
960 if ((flags & (LADJUST|ZEROPAD)) == 0)
961 PAD(width - realsz, blanks);
967 if (ox[1]) { /* ox[1] is either x, X, or \0 */
972 /* right-adjusting zero padding */
973 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
974 PAD(width - realsz, zeroes);
976 /* the string or number proper */
977 #ifndef NO_FLOATING_POINT
978 if ((flags & FPT) == 0) {
980 /* leading zeroes from decimal precision */
981 PAD(dprec - size, zeroes);
983 if (grouping_print(&gs, &io, cp, buf+BUF, locale) < 0)
988 #ifndef NO_FLOATING_POINT
989 } else { /* glue together f_p fragments */
990 if (!expchar) { /* %[fF] or sufficiently short %[gG] */
993 if (prec || flags & ALT)
994 PRINT(decimal_point,decpt_len);
996 /* already handled initial 0's */
1000 n = grouping_print(&gs, &io,
1001 cp, dtoaend, locale);
1006 PRINTANDPAD(cp, dtoaend,
1010 if (prec || flags & ALT)
1011 PRINT(decimal_point,decpt_len);
1013 PRINTANDPAD(cp, dtoaend, prec, zeroes);
1014 } else { /* %[eE] or sufficiently long %[gG] */
1015 if (prec > 1 || flags & ALT) {
1017 PRINT(decimal_point, decpt_len);
1019 PAD(prec - ndig, zeroes);
1022 PRINT(expstr, expsize);
1026 /* left-adjusting padding (always blank) */
1027 if (flags & LADJUST)
1028 PAD(width - realsz, blanks);
1030 /* finally, adjust ret */
1033 FLUSH(); /* copy out the I/O vectors */
1039 #ifndef NO_FLOATING_POINT
1040 if (dtoaresult != NULL)
1041 freedtoa(dtoaresult);
1043 if (convbuf != NULL)
1048 fp->_flags |= savserr;
1049 if ((argtable != NULL) && (argtable != statargtable))