1 /* $NetBSD: vfwprintf.c,v 1.30 2012/03/27 15:05:42 christos 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.30 2012/03/27 15:05:42 christos 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"
73 #define CHAR_T wchar_t
74 #define STRLEN(a) wcslen(a)
75 #define MEMCHR(a, b, c) wmemchr(a, b, c)
76 #define SCONV(a, b) __mbsconv(a, b)
77 #define STRCONST(a) L ## a
78 #define WDECL(a, b) a ## w ## b
79 #define END_OF_FILE WEOF
82 #define MCHAR_T wchar_t
84 #define STRLEN(a) strlen(a)
85 #define MEMCHR(a, b, c) memchr(a, b, c)
86 #define SCONV(a, b) __wcsconv(a, b)
88 #define WDECL(a, b) a ## b
89 #define END_OF_FILE EOF
98 long long longlongarg
;
99 unsigned long long ulonglongarg
;
100 ptrdiff_t ptrdiffarg
;
104 uintmax_t uintmaxarg
;
107 signed char *pschararg
;
111 long long *plonglongarg
;
112 ptrdiff_t *pptrdiffarg
;
114 intmax_t *pintmaxarg
;
115 #ifndef NO_FLOATING_POINT
117 long double longdoublearg
;
124 * Type ids for argument type table.
127 T_UNUSED
= 0, TP_SHORT
, T_INT
, T_U_INT
, TP_INT
,
128 T_LONG
, T_U_LONG
, TP_LONG
, T_LLONG
, T_U_LLONG
, TP_LLONG
,
129 T_PTRDIFFT
, TP_PTRDIFFT
, T_SSIZET
, T_SIZET
, TP_SIZET
,
130 T_INTMAXT
, T_UINTMAXT
, TP_INTMAXT
, TP_VOID
, TP_CHAR
, TP_SCHAR
,
131 T_DOUBLE
, T_LONG_DOUBLE
, T_WINT
, TP_WCHAR
134 static int __sbprintf(FILE *, const CHAR_T
*, va_list);
135 static CHAR_T
*__ujtoa(uintmax_t, CHAR_T
*, int, int, const char *, int,
137 static CHAR_T
*__ultoa(u_long
, CHAR_T
*, int, int, const char *, int,
140 static CHAR_T
*__mbsconv(char *, int);
141 static wint_t __xfputwc(CHAR_T
, FILE *);
143 static char *__wcsconv(wchar_t *, int);
144 static int __sprint(FILE *, struct __suio
*);
146 static int __find_arguments(const CHAR_T
*, va_list, union arg
**);
147 static int __grow_type_table(size_t, enum typeid **, size_t *);
150 * Helper function for `fprintf to unbuffered unix file': creates a
151 * temporary buffer. We only work on write-only files; this avoids
152 * worries about ungetc buffers and so forth.
155 __sbprintf(FILE *fp
, const CHAR_T
*fmt
, va_list ap
)
159 struct __sfileext fakeext
;
160 unsigned char buf
[BUFSIZ
];
162 _DIAGASSERT(fp
!= NULL
);
163 _DIAGASSERT(fmt
!= NULL
);
165 _FILEEXT_SETUP(&fake
, &fakeext
);
166 memset(WCIO_GET(&fake
), 0, sizeof(struct wchar_io_data
));
168 /* copy the important variables */
169 fake
._flags
= fp
->_flags
& ~__SNBF
;
170 fake
._file
= fp
->_file
;
171 fake
._cookie
= fp
->_cookie
;
172 fake
._write
= fp
->_write
;
173 fake
._flush
= fp
->_flush
;
175 /* set up the buffer */
176 fake
._bf
._base
= fake
._p
= buf
;
177 fake
._bf
._size
= fake
._w
= sizeof(buf
);
178 fake
._lbfsize
= 0; /* not actually used, but Just In Case */
180 /* do the work, then copy any error status */
181 ret
= WDECL(__vf
,printf_unlocked
)(&fake
, fmt
, ap
);
182 if (ret
>= 0 && fflush(&fake
))
184 if (fake
._flags
& __SERR
)
185 fp
->_flags
|= __SERR
;
191 * Like __fputwc, but handles fake string (__SSTR) files properly.
192 * File must already be locked.
195 __xfputwc(wchar_t wc
, FILE *fp
)
197 static const mbstate_t initial
;
199 char buf
[MB_LEN_MAX
];
204 if ((fp
->_flags
& __SSTR
) == 0)
205 return __fputwc_unlock(wc
, fp
);
208 if ((len
= wcrtomb(buf
, wc
, &mbs
)) == (size_t)-1) {
209 fp
->_flags
|= __SERR
;
217 return __sfvwrite(fp
, &uio
) != EOF
? (wint_t)wc
: END_OF_FILE
;
221 * Flush out all the vectors defined by the given uio,
222 * then reset it so that it can be reused.
225 __sprint(FILE *fp
, struct __suio
*uio
)
229 _DIAGASSERT(fp
!= NULL
);
230 _DIAGASSERT(uio
!= NULL
);
232 if (uio
->uio_resid
== 0) {
236 err
= __sfvwrite(fp
, uio
);
244 * Macros for converting digits to letters and vice versa
246 #define to_digit(c) ((c) - '0')
247 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
248 #define to_char(n) (CHAR_T)((n) + '0')
251 * Convert an unsigned long to ASCII for printf purposes, returning
252 * a pointer to the first character of the string representation.
253 * Octal numbers can be forced to have a leading zero; hex numbers
254 * use the given digits.
257 __ultoa(u_long val
, CHAR_T
*endp
, int base
, int octzero
, const char *xdigs
,
258 int needgrp
, char thousep
, const char *grp
)
265 * Handle the three cases separately, in the hope of getting
266 * better/faster code.
270 if (val
< 10) { /* many numbers are 1 digit */
271 *--cp
= to_char(val
);
276 * On many machines, unsigned arithmetic is harder than
277 * signed arithmetic, so we do at most one unsigned mod and
278 * divide; this is sufficient to reduce the range of
279 * the incoming value to where signed arithmetic works.
281 if (val
> LONG_MAX
) {
282 *--cp
= to_char(val
% 10);
288 *--cp
= to_char(sval
% 10);
291 * If (*grp == CHAR_MAX) then no more grouping
292 * should be performed.
294 if (needgrp
&& ndig
== *grp
295 && (unsigned char)*grp
!= (unsigned char)CHAR_MAX
300 * If (*(grp+1) == '\0') then we have to
301 * use *grp character (last grouping rule)
304 if (*(grp
+1) != '\0')
313 *--cp
= to_char(val
& 7);
316 if (octzero
&& *cp
!= '0')
322 *--cp
= xdigs
[(size_t)val
& 15];
333 /* Identical to __ultoa, but for intmax_t. */
335 __ujtoa(uintmax_t val
, CHAR_T
*endp
, int base
, int octzero
,
336 const char *xdigs
, int needgrp
, char thousep
, const char *grp
)
342 /* quick test for small values; __ultoa is typically much faster */
343 /* (perhaps instead we should run until small, then call __ultoa?) */
344 if (val
<= ULONG_MAX
)
345 return __ultoa((u_long
)val
, endp
, base
, octzero
, xdigs
,
346 needgrp
, thousep
, grp
);
350 *--cp
= to_char(val
% 10);
354 if (val
> INTMAX_MAX
) {
355 *--cp
= to_char(val
% 10);
361 *--cp
= to_char(sval
% 10);
364 * If (*grp == CHAR_MAX) then no more grouping
365 * should be performed.
368 && (unsigned char)*grp
!= (unsigned char)CHAR_MAX
374 * If (*(grp+1) == '\0') then we have to
375 * use *grp character (last grouping rule)
378 if (*(grp
+1) != '\0')
387 *--cp
= to_char(val
& 7);
390 if (octzero
&& *cp
!= '0')
396 *--cp
= xdigs
[(size_t)val
& 15];
409 * Convert a multibyte character string argument for the %s format to a wide
410 * string representation. ``prec'' specifies the maximum number of bytes
411 * to output. If ``prec'' is greater than or equal to zero, we can't assume
412 * that the multibyte char. string ends in a null character.
415 __mbsconv(char *mbsarg
, int prec
)
417 static const mbstate_t initial
;
419 wchar_t *convbuf
, *wcp
;
421 size_t insize
, nchars
, nconv
;
427 * Supplied argument is a multibyte string; convert it to wide
432 * String is not guaranteed to be NUL-terminated. Find the
433 * number of characters to print.
436 insize
= nchars
= nconv
= 0;
438 while (nchars
!= (size_t)prec
) {
439 nconv
= mbrlen(p
, MB_CUR_MAX
, &mbs
);
440 if (nconv
== 0 || nconv
== (size_t)-1 ||
447 if (nconv
== (size_t)-1 || nconv
== (size_t)-2)
450 insize
= strlen(mbsarg
);
453 * Allocate buffer for the result and perform the conversion,
454 * converting at most `size' bytes of the input multibyte string to
455 * wide characters for printing.
457 convbuf
= malloc((insize
+ 1) * sizeof(*convbuf
));
464 while (insize
!= 0) {
465 nconv
= mbrtowc(wcp
, p
, insize
, &mbs
);
466 if (nconv
== 0 || nconv
== (size_t)-1 || nconv
== (size_t)-2)
472 if (nconv
== (size_t)-1 || nconv
== (size_t)-2) {
482 * Convert a wide-character string argument for the %ls format to a multibyte
483 * string representation. If not -1, prec specifies the maximum number of
484 * bytes to output, and also means that we can't assume that the wide-char.
485 * string ends is null-terminated.
488 __wcsconv(wchar_t *wcsarg
, int prec
)
490 static const mbstate_t initial
;
492 char buf
[MB_LEN_MAX
];
497 /* Allocate space for the maximum number of bytes we could output. */
501 nbytes
= wcsrtombs(NULL
, (void *)&p
, 0, &mbs
);
502 if (nbytes
== (size_t)-1)
506 * Optimisation: if the output precision is small enough,
507 * just allocate enough memory for the maximum instead of
508 * scanning the string.
517 clen
= wcrtomb(buf
, *p
++, &mbs
);
518 if (clen
== 0 || clen
== (size_t)-1 ||
519 nbytes
+ clen
> (size_t)prec
)
525 if ((convbuf
= malloc(nbytes
+ 1)) == NULL
)
528 /* Fill the output buffer. */
531 if ((nbytes
= wcsrtombs(convbuf
, (void *)&p
,
532 nbytes
, &mbs
)) == (size_t)-1) {
536 convbuf
[nbytes
] = '\0';
545 WDECL(vf
,printf
)(FILE * __restrict fp
, const CHAR_T
* __restrict fmt0
, va_list ap
)
550 ret
= WDECL(__vf
,printf_unlocked
)(fp
, fmt0
, ap
);
555 #ifndef NO_FLOATING_POINT
563 static int exponent(CHAR_T
*, int, int);
565 static char *cvt(double, int, int, char *, int *, int, int *);
568 #endif /* !NO_FLOATING_POINT */
571 * The size of the buffer we use as scratch space for integer
572 * conversions, among other things. Technically, we would need the
573 * most space for base 10 conversions with thousands' grouping
574 * characters between each pair of digits. 100 bytes is a
575 * conservative overestimate even for a 128-bit uintmax_t.
579 #define STATIC_ARG_TBL_SIZE 8 /* Size of static argument table. */
582 * Flags used during conversion.
584 #define ALT 0x001 /* alternate form */
585 #define LADJUST 0x004 /* left adjustment */
586 #define LONGDBL 0x008 /* long double */
587 #define LONGINT 0x010 /* long integer */
588 #define LLONGINT 0x020 /* long long integer */
589 #define SHORTINT 0x040 /* short integer */
590 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
591 #define FPT 0x100 /* Floating point number */
592 #define GROUPING 0x200 /* use grouping ("'" flag) */
593 /* C99 additional size modifiers: */
594 #define SIZET 0x400 /* size_t */
595 #define PTRDIFFT 0x800 /* ptrdiff_t */
596 #define INTMAXT 0x1000 /* intmax_t */
597 #define CHARINT 0x2000 /* print char using int format */
600 * Non-MT-safe version
603 WDECL(__vf
,printf_unlocked
)(FILE *fp
, const CHAR_T
*fmt0
, va_list ap
)
605 CHAR_T
*fmt
; /* format string */
606 int ch
; /* character from fmt */
607 int n
, n2
; /* handy integer (short term usage) */
608 CHAR_T
*cp
; /* handy char pointer (short term usage) */
609 int flags
; /* flags as above */
610 int ret
; /* return value accumulator */
611 int width
; /* width from format (%8d), or 0 */
612 int prec
; /* precision from format; <0 for N/A */
613 CHAR_T sign
; /* sign prefix (' ', '+', '-', or \0) */
614 char thousands_sep
; /* locale specific thousands separator */
615 const char *grouping
; /* locale specific numeric grouping rules */
616 #ifndef NO_FLOATING_POINT
618 * We can decompose the printed representation of floating
619 * point numbers into several parts, some of which may be empty:
621 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
624 * A: 'sign' holds this value if present; '\0' otherwise
625 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
626 * C: cp points to the string MMMNNN. Leading and trailing
627 * zeros are not in the string and must be added.
628 * D: expchar holds this character; '\0' if no exponent, e.g. %f
629 * F: at least two digits for decimal, at least one digit for hex
631 char *decimal_point
; /* locale specific decimal point */
633 int signflag
; /* true if float is negative */
634 union { /* floating point arguments %[aAeEfFgG] */
638 char *dtoaend
; /* pointer to end of converted digits */
640 double _double
; /* double precision arguments %[eEfgG] */
641 char softsign
; /* temporary negative sign for floats */
643 char *dtoaresult
; /* buffer allocated by dtoa */
644 int expt
; /* integer value of exponent */
645 char expchar
; /* exponent character: [eEpP\0] */
646 int expsize
; /* character count for expstr */
647 int lead
; /* sig figs before decimal or group sep */
648 int ndig
; /* actual number of digits returned by dtoa */
649 CHAR_T expstr
[MAXEXPDIG
+2]; /* buffer for exponent string: e+ZZZ */
650 int nseps
; /* number of group separators with ' */
651 int nrepeats
; /* number of repeats of the last group */
653 u_long ulval
; /* integer arguments %[diouxX] */
654 uintmax_t ujval
; /* %j, %ll, %q, %t, %z integers */
655 int base
; /* base for [diouxX] conversion */
656 int dprec
; /* a copy of prec if [diouxX], 0 otherwise */
657 int realsz
; /* field size expanded by dprec, sign, etc */
658 int size
; /* size of converted field or string */
659 int prsize
; /* max size of printed field */
660 const char *xdigs
; /* digits for %[xX] conversion */
663 struct __siov
*iovp
; /* for PRINT macro */
664 struct __suio uio
; /* output information: summary */
665 struct __siov iov
[NIOV
];/* ... and individual io vectors */
669 CHAR_T buf
[BUF
]; /* buffer with space for digits of uintmax_t */
670 CHAR_T ox
[2]; /* space for 0x hex-prefix */
671 union arg
*argtable
; /* args, built due to positional arg */
672 union arg statargtable
[STATIC_ARG_TBL_SIZE
];
673 int nextarg
; /* 1-based argument index */
674 va_list orgap
; /* original argument pointer */
675 CHAR_T
*convbuf
; /* multibyte to wide conversion result */
678 * Choose PADSIZE to trade efficiency vs. size. If larger printf
679 * fields occur frequently, increase PADSIZE and make the initialisers
682 #define PADSIZE 16 /* pad chunk size */
683 static CHAR_T blanks
[PADSIZE
] =
684 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
685 static CHAR_T zeroes
[PADSIZE
] =
686 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
688 static const char xdigs_lower
[16] = "0123456789abcdef";
689 static const char xdigs_upper
[16] = "0123456789ABCDEF";
692 * BEWARE, these `goto error' on error, PRINT uses `n2' and
696 #define PRINT(ptr, len) do { \
697 for (n3 = 0; n3 < (len); n3++) \
698 __xfputwc((ptr)[n3], fp); \
699 } while (/*CONSTCOND*/0)
702 #define PRINT(ptr, len) do { \
703 iovp->iov_base = __UNCONST(ptr); \
704 iovp->iov_len = (len); \
705 uio.uio_resid += (len); \
707 if (++uio.uio_iovcnt >= NIOV) { \
708 if (__sprint(fp, &uio)) \
712 } while (/*CONSTCOND*/0)
713 #define FLUSH() do { \
714 if (uio.uio_resid && __sprint(fp, &uio)) \
716 uio.uio_iovcnt = 0; \
718 } while (/*CONSTCOND*/0)
721 #define PAD(howmany, with) do { \
722 if ((n = (howmany)) > 0) { \
723 while (n > PADSIZE) { \
724 PRINT(with, PADSIZE); \
729 } while (/*CONSTCOND*/0)
730 #define PRINTANDPAD(p, ep, len, with) do { \
731 ptrdiff_t td = (ep) - (p); \
732 _DIAGASSERT(__type_fit(int, td)); \
738 PAD((len) - (n2 > 0 ? n2 : 0), (with)); \
739 } while(/*CONSTCOND*/0)
742 * Get the argument indexed by nextarg. If the argument table is
743 * built, use it to get the argument. If its not, get the next
744 * argument (and arguments must be gotten sequentially).
746 #define GETARG(type) \
747 ((/*CONSTCOND*/argtable != NULL) ? *((type*)(void*)(&argtable[nextarg++])) : \
748 (nextarg++, va_arg(ap, type)))
751 * To extend shorts properly, we need both signed and unsigned
752 * argument extraction methods.
755 (flags&LONGINT ? GETARG(long) : \
756 flags&SHORTINT ? (long)(short)GETARG(int) : \
757 flags&CHARINT ? (long)(signed char)GETARG(int) : \
760 (flags&LONGINT ? GETARG(u_long) : \
761 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
762 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
763 (u_long)GETARG(u_int))
764 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
766 (flags&INTMAXT ? GETARG(intmax_t) : \
767 flags&SIZET ? (intmax_t)GETARG(ssize_t) : \
768 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
769 (intmax_t)GETARG(long long))
771 (flags&INTMAXT ? GETARG(uintmax_t) : \
772 flags&SIZET ? (uintmax_t)GETARG(size_t) : \
773 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
774 (uintmax_t)GETARG(unsigned long long))
777 * Get * arguments, including the form *nn$. Preserve the nextarg
778 * that the argument can be gotten once the type is determined.
780 #define GETASTER(val) \
783 while (is_digit(*cp)) { \
784 n2 = 10 * n2 + to_digit(*cp); \
788 int hold = nextarg; \
789 if (argtable == NULL) { \
790 argtable = statargtable; \
791 if (__find_arguments(fmt0, orgap, &argtable) == -1) \
795 val = GETARG (int); \
799 val = GETARG (int); \
802 _DIAGASSERT(fp
!= NULL
);
803 _DIAGASSERT(fmt0
!= NULL
);
805 _SET_ORIENTATION(fp
, -1);
807 ndig
= -1; /* XXX gcc */
809 thousands_sep
= '\0';
811 #ifndef NO_FLOATING_POINT
812 decimal_point
= localeconv()->decimal_point
;
813 expsize
= 0; /* XXXGCC -Wuninitialized [sh3,m68000] */
816 /* sorry, f{w,}printf(read_only_file, L"") returns {W,}EOF, not 0 */
822 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
823 if ((fp
->_flags
& (__SNBF
|__SWR
|__SRW
)) == (__SNBF
|__SWR
) &&
825 return __sbprintf(fp
, fmt0
, ap
);
827 fmt
= (CHAR_T
*)__UNCONST(fmt0
);
832 uio
.uio_iov
= iovp
= iov
;
839 * Scan the format for conversions (`%' character).
842 const CHAR_T
*result
;
844 for (cp
= fmt
; (ch
= *fmt
) != '\0' && ch
!= '%'; fmt
++)
846 _DIAGASSERT(__type_fit(int, fmt
- cp
));
847 if ((n
= (int)(fmt
- cp
)) != 0) {
848 if ((unsigned)ret
+ n
> INT_MAX
) {
857 fmt
++; /* skip over '%' */
867 nseps
= nrepeats
= 0;
873 reswitch
: switch (ch
) {
876 * ``If the space and + flags both appear, the space
877 * flag will be ignored.''
888 * ``A negative field width argument is taken as a
889 * - flag followed by a positive field width.''
891 * They don't exclude field widths read from args.
906 thousands_sep
= *(localeconv()->thousands_sep
);
907 grouping
= localeconv()->grouping
;
908 /* If the locale doesn't define the above, use sane
909 * defaults - otherwise silly things happen! */
910 if (thousands_sep
== 0)
912 if (!grouping
|| !*grouping
)
916 if ((ch
= *fmt
++) == '*') {
921 while (is_digit(ch
)) {
922 prec
= 10 * prec
+ to_digit(ch
);
928 * ``Note that 0 is taken as a flag, not as the
929 * beginning of a field width.''
934 case '1': case '2': case '3': case '4':
935 case '5': case '6': case '7': case '8': case '9':
938 n
= 10 * n
+ to_digit(ch
);
940 } while (is_digit(ch
));
943 if (argtable
== NULL
) {
944 argtable
= statargtable
;
945 if (__find_arguments(fmt0
, orgap
,
953 #ifndef NO_FLOATING_POINT
959 if (flags
& SHORTINT
) {
969 if (flags
& LONGINT
) {
976 flags
|= LLONGINT
; /* not necessarily */
989 if (flags
& LONGINT
) {
990 static const mbstate_t initial
;
995 mbseqlen
= wcrtomb(buf
,
996 (wchar_t)GETARG(wint_t), &mbs
);
997 if (mbseqlen
== (size_t)-1) {
998 fp
->_flags
|= __SERR
;
1001 size
= (int)mbseqlen
;
1007 if (flags
& LONGINT
)
1008 *buf
= (wchar_t)GETARG(wint_t);
1010 *buf
= (wchar_t)btowc(GETARG(int));
1021 if (flags
& INTMAX_SIZE
) {
1023 if ((intmax_t)ujval
< 0) {
1029 if ((long)ulval
< 0) {
1036 #ifndef NO_FLOATING_POINT
1042 xdigs
= xdigs_lower
;
1046 xdigs
= xdigs_upper
;
1051 if (flags
& LONGDBL
) {
1052 fparg
.ldbl
= GETARG(long double);
1054 __hldtoa(fparg
.ldbl
, xdigs
, prec
,
1055 &expt
, &signflag
, &dtoaend
);
1057 fparg
.dbl
= GETARG(double);
1059 __hdtoa(fparg
.dbl
, xdigs
, prec
,
1060 &expt
, &signflag
, &dtoaend
);
1062 if (dtoaresult
== NULL
)
1066 _DIAGASSERT(__type_fit(int,
1067 dtoaend
- dtoaresult
));
1068 prec
= (int)(dtoaend
- dtoaresult
);
1070 if (expt
== INT_MAX
)
1072 _DIAGASSERT(__type_fit(int, dtoaend
- dtoaresult
));
1073 ndig
= (int)(dtoaend
- dtoaresult
);
1074 if (convbuf
!= NULL
)
1077 result
= convbuf
= __mbsconv(dtoaresult
, -1);
1080 result
= convbuf
= strdup(dtoaresult
);
1084 __freedtoa(dtoaresult
);
1089 if (prec
< 0) /* account for digit before decpt */
1100 expchar
= ch
- ('g' - 'e');
1106 if (flags
& LONGDBL
) {
1107 fparg
.ldbl
= GETARG(long double);
1109 __ldtoa(&fparg
.ldbl
, expchar
? 2 : 3, prec
,
1110 &expt
, &signflag
, &dtoaend
);
1112 fparg
.dbl
= GETARG(double);
1114 __dtoa(fparg
.dbl
, expchar
? 2 : 3, prec
,
1115 &expt
, &signflag
, &dtoaend
);
1119 if (dtoaresult
== NULL
)
1121 _DIAGASSERT(__type_fit(int, dtoaend
- dtoaresult
));
1122 ndig
= (int)(dtoaend
- dtoaresult
);
1123 if (convbuf
!= NULL
)
1126 result
= convbuf
= __mbsconv(dtoaresult
, -1);
1129 result
= convbuf
= strdup(dtoaresult
);
1133 __freedtoa(dtoaresult
);
1137 if (expt
== INT_MAX
) { /* inf or nan */
1138 if (*result
== 'N') {
1139 result
= (ch
>= 'a') ? STRCONST("nan") :
1143 result
= (ch
>= 'a') ? STRCONST("inf") :
1158 } else if ((ch
== 'g' || ch
== 'G') && prec
== 0) {
1162 if (flags
& LONGDBL
) {
1163 _double
= (double) GETARG(long double);
1165 _double
= GETARG(double);
1168 /* do this before tricky precision changes */
1169 if (isinf(_double
)) {
1172 if (ch
== 'E' || ch
== 'F' || ch
== 'G')
1173 result
= STRCONST("INF");
1175 result
= STRCONST("inf");
1180 if (isnan(_double
)) {
1181 if (ch
== 'E' || ch
== 'F' || ch
== 'G')
1182 result
= STRCONST("NAN");
1184 result
= STRCONST("nan");
1191 dtoaresult
= cvt(_double
, prec
, flags
, &softsign
,
1193 if (dtoaresult
== NULL
)
1195 if (convbuf
!= NULL
)
1198 result
= convbuf
= __mbsconv(dtoaresult
, -1);
1201 result
= convbuf
= strdup(dtoaresult
);
1205 __freedtoa(dtoaresult
);
1210 if (ch
== 'g' || ch
== 'G') {
1211 if (expt
> -4 && expt
<= prec
) {
1212 /* Make %[gG] smell like %[fF] */
1222 * Make %[gG] smell like %[eE], but
1223 * trim trailing zeroes if no # flag.
1230 expsize
= exponent(expstr
, expt
- 1, expchar
);
1231 size
= expsize
+ prec
;
1232 if (prec
> 1 || flags
& ALT
)
1235 /* space for digits before decimal point */
1240 /* space for decimal pt and following digits */
1241 if (prec
|| flags
& ALT
)
1243 if (grouping
&& expt
> 0) {
1244 /* space for thousands' grouping */
1245 nseps
= nrepeats
= 0;
1247 while ((unsigned char)*grouping
1248 != (unsigned char)CHAR_MAX
) {
1249 if (lead
<= *grouping
)
1252 if (*(grouping
+1)) {
1258 size
+= nseps
+ nrepeats
;
1263 #endif /* !NO_FLOATING_POINT */
1266 * Assignment-like behavior is specified if the
1267 * value overflows or is otherwise unrepresentable.
1268 * C99 says to use `signed char' for %hhn conversions.
1270 if (flags
& LLONGINT
)
1271 *GETARG(long long *) = ret
;
1272 else if (flags
& SIZET
)
1273 *GETARG(ssize_t
*) = (ssize_t
)ret
;
1274 else if (flags
& PTRDIFFT
)
1275 *GETARG(ptrdiff_t *) = ret
;
1276 else if (flags
& INTMAXT
)
1277 *GETARG(intmax_t *) = ret
;
1278 else if (flags
& LONGINT
)
1279 *GETARG(long *) = ret
;
1280 else if (flags
& SHORTINT
)
1281 *GETARG(short *) = ret
;
1282 else if (flags
& CHARINT
)
1283 *GETARG(signed char *) = ret
;
1285 *GETARG(int *) = ret
;
1286 continue; /* no output */
1291 if (flags
& INTMAX_SIZE
)
1299 * ``The argument shall be a pointer to void. The
1300 * value of the pointer is converted to a sequence
1301 * of printable characters, in an implementation-
1305 ujval
= (uintmax_t)(uintptr_t)GETARG(void *);
1307 xdigs
= xdigs_lower
;
1308 flags
= flags
| INTMAXT
;
1315 if ((flags
& LONGINT
) != MULTI
) {
1316 if ((result
= GETARG(CHAR_T
*)) == NULL
)
1317 result
= STRCONST("(null)");
1321 if (convbuf
!= NULL
)
1323 if ((mc
= GETARG(MCHAR_T
*)) == NULL
)
1324 result
= STRCONST("(null)");
1326 convbuf
= SCONV(mc
, prec
);
1327 if (convbuf
== NULL
) {
1328 fp
->_flags
|= __SERR
;
1337 * can't use STRLEN; can only look for the
1338 * NUL in the first `prec' characters, and
1339 * STRLEN() will go further.
1341 CHAR_T
*p
= MEMCHR(result
, 0, (size_t)prec
);
1344 _DIAGASSERT(__type_fit(int,
1346 size
= (int)(p
- result
);
1352 size_t rlen
= STRLEN(result
);
1353 _DIAGASSERT(__type_fit(int, rlen
));
1362 if (flags
& INTMAX_SIZE
)
1369 xdigs
= xdigs_upper
;
1372 xdigs
= xdigs_lower
;
1374 if (flags
& INTMAX_SIZE
)
1379 /* leading 0x/X only if non-zero */
1381 (flags
& INTMAX_SIZE
? ujval
!= 0 : ulval
!= 0))
1385 /* unsigned conversions */
1386 nosign
: sign
= '\0';
1388 * ``... diouXx conversions ... if a precision is
1389 * specified, the 0 flag will be ignored.''
1392 number
: if ((dprec
= prec
) >= 0)
1396 * ``The result of converting a zero value with an
1397 * explicit precision of zero is no characters.''
1400 * ``The C Standard is clear enough as is. The call
1401 * printf("%#.0o", 0) should print 0.''
1402 * -- Defect Report #151
1404 result
= cp
= buf
+ BUF
;
1405 if (flags
& INTMAX_SIZE
) {
1406 if (ujval
!= 0 || prec
!= 0 ||
1407 (flags
& ALT
&& base
== 8))
1408 result
= __ujtoa(ujval
, cp
, base
,
1410 flags
& GROUPING
, thousands_sep
,
1413 if (ulval
!= 0 || prec
!= 0 ||
1414 (flags
& ALT
&& base
== 8))
1415 result
= __ultoa(ulval
, cp
, base
,
1417 flags
& GROUPING
, thousands_sep
,
1420 _DIAGASSERT(__type_fit(int, buf
+ BUF
- result
));
1421 size
= (int)(buf
+ BUF
- result
);
1422 if (size
> BUF
) /* should never happen */
1425 default: /* "%?" prints ?, unless ? is NUL */
1428 /* pretend it was %c with argument ch */
1437 * All reasonable formats wind up here. At this point, `result'
1438 * points to a string which (if not flags&LADJUST) should be
1439 * padded out to `width' places. If flags&ZEROPAD, it should
1440 * first be prefixed by any sign or other prefix; otherwise,
1441 * it should be blank padded before the prefix is emitted.
1442 * After any left-hand padding and prefixing, emit zeroes
1443 * required by a decimal [diouxX] precision, then print the
1444 * string proper, then emit zeroes required by any leftover
1445 * floating precision; finally, if LADJUST, pad with blanks.
1447 * Compute actual size, so we know how much to pad.
1448 * size excludes decimal prec; realsz includes it.
1450 realsz
= dprec
> size
? dprec
: size
;
1456 prsize
= width
> realsz
? width
: realsz
;
1457 if ((unsigned)ret
+ prsize
> INT_MAX
) {
1462 /* right-adjusting blank padding */
1463 if ((flags
& (LADJUST
|ZEROPAD
)) == 0)
1464 PAD(width
- realsz
, blanks
);
1470 if (ox
[1]) { /* ox[1] is either x, X, or \0 */
1475 /* right-adjusting zero padding */
1476 if ((flags
& (LADJUST
|ZEROPAD
)) == ZEROPAD
)
1477 PAD(width
- realsz
, zeroes
);
1479 /* leading zeroes from decimal precision */
1480 PAD(dprec
- size
, zeroes
);
1482 /* the string or number proper */
1483 #ifndef NO_FLOATING_POINT
1484 if ((flags
& FPT
) == 0) {
1485 PRINT(result
, size
);
1486 } else { /* glue together f_p fragments */
1487 if (!expchar
) { /* %[fF] or sufficiently short %[gG] */
1490 if (prec
|| flags
& ALT
)
1491 PRINT(decimal_point
, 1);
1493 /* already handled initial 0's */
1496 PRINTANDPAD(result
, convbuf
+ ndig
,
1500 while (nseps
>0 || nrepeats
>0) {
1507 PRINT(&thousands_sep
,
1512 result
+= *grouping
;
1514 if (result
> convbuf
+ ndig
)
1515 result
= convbuf
+ ndig
;
1517 if (prec
|| flags
& ALT
) {
1518 buf
[0] = *decimal_point
;
1522 PRINTANDPAD(result
, convbuf
+ ndig
, prec
,
1524 } else { /* %[eE] or sufficiently long %[gG] */
1525 if (prec
> 1 || flags
& ALT
) {
1527 buf
[1] = *decimal_point
;
1529 PRINT(result
, ndig
-1);
1530 PAD(prec
- ndig
, zeroes
);
1533 PRINT(expstr
, expsize
);
1537 PRINT(result
, size
);
1539 /* left-adjusting padding (always blank) */
1540 if (flags
& LADJUST
)
1541 PAD(width
- realsz
, blanks
);
1543 /* finally, adjust ret */
1551 if (convbuf
!= NULL
)
1555 if ((argtable
!= NULL
) && (argtable
!= statargtable
))
1566 * Find all arguments when a positional parameter is encountered. Returns a
1567 * table, indexed by argument number, of pointers to each arguments. The
1568 * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1569 * It will be replaces with a malloc-ed one if it overflows.
1572 __find_arguments(const CHAR_T
*fmt0
, va_list ap
, union arg
**argtable
)
1574 CHAR_T
*fmt
; /* format string */
1575 int ch
; /* character from fmt */
1576 size_t n
, n2
; /* handy index (short term usage) */
1577 CHAR_T
*cp
; /* handy char pointer (short term usage) */
1578 int flags
; /* flags as above */
1579 enum typeid *typetable
; /* table of types */
1580 enum typeid stattypetable
[STATIC_ARG_TBL_SIZE
];
1581 size_t tablesize
; /* current size of type table */
1582 size_t tablemax
; /* largest used index in table */
1583 size_t nextarg
; /* 1-based argument index */
1584 size_t nitems
; /* number of items we picked from the stack */
1587 * Add an argument type to the table, expanding if necessary.
1588 * Check for overflow.
1590 #define ADDTYPE(type) \
1592 if (nextarg > SIZE_MAX / sizeof(**argtable)) { \
1593 if (typetable != stattypetable) \
1597 if (nextarg >= tablesize) \
1598 if (__grow_type_table(nextarg, &typetable, \
1599 &tablesize) == -1) \
1601 if (nextarg > tablemax) \
1602 tablemax = nextarg; \
1603 typetable[nextarg++] = type; \
1605 } while (/*CONSTCOND*/0)
1609 if (flags & INTMAXT) \
1610 ADDTYPE(T_INTMAXT); \
1611 else if (flags & SIZET) \
1612 ADDTYPE(T_SSIZET); \
1613 else if (flags & PTRDIFFT) \
1614 ADDTYPE(T_PTRDIFFT); \
1615 else if (flags & LLONGINT) \
1617 else if (flags & LONGINT) \
1621 } while (/*CONSTCOND*/0)
1625 if (flags & INTMAXT) \
1626 ADDTYPE(T_UINTMAXT); \
1627 else if (flags & SIZET) \
1629 else if (flags & PTRDIFFT) \
1630 ADDTYPE(T_PTRDIFFT); \
1631 else if (flags & LLONGINT) \
1632 ADDTYPE(T_U_LLONG); \
1633 else if (flags & LONGINT) \
1634 ADDTYPE(T_U_LONG); \
1637 } while (/*CONSTCOND*/0)
1639 * Add * arguments to the type array.
1641 #define ADDASTER() \
1644 while (is_digit(*cp)) { \
1645 n2 = 10 * n2 + to_digit(*cp); \
1649 size_t hold = nextarg; \
1657 fmt
= (CHAR_T
*)__UNCONST(fmt0
);
1658 memset(stattypetable
, 0, sizeof(stattypetable
));
1659 typetable
= stattypetable
;
1660 tablesize
= STATIC_ARG_TBL_SIZE
;
1666 * Scan the format for conversions (`%' character).
1669 for (cp
= fmt
; (ch
= *fmt
) != '\0' && ch
!= '%'; fmt
++)
1673 fmt
++; /* skip over '%' */
1678 reswitch
: switch (ch
) {
1690 if ((ch
= *fmt
++) == '*') {
1694 while (is_digit(ch
)) {
1700 case '1': case '2': case '3': case '4':
1701 case '5': case '6': case '7': case '8': case '9':
1704 n
= 10 * n
+ to_digit(ch
);
1706 } while (is_digit(ch
));
1712 #ifndef NO_FLOATING_POINT
1718 if (flags
& SHORTINT
) {
1728 if (flags
& LONGINT
) {
1735 flags
|= LLONGINT
; /* not necessarily */
1747 if (flags
& LONGINT
)
1759 #ifndef NO_FLOATING_POINT
1767 if (flags
& LONGDBL
)
1768 ADDTYPE(T_LONG_DOUBLE
);
1772 #endif /* !NO_FLOATING_POINT */
1774 if (flags
& INTMAXT
)
1775 ADDTYPE(TP_INTMAXT
);
1776 else if (flags
& PTRDIFFT
)
1777 ADDTYPE(TP_PTRDIFFT
);
1778 else if (flags
& SIZET
)
1780 else if (flags
& LLONGINT
)
1782 else if (flags
& LONGINT
)
1784 else if (flags
& SHORTINT
)
1786 else if (flags
& CHARINT
)
1790 continue; /* no output */
1804 if (flags
& LONGINT
)
1817 default: /* "%?" prints ?, unless ? is NUL */
1825 * nitems contains the number of arguments we picked from the stack.
1826 * If tablemax is larger, this means that some positional argument,
1827 * tried to pick an argument the number of arguments possibly supplied.
1828 * Since positional arguments are typically used to swap the order of
1829 * the printf arguments and not to pick random arguments from strange
1830 * positions in the stack, we assume that if the positional argument
1831 * is trying to pick beyond the end of arguments, then this is wrong.
1832 * Alternatively we could find a way to figure out when va_arg() runs
1833 * out, but how to do that?
1835 if (nitems
< tablemax
) {
1836 if (typetable
!= stattypetable
)
1841 * Build the argument table.
1843 if (tablemax
>= STATIC_ARG_TBL_SIZE
) {
1844 *argtable
= malloc(sizeof(**argtable
) * (tablemax
+ 1));
1845 if (*argtable
== NULL
) {
1851 (*argtable
) [0].intarg
= 0;
1852 for (n
= 1; n
<= tablemax
; n
++) {
1853 switch (typetable
[n
]) {
1854 case T_UNUSED
: /* whoops! */
1855 (*argtable
) [n
].intarg
= va_arg (ap
, int);
1858 (*argtable
) [n
].pschararg
= va_arg (ap
, signed char *);
1861 (*argtable
) [n
].pshortarg
= va_arg (ap
, short *);
1864 (*argtable
) [n
].intarg
= va_arg (ap
, int);
1867 (*argtable
) [n
].uintarg
= va_arg (ap
, unsigned int);
1870 (*argtable
) [n
].pintarg
= va_arg (ap
, int *);
1873 (*argtable
) [n
].longarg
= va_arg (ap
, long);
1876 (*argtable
) [n
].ulongarg
= va_arg (ap
, unsigned long);
1879 (*argtable
) [n
].plongarg
= va_arg (ap
, long *);
1882 (*argtable
) [n
].longlongarg
= va_arg (ap
, long long);
1885 (*argtable
) [n
].ulonglongarg
= va_arg (ap
, unsigned long long);
1888 (*argtable
) [n
].plonglongarg
= va_arg (ap
, long long *);
1891 (*argtable
) [n
].ptrdiffarg
= va_arg (ap
, ptrdiff_t);
1894 (*argtable
) [n
].pptrdiffarg
= va_arg (ap
, ptrdiff_t *);
1897 (*argtable
) [n
].ssizearg
= va_arg (ap
, ssize_t
);
1900 (*argtable
) [n
].sizearg
= va_arg (ap
, size_t);
1903 (*argtable
) [n
].psizearg
= va_arg (ap
, size_t *);
1906 (*argtable
) [n
].intmaxarg
= va_arg (ap
, intmax_t);
1909 (*argtable
) [n
].uintmaxarg
= va_arg (ap
, uintmax_t);
1912 (*argtable
) [n
].pintmaxarg
= va_arg (ap
, intmax_t *);
1915 #ifndef NO_FLOATING_POINT
1916 (*argtable
) [n
].doublearg
= va_arg (ap
, double);
1920 #ifndef NO_FLOATING_POINT
1921 (*argtable
) [n
].longdoublearg
= va_arg (ap
, long double);
1925 (*argtable
) [n
].pchararg
= va_arg (ap
, char *);
1928 (*argtable
) [n
].pvoidarg
= va_arg (ap
, void *);
1931 (*argtable
) [n
].wintarg
= va_arg (ap
, wint_t);
1934 (*argtable
) [n
].pwchararg
= va_arg (ap
, wchar_t *);
1939 if (typetable
!= stattypetable
)
1945 * Increase the size of the type table.
1948 __grow_type_table (size_t nextarg
, enum typeid **typetable
, size_t *tablesize
)
1950 enum typeid *const oldtable
= *typetable
;
1951 const size_t oldsize
= *tablesize
;
1952 enum typeid *newtable
;
1953 size_t newsize
= oldsize
* 2;
1955 if (newsize
< nextarg
+ 1)
1956 newsize
= nextarg
+ 1;
1957 if (oldsize
== STATIC_ARG_TBL_SIZE
) {
1958 if ((newtable
= malloc(newsize
* sizeof(*newtable
))) == NULL
)
1960 memcpy(newtable
, oldtable
, oldsize
* sizeof(*newtable
));
1962 newtable
= realloc(oldtable
, newsize
* sizeof(*newtable
));
1963 if (newtable
== NULL
) {
1968 memset(&newtable
[oldsize
], 0, (newsize
- oldsize
) * sizeof(*newtable
));
1970 *typetable
= newtable
;
1971 *tablesize
= newsize
;
1976 #ifndef NO_FLOATING_POINT
1979 cvt(double value
, int ndigits
, int flags
, char *sign
, int *decpt
, int ch
,
1983 char *digits
, *bp
, *rve
;
1985 _DIAGASSERT(decpt
!= NULL
);
1986 _DIAGASSERT(length
!= NULL
);
1987 _DIAGASSERT(sign
!= NULL
);
1990 mode
= 3; /* ndigits after the decimal point */
1992 /* To obtain ndigits after the decimal point for the 'e'
1993 * and 'E' formats, round to ndigits + 1 significant
1996 if (ch
== 'e' || ch
== 'E') {
1999 mode
= 2; /* ndigits significant digits */
2002 digits
= __dtoa(value
, mode
, ndigits
, decpt
, &dsgn
, &rve
);
2010 if ((ch
!= 'g' && ch
!= 'G') || flags
& ALT
) { /* Print trailing zeros */
2011 bp
= digits
+ ndigits
;
2013 if (*digits
== '0' && value
)
2014 *decpt
= -ndigits
+ 1;
2017 if (value
== 0) /* kludge for __dtoa irregularity */
2022 *length
= rve
- digits
;
2028 exponent(CHAR_T
*p0
, int expo
, int fmtch
)
2031 CHAR_T expbuf
[MAXEXPDIG
];
2041 t
= expbuf
+ MAXEXPDIG
;
2044 *--t
= to_char(expo
% 10);
2045 } while ((expo
/= 10) > 9);
2046 *--t
= to_char(expo
);
2047 for (; t
< expbuf
+ MAXEXPDIG
; *p
++ = *t
++);
2051 * Exponents for decimal floating point conversions
2052 * (%[eEgG]) must be at least two characters long,
2053 * whereas exponents for hexadecimal conversions can
2054 * be only one character long.
2056 if (fmtch
== 'e' || fmtch
== 'E')
2058 *p
++ = to_char(expo
);
2060 _DIAGASSERT(__type_fit(int, p
- p0
));
2061 return (int)(p
- p0
);
2063 #endif /* !NO_FLOATING_POINT */