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
32 * @(#)vfprintf.c 8.1 (Berkeley) 6/4/93
33 * $FreeBSD: src/lib/libc/stdio/vfprintf.c,v 1.90 2009/02/28 06:06:57 das Exp $
34 * $DragonFly: src/lib/libc/stdio/vfprintf.c,v 1.16 2006/07/05 15:04:54 joerg Exp $
38 * Actual printf innards.
40 * This code is large and complicated...
43 #include "namespace.h"
44 #include <sys/types.h>
58 #include "un-namespace.h"
60 #include "libc_private.h"
62 #include "priv_stdio.h"
63 #include "printflocal.h"
65 static int __sprint(FILE *, struct __suio
*);
66 static int __sbprintf(FILE *, const char *, va_list) __printflike(2, 0)
68 static char *__wcsconv(wchar_t *, int);
71 #include "printfcommon.h"
73 struct grouping_state
{
74 char *thousands_sep
; /* locale-specific thousands separator */
75 int thousep_len
; /* length of thousands_sep */
76 const char *grouping
; /* locale-specific numeric grouping rules */
77 int lead
; /* sig figs before decimal or group sep */
78 int nseps
; /* number of group separators with ' */
79 int nrepeats
; /* number of repeats of the last group */
83 * Initialize the thousands' grouping state in preparation to print a
84 * number with ndigits digits. This routine returns the total number
85 * of bytes that will be needed.
88 grouping_init(struct grouping_state
*gs
, int ndigits
)
92 locale
= localeconv();
93 gs
->grouping
= locale
->grouping
;
94 gs
->thousands_sep
= locale
->thousands_sep
;
95 gs
->thousep_len
= strlen(gs
->thousands_sep
);
97 gs
->nseps
= gs
->nrepeats
= 0;
99 while (*gs
->grouping
!= CHAR_MAX
) {
100 if (gs
->lead
<= *gs
->grouping
)
102 gs
->lead
-= *gs
->grouping
;
103 if (*(gs
->grouping
+1)) {
109 return ((gs
->nseps
+ gs
->nrepeats
) * gs
->thousep_len
);
113 * Print a number with thousands' separators.
116 grouping_print(struct grouping_state
*gs
, struct io_state
*iop
,
117 const CHAR
*cp
, const CHAR
*ep
)
119 const CHAR
*cp0
= cp
;
121 if (io_printandpad(iop
, cp
, ep
, gs
->lead
, zeroes
))
124 while (gs
->nseps
> 0 || gs
->nrepeats
> 0) {
125 if (gs
->nrepeats
> 0)
131 if (io_print(iop
, gs
->thousands_sep
, gs
->thousep_len
))
133 if (io_printandpad(iop
, cp
, ep
, *gs
->grouping
, zeroes
))
143 * Flush out all the vectors defined by the given uio,
144 * then reset it so that it can be reused.
147 __sprint(FILE *fp
, struct __suio
*uio
)
151 if (uio
->uio_resid
== 0) {
155 err
= __sfvwrite(fp
, uio
);
162 * Helper function for `fprintf to unbuffered unix file': creates a
163 * temporary buffer. We only work on write-only files; this avoids
164 * worries about ungetc buffers and so forth.
167 __sbprintf(FILE *fp
, const char *fmt
, va_list ap
)
171 unsigned char buf
[BUFSIZ
];
173 /* XXX This is probably not needed. */
174 if (prepwrite(fp
) != 0)
177 /* copy the important variables */
178 fake
.pub
._flags
= fp
->pub
._flags
& ~__SNBF
;
179 fake
.pub
._fileno
= fp
->pub
._fileno
;
180 fake
._cookie
= fp
->_cookie
;
181 fake
._write
= fp
->_write
;
182 memcpy(WCIO_GET(&fake
), WCIO_GET(fp
), sizeof(struct wchar_io_data
));
184 /* set up the buffer */
185 fake
._bf
._base
= fake
.pub
._p
= buf
;
186 fake
._bf
._size
= fake
.pub
._w
= sizeof(buf
);
187 fake
.pub
._lbfsize
= 0; /* not actually used, but Just In Case */
189 /* do the work, then copy any error status */
190 ret
= __vfprintf(&fake
, fmt
, ap
);
191 if (ret
>= 0 && __fflush(&fake
))
193 if (fake
.pub
._flags
& __SERR
)
194 fp
->pub
._flags
|= __SERR
;
199 * Convert a wide character string argument for the %ls format to a multibyte
200 * string representation. If not -1, prec specifies the maximum number of
201 * bytes to output, and also means that we can't assume that the wide char.
202 * string ends is null-terminated.
205 __wcsconv(wchar_t *wcsarg
, int prec
)
207 static const mbstate_t initial
;
209 char buf
[MB_LEN_MAX
];
214 /* Allocate space for the maximum number of bytes we could output. */
218 nbytes
= wcsrtombs(NULL
, (const wchar_t **)&p
, 0, &mbs
);
219 if (nbytes
== (size_t)-1)
223 * Optimisation: if the output precision is small enough,
224 * just allocate enough memory for the maximum instead of
225 * scanning the string.
234 clen
= wcrtomb(buf
, *p
++, &mbs
);
235 if (clen
== 0 || clen
== (size_t)-1 ||
236 nbytes
+ clen
> prec
)
242 if ((convbuf
= malloc(nbytes
+ 1)) == NULL
)
245 /* Fill the output buffer. */
248 if ((nbytes
= wcsrtombs(convbuf
, (const wchar_t **)&p
,
249 nbytes
, &mbs
)) == (size_t)-1) {
253 convbuf
[nbytes
] = '\0';
261 vfprintf(FILE * __restrict fp
, const char * __restrict fmt0
, va_list ap
)
266 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
267 if ((fp
->pub
._flags
& (__SNBF
|__SWR
|__SRW
)) == (__SNBF
|__SWR
) &&
268 fp
->pub
._fileno
>= 0)
269 ret
= __sbprintf(fp
, fmt0
, ap
);
271 ret
= __vfprintf(fp
, fmt0
, ap
);
277 * The size of the buffer we use as scratch space for integer
278 * conversions, among other things. We need enough space to
279 * write a uintmax_t in octal (plus one byte).
281 #if UINTMAX_MAX <= UINT64_MAX
284 #error "BUF must be large enough to format a uintmax_t"
288 * Non-MT-safe version
291 __vfprintf(FILE *fp
, const char *fmt0
, va_list ap
)
293 char *fmt
; /* format string */
294 int ch
; /* character from fmt */
295 int n
, n2
; /* handy integer (short term usage) */
296 char *cp
; /* handy char pointer (short term usage) */
297 int flags
; /* flags as above */
298 int ret
; /* return value accumulator */
299 int width
; /* width from format (%8d), or 0 */
300 int prec
; /* precision from format; <0 for N/A */
301 char sign
; /* sign prefix (' ', '+', '-', or \0) */
302 struct grouping_state gs
; /* thousands' grouping info */
304 #ifndef NO_FLOATING_POINT
306 * We can decompose the printed representation of floating
307 * point numbers into several parts, some of which may be empty:
309 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
312 * A: 'sign' holds this value if present; '\0' otherwise
313 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
314 * C: cp points to the string MMMNNN. Leading and trailing
315 * zeros are not in the string and must be added.
316 * D: expchar holds this character; '\0' if no exponent, e.g. %f
317 * F: at least two digits for decimal, at least one digit for hex
319 char *decimal_point
; /* locale specific decimal point */
320 int decpt_len
; /* length of decimal_point */
321 int signflag
; /* true if float is negative */
322 union { /* floating point arguments %[aAeEfFgG] */
326 int expt
; /* integer value of exponent */
327 char expchar
; /* exponent character: [eEpP\0] */
328 char *dtoaend
; /* pointer to end of converted digits */
329 int expsize
; /* character count for expstr */
330 int ndig
; /* actual number of digits returned by dtoa */
331 char expstr
[MAXEXPDIG
+2]; /* buffer for exponent string: e+ZZZ */
332 char *dtoaresult
; /* buffer allocated by dtoa */
334 u_long ulval
; /* integer arguments %[diouxX] */
335 uintmax_t ujval
; /* %j, %ll, %q, %t, %z integers */
336 int base
; /* base for [diouxX] conversion */
337 int dprec
; /* a copy of prec if [diouxX], 0 otherwise */
338 int realsz
; /* field size expanded by dprec, sign, etc */
339 int size
; /* size of converted field or string */
340 int prsize
; /* max size of printed field */
341 const char *xdigs
; /* digits for %[xX] conversion */
342 struct io_state io
; /* I/O buffering state */
343 char buf
[BUF
]; /* buffer with space for digits of uintmax_t */
344 char ox
[2]; /* space for 0x; ox[1] is either x, X, or \0 */
345 union arg
*argtable
; /* args, built due to positional arg */
346 union arg statargtable
[STATIC_ARG_TBL_SIZE
];
347 int nextarg
; /* 1-based argument index */
348 va_list orgap
; /* original argument pointer */
349 char *convbuf
; /* wide to multibyte conversion result */
351 static const char xdigs_lower
[16] = "0123456789abcdef";
352 static const char xdigs_upper
[16] = "0123456789ABCDEF";
354 /* BEWARE, these `goto error' on error. */
355 #define PRINT(ptr, len) { \
356 if (io_print(&io, (ptr), (len))) \
359 #define PAD(howmany, with) { \
360 if (io_pad(&io, (howmany), (with))) \
363 #define PRINTANDPAD(p, ep, len, with) { \
364 if (io_printandpad(&io, (p), (ep), (len), (with))) \
373 * Get the argument indexed by nextarg. If the argument table is
374 * built, use it to get the argument. If its not, get the next
375 * argument (and arguments must be gotten sequentially).
377 #define GETARG(type) \
378 ((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
379 (nextarg++, va_arg(ap, type)))
382 * To extend shorts properly, we need both signed and unsigned
383 * argument extraction methods.
386 (flags&LONGINT ? GETARG(long) : \
387 flags&SHORTINT ? (long)(short)GETARG(int) : \
388 flags&CHARINT ? (long)(signed char)GETARG(int) : \
391 (flags&LONGINT ? GETARG(u_long) : \
392 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
393 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
394 (u_long)GETARG(u_int))
395 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
397 (flags&INTMAXT ? GETARG(intmax_t) : \
398 flags&SIZET ? (intmax_t)GETARG(ssize_t) : \
399 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
400 (intmax_t)GETARG(long long))
402 (flags&INTMAXT ? GETARG(uintmax_t) : \
403 flags&SIZET ? (uintmax_t)GETARG(size_t) : \
404 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
405 (uintmax_t)GETARG(unsigned long long))
408 * Get * arguments, including the form *nn$. Preserve the nextarg
409 * that the argument can be gotten once the type is determined.
411 #define GETASTER(val) \
414 while (is_digit(*cp)) { \
415 n2 = 10 * n2 + to_digit(*cp); \
419 int hold = nextarg; \
420 if (argtable == NULL) { \
421 argtable = statargtable; \
422 if (__find_arguments (fmt0, orgap, &argtable)) { \
428 val = GETARG (int); \
432 val = GETARG (int); \
435 if (__use_xprintf
== 0 && getenv("USE_XPRINTF"))
437 if (__use_xprintf
> 0)
438 return (__xvprintf(fp
, fmt0
, ap
));
440 /* sorry, fprintf(read_only_file, "") returns EOF, not 0 */
441 if (prepwrite(fp
) != 0)
445 fmt
= __DECONST(char *, fmt0
);
451 #ifndef NO_FLOATING_POINT
453 decimal_point
= localeconv()->decimal_point
;
454 /* The overwhelmingly common case is decpt_len == 1. */
455 decpt_len
= (decimal_point
[1] == '\0' ? 1 : strlen(decimal_point
));
459 * Scan the format for conversions (`%' character).
462 for (cp
= fmt
; (ch
= *fmt
) != '\0' && ch
!= '%'; fmt
++)
464 if ((n
= fmt
- cp
) != 0) {
465 if ((unsigned)ret
+ n
> INT_MAX
) {
474 fmt
++; /* skip over '%' */
485 reswitch
: switch (ch
) {
488 * ``If the space and + flags both appear, the space
489 * flag will be ignored.''
500 * ``A negative field width argument is taken as a
501 * - flag followed by a positive field width.''
503 * They don't exclude field widths read from args.
520 if ((ch
= *fmt
++) == '*') {
525 while (is_digit(ch
)) {
526 prec
= 10 * prec
+ to_digit(ch
);
532 * ``Note that 0 is taken as a flag, not as the
533 * beginning of a field width.''
538 case '1': case '2': case '3': case '4':
539 case '5': case '6': case '7': case '8': case '9':
542 n
= 10 * n
+ to_digit(ch
);
544 } while (is_digit(ch
));
547 if (argtable
== NULL
) {
548 argtable
= statargtable
;
549 if (__find_arguments (fmt0
, orgap
,
559 #ifndef NO_FLOATING_POINT
565 if (flags
& SHORTINT
) {
575 if (flags
& LONGINT
) {
582 flags
|= LLONGINT
; /* not necessarily */
594 if (flags
& LONGINT
) {
595 static const mbstate_t initial
;
600 mbseqlen
= wcrtomb(cp
= buf
,
601 (wchar_t)GETARG(wint_t), &mbs
);
602 if (mbseqlen
== (size_t)-1) {
603 fp
->pub
._flags
|= __SERR
;
606 size
= (int)mbseqlen
;
608 *(cp
= buf
) = GETARG(int);
618 if (flags
& INTMAX_SIZE
) {
620 if ((intmax_t)ujval
< 0) {
626 if ((long)ulval
< 0) {
633 #ifndef NO_FLOATING_POINT
647 if (dtoaresult
!= NULL
)
648 freedtoa(dtoaresult
);
649 if (flags
& LONGDBL
) {
650 fparg
.ldbl
= GETARG(long double);
652 __hldtoa(fparg
.ldbl
, xdigs
, prec
,
653 &expt
, &signflag
, &dtoaend
);
655 fparg
.dbl
= GETARG(double);
657 __hdtoa(fparg
.dbl
, xdigs
, prec
,
658 &expt
, &signflag
, &dtoaend
);
668 if (prec
< 0) /* account for digit before decpt */
679 expchar
= ch
- ('g' - 'e');
685 if (dtoaresult
!= NULL
)
686 freedtoa(dtoaresult
);
687 if (flags
& LONGDBL
) {
688 fparg
.ldbl
= GETARG(long double);
690 __ldtoa(&fparg
.ldbl
, expchar
? 2 : 3, prec
,
691 &expt
, &signflag
, &dtoaend
);
693 fparg
.dbl
= GETARG(double);
695 dtoa(fparg
.dbl
, expchar
? 2 : 3, prec
,
696 &expt
, &signflag
, &dtoaend
);
703 if (expt
== INT_MAX
) { /* inf or nan */
705 cp
= (ch
>= 'a') ? "nan" : "NAN";
708 cp
= (ch
>= 'a') ? "inf" : "INF";
715 if (ch
== 'g' || ch
== 'G') {
716 if (expt
> -4 && expt
<= prec
) {
717 /* Make %[gG] smell like %[fF] */
727 * Make %[gG] smell like %[eE], but
728 * trim trailing zeroes if no # flag.
735 expsize
= exponent(expstr
, expt
- 1, expchar
);
736 size
= expsize
+ prec
;
737 if (prec
> 1 || flags
& ALT
)
740 /* space for digits before decimal point */
745 /* space for decimal pt and following digits */
746 if (prec
|| flags
& ALT
)
747 size
+= prec
+ decpt_len
;
748 if ((flags
& GROUPING
) && expt
> 0)
749 size
+= grouping_init(&gs
, expt
);
752 #endif /* !NO_FLOATING_POINT */
755 * Assignment-like behavior is specified if the
756 * value overflows or is otherwise unrepresentable.
757 * C99 says to use `signed char' for %hhn conversions.
759 if (flags
& LLONGINT
)
760 *GETARG(long long *) = ret
;
761 else if (flags
& SIZET
)
762 *GETARG(ssize_t
*) = (ssize_t
)ret
;
763 else if (flags
& PTRDIFFT
)
764 *GETARG(ptrdiff_t *) = ret
;
765 else if (flags
& INTMAXT
)
766 *GETARG(intmax_t *) = ret
;
767 else if (flags
& LONGINT
)
768 *GETARG(long *) = ret
;
769 else if (flags
& SHORTINT
)
770 *GETARG(short *) = ret
;
771 else if (flags
& CHARINT
)
772 *GETARG(signed char *) = ret
;
774 *GETARG(int *) = ret
;
775 continue; /* no output */
780 if (flags
& INTMAX_SIZE
)
788 * ``The argument shall be a pointer to void. The
789 * value of the pointer is converted to a sequence
790 * of printable characters, in an implementation-
794 ujval
= (uintmax_t)(uintptr_t)GETARG(void *);
797 flags
= flags
| INTMAXT
;
804 if (flags
& LONGINT
) {
809 if ((wcp
= GETARG(wchar_t *)) == NULL
)
812 convbuf
= __wcsconv(wcp
, prec
);
813 if (convbuf
== NULL
) {
814 fp
->pub
._flags
|= __SERR
;
819 } else if ((cp
= GETARG(char *)) == NULL
)
821 size
= (prec
>= 0) ? strnlen(cp
, prec
) : strlen(cp
);
828 if (flags
& INTMAX_SIZE
)
840 if (flags
& INTMAX_SIZE
)
845 /* leading 0x/X only if non-zero */
847 (flags
& INTMAX_SIZE
? ujval
!= 0 : ulval
!= 0))
851 /* unsigned conversions */
854 * ``... diouXx conversions ... if a precision is
855 * specified, the 0 flag will be ignored.''
858 number
: if ((dprec
= prec
) >= 0)
862 * ``The result of converting a zero value with an
863 * explicit precision of zero is no characters.''
866 * ``The C Standard is clear enough as is. The call
867 * printf("%#.0o", 0) should print 0.''
868 * -- Defect Report #151
871 if (flags
& INTMAX_SIZE
) {
872 if (ujval
!= 0 || prec
!= 0 ||
873 (flags
& ALT
&& base
== 8))
874 cp
= __ujtoa(ujval
, cp
, base
,
877 if (ulval
!= 0 || prec
!= 0 ||
878 (flags
& ALT
&& base
== 8))
879 cp
= __ultoa(ulval
, cp
, base
,
882 size
= buf
+ BUF
- cp
;
883 if (size
> BUF
) /* should never happen */
885 if ((flags
& GROUPING
) && size
!= 0)
886 size
+= grouping_init(&gs
, size
);
888 default: /* "%?" prints ?, unless ? is NUL */
891 /* pretend it was %c with argument ch */
900 * All reasonable formats wind up here. At this point, `cp'
901 * points to a string which (if not flags&LADJUST) should be
902 * padded out to `width' places. If flags&ZEROPAD, it should
903 * first be prefixed by any sign or other prefix; otherwise,
904 * it should be blank padded before the prefix is emitted.
905 * After any left-hand padding and prefixing, emit zeroes
906 * required by a decimal [diouxX] precision, then print the
907 * string proper, then emit zeroes required by any leftover
908 * floating precision; finally, if LADJUST, pad with blanks.
910 * Compute actual size, so we know how much to pad.
911 * size excludes decimal prec; realsz includes it.
913 realsz
= dprec
> size
? dprec
: size
;
919 prsize
= width
> realsz
? width
: realsz
;
920 if ((unsigned)ret
+ prsize
> INT_MAX
) {
925 /* right-adjusting blank padding */
926 if ((flags
& (LADJUST
|ZEROPAD
)) == 0)
927 PAD(width
- realsz
, blanks
);
933 if (ox
[1]) { /* ox[1] is either x, X, or \0 */
938 /* right-adjusting zero padding */
939 if ((flags
& (LADJUST
|ZEROPAD
)) == ZEROPAD
)
940 PAD(width
- realsz
, zeroes
);
942 /* the string or number proper */
943 #ifndef NO_FLOATING_POINT
944 if ((flags
& FPT
) == 0) {
946 /* leading zeroes from decimal precision */
947 PAD(dprec
- size
, zeroes
);
949 if (grouping_print(&gs
, &io
, cp
, buf
+BUF
) < 0)
954 #ifndef NO_FLOATING_POINT
955 } else { /* glue together f_p fragments */
956 if (!expchar
) { /* %[fF] or sufficiently short %[gG] */
959 if (prec
|| flags
& ALT
)
960 PRINT(decimal_point
,decpt_len
);
962 /* already handled initial 0's */
966 n
= grouping_print(&gs
, &io
,
972 PRINTANDPAD(cp
, dtoaend
,
976 if (prec
|| flags
& ALT
)
977 PRINT(decimal_point
,decpt_len
);
979 PRINTANDPAD(cp
, dtoaend
, prec
, zeroes
);
980 } else { /* %[eE] or sufficiently long %[gG] */
981 if (prec
> 1 || flags
& ALT
) {
983 PRINT(decimal_point
, decpt_len
);
985 PAD(prec
- ndig
, zeroes
);
988 PRINT(expstr
, expsize
);
992 /* left-adjusting padding (always blank) */
994 PAD(width
- realsz
, blanks
);
996 /* finally, adjust ret */
999 FLUSH(); /* copy out the I/O vectors */
1005 #ifndef NO_FLOATING_POINT
1006 if (dtoaresult
!= NULL
)
1007 freedtoa(dtoaresult
);
1009 if (convbuf
!= NULL
)
1013 if ((argtable
!= NULL
) && (argtable
!= statargtable
))