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
34 #if defined(LIBC_SCCS) && !defined(lint)
35 static char sccsid[] = "@(#)vfprintf.c 8.1 (Berkeley) 6/4/93";
36 #endif /* LIBC_SCCS and not lint */
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
42 * Actual wprintf innards.
44 * Avoid making gratuitous changes to this source file; it should be kept
45 * as close as possible to vfprintf.c for ease of maintenance.
48 #include "namespace.h"
49 #include <sys/types.h>
62 #include "un-namespace.h"
64 #include "libc_private.h"
67 #include "printflocal.h"
69 static int __sprint(FILE *, struct __suio *);
70 static int __sbprintf(FILE *, const wchar_t *, va_list) __noinline;
71 static wint_t __xfputwc(wchar_t, FILE *);
72 static wchar_t *__mbsconv(char *, int);
75 #include "printfcommon.h"
77 struct grouping_state {
78 wchar_t thousands_sep; /* locale-specific thousands separator */
79 const char *grouping; /* locale-specific numeric grouping rules */
80 int lead; /* sig figs before decimal or group sep */
81 int nseps; /* number of group separators with ' */
82 int nrepeats; /* number of repeats of the last group */
85 static const mbstate_t initial_mbs;
95 nconv = mbrtowc(&decpt, localeconv()->decimal_point, MB_CUR_MAX, &mbs);
96 if (nconv == (size_t)-1 || nconv == (size_t)-2)
97 decpt = '.'; /* failsafe */
101 static inline wchar_t
109 nconv = mbrtowc(&thousep, localeconv()->thousands_sep,
111 if (nconv == (size_t)-1 || nconv == (size_t)-2)
112 thousep = '\0'; /* failsafe */
117 * Initialize the thousands' grouping state in preparation to print a
118 * number with ndigits digits. This routine returns the total number
119 * of wide characters that will be printed.
122 grouping_init(struct grouping_state *gs, int ndigits)
125 gs->grouping = localeconv()->grouping;
126 gs->thousands_sep = get_thousep();
128 gs->nseps = gs->nrepeats = 0;
130 while (*gs->grouping != CHAR_MAX) {
131 if (gs->lead <= *gs->grouping)
133 gs->lead -= *gs->grouping;
134 if (*(gs->grouping+1)) {
140 return (gs->nseps + gs->nrepeats);
144 * Print a number with thousands' separators.
147 grouping_print(struct grouping_state *gs, struct io_state *iop,
148 const CHAR *cp, const CHAR *ep)
150 const CHAR *cp0 = cp;
152 if (io_printandpad(iop, cp, ep, gs->lead, zeroes))
155 while (gs->nseps > 0 || gs->nrepeats > 0) {
156 if (gs->nrepeats > 0)
162 if (io_print(iop, &gs->thousands_sep, 1))
164 if (io_printandpad(iop, cp, ep, *gs->grouping, zeroes))
175 * Flush out all the vectors defined by the given uio,
176 * then reset it so that it can be reused.
178 * XXX The fact that we do this a character at a time and convert to a
179 * multibyte character sequence even if the destination is a wide
180 * string eclipses the benefits of buffering.
183 __sprint(FILE *fp, struct __suio *uio)
190 for (; uio->uio_resid != 0; uio->uio_resid -= len, iov++) {
191 p = (wchar_t *)iov->iov_base;
193 for (i = 0; i < len; i++) {
194 if (__xfputwc(p[i], fp) == WEOF)
203 * Helper function for `fprintf to unbuffered unix file': creates a
204 * temporary buffer. We only work on write-only files; this avoids
205 * worries about ungetc buffers and so forth.
208 __sbprintf(FILE *fp, const wchar_t *fmt, va_list ap)
212 unsigned char buf[BUFSIZ];
214 /* XXX This is probably not needed. */
215 if (prepwrite(fp) != 0)
218 /* copy the important variables */
219 fake._flags = fp->_flags & ~__SNBF;
220 fake._file = fp->_file;
221 fake._cookie = fp->_cookie;
222 fake._write = fp->_write;
223 fake._orientation = fp->_orientation;
224 fake._mbstate = fp->_mbstate;
226 /* set up the buffer */
227 fake._bf._base = fake._p = buf;
228 fake._bf._size = fake._w = sizeof(buf);
229 fake._lbfsize = 0; /* not actually used, but Just In Case */
231 /* do the work, then copy any error status */
232 ret = __vfwprintf(&fake, fmt, ap);
233 if (ret >= 0 && __fflush(&fake))
235 if (fake._flags & __SERR)
236 fp->_flags |= __SERR;
241 * Like __fputwc, but handles fake string (__SSTR) files properly.
242 * File must already be locked.
245 __xfputwc(wchar_t wc, FILE *fp)
248 char buf[MB_LEN_MAX];
253 if ((fp->_flags & __SSTR) == 0)
254 return (__fputwc(wc, fp));
257 if ((len = wcrtomb(buf, wc, &mbs)) == (size_t)-1) {
258 fp->_flags |= __SERR;
266 return (__sfvwrite(fp, &uio) != EOF ? (wint_t)wc : WEOF);
270 * Convert a multibyte character string argument for the %s format to a wide
271 * string representation. ``prec'' specifies the maximum number of bytes
272 * to output. If ``prec'' is greater than or equal to zero, we can't assume
273 * that the multibyte char. string ends in a null character.
276 __mbsconv(char *mbsarg, int prec)
279 wchar_t *convbuf, *wcp;
281 size_t insize, nchars, nconv;
287 * Supplied argument is a multibyte string; convert it to wide
292 * String is not guaranteed to be NUL-terminated. Find the
293 * number of characters to print.
296 insize = nchars = nconv = 0;
298 while (nchars != (size_t)prec) {
299 nconv = mbrlen(p, MB_CUR_MAX, &mbs);
300 if (nconv == 0 || nconv == (size_t)-1 ||
307 if (nconv == (size_t)-1 || nconv == (size_t)-2)
310 insize = strlen(mbsarg);
315 * Allocate buffer for the result and perform the conversion,
316 * converting at most `size' bytes of the input multibyte string to
317 * wide characters for printing.
319 convbuf = malloc((insize + 1) * sizeof(*convbuf));
325 while (insize != 0) {
326 nconv = mbrtowc(wcp, p, insize, &mbs);
327 if (nconv == 0 || nconv == (size_t)-1 || nconv == (size_t)-2)
333 if (nconv == (size_t)-1 || nconv == (size_t)-2) {
346 vfwprintf(FILE * __restrict fp, const wchar_t * __restrict fmt0, va_list ap)
352 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
353 if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
355 ret = __sbprintf(fp, fmt0, ap);
357 ret = __vfwprintf(fp, fmt0, ap);
363 * The size of the buffer we use as scratch space for integer
364 * conversions, among other things. We need enough space to
365 * write a uintmax_t in octal (plus one byte).
367 #if UINTMAX_MAX <= UINT64_MAX
370 #error "BUF must be large enough to format a uintmax_t"
374 * Non-MT-safe version
377 __vfwprintf(FILE *fp, const wchar_t *fmt0, va_list ap)
379 wchar_t *fmt; /* format string */
380 wchar_t ch; /* character from fmt */
381 int n, n2; /* handy integer (short term usage) */
382 wchar_t *cp; /* handy char pointer (short term usage) */
383 int flags; /* flags as above */
384 int ret; /* return value accumulator */
385 int width; /* width from format (%8d), or 0 */
386 int prec; /* precision from format; <0 for N/A */
387 wchar_t sign; /* sign prefix (' ', '+', '-', or \0) */
388 struct grouping_state gs; /* thousands' grouping info */
389 #ifndef NO_FLOATING_POINT
391 * We can decompose the printed representation of floating
392 * point numbers into several parts, some of which may be empty:
394 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
397 * A: 'sign' holds this value if present; '\0' otherwise
398 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
399 * C: cp points to the string MMMNNN. Leading and trailing
400 * zeros are not in the string and must be added.
401 * D: expchar holds this character; '\0' if no exponent, e.g. %f
402 * F: at least two digits for decimal, at least one digit for hex
404 wchar_t decimal_point; /* locale specific decimal point */
405 int signflag; /* true if float is negative */
406 union { /* floating point arguments %[aAeEfFgG] */
410 int expt; /* integer value of exponent */
411 char expchar; /* exponent character: [eEpP\0] */
412 char *dtoaend; /* pointer to end of converted digits */
413 int expsize; /* character count for expstr */
414 int ndig; /* actual number of digits returned by dtoa */
415 wchar_t expstr[MAXEXPDIG+2]; /* buffer for exponent string: e+ZZZ */
416 char *dtoaresult; /* buffer allocated by dtoa */
418 u_long ulval; /* integer arguments %[diouxX] */
419 uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */
420 int base; /* base for [diouxX] conversion */
421 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
422 int realsz; /* field size expanded by dprec, sign, etc */
423 int size; /* size of converted field or string */
424 int prsize; /* max size of printed field */
425 const char *xdigs; /* digits for [xX] conversion */
426 struct io_state io; /* I/O buffering state */
427 wchar_t buf[BUF]; /* buffer with space for digits of uintmax_t */
428 wchar_t ox[2]; /* space for 0x hex-prefix */
429 union arg *argtable; /* args, built due to positional arg */
430 union arg statargtable [STATIC_ARG_TBL_SIZE];
431 int nextarg; /* 1-based argument index */
432 va_list orgap; /* original argument pointer */
433 wchar_t *convbuf; /* multibyte to wide conversion result */
435 static const char xdigs_lower[16] = "0123456789abcdef";
436 static const char xdigs_upper[16] = "0123456789ABCDEF";
438 /* BEWARE, these `goto error' on error. */
439 #define PRINT(ptr, len) do { \
440 if (io_print(&io, (ptr), (len))) \
443 #define PAD(howmany, with) { \
444 if (io_pad(&io, (howmany), (with))) \
447 #define PRINTANDPAD(p, ep, len, with) { \
448 if (io_printandpad(&io, (p), (ep), (len), (with))) \
457 * Get the argument indexed by nextarg. If the argument table is
458 * built, use it to get the argument. If its not, get the next
459 * argument (and arguments must be gotten sequentially).
461 #define GETARG(type) \
462 ((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
463 (nextarg++, va_arg(ap, type)))
466 * To extend shorts properly, we need both signed and unsigned
467 * argument extraction methods.
470 (flags&LONGINT ? GETARG(long) : \
471 flags&SHORTINT ? (long)(short)GETARG(int) : \
472 flags&CHARINT ? (long)(signed char)GETARG(int) : \
475 (flags&LONGINT ? GETARG(u_long) : \
476 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
477 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
478 (u_long)GETARG(u_int))
479 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
481 (flags&INTMAXT ? GETARG(intmax_t) : \
482 flags&SIZET ? (intmax_t)GETARG(ssize_t) : \
483 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
484 (intmax_t)GETARG(long long))
486 (flags&INTMAXT ? GETARG(uintmax_t) : \
487 flags&SIZET ? (uintmax_t)GETARG(size_t) : \
488 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
489 (uintmax_t)GETARG(unsigned long long))
492 * Get * arguments, including the form *nn$. Preserve the nextarg
493 * that the argument can be gotten once the type is determined.
495 #define GETASTER(val) \
498 while (is_digit(*cp)) { \
499 n2 = 10 * n2 + to_digit(*cp); \
503 int hold = nextarg; \
504 if (argtable == NULL) { \
505 argtable = statargtable; \
506 if (__find_warguments (fmt0, orgap, &argtable)) { \
512 val = GETARG (int); \
516 val = GETARG (int); \
520 /* sorry, fwprintf(read_only_file, L"") returns WEOF, not 0 */
521 if (prepwrite(fp) != 0)
525 fmt = (wchar_t *)fmt0;
531 #ifndef NO_FLOATING_POINT
532 decimal_point = get_decpt();
536 * Scan the format for conversions (`%' character).
539 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
541 if ((n = fmt - cp) != 0) {
542 if ((unsigned)ret + n > INT_MAX) {
551 fmt++; /* skip over '%' */
562 reswitch: switch (ch) {
565 * ``If the space and + flags both appear, the space
566 * flag will be ignored.''
577 * ``A negative field width argument is taken as a
578 * - flag followed by a positive field width.''
580 * They don't exclude field widths read from args.
597 if ((ch = *fmt++) == '*') {
602 while (is_digit(ch)) {
603 prec = 10 * prec + to_digit(ch);
609 * ``Note that 0 is taken as a flag, not as the
610 * beginning of a field width.''
615 case '1': case '2': case '3': case '4':
616 case '5': case '6': case '7': case '8': case '9':
619 n = 10 * n + to_digit(ch);
621 } while (is_digit(ch));
624 if (argtable == NULL) {
625 argtable = statargtable;
626 if (__find_warguments (fmt0, orgap,
636 #ifndef NO_FLOATING_POINT
642 if (flags & SHORTINT) {
652 if (flags & LONGINT) {
659 flags |= LLONGINT; /* not necessarily */
672 *(cp = buf) = (wchar_t)GETARG(wint_t);
674 *(cp = buf) = (wchar_t)btowc(GETARG(int));
683 if (flags & INTMAX_SIZE) {
685 if ((intmax_t)ujval < 0) {
691 if ((long)ulval < 0) {
698 #ifndef NO_FLOATING_POINT
712 if (flags & LONGDBL) {
713 fparg.ldbl = GETARG(long double);
715 __hldtoa(fparg.ldbl, xdigs, prec,
716 &expt, &signflag, &dtoaend);
718 fparg.dbl = GETARG(double);
720 __hdtoa(fparg.dbl, xdigs, prec,
721 &expt, &signflag, &dtoaend);
724 prec = dtoaend - dtoaresult;
729 ndig = dtoaend - dtoaresult;
730 cp = convbuf = __mbsconv(dtoaresult, -1);
731 freedtoa(dtoaresult);
736 if (prec < 0) /* account for digit before decpt */
747 expchar = ch - ('g' - 'e');
755 if (flags & LONGDBL) {
756 fparg.ldbl = GETARG(long double);
758 __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
759 &expt, &signflag, &dtoaend);
761 fparg.dbl = GETARG(double);
763 dtoa(fparg.dbl, expchar ? 2 : 3, prec,
764 &expt, &signflag, &dtoaend);
768 ndig = dtoaend - dtoaresult;
769 cp = convbuf = __mbsconv(dtoaresult, -1);
770 freedtoa(dtoaresult);
774 if (expt == INT_MAX) { /* inf or nan */
776 cp = (ch >= 'a') ? L"nan" : L"NAN";
779 cp = (ch >= 'a') ? L"inf" : L"INF";
785 if (ch == 'g' || ch == 'G') {
786 if (expt > -4 && expt <= prec) {
787 /* Make %[gG] smell like %[fF] */
797 * Make %[gG] smell like %[eE], but
798 * trim trailing zeroes if no # flag.
805 expsize = exponent(expstr, expt - 1, expchar);
806 size = expsize + prec;
807 if (prec > 1 || flags & ALT)
810 /* space for digits before decimal point */
815 /* space for decimal pt and following digits */
816 if (prec || flags & ALT)
818 if ((flags & GROUPING) && expt > 0)
819 size += grouping_init(&gs, expt);
822 #endif /* !NO_FLOATING_POINT */
825 * Assignment-like behavior is specified if the
826 * value overflows or is otherwise unrepresentable.
827 * C99 says to use `signed char' for %hhn conversions.
829 if (flags & LLONGINT)
830 *GETARG(long long *) = ret;
831 else if (flags & SIZET)
832 *GETARG(ssize_t *) = (ssize_t)ret;
833 else if (flags & PTRDIFFT)
834 *GETARG(ptrdiff_t *) = ret;
835 else if (flags & INTMAXT)
836 *GETARG(intmax_t *) = ret;
837 else if (flags & LONGINT)
838 *GETARG(long *) = ret;
839 else if (flags & SHORTINT)
840 *GETARG(short *) = ret;
841 else if (flags & CHARINT)
842 *GETARG(signed char *) = ret;
844 *GETARG(int *) = ret;
845 continue; /* no output */
850 if (flags & INTMAX_SIZE)
858 * ``The argument shall be a pointer to void. The
859 * value of the pointer is converted to a sequence
860 * of printable characters, in an implementation-
864 ujval = (uintmax_t)(uintptr_t)GETARG(void *);
867 flags = flags | INTMAXT;
874 if (flags & LONGINT) {
875 if ((cp = GETARG(wchar_t *)) == NULL)
882 if ((mbp = GETARG(char *)) == NULL)
885 convbuf = __mbsconv(mbp, prec);
886 if (convbuf == NULL) {
887 fp->_flags |= __SERR;
893 size = (prec >= 0) ? wcsnlen(cp, prec) : wcslen(cp);
900 if (flags & INTMAX_SIZE)
912 if (flags & INTMAX_SIZE)
917 /* leading 0x/X only if non-zero */
919 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
923 /* unsigned conversions */
926 * ``... diouXx conversions ... if a precision is
927 * specified, the 0 flag will be ignored.''
930 number: if ((dprec = prec) >= 0)
934 * ``The result of converting a zero value with an
935 * explicit precision of zero is no characters.''
938 * ``The C Standard is clear enough as is. The call
939 * printf("%#.0o", 0) should print 0.''
940 * -- Defect Report #151
943 if (flags & INTMAX_SIZE) {
944 if (ujval != 0 || prec != 0 ||
945 (flags & ALT && base == 8))
946 cp = __ujtoa(ujval, cp, base,
949 if (ulval != 0 || prec != 0 ||
950 (flags & ALT && base == 8))
951 cp = __ultoa(ulval, cp, base,
954 size = buf + BUF - cp;
955 if (size > BUF) /* should never happen */
957 if ((flags & GROUPING) && size != 0)
958 size += grouping_init(&gs, size);
960 default: /* "%?" prints ?, unless ? is NUL */
963 /* pretend it was %c with argument ch */
972 * All reasonable formats wind up here. At this point, `cp'
973 * points to a string which (if not flags&LADJUST) should be
974 * padded out to `width' places. If flags&ZEROPAD, it should
975 * first be prefixed by any sign or other prefix; otherwise,
976 * it should be blank padded before the prefix is emitted.
977 * After any left-hand padding and prefixing, emit zeroes
978 * required by a decimal [diouxX] precision, then print the
979 * string proper, then emit zeroes required by any leftover
980 * floating precision; finally, if LADJUST, pad with blanks.
982 * Compute actual size, so we know how much to pad.
983 * size excludes decimal prec; realsz includes it.
985 realsz = dprec > size ? dprec : size;
991 prsize = width > realsz ? width : realsz;
992 if ((unsigned)ret + prsize > INT_MAX) {
997 /* right-adjusting blank padding */
998 if ((flags & (LADJUST|ZEROPAD)) == 0)
999 PAD(width - realsz, blanks);
1005 if (ox[1]) { /* ox[1] is either x, X, or \0 */
1010 /* right-adjusting zero padding */
1011 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1012 PAD(width - realsz, zeroes);
1014 /* the string or number proper */
1015 #ifndef NO_FLOATING_POINT
1016 if ((flags & FPT) == 0) {
1018 /* leading zeroes from decimal precision */
1019 PAD(dprec - size, zeroes);
1021 if (grouping_print(&gs, &io, cp, buf+BUF) < 0)
1026 #ifndef NO_FLOATING_POINT
1027 } else { /* glue together f_p fragments */
1028 if (!expchar) { /* %[fF] or sufficiently short %[gG] */
1031 if (prec || flags & ALT)
1032 PRINT(&decimal_point, 1);
1034 /* already handled initial 0's */
1038 n = grouping_print(&gs, &io,
1039 cp, convbuf + ndig);
1044 PRINTANDPAD(cp, convbuf + ndig,
1048 if (prec || flags & ALT)
1049 PRINT(&decimal_point, 1);
1051 PRINTANDPAD(cp, convbuf + ndig, prec, zeroes);
1052 } else { /* %[eE] or sufficiently long %[gG] */
1053 if (prec > 1 || flags & ALT) {
1055 buf[1] = decimal_point;
1058 PAD(prec - ndig, zeroes);
1061 PRINT(expstr, expsize);
1065 /* left-adjusting padding (always blank) */
1066 if (flags & LADJUST)
1067 PAD(width - realsz, blanks);
1069 /* finally, adjust ret */
1072 FLUSH(); /* copy out the I/O vectors */
1078 if (convbuf != NULL)
1082 if ((argtable != NULL) && (argtable != statargtable))