1 /* $NetBSD: vfwprintf.c,v 1.34 2014/01/20 14:11:03 yamt Exp $ */
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 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 #include <sys/cdefs.h>
36 #if defined(LIBC_SCCS) && !defined(lint)
38 static char sccsid
[] = "@(#)vfprintf.c 8.1 (Berkeley) 6/4/93";
39 __FBSDID("$FreeBSD: src/lib/libc/stdio/vfwprintf.c,v 1.27 2007/01/09 00:28:08 imp Exp $");
41 __RCSID("$NetBSD: vfwprintf.c,v 1.34 2014/01/20 14:11:03 yamt Exp $");
43 #endif /* LIBC_SCCS and not lint */
46 * Actual {w,}printf innards.
49 #include "namespace.h"
50 #include <sys/types.h>
66 #include "reentrant.h"
67 #include "setlocale_local.h"
74 #define CHAR_T wchar_t
75 #define STRLEN(a) wcslen(a)
76 #define MEMCHR(a, b, c) wmemchr(a, b, c)
77 #define SCONV(a, b, loc) __mbsconv(a, b, loc)
78 #define STRCONST(a) L ## a
79 #define WDECL(a, b) a ## w ## b
80 #define END_OF_FILE WEOF
83 #define MCHAR_T wchar_t
85 #define STRLEN(a) strlen(a)
86 #define MEMCHR(a, b, c) memchr(a, b, c)
87 #define SCONV(a, b, loc) __wcsconv(a, b, loc)
89 #define WDECL(a, b) a ## b
90 #define END_OF_FILE EOF
99 long long longlongarg
;
100 unsigned long long ulonglongarg
;
101 ptrdiff_t ptrdiffarg
;
105 uintmax_t uintmaxarg
;
108 signed char *pschararg
;
112 long long *plonglongarg
;
113 ptrdiff_t *pptrdiffarg
;
115 intmax_t *pintmaxarg
;
116 #ifndef NO_FLOATING_POINT
118 long double longdoublearg
;
125 * Type ids for argument type table.
128 T_UNUSED
= 0, TP_SHORT
, T_INT
, T_U_INT
, TP_INT
,
129 T_LONG
, T_U_LONG
, TP_LONG
, T_LLONG
, T_U_LLONG
, TP_LLONG
,
130 T_PTRDIFFT
, TP_PTRDIFFT
, T_SSIZET
, T_SIZET
, TP_SIZET
,
131 T_INTMAXT
, T_UINTMAXT
, TP_INTMAXT
, TP_VOID
, TP_CHAR
, TP_SCHAR
,
132 T_DOUBLE
, T_LONG_DOUBLE
, T_WINT
, TP_WCHAR
138 static int __sbprintf(FILE *, locale_t
, const CHAR_T
*, va_list);
140 static CHAR_T
*__ujtoa(uintmax_t, CHAR_T
*, int, int, const char *, int,
142 static CHAR_T
*__ultoa(u_long
, CHAR_T
*, int, int, const char *, int,
145 static CHAR_T
*__mbsconv(char *, int, locale_t
);
146 static wint_t __xfputwc(CHAR_T
, FILE *, locale_t
);
148 static char *__wcsconv(wchar_t *, int, locale_t
);
149 static int __sprint(FILE *, struct __suio
*);
151 static int __find_arguments(const CHAR_T
*, va_list, union arg
**);
152 static int __grow_type_table(size_t, enum typeid **, size_t *);
155 * Helper function for `fprintf to unbuffered unix file': creates a
156 * temporary buffer. We only work on write-only files; this avoids
157 * worries about ungetc buffers and so forth.
160 __sbprintf(FILE *fp
, locale_t loc
, const CHAR_T
*fmt
, va_list ap
)
164 struct __sfileext fakeext
;
165 unsigned char buf
[BUFSIZ
];
167 _DIAGASSERT(fp
!= NULL
);
168 _DIAGASSERT(fmt
!= NULL
);
170 _FILEEXT_SETUP(&fake
, &fakeext
);
171 memset(WCIO_GET(&fake
), 0, sizeof(struct wchar_io_data
));
173 /* copy the important variables */
174 fake
._flags
= fp
->_flags
& ~__SNBF
;
175 fake
._file
= fp
->_file
;
176 fake
._cookie
= fp
->_cookie
;
177 fake
._write
= fp
->_write
;
178 fake
._flush
= fp
->_flush
;
180 /* set up the buffer */
181 fake
._bf
._base
= fake
._p
= buf
;
182 fake
._bf
._size
= fake
._w
= sizeof(buf
);
183 fake
._lbfsize
= 0; /* not actually used, but Just In Case */
185 /* do the work, then copy any error status */
186 ret
= WDECL(__vf
,printf_unlocked_l
)(&fake
, loc
, fmt
, ap
);
187 if (ret
>= 0 && fflush(&fake
))
189 if (fake
._flags
& __SERR
)
190 fp
->_flags
|= __SERR
;
196 * Like __fputwc, but handles fake string (__SSTR) files properly.
197 * File must already be locked.
200 __xfputwc(wchar_t wc
, FILE *fp
, locale_t loc
)
202 static const mbstate_t initial
;
204 char buf
[MB_LEN_MAX
];
209 if ((fp
->_flags
& __SSTR
) == 0)
210 return __fputwc_unlock(wc
, fp
);
213 if ((len
= wcrtomb_l(buf
, wc
, &mbs
, loc
)) == (size_t)-1) {
214 fp
->_flags
|= __SERR
;
222 return __sfvwrite(fp
, &uio
) != EOF
? (wint_t)wc
: END_OF_FILE
;
226 * Flush out all the vectors defined by the given uio,
227 * then reset it so that it can be reused.
230 __sprint(FILE *fp
, struct __suio
*uio
)
234 _DIAGASSERT(fp
!= NULL
);
235 _DIAGASSERT(uio
!= NULL
);
237 if (uio
->uio_resid
== 0) {
241 err
= __sfvwrite(fp
, uio
);
249 * Macros for converting digits to letters and vice versa
251 #define to_digit(c) ((c) - '0')
252 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
253 #define to_char(n) (CHAR_T)((n) + '0')
256 * Convert an unsigned long to ASCII for printf purposes, returning
257 * a pointer to the first character of the string representation.
258 * Octal numbers can be forced to have a leading zero; hex numbers
259 * use the given digits.
262 __ultoa(u_long val
, CHAR_T
*endp
, int base
, int octzero
, const char *xdigs
,
263 int needgrp
, char thousep
, const char *grp
)
270 * Handle the three cases separately, in the hope of getting
271 * better/faster code.
275 if (val
< 10) { /* many numbers are 1 digit */
276 *--cp
= to_char(val
);
281 * On many machines, unsigned arithmetic is harder than
282 * signed arithmetic, so we do at most one unsigned mod and
283 * divide; this is sufficient to reduce the range of
284 * the incoming value to where signed arithmetic works.
286 if (val
> LONG_MAX
) {
287 *--cp
= to_char(val
% 10);
293 *--cp
= to_char(sval
% 10);
296 * If (*grp == CHAR_MAX) then no more grouping
297 * should be performed.
299 if (needgrp
&& ndig
== *grp
300 && (unsigned char)*grp
!= (unsigned char)CHAR_MAX
305 * If (*(grp+1) == '\0') then we have to
306 * use *grp character (last grouping rule)
309 if (*(grp
+1) != '\0')
318 *--cp
= to_char(val
& 7);
321 if (octzero
&& *cp
!= '0')
327 *--cp
= xdigs
[(size_t)val
& 15];
338 /* Identical to __ultoa, but for intmax_t. */
340 __ujtoa(uintmax_t val
, CHAR_T
*endp
, int base
, int octzero
,
341 const char *xdigs
, int needgrp
, char thousep
, const char *grp
)
347 /* quick test for small values; __ultoa is typically much faster */
348 /* (perhaps instead we should run until small, then call __ultoa?) */
349 if (val
<= ULONG_MAX
)
350 return __ultoa((u_long
)val
, endp
, base
, octzero
, xdigs
,
351 needgrp
, thousep
, grp
);
355 *--cp
= to_char(val
% 10);
359 if (val
> INTMAX_MAX
) {
360 *--cp
= to_char(val
% 10);
366 *--cp
= to_char(sval
% 10);
369 * If (*grp == CHAR_MAX) then no more grouping
370 * should be performed.
373 && (unsigned char)*grp
!= (unsigned char)CHAR_MAX
379 * If (*(grp+1) == '\0') then we have to
380 * use *grp character (last grouping rule)
383 if (*(grp
+1) != '\0')
392 *--cp
= to_char(val
& 7);
395 if (octzero
&& *cp
!= '0')
401 *--cp
= xdigs
[(size_t)val
& 15];
414 * Convert a multibyte character string argument for the %s format to a wide
415 * string representation. ``prec'' specifies the maximum number of bytes
416 * to output. If ``prec'' is greater than or equal to zero, we can't assume
417 * that the multibyte char. string ends in a null character.
420 __mbsconv(char *mbsarg
, int prec
, locale_t loc
)
422 static const mbstate_t initial
;
424 wchar_t *convbuf
, *wcp
;
426 size_t insize
, nchars
, nconv
;
432 * Supplied argument is a multibyte string; convert it to wide
437 * String is not guaranteed to be NUL-terminated. Find the
438 * number of characters to print.
441 insize
= nchars
= nconv
= 0;
443 while (nchars
!= (size_t)prec
) {
444 nconv
= mbrlen_l(p
, MB_CUR_MAX_L(loc
), &mbs
, loc
);
445 if (nconv
== 0 || nconv
== (size_t)-1 ||
452 if (nconv
== (size_t)-1 || nconv
== (size_t)-2)
455 insize
= strlen(mbsarg
);
458 * Allocate buffer for the result and perform the conversion,
459 * converting at most `size' bytes of the input multibyte string to
460 * wide characters for printing.
462 convbuf
= malloc((insize
+ 1) * sizeof(*convbuf
));
469 while (insize
!= 0) {
470 nconv
= mbrtowc_l(wcp
, p
, insize
, &mbs
, loc
);
471 if (nconv
== 0 || nconv
== (size_t)-1 || nconv
== (size_t)-2)
477 if (nconv
== (size_t)-1 || nconv
== (size_t)-2) {
487 * Convert a wide-character string argument for the %ls format to a multibyte
488 * string representation. If not -1, prec specifies the maximum number of
489 * bytes to output, and also means that we can't assume that the wide-char.
490 * string ends is null-terminated.
493 __wcsconv(wchar_t *wcsarg
, int prec
, locale_t loc
)
495 static const mbstate_t initial
;
497 char buf
[MB_LEN_MAX
];
502 /* Allocate space for the maximum number of bytes we could output. */
506 nbytes
= wcsrtombs_l(NULL
, (void *)&p
, 0, &mbs
, loc
);
507 if (nbytes
== (size_t)-1)
511 * Optimisation: if the output precision is small enough,
512 * just allocate enough memory for the maximum instead of
513 * scanning the string.
522 clen
= wcrtomb_l(buf
, *p
++, &mbs
, loc
);
523 if (clen
== 0 || clen
== (size_t)-1 ||
524 nbytes
+ clen
> (size_t)prec
)
530 if ((convbuf
= malloc(nbytes
+ 1)) == NULL
)
533 /* Fill the output buffer. */
536 if ((nbytes
= wcsrtombs_l(convbuf
, (void *)&p
,
537 nbytes
, &mbs
, loc
)) == (size_t)-1) {
541 convbuf
[nbytes
] = '\0';
550 WDECL(vf
,printf
)(FILE * __restrict fp
, const CHAR_T
* __restrict fmt0
, va_list ap
)
555 ret
= WDECL(__vf
,printf_unlocked_l
)(fp
, _current_locale(), fmt0
, ap
);
561 WDECL(vf
,printf_l
)(FILE * __restrict fp
, locale_t loc
, const CHAR_T
* __restrict fmt0
,
567 ret
= WDECL(__vf
,printf_unlocked_l
)(fp
, loc
, fmt0
, ap
);
572 #ifndef NO_FLOATING_POINT
580 static int exponent(CHAR_T
*, int, int);
582 static char *cvt(double, int, int, char *, int *, int, int *);
585 #endif /* !NO_FLOATING_POINT */
588 * The size of the buffer we use as scratch space for integer
589 * conversions, among other things. Technically, we would need the
590 * most space for base 10 conversions with thousands' grouping
591 * characters between each pair of digits. 100 bytes is a
592 * conservative overestimate even for a 128-bit uintmax_t.
596 #define STATIC_ARG_TBL_SIZE 8 /* Size of static argument table. */
599 * Flags used during conversion.
601 #define ALT 0x001 /* alternate form */
602 #define LADJUST 0x004 /* left adjustment */
603 #define LONGDBL 0x008 /* long double */
604 #define LONGINT 0x010 /* long integer */
605 #define LLONGINT 0x020 /* long long integer */
606 #define SHORTINT 0x040 /* short integer */
607 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
608 #define FPT 0x100 /* Floating point number */
609 #define GROUPING 0x200 /* use grouping ("'" flag) */
610 /* C99 additional size modifiers: */
611 #define SIZET 0x400 /* size_t */
612 #define PTRDIFFT 0x800 /* ptrdiff_t */
613 #define INTMAXT 0x1000 /* intmax_t */
614 #define CHARINT 0x2000 /* print char using int format */
617 * Non-MT-safe version
620 WDECL(__vf
,printf_unlocked_l
)(FILE *fp
, locale_t loc
, const CHAR_T
*fmt0
, va_list ap
)
622 CHAR_T
*fmt
; /* format string */
623 int ch
; /* character from fmt */
624 int n
, n2
; /* handy integer (short term usage) */
625 CHAR_T
*cp
; /* handy char pointer (short term usage) */
626 int flags
; /* flags as above */
627 int ret
; /* return value accumulator */
628 int width
; /* width from format (%8d), or 0 */
629 int prec
; /* precision from format; <0 for N/A */
630 CHAR_T sign
; /* sign prefix (' ', '+', '-', or \0) */
631 char thousands_sep
; /* locale specific thousands separator */
632 const char *grouping
; /* locale specific numeric grouping rules */
633 #ifndef NO_FLOATING_POINT
635 * We can decompose the printed representation of floating
636 * point numbers into several parts, some of which may be empty:
638 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
641 * A: 'sign' holds this value if present; '\0' otherwise
642 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
643 * C: cp points to the string MMMNNN. Leading and trailing
644 * zeros are not in the string and must be added.
645 * D: expchar holds this character; '\0' if no exponent, e.g. %f
646 * F: at least two digits for decimal, at least one digit for hex
648 char *decimal_point
; /* locale specific decimal point */
650 int signflag
; /* true if float is negative */
651 union { /* floating point arguments %[aAeEfFgG] */
655 char *dtoaend
; /* pointer to end of converted digits */
657 double _double
; /* double precision arguments %[eEfgG] */
658 char softsign
; /* temporary negative sign for floats */
660 char *dtoaresult
; /* buffer allocated by dtoa */
661 int expt
; /* integer value of exponent */
662 char expchar
; /* exponent character: [eEpP\0] */
663 int expsize
; /* character count for expstr */
664 int lead
; /* sig figs before decimal or group sep */
665 int ndig
; /* actual number of digits returned by dtoa */
666 CHAR_T expstr
[MAXEXPDIG
+2]; /* buffer for exponent string: e+ZZZ */
667 int nseps
; /* number of group separators with ' */
668 int nrepeats
; /* number of repeats of the last group */
670 u_long ulval
; /* integer arguments %[diouxX] */
671 uintmax_t ujval
; /* %j, %ll, %q, %t, %z integers */
672 int base
; /* base for [diouxX] conversion */
673 int dprec
; /* a copy of prec if [diouxX], 0 otherwise */
674 int realsz
; /* field size expanded by dprec, sign, etc */
675 int size
; /* size of converted field or string */
676 int prsize
; /* max size of printed field */
677 const char *xdigs
; /* digits for %[xX] conversion */
680 struct __siov
*iovp
; /* for PRINT macro */
681 struct __suio uio
; /* output information: summary */
682 struct __siov iov
[NIOV
];/* ... and individual io vectors */
686 CHAR_T buf
[BUF
]; /* buffer with space for digits of uintmax_t */
687 CHAR_T ox
[2]; /* space for 0x hex-prefix */
688 union arg
*argtable
; /* args, built due to positional arg */
689 union arg statargtable
[STATIC_ARG_TBL_SIZE
];
690 int nextarg
; /* 1-based argument index */
691 va_list orgap
; /* original argument pointer */
692 CHAR_T
*convbuf
; /* multibyte to wide conversion result */
695 * Choose PADSIZE to trade efficiency vs. size. If larger printf
696 * fields occur frequently, increase PADSIZE and make the initialisers
699 #define PADSIZE 16 /* pad chunk size */
700 static CHAR_T blanks
[PADSIZE
] =
701 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
702 static CHAR_T zeroes
[PADSIZE
] =
703 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
705 static const char xdigs_lower
[16] = "0123456789abcdef";
706 static const char xdigs_upper
[16] = "0123456789ABCDEF";
709 * BEWARE, these `goto error' on error, PRINT uses `n2' and
713 #define PRINT(ptr, len) do { \
714 for (n3 = 0; n3 < (len); n3++) \
715 if (__xfputwc((ptr)[n3], fp, loc) == END_OF_FILE) { \
716 fp->_flags |= __SERR; \
719 } while (/*CONSTCOND*/0)
722 #define PRINT(ptr, len) do { \
723 iovp->iov_base = __UNCONST(ptr); \
724 iovp->iov_len = (len); \
725 uio.uio_resid += (len); \
727 if (++uio.uio_iovcnt >= NIOV) { \
728 if (__sprint(fp, &uio)) \
732 } while (/*CONSTCOND*/0)
733 #define FLUSH() do { \
734 if (uio.uio_resid && __sprint(fp, &uio)) \
736 uio.uio_iovcnt = 0; \
738 } while (/*CONSTCOND*/0)
741 #define PAD(howmany, with) do { \
742 if ((n = (howmany)) > 0) { \
743 while (n > PADSIZE) { \
744 PRINT(with, PADSIZE); \
749 } while (/*CONSTCOND*/0)
750 #define PRINTANDPAD(p, ep, len, with) do { \
751 ptrdiff_t td = (ep) - (p); \
752 _DIAGASSERT(__type_fit(int, td)); \
758 PAD((len) - (n2 > 0 ? n2 : 0), (with)); \
759 } while(/*CONSTCOND*/0)
762 * Get the argument indexed by nextarg. If the argument table is
763 * built, use it to get the argument. If its not, get the next
764 * argument (and arguments must be gotten sequentially).
766 #define GETARG(type) \
767 ((/*CONSTCOND*/argtable != NULL) ? *((type*)(void*)(&argtable[nextarg++])) : \
768 (nextarg++, va_arg(ap, type)))
771 * To extend shorts properly, we need both signed and unsigned
772 * argument extraction methods.
775 (flags&LONGINT ? GETARG(long) : \
776 flags&SHORTINT ? (long)(short)GETARG(int) : \
777 flags&CHARINT ? (long)(signed char)GETARG(int) : \
780 (flags&LONGINT ? GETARG(u_long) : \
781 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
782 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
783 (u_long)GETARG(u_int))
784 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
786 (flags&INTMAXT ? GETARG(intmax_t) : \
787 flags&SIZET ? (intmax_t)GETARG(ssize_t) : \
788 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
789 (intmax_t)GETARG(long long))
791 (flags&INTMAXT ? GETARG(uintmax_t) : \
792 flags&SIZET ? (uintmax_t)GETARG(size_t) : \
793 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
794 (uintmax_t)GETARG(unsigned long long))
797 * Get * arguments, including the form *nn$. Preserve the nextarg
798 * that the argument can be gotten once the type is determined.
800 #define GETASTER(val) \
803 while (is_digit(*cp)) { \
804 n2 = 10 * n2 + to_digit(*cp); \
808 int hold = nextarg; \
809 if (argtable == NULL) { \
810 argtable = statargtable; \
811 if (__find_arguments(fmt0, orgap, &argtable) == -1) \
815 val = GETARG (int); \
819 val = GETARG (int); \
822 _DIAGASSERT(fp
!= NULL
);
823 _DIAGASSERT(fmt0
!= NULL
);
825 _SET_ORIENTATION(fp
, -1);
827 thousands_sep
= '\0';
829 #ifndef NO_FLOATING_POINT
830 decimal_point
= localeconv_l(loc
)->decimal_point
;
831 expsize
= 0; /* XXXGCC -Wuninitialized [sh3,m68000] */
832 ndig
= -1; /* XXX gcc */
835 /* sorry, f{w,}printf(read_only_file, L"") returns {W,}EOF, not 0 */
841 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
842 if ((fp
->_flags
& (__SNBF
|__SWR
|__SRW
)) == (__SNBF
|__SWR
) &&
844 return __sbprintf(fp
, loc
, fmt0
, ap
);
846 fmt
= (CHAR_T
*)__UNCONST(fmt0
);
851 uio
.uio_iov
= iovp
= iov
;
858 * Scan the format for conversions (`%' character).
861 const CHAR_T
*result
;
863 for (cp
= fmt
; (ch
= *fmt
) != '\0' && ch
!= '%'; fmt
++)
865 _DIAGASSERT(__type_fit(int, fmt
- cp
));
866 if ((n
= (int)(fmt
- cp
)) != 0) {
867 if ((unsigned)ret
+ n
> INT_MAX
) {
876 fmt
++; /* skip over '%' */
884 #ifndef NO_FLOATING_POINT
887 nseps
= nrepeats
= 0;
894 reswitch
: switch (ch
) {
897 * ``If the space and + flags both appear, the space
898 * flag will be ignored.''
909 * ``A negative field width argument is taken as a
910 * - flag followed by a positive field width.''
912 * They don't exclude field widths read from args.
927 thousands_sep
= *(localeconv_l(loc
)->thousands_sep
);
928 grouping
= localeconv_l(loc
)->grouping
;
929 /* If the locale doesn't define the above, use sane
930 * defaults - otherwise silly things happen! */
931 if (thousands_sep
== 0)
933 if (!grouping
|| !*grouping
)
937 if ((ch
= *fmt
++) == '*') {
942 while (is_digit(ch
)) {
943 prec
= 10 * prec
+ to_digit(ch
);
949 * ``Note that 0 is taken as a flag, not as the
950 * beginning of a field width.''
955 case '1': case '2': case '3': case '4':
956 case '5': case '6': case '7': case '8': case '9':
959 n
= 10 * n
+ to_digit(ch
);
961 } while (is_digit(ch
));
964 if (argtable
== NULL
) {
965 argtable
= statargtable
;
966 if (__find_arguments(fmt0
, orgap
,
974 #ifndef NO_FLOATING_POINT
980 if (flags
& SHORTINT
) {
990 if (flags
& LONGINT
) {
997 flags
|= LLONGINT
; /* not necessarily */
1010 if (flags
& LONGINT
) {
1011 static const mbstate_t initial
;
1016 mbseqlen
= wcrtomb_l(buf
,
1017 (wchar_t)GETARG(wint_t), &mbs
, loc
);
1018 if (mbseqlen
== (size_t)-1) {
1019 fp
->_flags
|= __SERR
;
1022 size
= (int)mbseqlen
;
1028 if (flags
& LONGINT
)
1029 *buf
= (wchar_t)GETARG(wint_t);
1031 *buf
= (wchar_t)btowc_l(GETARG(int), loc
);
1042 if (flags
& INTMAX_SIZE
) {
1044 if ((intmax_t)ujval
< 0) {
1050 if ((long)ulval
< 0) {
1057 #ifndef NO_FLOATING_POINT
1063 xdigs
= xdigs_lower
;
1067 xdigs
= xdigs_upper
;
1072 if (flags
& LONGDBL
) {
1073 fparg
.ldbl
= GETARG(long double);
1075 __hldtoa(fparg
.ldbl
, xdigs
, prec
,
1076 &expt
, &signflag
, &dtoaend
);
1078 fparg
.dbl
= GETARG(double);
1080 __hdtoa(fparg
.dbl
, xdigs
, prec
,
1081 &expt
, &signflag
, &dtoaend
);
1083 if (dtoaresult
== NULL
)
1087 _DIAGASSERT(__type_fit(int,
1088 dtoaend
- dtoaresult
));
1089 prec
= (int)(dtoaend
- dtoaresult
);
1091 if (expt
== INT_MAX
)
1093 _DIAGASSERT(__type_fit(int, dtoaend
- dtoaresult
));
1094 ndig
= (int)(dtoaend
- dtoaresult
);
1095 if (convbuf
!= NULL
)
1098 result
= convbuf
= __mbsconv(dtoaresult
, -1, loc
);
1101 result
= convbuf
= strdup(dtoaresult
);
1105 __freedtoa(dtoaresult
);
1110 if (prec
< 0) /* account for digit before decpt */
1121 expchar
= ch
- ('g' - 'e');
1127 if (flags
& LONGDBL
) {
1128 fparg
.ldbl
= GETARG(long double);
1130 __ldtoa(&fparg
.ldbl
, expchar
? 2 : 3, prec
,
1131 &expt
, &signflag
, &dtoaend
);
1133 fparg
.dbl
= GETARG(double);
1135 __dtoa(fparg
.dbl
, expchar
? 2 : 3, prec
,
1136 &expt
, &signflag
, &dtoaend
);
1140 if (dtoaresult
== NULL
)
1142 _DIAGASSERT(__type_fit(int, dtoaend
- dtoaresult
));
1143 ndig
= (int)(dtoaend
- dtoaresult
);
1144 if (convbuf
!= NULL
)
1147 result
= convbuf
= __mbsconv(dtoaresult
, -1, loc
);
1150 result
= convbuf
= strdup(dtoaresult
);
1154 __freedtoa(dtoaresult
);
1158 if (expt
== INT_MAX
) { /* inf or nan */
1159 if (*result
== 'N') {
1160 result
= (ch
>= 'a') ? STRCONST("nan") :
1164 result
= (ch
>= 'a') ? STRCONST("inf") :
1179 } else if ((ch
== 'g' || ch
== 'G') && prec
== 0) {
1183 if (flags
& LONGDBL
) {
1184 _double
= (double) GETARG(long double);
1186 _double
= GETARG(double);
1189 /* do this before tricky precision changes */
1190 if (isinf(_double
)) {
1193 if (ch
== 'E' || ch
== 'F' || ch
== 'G')
1194 result
= STRCONST("INF");
1196 result
= STRCONST("inf");
1201 if (isnan(_double
)) {
1202 if (ch
== 'E' || ch
== 'F' || ch
== 'G')
1203 result
= STRCONST("NAN");
1205 result
= STRCONST("nan");
1212 dtoaresult
= cvt(_double
, prec
, flags
, &softsign
,
1214 if (dtoaresult
== NULL
)
1216 if (convbuf
!= NULL
)
1219 result
= convbuf
= __mbsconv(dtoaresult
, -1, loc
);
1222 result
= convbuf
= strdup(dtoaresult
);
1226 __freedtoa(dtoaresult
);
1231 if (ch
== 'g' || ch
== 'G') {
1232 if (expt
> -4 && expt
<= prec
) {
1233 /* Make %[gG] smell like %[fF] */
1243 * Make %[gG] smell like %[eE], but
1244 * trim trailing zeroes if no # flag.
1251 expsize
= exponent(expstr
, expt
- 1, expchar
);
1252 size
= expsize
+ prec
;
1253 if (prec
> 1 || flags
& ALT
)
1256 /* space for digits before decimal point */
1261 /* space for decimal pt and following digits */
1262 if (prec
|| flags
& ALT
)
1264 if (grouping
&& expt
> 0) {
1265 /* space for thousands' grouping */
1266 nseps
= nrepeats
= 0;
1268 while ((unsigned char)*grouping
1269 != (unsigned char)CHAR_MAX
) {
1270 if (lead
<= *grouping
)
1273 if (*(grouping
+1)) {
1279 size
+= nseps
+ nrepeats
;
1284 #endif /* !NO_FLOATING_POINT */
1287 * Assignment-like behavior is specified if the
1288 * value overflows or is otherwise unrepresentable.
1289 * C99 says to use `signed char' for %hhn conversions.
1291 if (flags
& LLONGINT
)
1292 *GETARG(long long *) = ret
;
1293 else if (flags
& SIZET
)
1294 *GETARG(ssize_t
*) = (ssize_t
)ret
;
1295 else if (flags
& PTRDIFFT
)
1296 *GETARG(ptrdiff_t *) = ret
;
1297 else if (flags
& INTMAXT
)
1298 *GETARG(intmax_t *) = ret
;
1299 else if (flags
& LONGINT
)
1300 *GETARG(long *) = ret
;
1301 else if (flags
& SHORTINT
)
1302 *GETARG(short *) = ret
;
1303 else if (flags
& CHARINT
)
1304 *GETARG(signed char *) = ret
;
1306 *GETARG(int *) = ret
;
1307 continue; /* no output */
1312 if (flags
& INTMAX_SIZE
)
1320 * ``The argument shall be a pointer to void. The
1321 * value of the pointer is converted to a sequence
1322 * of printable characters, in an implementation-
1326 ujval
= (uintmax_t)(uintptr_t)GETARG(void *);
1328 xdigs
= xdigs_lower
;
1329 flags
= flags
| INTMAXT
;
1336 if ((flags
& LONGINT
) != MULTI
) {
1337 if ((result
= GETARG(CHAR_T
*)) == NULL
)
1338 result
= STRCONST("(null)");
1342 if (convbuf
!= NULL
)
1344 if ((mc
= GETARG(MCHAR_T
*)) == NULL
)
1345 result
= STRCONST("(null)");
1347 convbuf
= SCONV(mc
, prec
, loc
);
1348 if (convbuf
== NULL
) {
1349 fp
->_flags
|= __SERR
;
1358 * can't use STRLEN; can only look for the
1359 * NUL in the first `prec' characters, and
1360 * STRLEN() will go further.
1362 CHAR_T
*p
= MEMCHR(result
, 0, (size_t)prec
);
1365 _DIAGASSERT(__type_fit(int,
1367 size
= (int)(p
- result
);
1373 size_t rlen
= STRLEN(result
);
1374 _DIAGASSERT(__type_fit(int, rlen
));
1383 if (flags
& INTMAX_SIZE
)
1390 xdigs
= xdigs_upper
;
1393 xdigs
= xdigs_lower
;
1395 if (flags
& INTMAX_SIZE
)
1400 /* leading 0x/X only if non-zero */
1402 (flags
& INTMAX_SIZE
? ujval
!= 0 : ulval
!= 0))
1406 /* unsigned conversions */
1407 nosign
: sign
= '\0';
1409 * ``... diouXx conversions ... if a precision is
1410 * specified, the 0 flag will be ignored.''
1413 number
: if ((dprec
= prec
) >= 0)
1417 * ``The result of converting a zero value with an
1418 * explicit precision of zero is no characters.''
1421 * ``The C Standard is clear enough as is. The call
1422 * printf("%#.0o", 0) should print 0.''
1423 * -- Defect Report #151
1425 result
= cp
= buf
+ BUF
;
1426 if (flags
& INTMAX_SIZE
) {
1427 if (ujval
!= 0 || prec
!= 0 ||
1428 (flags
& ALT
&& base
== 8))
1429 result
= __ujtoa(ujval
, cp
, base
,
1431 flags
& GROUPING
, thousands_sep
,
1434 if (ulval
!= 0 || prec
!= 0 ||
1435 (flags
& ALT
&& base
== 8))
1436 result
= __ultoa(ulval
, cp
, base
,
1438 flags
& GROUPING
, thousands_sep
,
1441 _DIAGASSERT(__type_fit(int, buf
+ BUF
- result
));
1442 size
= (int)(buf
+ BUF
- result
);
1443 if (size
> BUF
) /* should never happen */
1446 default: /* "%?" prints ?, unless ? is NUL */
1449 /* pretend it was %c with argument ch */
1458 * All reasonable formats wind up here. At this point, `result'
1459 * points to a string which (if not flags&LADJUST) should be
1460 * padded out to `width' places. If flags&ZEROPAD, it should
1461 * first be prefixed by any sign or other prefix; otherwise,
1462 * it should be blank padded before the prefix is emitted.
1463 * After any left-hand padding and prefixing, emit zeroes
1464 * required by a decimal [diouxX] precision, then print the
1465 * string proper, then emit zeroes required by any leftover
1466 * floating precision; finally, if LADJUST, pad with blanks.
1468 * Compute actual size, so we know how much to pad.
1469 * size excludes decimal prec; realsz includes it.
1471 realsz
= dprec
> size
? dprec
: size
;
1477 prsize
= width
> realsz
? width
: realsz
;
1478 if ((unsigned)ret
+ prsize
> INT_MAX
) {
1483 /* right-adjusting blank padding */
1484 if ((flags
& (LADJUST
|ZEROPAD
)) == 0)
1485 PAD(width
- realsz
, blanks
);
1491 if (ox
[1]) { /* ox[1] is either x, X, or \0 */
1496 /* right-adjusting zero padding */
1497 if ((flags
& (LADJUST
|ZEROPAD
)) == ZEROPAD
)
1498 PAD(width
- realsz
, zeroes
);
1500 /* leading zeroes from decimal precision */
1501 PAD(dprec
- size
, zeroes
);
1503 /* the string or number proper */
1504 #ifndef NO_FLOATING_POINT
1505 if ((flags
& FPT
) == 0) {
1506 PRINT(result
, size
);
1507 } else { /* glue together f_p fragments */
1508 if (!expchar
) { /* %[fF] or sufficiently short %[gG] */
1511 if (prec
|| flags
& ALT
)
1512 PRINT(decimal_point
, 1);
1514 /* already handled initial 0's */
1517 PRINTANDPAD(result
, convbuf
+ ndig
,
1521 while (nseps
>0 || nrepeats
>0) {
1528 PRINT(&thousands_sep
,
1533 result
+= *grouping
;
1535 if (result
> convbuf
+ ndig
)
1536 result
= convbuf
+ ndig
;
1538 if (prec
|| flags
& ALT
) {
1539 buf
[0] = *decimal_point
;
1543 PRINTANDPAD(result
, convbuf
+ ndig
, prec
,
1545 } else { /* %[eE] or sufficiently long %[gG] */
1546 if (prec
> 1 || flags
& ALT
) {
1548 buf
[1] = *decimal_point
;
1550 PRINT(result
, ndig
-1);
1551 PAD(prec
- ndig
, zeroes
);
1554 PRINT(expstr
, expsize
);
1558 PRINT(result
, size
);
1560 /* left-adjusting padding (always blank) */
1561 if (flags
& LADJUST
)
1562 PAD(width
- realsz
, blanks
);
1564 /* finally, adjust ret */
1572 if (convbuf
!= NULL
)
1576 if ((argtable
!= NULL
) && (argtable
!= statargtable
))
1587 * Find all arguments when a positional parameter is encountered. Returns a
1588 * table, indexed by argument number, of pointers to each arguments. The
1589 * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1590 * It will be replaces with a malloc-ed one if it overflows.
1593 __find_arguments(const CHAR_T
*fmt0
, va_list ap
, union arg
**argtable
)
1595 CHAR_T
*fmt
; /* format string */
1596 int ch
; /* character from fmt */
1597 size_t n
, n2
; /* handy index (short term usage) */
1598 CHAR_T
*cp
; /* handy char pointer (short term usage) */
1599 int flags
; /* flags as above */
1600 enum typeid *typetable
; /* table of types */
1601 enum typeid stattypetable
[STATIC_ARG_TBL_SIZE
];
1602 size_t tablesize
; /* current size of type table */
1603 size_t tablemax
; /* largest used index in table */
1604 size_t nextarg
; /* 1-based argument index */
1605 size_t nitems
; /* number of items we picked from the stack */
1608 * Add an argument type to the table, expanding if necessary.
1609 * Check for overflow.
1611 #define ADDTYPE(type) \
1613 if (nextarg > SIZE_MAX / sizeof(**argtable)) { \
1614 if (typetable != stattypetable) \
1618 if (nextarg >= tablesize) \
1619 if (__grow_type_table(nextarg, &typetable, \
1620 &tablesize) == -1) \
1622 if (nextarg > tablemax) \
1623 tablemax = nextarg; \
1624 typetable[nextarg++] = type; \
1626 } while (/*CONSTCOND*/0)
1630 if (flags & INTMAXT) \
1631 ADDTYPE(T_INTMAXT); \
1632 else if (flags & SIZET) \
1633 ADDTYPE(T_SSIZET); \
1634 else if (flags & PTRDIFFT) \
1635 ADDTYPE(T_PTRDIFFT); \
1636 else if (flags & LLONGINT) \
1638 else if (flags & LONGINT) \
1642 } while (/*CONSTCOND*/0)
1646 if (flags & INTMAXT) \
1647 ADDTYPE(T_UINTMAXT); \
1648 else if (flags & SIZET) \
1650 else if (flags & PTRDIFFT) \
1651 ADDTYPE(T_PTRDIFFT); \
1652 else if (flags & LLONGINT) \
1653 ADDTYPE(T_U_LLONG); \
1654 else if (flags & LONGINT) \
1655 ADDTYPE(T_U_LONG); \
1658 } while (/*CONSTCOND*/0)
1660 * Add * arguments to the type array.
1662 #define ADDASTER() \
1665 while (is_digit(*cp)) { \
1666 n2 = 10 * n2 + to_digit(*cp); \
1670 size_t hold = nextarg; \
1678 fmt
= (CHAR_T
*)__UNCONST(fmt0
);
1679 memset(stattypetable
, 0, sizeof(stattypetable
));
1680 typetable
= stattypetable
;
1681 tablesize
= STATIC_ARG_TBL_SIZE
;
1687 * Scan the format for conversions (`%' character).
1690 for (cp
= fmt
; (ch
= *fmt
) != '\0' && ch
!= '%'; fmt
++)
1694 fmt
++; /* skip over '%' */
1699 reswitch
: switch (ch
) {
1711 if ((ch
= *fmt
++) == '*') {
1715 while (is_digit(ch
)) {
1721 case '1': case '2': case '3': case '4':
1722 case '5': case '6': case '7': case '8': case '9':
1725 n
= 10 * n
+ to_digit(ch
);
1727 } while (is_digit(ch
));
1733 #ifndef NO_FLOATING_POINT
1739 if (flags
& SHORTINT
) {
1749 if (flags
& LONGINT
) {
1756 flags
|= LLONGINT
; /* not necessarily */
1768 if (flags
& LONGINT
)
1780 #ifndef NO_FLOATING_POINT
1788 if (flags
& LONGDBL
)
1789 ADDTYPE(T_LONG_DOUBLE
);
1793 #endif /* !NO_FLOATING_POINT */
1795 if (flags
& INTMAXT
)
1796 ADDTYPE(TP_INTMAXT
);
1797 else if (flags
& PTRDIFFT
)
1798 ADDTYPE(TP_PTRDIFFT
);
1799 else if (flags
& SIZET
)
1801 else if (flags
& LLONGINT
)
1803 else if (flags
& LONGINT
)
1805 else if (flags
& SHORTINT
)
1807 else if (flags
& CHARINT
)
1811 continue; /* no output */
1825 if (flags
& LONGINT
)
1838 default: /* "%?" prints ?, unless ? is NUL */
1846 * nitems contains the number of arguments we picked from the stack.
1847 * If tablemax is larger, this means that some positional argument,
1848 * tried to pick an argument the number of arguments possibly supplied.
1849 * Since positional arguments are typically used to swap the order of
1850 * the printf arguments and not to pick random arguments from strange
1851 * positions in the stack, we assume that if the positional argument
1852 * is trying to pick beyond the end of arguments, then this is wrong.
1853 * Alternatively we could find a way to figure out when va_arg() runs
1854 * out, but how to do that?
1856 if (nitems
< tablemax
) {
1857 if (typetable
!= stattypetable
)
1862 * Build the argument table.
1864 if (tablemax
>= STATIC_ARG_TBL_SIZE
) {
1865 *argtable
= malloc(sizeof(**argtable
) * (tablemax
+ 1));
1866 if (*argtable
== NULL
) {
1872 (*argtable
) [0].intarg
= 0;
1873 for (n
= 1; n
<= tablemax
; n
++) {
1874 switch (typetable
[n
]) {
1875 case T_UNUSED
: /* whoops! */
1876 (*argtable
) [n
].intarg
= va_arg (ap
, int);
1879 (*argtable
) [n
].pschararg
= va_arg (ap
, signed char *);
1882 (*argtable
) [n
].pshortarg
= va_arg (ap
, short *);
1885 (*argtable
) [n
].intarg
= va_arg (ap
, int);
1888 (*argtable
) [n
].uintarg
= va_arg (ap
, unsigned int);
1891 (*argtable
) [n
].pintarg
= va_arg (ap
, int *);
1894 (*argtable
) [n
].longarg
= va_arg (ap
, long);
1897 (*argtable
) [n
].ulongarg
= va_arg (ap
, unsigned long);
1900 (*argtable
) [n
].plongarg
= va_arg (ap
, long *);
1903 (*argtable
) [n
].longlongarg
= va_arg (ap
, long long);
1906 (*argtable
) [n
].ulonglongarg
= va_arg (ap
, unsigned long long);
1909 (*argtable
) [n
].plonglongarg
= va_arg (ap
, long long *);
1912 (*argtable
) [n
].ptrdiffarg
= va_arg (ap
, ptrdiff_t);
1915 (*argtable
) [n
].pptrdiffarg
= va_arg (ap
, ptrdiff_t *);
1918 (*argtable
) [n
].ssizearg
= va_arg (ap
, ssize_t
);
1921 (*argtable
) [n
].sizearg
= va_arg (ap
, size_t);
1924 (*argtable
) [n
].psizearg
= va_arg (ap
, size_t *);
1927 (*argtable
) [n
].intmaxarg
= va_arg (ap
, intmax_t);
1930 (*argtable
) [n
].uintmaxarg
= va_arg (ap
, uintmax_t);
1933 (*argtable
) [n
].pintmaxarg
= va_arg (ap
, intmax_t *);
1936 #ifndef NO_FLOATING_POINT
1937 (*argtable
) [n
].doublearg
= va_arg (ap
, double);
1941 #ifndef NO_FLOATING_POINT
1942 (*argtable
) [n
].longdoublearg
= va_arg (ap
, long double);
1946 (*argtable
) [n
].pchararg
= va_arg (ap
, char *);
1949 (*argtable
) [n
].pvoidarg
= va_arg (ap
, void *);
1952 (*argtable
) [n
].wintarg
= va_arg (ap
, wint_t);
1955 (*argtable
) [n
].pwchararg
= va_arg (ap
, wchar_t *);
1960 if (typetable
!= stattypetable
)
1966 * Increase the size of the type table.
1969 __grow_type_table (size_t nextarg
, enum typeid **typetable
, size_t *tablesize
)
1971 enum typeid *const oldtable
= *typetable
;
1972 const size_t oldsize
= *tablesize
;
1973 enum typeid *newtable
;
1974 size_t newsize
= oldsize
* 2;
1976 if (newsize
< nextarg
+ 1)
1977 newsize
= nextarg
+ 1;
1978 if (oldsize
== STATIC_ARG_TBL_SIZE
) {
1979 if ((newtable
= malloc(newsize
* sizeof(*newtable
))) == NULL
)
1981 memcpy(newtable
, oldtable
, oldsize
* sizeof(*newtable
));
1983 newtable
= realloc(oldtable
, newsize
* sizeof(*newtable
));
1984 if (newtable
== NULL
) {
1989 memset(&newtable
[oldsize
], 0, (newsize
- oldsize
) * sizeof(*newtable
));
1991 *typetable
= newtable
;
1992 *tablesize
= newsize
;
1997 #ifndef NO_FLOATING_POINT
2000 cvt(double value
, int ndigits
, int flags
, char *sign
, int *decpt
, int ch
,
2004 char *digits
, *bp
, *rve
;
2006 _DIAGASSERT(decpt
!= NULL
);
2007 _DIAGASSERT(length
!= NULL
);
2008 _DIAGASSERT(sign
!= NULL
);
2011 mode
= 3; /* ndigits after the decimal point */
2013 /* To obtain ndigits after the decimal point for the 'e'
2014 * and 'E' formats, round to ndigits + 1 significant
2017 if (ch
== 'e' || ch
== 'E') {
2020 mode
= 2; /* ndigits significant digits */
2023 digits
= __dtoa(value
, mode
, ndigits
, decpt
, &dsgn
, &rve
);
2031 if ((ch
!= 'g' && ch
!= 'G') || flags
& ALT
) { /* Print trailing zeros */
2032 bp
= digits
+ ndigits
;
2034 if (*digits
== '0' && value
)
2035 *decpt
= -ndigits
+ 1;
2038 if (value
== 0) /* kludge for __dtoa irregularity */
2043 *length
= rve
- digits
;
2049 exponent(CHAR_T
*p0
, int expo
, int fmtch
)
2052 CHAR_T expbuf
[MAXEXPDIG
];
2062 t
= expbuf
+ MAXEXPDIG
;
2065 *--t
= to_char(expo
% 10);
2066 } while ((expo
/= 10) > 9);
2067 *--t
= to_char(expo
);
2068 for (; t
< expbuf
+ MAXEXPDIG
; *p
++ = *t
++);
2072 * Exponents for decimal floating point conversions
2073 * (%[eEgG]) must be at least two characters long,
2074 * whereas exponents for hexadecimal conversions can
2075 * be only one character long.
2077 if (fmtch
== 'e' || fmtch
== 'E')
2079 *p
++ = to_char(expo
);
2081 _DIAGASSERT(__type_fit(int, p
- p0
));
2082 return (int)(p
- p0
);
2084 #endif /* !NO_FLOATING_POINT */