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 * Copyright (c) 2011 The FreeBSD Foundation
10 * Portions of this software were developed by David Chisnall
11 * under sponsorship from the FreeBSD Foundation.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * 4. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 #if defined(LIBC_SCCS) && !defined(lint)
40 static char sccsid[] = "@(#)vfprintf.c 8.1 (Berkeley) 6/4/93";
41 #endif /* LIBC_SCCS and not lint */
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
47 * Actual wprintf innards.
49 * Avoid making gratuitous changes to this source file; it should be kept
50 * as close as possible to vfprintf.c for ease of maintenance.
53 #include "namespace.h"
54 #include <sys/types.h>
67 #include "un-namespace.h"
69 #include "libc_private.h"
72 #include "printflocal.h"
73 #include "xlocale_private.h"
75 static int __sprint(FILE *, struct __suio *, locale_t);
76 static int __sbprintf(FILE *, locale_t, const wchar_t *, va_list) __noinline;
77 static wint_t __xfputwc(wchar_t, FILE *, locale_t);
78 static wchar_t *__mbsconv(char *, int);
81 #include "printfcommon.h"
83 struct grouping_state {
84 wchar_t thousands_sep; /* locale-specific thousands separator */
85 const char *grouping; /* locale-specific numeric grouping rules */
86 int lead; /* sig figs before decimal or group sep */
87 int nseps; /* number of group separators with ' */
88 int nrepeats; /* number of repeats of the last group */
91 static const mbstate_t initial_mbs;
94 get_decpt(locale_t locale)
101 nconv = mbrtowc(&decpt, localeconv_l(locale)->decimal_point, MB_CUR_MAX, &mbs);
102 if (nconv == (size_t)-1 || nconv == (size_t)-2)
103 decpt = '.'; /* failsafe */
107 static inline wchar_t
108 get_thousep(locale_t locale)
115 nconv = mbrtowc(&thousep, localeconv_l(locale)->thousands_sep,
117 if (nconv == (size_t)-1 || nconv == (size_t)-2)
118 thousep = '\0'; /* failsafe */
123 * Initialize the thousands' grouping state in preparation to print a
124 * number with ndigits digits. This routine returns the total number
125 * of wide characters that will be printed.
128 grouping_init(struct grouping_state *gs, int ndigits, locale_t locale)
131 gs->grouping = localeconv_l(locale)->grouping;
132 gs->thousands_sep = get_thousep(locale);
134 gs->nseps = gs->nrepeats = 0;
136 while (*gs->grouping != CHAR_MAX) {
137 if (gs->lead <= *gs->grouping)
139 gs->lead -= *gs->grouping;
140 if (*(gs->grouping+1)) {
146 return (gs->nseps + gs->nrepeats);
150 * Print a number with thousands' separators.
153 grouping_print(struct grouping_state *gs, struct io_state *iop,
154 const CHAR *cp, const CHAR *ep, locale_t locale)
156 const CHAR *cp0 = cp;
158 if (io_printandpad(iop, cp, ep, gs->lead, zeroes, locale))
161 while (gs->nseps > 0 || gs->nrepeats > 0) {
162 if (gs->nrepeats > 0)
168 if (io_print(iop, &gs->thousands_sep, 1, locale))
170 if (io_printandpad(iop, cp, ep, *gs->grouping, zeroes, locale))
181 * Flush out all the vectors defined by the given uio,
182 * then reset it so that it can be reused.
184 * XXX The fact that we do this a character at a time and convert to a
185 * multibyte character sequence even if the destination is a wide
186 * string eclipses the benefits of buffering.
189 __sprint(FILE *fp, struct __suio *uio, locale_t locale)
196 for (; uio->uio_resid != 0; uio->uio_resid -= len, iov++) {
197 p = (wchar_t *)iov->iov_base;
199 for (i = 0; i < len; i++) {
200 if (__xfputwc(p[i], fp, locale) == WEOF)
209 * Helper function for `fprintf to unbuffered unix file': creates a
210 * temporary buffer. We only work on write-only files; this avoids
211 * worries about ungetc buffers and so forth.
214 __sbprintf(FILE *fp, locale_t locale, const wchar_t *fmt, va_list ap)
218 unsigned char buf[BUFSIZ];
220 /* XXX This is probably not needed. */
221 if (prepwrite(fp) != 0)
224 /* copy the important variables */
225 fake._flags = fp->_flags & ~__SNBF;
226 fake._file = fp->_file;
227 fake._cookie = fp->_cookie;
228 fake._write = fp->_write;
229 fake._orientation = fp->_orientation;
230 fake._mbstate = fp->_mbstate;
232 /* set up the buffer */
233 fake._bf._base = fake._p = buf;
234 fake._bf._size = fake._w = sizeof(buf);
235 fake._lbfsize = 0; /* not actually used, but Just In Case */
237 /* do the work, then copy any error status */
238 ret = __vfwprintf(&fake, locale, fmt, ap);
239 if (ret >= 0 && __fflush(&fake))
241 if (fake._flags & __SERR)
242 fp->_flags |= __SERR;
247 * Like __fputwc, but handles fake string (__SSTR) files properly.
248 * File must already be locked.
251 __xfputwc(wchar_t wc, FILE *fp, locale_t locale)
254 char buf[MB_LEN_MAX];
259 if ((fp->_flags & __SSTR) == 0)
260 return (__fputwc(wc, fp, locale));
263 if ((len = wcrtomb(buf, wc, &mbs)) == (size_t)-1) {
264 fp->_flags |= __SERR;
272 return (__sfvwrite(fp, &uio) != EOF ? (wint_t)wc : WEOF);
276 * Convert a multibyte character string argument for the %s format to a wide
277 * string representation. ``prec'' specifies the maximum number of bytes
278 * to output. If ``prec'' is greater than or equal to zero, we can't assume
279 * that the multibyte char. string ends in a null character.
282 __mbsconv(char *mbsarg, int prec)
285 wchar_t *convbuf, *wcp;
287 size_t insize, nchars, nconv;
293 * Supplied argument is a multibyte string; convert it to wide
298 * String is not guaranteed to be NUL-terminated. Find the
299 * number of characters to print.
302 insize = nchars = nconv = 0;
304 while (nchars != (size_t)prec) {
305 nconv = mbrlen(p, MB_CUR_MAX, &mbs);
306 if (nconv == 0 || nconv == (size_t)-1 ||
313 if (nconv == (size_t)-1 || nconv == (size_t)-2)
316 insize = strlen(mbsarg);
321 * Allocate buffer for the result and perform the conversion,
322 * converting at most `size' bytes of the input multibyte string to
323 * wide characters for printing.
325 convbuf = malloc((insize + 1) * sizeof(*convbuf));
331 while (insize != 0) {
332 nconv = mbrtowc(wcp, p, insize, &mbs);
333 if (nconv == 0 || nconv == (size_t)-1 || nconv == (size_t)-2)
339 if (nconv == (size_t)-1 || nconv == (size_t)-2) {
352 vfwprintf_l(FILE * __restrict fp, locale_t locale,
353 const wchar_t * __restrict fmt0, va_list ap)
359 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
360 if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
362 ret = __sbprintf(fp, locale, fmt0, ap);
364 ret = __vfwprintf(fp, locale, fmt0, ap);
369 vfwprintf(FILE * __restrict fp, const wchar_t * __restrict fmt0, va_list ap)
371 return vfwprintf_l(fp, __get_locale(), fmt0, ap);
375 * The size of the buffer we use as scratch space for integer
376 * conversions, among other things. We need enough space to
377 * write a uintmax_t in octal (plus one byte).
379 #if UINTMAX_MAX <= UINT64_MAX
382 #error "BUF must be large enough to format a uintmax_t"
386 * Non-MT-safe version
389 __vfwprintf(FILE *fp, locale_t locale, const wchar_t *fmt0, va_list ap)
391 wchar_t *fmt; /* format string */
392 wchar_t ch; /* character from fmt */
393 int n, n2; /* handy integer (short term usage) */
394 wchar_t *cp; /* handy char pointer (short term usage) */
395 int flags; /* flags as above */
396 int ret; /* return value accumulator */
397 int width; /* width from format (%8d), or 0 */
398 int prec; /* precision from format; <0 for N/A */
399 wchar_t sign; /* sign prefix (' ', '+', '-', or \0) */
400 struct grouping_state gs; /* thousands' grouping info */
401 #ifndef NO_FLOATING_POINT
403 * We can decompose the printed representation of floating
404 * point numbers into several parts, some of which may be empty:
406 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
409 * A: 'sign' holds this value if present; '\0' otherwise
410 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
411 * C: cp points to the string MMMNNN. Leading and trailing
412 * zeros are not in the string and must be added.
413 * D: expchar holds this character; '\0' if no exponent, e.g. %f
414 * F: at least two digits for decimal, at least one digit for hex
416 wchar_t decimal_point; /* locale specific decimal point */
417 int signflag; /* true if float is negative */
418 union { /* floating point arguments %[aAeEfFgG] */
422 int expt; /* integer value of exponent */
423 char expchar; /* exponent character: [eEpP\0] */
424 char *dtoaend; /* pointer to end of converted digits */
425 int expsize; /* character count for expstr */
426 int ndig; /* actual number of digits returned by dtoa */
427 wchar_t expstr[MAXEXPDIG+2]; /* buffer for exponent string: e+ZZZ */
428 char *dtoaresult; /* buffer allocated by dtoa */
430 u_long ulval; /* integer arguments %[diouxX] */
431 uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */
432 int base; /* base for [diouxX] conversion */
433 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
434 int realsz; /* field size expanded by dprec, sign, etc */
435 int size; /* size of converted field or string */
436 int prsize; /* max size of printed field */
437 const char *xdigs; /* digits for [xX] conversion */
438 struct io_state io; /* I/O buffering state */
439 wchar_t buf[BUF]; /* buffer with space for digits of uintmax_t */
440 wchar_t ox[2]; /* space for 0x hex-prefix */
441 union arg *argtable; /* args, built due to positional arg */
442 union arg statargtable [STATIC_ARG_TBL_SIZE];
443 int nextarg; /* 1-based argument index */
444 va_list orgap; /* original argument pointer */
445 wchar_t *convbuf; /* multibyte to wide conversion result */
447 static const char xdigs_lower[16] = "0123456789abcdef";
448 static const char xdigs_upper[16] = "0123456789ABCDEF";
450 /* BEWARE, these `goto error' on error. */
451 #define PRINT(ptr, len) do { \
452 if (io_print(&io, (ptr), (len), locale)) \
455 #define PAD(howmany, with) { \
456 if (io_pad(&io, (howmany), (with), locale)) \
459 #define PRINTANDPAD(p, ep, len, with) { \
460 if (io_printandpad(&io, (p), (ep), (len), (with), locale)) \
464 if (io_flush(&io, locale)) \
469 * Get the argument indexed by nextarg. If the argument table is
470 * built, use it to get the argument. If its not, get the next
471 * argument (and arguments must be gotten sequentially).
473 #define GETARG(type) \
474 ((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
475 (nextarg++, va_arg(ap, type)))
478 * To extend shorts properly, we need both signed and unsigned
479 * argument extraction methods.
482 (flags&LONGINT ? GETARG(long) : \
483 flags&SHORTINT ? (long)(short)GETARG(int) : \
484 flags&CHARINT ? (long)(signed char)GETARG(int) : \
487 (flags&LONGINT ? GETARG(u_long) : \
488 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
489 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
490 (u_long)GETARG(u_int))
491 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
493 (flags&INTMAXT ? GETARG(intmax_t) : \
494 flags&SIZET ? (intmax_t)GETARG(ssize_t) : \
495 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
496 (intmax_t)GETARG(long long))
498 (flags&INTMAXT ? GETARG(uintmax_t) : \
499 flags&SIZET ? (uintmax_t)GETARG(size_t) : \
500 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
501 (uintmax_t)GETARG(unsigned long long))
504 * Get * arguments, including the form *nn$. Preserve the nextarg
505 * that the argument can be gotten once the type is determined.
507 #define GETASTER(val) \
510 while (is_digit(*cp)) { \
511 n2 = 10 * n2 + to_digit(*cp); \
515 int hold = nextarg; \
516 if (argtable == NULL) { \
517 argtable = statargtable; \
518 if (__find_warguments (fmt0, orgap, &argtable)) { \
524 val = GETARG (int); \
528 val = GETARG (int); \
532 /* sorry, fwprintf(read_only_file, L"") returns WEOF, not 0 */
533 if (prepwrite(fp) != 0)
537 fmt = (wchar_t *)fmt0;
543 #ifndef NO_FLOATING_POINT
544 decimal_point = get_decpt(locale);
548 * Scan the format for conversions (`%' character).
551 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
553 if ((n = fmt - cp) != 0) {
554 if ((unsigned)ret + n > INT_MAX) {
563 fmt++; /* skip over '%' */
574 reswitch: switch (ch) {
577 * ``If the space and + flags both appear, the space
578 * flag will be ignored.''
589 * ``A negative field width argument is taken as a
590 * - flag followed by a positive field width.''
592 * They don't exclude field widths read from args.
609 if ((ch = *fmt++) == '*') {
614 while (is_digit(ch)) {
615 prec = 10 * prec + to_digit(ch);
621 * ``Note that 0 is taken as a flag, not as the
622 * beginning of a field width.''
627 case '1': case '2': case '3': case '4':
628 case '5': case '6': case '7': case '8': case '9':
631 n = 10 * n + to_digit(ch);
633 } while (is_digit(ch));
636 if (argtable == NULL) {
637 argtable = statargtable;
638 if (__find_warguments (fmt0, orgap,
648 #ifndef NO_FLOATING_POINT
654 if (flags & SHORTINT) {
664 if (flags & LONGINT) {
671 flags |= LLONGINT; /* not necessarily */
684 *(cp = buf) = (wchar_t)GETARG(wint_t);
686 *(cp = buf) = (wchar_t)btowc(GETARG(int));
695 if (flags & INTMAX_SIZE) {
697 if ((intmax_t)ujval < 0) {
703 if ((long)ulval < 0) {
710 #ifndef NO_FLOATING_POINT
724 if (flags & LONGDBL) {
725 fparg.ldbl = GETARG(long double);
727 __hldtoa(fparg.ldbl, xdigs, prec,
728 &expt, &signflag, &dtoaend);
730 fparg.dbl = GETARG(double);
732 __hdtoa(fparg.dbl, xdigs, prec,
733 &expt, &signflag, &dtoaend);
736 prec = dtoaend - dtoaresult;
741 ndig = dtoaend - dtoaresult;
742 cp = convbuf = __mbsconv(dtoaresult, -1);
743 freedtoa(dtoaresult);
748 if (prec < 0) /* account for digit before decpt */
759 expchar = ch - ('g' - 'e');
767 if (flags & LONGDBL) {
768 fparg.ldbl = GETARG(long double);
770 __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
771 &expt, &signflag, &dtoaend);
773 fparg.dbl = GETARG(double);
775 dtoa(fparg.dbl, expchar ? 2 : 3, prec,
776 &expt, &signflag, &dtoaend);
780 ndig = dtoaend - dtoaresult;
781 cp = convbuf = __mbsconv(dtoaresult, -1);
782 freedtoa(dtoaresult);
786 if (expt == INT_MAX) { /* inf or nan */
788 cp = (ch >= 'a') ? L"nan" : L"NAN";
791 cp = (ch >= 'a') ? L"inf" : L"INF";
797 if (ch == 'g' || ch == 'G') {
798 if (expt > -4 && expt <= prec) {
799 /* Make %[gG] smell like %[fF] */
809 * Make %[gG] smell like %[eE], but
810 * trim trailing zeroes if no # flag.
817 expsize = exponent(expstr, expt - 1, expchar);
818 size = expsize + prec;
819 if (prec > 1 || flags & ALT)
822 /* space for digits before decimal point */
827 /* space for decimal pt and following digits */
828 if (prec || flags & ALT)
830 if ((flags & GROUPING) && expt > 0)
831 size += grouping_init(&gs, expt, locale);
834 #endif /* !NO_FLOATING_POINT */
837 * Assignment-like behavior is specified if the
838 * value overflows or is otherwise unrepresentable.
839 * C99 says to use `signed char' for %hhn conversions.
841 if (flags & LLONGINT)
842 *GETARG(long long *) = ret;
843 else if (flags & SIZET)
844 *GETARG(ssize_t *) = (ssize_t)ret;
845 else if (flags & PTRDIFFT)
846 *GETARG(ptrdiff_t *) = ret;
847 else if (flags & INTMAXT)
848 *GETARG(intmax_t *) = ret;
849 else if (flags & LONGINT)
850 *GETARG(long *) = ret;
851 else if (flags & SHORTINT)
852 *GETARG(short *) = ret;
853 else if (flags & CHARINT)
854 *GETARG(signed char *) = ret;
856 *GETARG(int *) = ret;
857 continue; /* no output */
862 if (flags & INTMAX_SIZE)
870 * ``The argument shall be a pointer to void. The
871 * value of the pointer is converted to a sequence
872 * of printable characters, in an implementation-
876 ujval = (uintmax_t)(uintptr_t)GETARG(void *);
879 flags = flags | INTMAXT;
886 if (flags & LONGINT) {
887 if ((cp = GETARG(wchar_t *)) == NULL)
894 if ((mbp = GETARG(char *)) == NULL)
897 convbuf = __mbsconv(mbp, prec);
898 if (convbuf == NULL) {
899 fp->_flags |= __SERR;
905 size = (prec >= 0) ? wcsnlen(cp, prec) : wcslen(cp);
912 if (flags & INTMAX_SIZE)
924 if (flags & INTMAX_SIZE)
929 /* leading 0x/X only if non-zero */
931 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
935 /* unsigned conversions */
938 * ``... diouXx conversions ... if a precision is
939 * specified, the 0 flag will be ignored.''
942 number: if ((dprec = prec) >= 0)
946 * ``The result of converting a zero value with an
947 * explicit precision of zero is no characters.''
950 * ``The C Standard is clear enough as is. The call
951 * printf("%#.0o", 0) should print 0.''
952 * -- Defect Report #151
955 if (flags & INTMAX_SIZE) {
956 if (ujval != 0 || prec != 0 ||
957 (flags & ALT && base == 8))
958 cp = __ujtoa(ujval, cp, base,
961 if (ulval != 0 || prec != 0 ||
962 (flags & ALT && base == 8))
963 cp = __ultoa(ulval, cp, base,
966 size = buf + BUF - cp;
967 if (size > BUF) /* should never happen */
969 if ((flags & GROUPING) && size != 0)
970 size += grouping_init(&gs, size, locale);
972 default: /* "%?" prints ?, unless ? is NUL */
975 /* pretend it was %c with argument ch */
984 * All reasonable formats wind up here. At this point, `cp'
985 * points to a string which (if not flags&LADJUST) should be
986 * padded out to `width' places. If flags&ZEROPAD, it should
987 * first be prefixed by any sign or other prefix; otherwise,
988 * it should be blank padded before the prefix is emitted.
989 * After any left-hand padding and prefixing, emit zeroes
990 * required by a decimal [diouxX] precision, then print the
991 * string proper, then emit zeroes required by any leftover
992 * floating precision; finally, if LADJUST, pad with blanks.
994 * Compute actual size, so we know how much to pad.
995 * size excludes decimal prec; realsz includes it.
997 realsz = dprec > size ? dprec : size;
1003 prsize = width > realsz ? width : realsz;
1004 if ((unsigned)ret + prsize > INT_MAX) {
1009 /* right-adjusting blank padding */
1010 if ((flags & (LADJUST|ZEROPAD)) == 0)
1011 PAD(width - realsz, blanks);
1017 if (ox[1]) { /* ox[1] is either x, X, or \0 */
1022 /* right-adjusting zero padding */
1023 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1024 PAD(width - realsz, zeroes);
1026 /* the string or number proper */
1027 #ifndef NO_FLOATING_POINT
1028 if ((flags & FPT) == 0) {
1030 /* leading zeroes from decimal precision */
1031 PAD(dprec - size, zeroes);
1033 if (grouping_print(&gs, &io, cp, buf+BUF, locale) < 0)
1038 #ifndef NO_FLOATING_POINT
1039 } else { /* glue together f_p fragments */
1040 if (!expchar) { /* %[fF] or sufficiently short %[gG] */
1043 if (prec || flags & ALT)
1044 PRINT(&decimal_point, 1);
1046 /* already handled initial 0's */
1050 n = grouping_print(&gs, &io,
1051 cp, convbuf + ndig, locale);
1056 PRINTANDPAD(cp, convbuf + ndig,
1060 if (prec || flags & ALT)
1061 PRINT(&decimal_point, 1);
1063 PRINTANDPAD(cp, convbuf + ndig, prec, zeroes);
1064 } else { /* %[eE] or sufficiently long %[gG] */
1065 if (prec > 1 || flags & ALT) {
1067 buf[1] = decimal_point;
1070 PAD(prec - ndig, zeroes);
1073 PRINT(expstr, expsize);
1077 /* left-adjusting padding (always blank) */
1078 if (flags & LADJUST)
1079 PAD(width - realsz, blanks);
1081 /* finally, adjust ret */
1084 FLUSH(); /* copy out the I/O vectors */
1090 if (convbuf != NULL)
1094 if ((argtable != NULL) && (argtable != statargtable))