1 /* $NetBSD: vfwprintf.c,v 1.16 2009/08/05 20:46:01 dsl 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.16 2009/08/05 20:46:01 dsl 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
, 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(int, enum typeid **, int *);
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
);
167 /* copy the important variables */
168 fake
._flags
= fp
->_flags
& ~__SNBF
;
169 fake
._file
= fp
->_file
;
170 fake
._cookie
= fp
->_cookie
;
171 fake
._write
= fp
->_write
;
173 /* set up the buffer */
174 fake
._bf
._base
= fake
._p
= buf
;
175 fake
._bf
._size
= fake
._w
= sizeof(buf
);
176 fake
._lbfsize
= 0; /* not actually used, but Just In Case */
178 /* do the work, then copy any error status */
179 ret
= WDECL(__vf
,printf_unlocked
)(&fake
, fmt
, ap
);
180 if (ret
>= 0 && fflush(&fake
))
182 if (fake
._flags
& __SERR
)
183 fp
->_flags
|= __SERR
;
189 * Like __fputwc, but handles fake string (__SSTR) files properly.
190 * File must already be locked.
193 __xfputwc(wchar_t wc
, FILE *fp
)
195 static const mbstate_t initial
;
197 char buf
[MB_LEN_MAX
];
202 if ((fp
->_flags
& __SSTR
) == 0)
203 return (__fputwc_unlock(wc
, fp
));
206 if ((len
= wcrtomb(buf
, wc
, &mbs
)) == (size_t)-1) {
207 fp
->_flags
|= __SERR
;
208 return (END_OF_FILE
);
215 return (__sfvwrite(fp
, &uio
) != EOF
? (wint_t)wc
: END_OF_FILE
);
219 * Flush out all the vectors defined by the given uio,
220 * then reset it so that it can be reused.
223 __sprint(FILE *fp
, struct __suio
*uio
)
227 _DIAGASSERT(fp
!= NULL
);
228 _DIAGASSERT(uio
!= NULL
);
230 if (uio
->uio_resid
== 0) {
234 err
= __sfvwrite(fp
, uio
);
242 * Macros for converting digits to letters and vice versa
244 #define to_digit(c) ((c) - '0')
245 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
246 #define to_char(n) (CHAR_T)((n) + '0')
249 * Convert an unsigned long to ASCII for printf purposes, returning
250 * a pointer to the first character of the string representation.
251 * Octal numbers can be forced to have a leading zero; hex numbers
252 * use the given digits.
255 __ultoa(u_long val
, CHAR_T
*endp
, int base
, int octzero
, const char *xdigs
,
256 int needgrp
, char thousep
, const char *grp
)
263 * Handle the three cases separately, in the hope of getting
264 * better/faster code.
268 if (val
< 10) { /* many numbers are 1 digit */
269 *--cp
= to_char(val
);
274 * On many machines, unsigned arithmetic is harder than
275 * signed arithmetic, so we do at most one unsigned mod and
276 * divide; this is sufficient to reduce the range of
277 * the incoming value to where signed arithmetic works.
279 if (val
> LONG_MAX
) {
280 *--cp
= to_char(val
% 10);
286 *--cp
= to_char(sval
% 10);
289 * If (*grp == CHAR_MAX) then no more grouping
290 * should be performed.
292 if (needgrp
&& ndig
== *grp
&& *grp
!= CHAR_MAX
297 * If (*(grp+1) == '\0') then we have to
298 * use *grp character (last grouping rule)
301 if (*(grp
+1) != '\0')
310 *--cp
= to_char(val
& 7);
313 if (octzero
&& *cp
!= '0')
319 *--cp
= xdigs
[(size_t)val
& 15];
330 /* Identical to __ultoa, but for intmax_t. */
332 __ujtoa(uintmax_t val
, CHAR_T
*endp
, int base
, int octzero
,
333 const char *xdigs
, int needgrp
, char thousep
, const char *grp
)
339 /* quick test for small values; __ultoa is typically much faster */
340 /* (perhaps instead we should run until small, then call __ultoa?) */
341 if (val
<= ULONG_MAX
)
342 return (__ultoa((u_long
)val
, endp
, base
, octzero
, xdigs
,
343 needgrp
, thousep
, grp
));
347 *--cp
= to_char(val
% 10);
351 if (val
> INTMAX_MAX
) {
352 *--cp
= to_char(val
% 10);
358 *--cp
= to_char(sval
% 10);
361 * If (*grp == CHAR_MAX) then no more grouping
362 * should be performed.
364 if (needgrp
&& *grp
!= CHAR_MAX
&& ndig
== *grp
369 * If (*(grp+1) == '\0') then we have to
370 * use *grp character (last grouping rule)
373 if (*(grp
+1) != '\0')
382 *--cp
= to_char(val
& 7);
385 if (octzero
&& *cp
!= '0')
391 *--cp
= xdigs
[(size_t)val
& 15];
404 * Convert a multibyte character string argument for the %s format to a wide
405 * string representation. ``prec'' specifies the maximum number of bytes
406 * to output. If ``prec'' is greater than or equal to zero, we can't assume
407 * that the multibyte char. string ends in a null character.
410 __mbsconv(char *mbsarg
, int prec
)
412 static const mbstate_t initial
;
414 wchar_t *convbuf
, *wcp
;
416 size_t insize
, nchars
, nconv
;
422 * Supplied argument is a multibyte string; convert it to wide
427 * String is not guaranteed to be NUL-terminated. Find the
428 * number of characters to print.
431 insize
= nchars
= nconv
= 0;
433 while (nchars
!= (size_t)prec
) {
434 nconv
= mbrlen(p
, MB_CUR_MAX
, &mbs
);
435 if (nconv
== 0 || nconv
== (size_t)-1 ||
442 if (nconv
== (size_t)-1 || nconv
== (size_t)-2)
445 insize
= strlen(mbsarg
);
448 * Allocate buffer for the result and perform the conversion,
449 * converting at most `size' bytes of the input multibyte string to
450 * wide characters for printing.
452 convbuf
= malloc((insize
+ 1) * sizeof(*convbuf
));
459 while (insize
!= 0) {
460 nconv
= mbrtowc(wcp
, p
, insize
, &mbs
);
461 if (nconv
== 0 || nconv
== (size_t)-1 || nconv
== (size_t)-2)
467 if (nconv
== (size_t)-1 || nconv
== (size_t)-2) {
477 * Convert a wide character string argument for the %ls format to a multibyte
478 * string representation. If not -1, prec specifies the maximum number of
479 * bytes to output, and also means that we can't assume that the wide char.
480 * string ends is null-terminated.
483 __wcsconv(wchar_t *wcsarg
, int prec
)
485 static const mbstate_t initial
;
487 char buf
[MB_LEN_MAX
];
492 /* Allocate space for the maximum number of bytes we could output. */
496 nbytes
= wcsrtombs(NULL
, (const wchar_t **)&p
, 0, &mbs
);
497 if (nbytes
== (size_t)-1)
501 * Optimisation: if the output precision is small enough,
502 * just allocate enough memory for the maximum instead of
503 * scanning the string.
512 clen
= wcrtomb(buf
, *p
++, &mbs
);
513 if (clen
== 0 || clen
== (size_t)-1 ||
514 nbytes
+ clen
> (size_t)prec
)
520 if ((convbuf
= malloc(nbytes
+ 1)) == NULL
)
523 /* Fill the output buffer. */
526 if ((nbytes
= wcsrtombs(convbuf
, (const wchar_t **)&p
,
527 nbytes
, &mbs
)) == (size_t)-1) {
531 convbuf
[nbytes
] = '\0';
540 WDECL(vf
,printf
)(FILE * __restrict fp
, const CHAR_T
* __restrict fmt0
, va_list ap
)
545 ret
= WDECL(__vf
,printf_unlocked
)(fp
, fmt0
, ap
);
550 #ifndef NO_FLOATING_POINT
558 static int exponent(CHAR_T
*, int, int);
560 static char *cvt(double, int, int, char *, int *, int, int *);
563 #endif /* !NO_FLOATING_POINT */
566 * The size of the buffer we use as scratch space for integer
567 * conversions, among other things. Technically, we would need the
568 * most space for base 10 conversions with thousands' grouping
569 * characters between each pair of digits. 100 bytes is a
570 * conservative overestimate even for a 128-bit uintmax_t.
574 #define STATIC_ARG_TBL_SIZE 8 /* Size of static argument table. */
577 * Flags used during conversion.
579 #define ALT 0x001 /* alternate form */
580 #define LADJUST 0x004 /* left adjustment */
581 #define LONGDBL 0x008 /* long double */
582 #define LONGINT 0x010 /* long integer */
583 #define LLONGINT 0x020 /* long long integer */
584 #define SHORTINT 0x040 /* short integer */
585 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
586 #define FPT 0x100 /* Floating point number */
587 #define GROUPING 0x200 /* use grouping ("'" flag) */
588 /* C99 additional size modifiers: */
589 #define SIZET 0x400 /* size_t */
590 #define PTRDIFFT 0x800 /* ptrdiff_t */
591 #define INTMAXT 0x1000 /* intmax_t */
592 #define CHARINT 0x2000 /* print char using int format */
595 * Non-MT-safe version
598 WDECL(__vf
,printf_unlocked
)(FILE *fp
, const CHAR_T
*fmt0
, va_list ap
)
600 CHAR_T
*fmt
; /* format string */
601 int ch
; /* character from fmt */
602 int n
, n2
; /* handy integer (short term usage) */
603 CHAR_T
*cp
; /* handy char pointer (short term usage) */
604 int flags
; /* flags as above */
605 int ret
; /* return value accumulator */
606 int width
; /* width from format (%8d), or 0 */
607 int prec
; /* precision from format; <0 for N/A */
608 CHAR_T sign
; /* sign prefix (' ', '+', '-', or \0) */
609 char thousands_sep
; /* locale specific thousands separator */
610 const char *grouping
; /* locale specific numeric grouping rules */
611 #ifndef NO_FLOATING_POINT
613 * We can decompose the printed representation of floating
614 * point numbers into several parts, some of which may be empty:
616 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
619 * A: 'sign' holds this value if present; '\0' otherwise
620 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
621 * C: cp points to the string MMMNNN. Leading and trailing
622 * zeros are not in the string and must be added.
623 * D: expchar holds this character; '\0' if no exponent, e.g. %f
624 * F: at least two digits for decimal, at least one digit for hex
626 char *decimal_point
; /* locale specific decimal point */
628 int signflag
; /* true if float is negative */
629 union { /* floating point arguments %[aAeEfFgG] */
633 char *dtoaend
; /* pointer to end of converted digits */
635 double _double
; /* double precision arguments %[eEfgG] */
636 char softsign
; /* temporary negative sign for floats */
638 char *dtoaresult
; /* buffer allocated by dtoa */
639 int expt
; /* integer value of exponent */
640 char expchar
; /* exponent character: [eEpP\0] */
641 int expsize
; /* character count for expstr */
642 int lead
; /* sig figs before decimal or group sep */
643 int ndig
; /* actual number of digits returned by dtoa */
644 CHAR_T expstr
[MAXEXPDIG
+2]; /* buffer for exponent string: e+ZZZ */
645 int nseps
; /* number of group separators with ' */
646 int nrepeats
; /* number of repeats of the last group */
648 u_long ulval
; /* integer arguments %[diouxX] */
649 uintmax_t ujval
; /* %j, %ll, %q, %t, %z integers */
650 int base
; /* base for [diouxX] conversion */
651 int dprec
; /* a copy of prec if [diouxX], 0 otherwise */
652 int realsz
; /* field size expanded by dprec, sign, etc */
653 int size
; /* size of converted field or string */
654 int prsize
; /* max size of printed field */
655 const char *xdigs
; /* digits for %[xX] conversion */
658 struct __siov
*iovp
; /* for PRINT macro */
659 struct __suio uio
; /* output information: summary */
660 struct __siov iov
[NIOV
];/* ... and individual io vectors */
664 CHAR_T buf
[BUF
]; /* buffer with space for digits of uintmax_t */
665 CHAR_T ox
[2]; /* space for 0x hex-prefix */
666 union arg
*argtable
; /* args, built due to positional arg */
667 union arg statargtable
[STATIC_ARG_TBL_SIZE
];
668 int nextarg
; /* 1-based argument index */
669 va_list orgap
; /* original argument pointer */
670 CHAR_T
*convbuf
; /* multibyte to wide conversion result */
673 * Choose PADSIZE to trade efficiency vs. size. If larger printf
674 * fields occur frequently, increase PADSIZE and make the initialisers
677 #define PADSIZE 16 /* pad chunk size */
678 static CHAR_T blanks
[PADSIZE
] =
679 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
680 static CHAR_T zeroes
[PADSIZE
] =
681 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
683 static const char xdigs_lower
[16] = "0123456789abcdef";
684 static const char xdigs_upper
[16] = "0123456789ABCDEF";
687 * BEWARE, these `goto error' on error, PRINT uses `n2' and
691 #define PRINT(ptr, len) do { \
692 for (n3 = 0; n3 < (len); n3++) \
693 __xfputwc((ptr)[n3], fp); \
694 } while (/*CONSTCOND*/0)
697 #define PRINT(ptr, len) do { \
698 iovp->iov_base = __UNCONST(ptr); \
699 iovp->iov_len = (len); \
700 uio.uio_resid += (len); \
702 if (++uio.uio_iovcnt >= NIOV) { \
703 if (__sprint(fp, &uio)) \
707 } while (/*CONSTCOND*/0)
708 #define FLUSH() do { \
709 if (uio.uio_resid && __sprint(fp, &uio)) \
711 uio.uio_iovcnt = 0; \
713 } while (/*CONSTCOND*/0)
716 #define PAD(howmany, with) do { \
717 if ((n = (howmany)) > 0) { \
718 while (n > PADSIZE) { \
719 PRINT(with, PADSIZE); \
724 } while (/*CONSTCOND*/0)
725 #define PRINTANDPAD(p, ep, len, with) do { \
731 PAD((len) - (n2 > 0 ? n2 : 0), (with)); \
732 } while(/*CONSTCOND*/0)
735 * Get the argument indexed by nextarg. If the argument table is
736 * built, use it to get the argument. If its not, get the next
737 * argument (and arguments must be gotten sequentially).
739 #define GETARG(type) \
740 ((/*CONSTCOND*/argtable != NULL) ? *((type*)(void*)(&argtable[nextarg++])) : \
741 (nextarg++, va_arg(ap, type)))
744 * To extend shorts properly, we need both signed and unsigned
745 * argument extraction methods.
748 (flags&LONGINT ? GETARG(long) : \
749 flags&SHORTINT ? (long)(short)GETARG(int) : \
750 flags&CHARINT ? (long)(signed char)GETARG(int) : \
753 (flags&LONGINT ? GETARG(u_long) : \
754 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
755 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
756 (u_long)GETARG(u_int))
757 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
759 (flags&INTMAXT ? GETARG(intmax_t) : \
760 flags&SIZET ? (intmax_t)GETARG(ssize_t) : \
761 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
762 (intmax_t)GETARG(long long))
764 (flags&INTMAXT ? GETARG(uintmax_t) : \
765 flags&SIZET ? (uintmax_t)GETARG(size_t) : \
766 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
767 (uintmax_t)GETARG(unsigned long long))
770 * Get * arguments, including the form *nn$. Preserve the nextarg
771 * that the argument can be gotten once the type is determined.
773 #define GETASTER(val) \
776 while (is_digit(*cp)) { \
777 n2 = 10 * n2 + to_digit(*cp); \
781 int hold = nextarg; \
782 if (argtable == NULL) { \
783 argtable = statargtable; \
784 if (__find_arguments(fmt0, orgap, &argtable) == -1) \
788 val = GETARG (int); \
792 val = GETARG (int); \
795 _DIAGASSERT(fp
!= NULL
);
796 _DIAGASSERT(fmt0
!= NULL
);
798 _SET_ORIENTATION(fp
, -1);
800 ndig
= -1; /* XXX gcc */
802 thousands_sep
= '\0';
804 #ifndef NO_FLOATING_POINT
805 decimal_point
= localeconv()->decimal_point
;
806 expsize
= 0; /* XXXGCC -Wuninitialized [sh3,m68000] */
809 /* sorry, f{w,}printf(read_only_file, L"") returns {W,}EOF, not 0 */
812 return (END_OF_FILE
);
815 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
816 if ((fp
->_flags
& (__SNBF
|__SWR
|__SRW
)) == (__SNBF
|__SWR
) &&
818 return (__sbprintf(fp
, fmt0
, ap
));
820 fmt
= (CHAR_T
*)__UNCONST(fmt0
);
825 uio
.uio_iov
= iovp
= iov
;
832 * Scan the format for conversions (`%' character).
835 const CHAR_T
*result
;
837 for (cp
= fmt
; (ch
= *fmt
) != '\0' && ch
!= '%'; fmt
++)
839 if ((n
= fmt
- cp
) != 0) {
840 if ((unsigned)ret
+ n
> INT_MAX
) {
849 fmt
++; /* skip over '%' */
859 nseps
= nrepeats
= 0;
865 reswitch
: switch (ch
) {
868 * ``If the space and + flags both appear, the space
869 * flag will be ignored.''
880 * ``A negative field width argument is taken as a
881 * - flag followed by a positive field width.''
883 * They don't exclude field widths read from args.
898 thousands_sep
= *(localeconv()->thousands_sep
);
899 grouping
= localeconv()->grouping
;
900 /* If the locale doesn't define the above, use sane
901 * defaults - otherwise silly things happen! */
902 if (thousands_sep
== 0)
904 if (!grouping
|| !*grouping
)
908 if ((ch
= *fmt
++) == '*') {
913 while (is_digit(ch
)) {
914 prec
= 10 * prec
+ to_digit(ch
);
920 * ``Note that 0 is taken as a flag, not as the
921 * beginning of a field width.''
926 case '1': case '2': case '3': case '4':
927 case '5': case '6': case '7': case '8': case '9':
930 n
= 10 * n
+ to_digit(ch
);
932 } while (is_digit(ch
));
935 if (argtable
== NULL
) {
936 argtable
= statargtable
;
937 if (__find_arguments(fmt0
, orgap
,
945 #ifndef NO_FLOATING_POINT
951 if (flags
& SHORTINT
) {
961 if (flags
& LONGINT
) {
968 flags
|= LLONGINT
; /* not necessarily */
981 if (flags
& LONGINT
) {
982 static const mbstate_t initial
;
987 mbseqlen
= wcrtomb(buf
,
988 (wchar_t)GETARG(wint_t), &mbs
);
989 if (mbseqlen
== (size_t)-1) {
990 fp
->_flags
|= __SERR
;
993 size
= (int)mbseqlen
;
1000 *buf
= (wchar_t)GETARG(wint_t);
1002 *buf
= (wchar_t)btowc(GETARG(int));
1013 if (flags
& INTMAX_SIZE
) {
1015 if ((intmax_t)ujval
< 0) {
1021 if ((long)ulval
< 0) {
1028 #ifndef NO_FLOATING_POINT
1034 xdigs
= xdigs_lower
;
1038 xdigs
= xdigs_upper
;
1043 if (flags
& LONGDBL
) {
1044 fparg
.ldbl
= GETARG(long double);
1046 __hldtoa(fparg
.ldbl
, xdigs
, prec
,
1047 &expt
, &signflag
, &dtoaend
);
1049 fparg
.dbl
= GETARG(double);
1051 __hdtoa(fparg
.dbl
, xdigs
, prec
,
1052 &expt
, &signflag
, &dtoaend
);
1054 if (dtoaresult
== NULL
)
1058 prec
= dtoaend
- dtoaresult
;
1059 if (expt
== INT_MAX
)
1061 ndig
= dtoaend
- dtoaresult
;
1062 if (convbuf
!= NULL
)
1065 result
= convbuf
= __mbsconv(dtoaresult
, -1);
1068 result
= convbuf
= strdup(dtoaresult
);
1072 __freedtoa(dtoaresult
);
1077 if (prec
< 0) /* account for digit before decpt */
1088 expchar
= ch
- ('g' - 'e');
1094 if (flags
& LONGDBL
) {
1095 fparg
.ldbl
= GETARG(long double);
1097 __ldtoa(&fparg
.ldbl
, expchar
? 2 : 3, prec
,
1098 &expt
, &signflag
, &dtoaend
);
1100 fparg
.dbl
= GETARG(double);
1102 __dtoa(fparg
.dbl
, expchar
? 2 : 3, prec
,
1103 &expt
, &signflag
, &dtoaend
);
1107 if (dtoaresult
== NULL
)
1109 ndig
= dtoaend
- dtoaresult
;
1110 if (convbuf
!= NULL
)
1113 result
= convbuf
= __mbsconv(dtoaresult
, -1);
1116 result
= convbuf
= strdup(dtoaresult
);
1120 __freedtoa(dtoaresult
);
1124 if (expt
== INT_MAX
) { /* inf or nan */
1125 if (*result
== 'N') {
1126 result
= (ch
>= 'a') ? STRCONST("nan") :
1130 result
= (ch
>= 'a') ? STRCONST("inf") :
1144 } else if ((ch
== 'g' || ch
== 'G') && prec
== 0) {
1148 if (flags
& LONGDBL
) {
1149 _double
= (double) GETARG(long double);
1151 _double
= GETARG(double);
1154 /* do this before tricky precision changes */
1155 if (isinf(_double
)) {
1158 if (ch
== 'E' || ch
== 'F' || ch
== 'G')
1159 result
= STRCONST("INF");
1161 result
= STRCONST("inf");
1165 if (isnan(_double
)) {
1166 if (ch
== 'E' || ch
== 'F' || ch
== 'G')
1167 result
= STRCONST("NAN");
1169 result
= STRCONST("nan");
1175 dtoaresult
= cvt(_double
, prec
, flags
, &softsign
,
1177 if (dtoaresult
== NULL
)
1179 if (convbuf
!= NULL
)
1182 result
= convbuf
= __mbsconv(dtoaresult
, -1);
1185 result
= convbuf
= strdup(dtoaresult
);
1189 __freedtoa(dtoaresult
);
1194 if (ch
== 'g' || ch
== 'G') {
1195 if (expt
> -4 && expt
<= prec
) {
1196 /* Make %[gG] smell like %[fF] */
1206 * Make %[gG] smell like %[eE], but
1207 * trim trailing zeroes if no # flag.
1214 expsize
= exponent(expstr
, expt
- 1, expchar
);
1215 size
= expsize
+ prec
;
1216 if (prec
> 1 || flags
& ALT
)
1219 /* space for digits before decimal point */
1224 /* space for decimal pt and following digits */
1225 if (prec
|| flags
& ALT
)
1227 if (grouping
&& expt
> 0) {
1228 /* space for thousands' grouping */
1229 nseps
= nrepeats
= 0;
1231 while (*grouping
!= CHAR_MAX
) {
1232 if (lead
<= *grouping
)
1235 if (*(grouping
+1)) {
1241 size
+= nseps
+ nrepeats
;
1246 #endif /* !NO_FLOATING_POINT */
1249 * Assignment-like behavior is specified if the
1250 * value overflows or is otherwise unrepresentable.
1251 * C99 says to use `signed char' for %hhn conversions.
1253 if (flags
& LLONGINT
)
1254 *GETARG(long long *) = ret
;
1255 else if (flags
& SIZET
)
1256 *GETARG(ssize_t
*) = (ssize_t
)ret
;
1257 else if (flags
& PTRDIFFT
)
1258 *GETARG(ptrdiff_t *) = ret
;
1259 else if (flags
& INTMAXT
)
1260 *GETARG(intmax_t *) = ret
;
1261 else if (flags
& LONGINT
)
1262 *GETARG(long *) = ret
;
1263 else if (flags
& SHORTINT
)
1264 *GETARG(short *) = ret
;
1265 else if (flags
& CHARINT
)
1266 *GETARG(signed char *) = ret
;
1268 *GETARG(int *) = ret
;
1269 continue; /* no output */
1274 if (flags
& INTMAX_SIZE
)
1282 * ``The argument shall be a pointer to void. The
1283 * value of the pointer is converted to a sequence
1284 * of printable characters, in an implementation-
1288 ujval
= (uintmax_t)(uintptr_t)GETARG(void *);
1290 xdigs
= xdigs_lower
;
1291 flags
= flags
| INTMAXT
;
1298 if ((flags
& LONGINT
) != MULTI
) {
1299 if ((result
= GETARG(CHAR_T
*)) == NULL
)
1300 result
= STRCONST("(null)");
1304 if (convbuf
!= NULL
)
1306 if ((mc
= GETARG(MCHAR_T
*)) == NULL
)
1307 result
= STRCONST("(null)");
1309 convbuf
= SCONV(mc
, prec
);
1310 if (convbuf
== NULL
) {
1311 fp
->_flags
|= __SERR
;
1320 * can't use STRLEN; can only look for the
1321 * NUL in the first `prec' characters, and
1322 * STRLEN() will go further.
1324 CHAR_T
*p
= MEMCHR(result
, 0, (size_t)prec
);
1333 size
= STRLEN(result
);
1340 if (flags
& INTMAX_SIZE
)
1347 xdigs
= xdigs_upper
;
1350 xdigs
= xdigs_lower
;
1352 if (flags
& INTMAX_SIZE
)
1357 /* leading 0x/X only if non-zero */
1359 (flags
& INTMAX_SIZE
? ujval
!= 0 : ulval
!= 0))
1363 /* unsigned conversions */
1364 nosign
: sign
= '\0';
1366 * ``... diouXx conversions ... if a precision is
1367 * specified, the 0 flag will be ignored.''
1370 number
: if ((dprec
= prec
) >= 0)
1374 * ``The result of converting a zero value with an
1375 * explicit precision of zero is no characters.''
1378 * ``The C Standard is clear enough as is. The call
1379 * printf("%#.0o", 0) should print 0.''
1380 * -- Defect Report #151
1382 result
= cp
= buf
+ BUF
;
1383 if (flags
& INTMAX_SIZE
) {
1384 if (ujval
!= 0 || prec
!= 0 ||
1385 (flags
& ALT
&& base
== 8))
1386 result
= __ujtoa(ujval
, cp
, base
,
1388 flags
& GROUPING
, thousands_sep
,
1391 if (ulval
!= 0 || prec
!= 0 ||
1392 (flags
& ALT
&& base
== 8))
1393 result
= __ultoa(ulval
, cp
, base
,
1395 flags
& GROUPING
, thousands_sep
,
1398 size
= buf
+ BUF
- result
;
1399 if (size
> BUF
) /* should never happen */
1402 default: /* "%?" prints ?, unless ? is NUL */
1405 /* pretend it was %c with argument ch */
1414 * All reasonable formats wind up here. At this point, `result'
1415 * points to a string which (if not flags&LADJUST) should be
1416 * padded out to `width' places. If flags&ZEROPAD, it should
1417 * first be prefixed by any sign or other prefix; otherwise,
1418 * it should be blank padded before the prefix is emitted.
1419 * After any left-hand padding and prefixing, emit zeroes
1420 * required by a decimal [diouxX] precision, then print the
1421 * string proper, then emit zeroes required by any leftover
1422 * floating precision; finally, if LADJUST, pad with blanks.
1424 * Compute actual size, so we know how much to pad.
1425 * size excludes decimal prec; realsz includes it.
1427 realsz
= dprec
> size
? dprec
: size
;
1433 prsize
= width
> realsz
? width
: realsz
;
1434 if ((unsigned)ret
+ prsize
> INT_MAX
) {
1439 /* right-adjusting blank padding */
1440 if ((flags
& (LADJUST
|ZEROPAD
)) == 0)
1441 PAD(width
- realsz
, blanks
);
1447 if (ox
[1]) { /* ox[1] is either x, X, or \0 */
1452 /* right-adjusting zero padding */
1453 if ((flags
& (LADJUST
|ZEROPAD
)) == ZEROPAD
)
1454 PAD(width
- realsz
, zeroes
);
1456 /* leading zeroes from decimal precision */
1457 PAD(dprec
- size
, zeroes
);
1459 /* the string or number proper */
1460 #ifndef NO_FLOATING_POINT
1461 if ((flags
& FPT
) == 0) {
1462 PRINT(result
, size
);
1463 } else { /* glue together f_p fragments */
1464 if (!expchar
) { /* %[fF] or sufficiently short %[gG] */
1467 if (prec
|| flags
& ALT
)
1468 PRINT(decimal_point
, 1);
1470 /* already handled initial 0's */
1473 PRINTANDPAD(result
, convbuf
+ ndig
,
1477 while (nseps
>0 || nrepeats
>0) {
1484 PRINT(&thousands_sep
,
1489 result
+= *grouping
;
1491 if (result
> convbuf
+ ndig
)
1492 result
= convbuf
+ ndig
;
1494 if (prec
|| flags
& ALT
) {
1495 buf
[0] = *decimal_point
;
1499 PRINTANDPAD(result
, convbuf
+ ndig
, prec
,
1501 } else { /* %[eE] or sufficiently long %[gG] */
1502 if (prec
> 1 || flags
& ALT
) {
1504 buf
[1] = *decimal_point
;
1506 PRINT(result
, ndig
-1);
1507 PAD(prec
- ndig
, zeroes
);
1510 PRINT(expstr
, expsize
);
1514 PRINT(result
, size
);
1516 /* left-adjusting padding (always blank) */
1517 if (flags
& LADJUST
)
1518 PAD(width
- realsz
, blanks
);
1520 /* finally, adjust ret */
1528 if (convbuf
!= NULL
)
1532 if ((argtable
!= NULL
) && (argtable
!= statargtable
))
1543 * Find all arguments when a positional parameter is encountered. Returns a
1544 * table, indexed by argument number, of pointers to each arguments. The
1545 * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1546 * It will be replaces with a malloc-ed one if it overflows.
1549 __find_arguments(const CHAR_T
*fmt0
, va_list ap
, union arg
**argtable
)
1551 CHAR_T
*fmt
; /* format string */
1552 int ch
; /* character from fmt */
1553 int n
, n2
; /* handy integer (short term usage) */
1554 CHAR_T
*cp
; /* handy char pointer (short term usage) */
1555 int flags
; /* flags as above */
1556 enum typeid *typetable
; /* table of types */
1557 enum typeid stattypetable
[STATIC_ARG_TBL_SIZE
];
1558 int tablesize
; /* current size of type table */
1559 int tablemax
; /* largest used index in table */
1560 int nextarg
; /* 1-based argument index */
1563 * Add an argument type to the table, expanding if necessary.
1565 #define ADDTYPE(type) \
1567 if (nextarg >= tablesize) \
1568 if (__grow_type_table(nextarg, &typetable, \
1569 &tablesize) == -1) \
1571 if (nextarg > tablemax) \
1572 tablemax = nextarg; \
1573 typetable[nextarg++] = type; \
1574 } while (/*CONSTCOND*/0)
1578 if (flags & INTMAXT) \
1579 ADDTYPE(T_INTMAXT); \
1580 else if (flags & SIZET) \
1581 ADDTYPE(T_SSIZET); \
1582 else if (flags & PTRDIFFT) \
1583 ADDTYPE(T_PTRDIFFT); \
1584 else if (flags & LLONGINT) \
1586 else if (flags & LONGINT) \
1590 } while (/*CONSTCOND*/0)
1594 if (flags & INTMAXT) \
1595 ADDTYPE(T_UINTMAXT); \
1596 else if (flags & SIZET) \
1598 else if (flags & PTRDIFFT) \
1599 ADDTYPE(T_PTRDIFFT); \
1600 else if (flags & LLONGINT) \
1601 ADDTYPE(T_U_LLONG); \
1602 else if (flags & LONGINT) \
1603 ADDTYPE(T_U_LONG); \
1606 } while (/*CONSTCOND*/0)
1608 * Add * arguments to the type array.
1610 #define ADDASTER() \
1613 while (is_digit(*cp)) { \
1614 n2 = 10 * n2 + to_digit(*cp); \
1618 int hold = nextarg; \
1626 fmt
= (CHAR_T
*)__UNCONST(fmt0
);
1627 typetable
= stattypetable
;
1628 tablesize
= STATIC_ARG_TBL_SIZE
;
1631 for (n
= 0; n
< STATIC_ARG_TBL_SIZE
; n
++)
1632 typetable
[n
] = T_UNUSED
;
1635 * Scan the format for conversions (`%' character).
1638 for (cp
= fmt
; (ch
= *fmt
) != '\0' && ch
!= '%'; fmt
++)
1642 fmt
++; /* skip over '%' */
1647 reswitch
: switch (ch
) {
1659 if ((ch
= *fmt
++) == '*') {
1663 while (is_digit(ch
)) {
1669 case '1': case '2': case '3': case '4':
1670 case '5': case '6': case '7': case '8': case '9':
1673 n
= 10 * n
+ to_digit(ch
);
1675 } while (is_digit(ch
));
1681 #ifndef NO_FLOATING_POINT
1687 if (flags
& SHORTINT
) {
1697 if (flags
& LONGINT
) {
1704 flags
|= LLONGINT
; /* not necessarily */
1716 if (flags
& LONGINT
)
1728 #ifndef NO_FLOATING_POINT
1736 if (flags
& LONGDBL
)
1737 ADDTYPE(T_LONG_DOUBLE
);
1741 #endif /* !NO_FLOATING_POINT */
1743 if (flags
& INTMAXT
)
1744 ADDTYPE(TP_INTMAXT
);
1745 else if (flags
& PTRDIFFT
)
1746 ADDTYPE(TP_PTRDIFFT
);
1747 else if (flags
& SIZET
)
1749 else if (flags
& LLONGINT
)
1751 else if (flags
& LONGINT
)
1753 else if (flags
& SHORTINT
)
1755 else if (flags
& CHARINT
)
1759 continue; /* no output */
1773 if (flags
& LONGINT
)
1786 default: /* "%?" prints ?, unless ? is NUL */
1794 * Build the argument table.
1796 if (tablemax
>= STATIC_ARG_TBL_SIZE
) {
1797 *argtable
= (union arg
*)
1798 malloc (sizeof (union arg
) * (tablemax
+ 1));
1799 if (*argtable
== NULL
)
1803 (*argtable
) [0].intarg
= 0;
1804 for (n
= 1; n
<= tablemax
; n
++) {
1805 switch (typetable
[n
]) {
1806 case T_UNUSED
: /* whoops! */
1807 (*argtable
) [n
].intarg
= va_arg (ap
, int);
1810 (*argtable
) [n
].pschararg
= va_arg (ap
, signed char *);
1813 (*argtable
) [n
].pshortarg
= va_arg (ap
, short *);
1816 (*argtable
) [n
].intarg
= va_arg (ap
, int);
1819 (*argtable
) [n
].uintarg
= va_arg (ap
, unsigned int);
1822 (*argtable
) [n
].pintarg
= va_arg (ap
, int *);
1825 (*argtable
) [n
].longarg
= va_arg (ap
, long);
1828 (*argtable
) [n
].ulongarg
= va_arg (ap
, unsigned long);
1831 (*argtable
) [n
].plongarg
= va_arg (ap
, long *);
1834 (*argtable
) [n
].longlongarg
= va_arg (ap
, long long);
1837 (*argtable
) [n
].ulonglongarg
= va_arg (ap
, unsigned long long);
1840 (*argtable
) [n
].plonglongarg
= va_arg (ap
, long long *);
1843 (*argtable
) [n
].ptrdiffarg
= va_arg (ap
, ptrdiff_t);
1846 (*argtable
) [n
].pptrdiffarg
= va_arg (ap
, ptrdiff_t *);
1849 (*argtable
) [n
].ssizearg
= va_arg (ap
, ssize_t
);
1852 (*argtable
) [n
].sizearg
= va_arg (ap
, size_t);
1855 (*argtable
) [n
].psizearg
= va_arg (ap
, size_t *);
1858 (*argtable
) [n
].intmaxarg
= va_arg (ap
, intmax_t);
1861 (*argtable
) [n
].uintmaxarg
= va_arg (ap
, uintmax_t);
1864 (*argtable
) [n
].pintmaxarg
= va_arg (ap
, intmax_t *);
1867 #ifndef NO_FLOATING_POINT
1868 (*argtable
) [n
].doublearg
= va_arg (ap
, double);
1872 #ifndef NO_FLOATING_POINT
1873 (*argtable
) [n
].longdoublearg
= va_arg (ap
, long double);
1877 (*argtable
) [n
].pchararg
= va_arg (ap
, char *);
1880 (*argtable
) [n
].pvoidarg
= va_arg (ap
, void *);
1883 (*argtable
) [n
].wintarg
= va_arg (ap
, wint_t);
1886 (*argtable
) [n
].pwchararg
= va_arg (ap
, wchar_t *);
1891 if ((typetable
!= NULL
) && (typetable
!= stattypetable
))
1897 * Increase the size of the type table.
1900 __grow_type_table (int nextarg
, enum typeid **typetable
, int *tablesize
)
1902 enum typeid *const oldtable
= *typetable
;
1903 const int oldsize
= *tablesize
;
1904 enum typeid *newtable
;
1905 int n
, newsize
= oldsize
* 2;
1907 if (newsize
< nextarg
+ 1)
1908 newsize
= nextarg
+ 1;
1909 if (oldsize
== STATIC_ARG_TBL_SIZE
) {
1910 if ((newtable
= malloc(newsize
* sizeof(enum typeid))) == NULL
)
1912 memcpy(newtable
, oldtable
, oldsize
* sizeof(enum typeid));
1914 newtable
= realloc(oldtable
, newsize
* sizeof(enum typeid));
1915 if (newtable
== NULL
) {
1920 for (n
= oldsize
; n
< newsize
; n
++)
1921 newtable
[n
] = T_UNUSED
;
1923 *typetable
= newtable
;
1924 *tablesize
= newsize
;
1929 #ifndef NO_FLOATING_POINT
1932 cvt(double value
, int ndigits
, int flags
, char *sign
, int *decpt
, int ch
,
1936 char *digits
, *bp
, *rve
;
1938 _DIAGASSERT(decpt
!= NULL
);
1939 _DIAGASSERT(length
!= NULL
);
1940 _DIAGASSERT(sign
!= NULL
);
1943 mode
= 3; /* ndigits after the decimal point */
1945 /* To obtain ndigits after the decimal point for the 'e'
1946 * and 'E' formats, round to ndigits + 1 significant
1949 if (ch
== 'e' || ch
== 'E') {
1952 mode
= 2; /* ndigits significant digits */
1955 digits
= __dtoa(value
, mode
, ndigits
, decpt
, &dsgn
, &rve
);
1963 if ((ch
!= 'g' && ch
!= 'G') || flags
& ALT
) { /* Print trailing zeros */
1964 bp
= digits
+ ndigits
;
1966 if (*digits
== '0' && value
)
1967 *decpt
= -ndigits
+ 1;
1970 if (value
== 0) /* kludge for __dtoa irregularity */
1975 *length
= rve
- digits
;
1981 exponent(CHAR_T
*p0
, int expo
, int fmtch
)
1984 CHAR_T expbuf
[MAXEXPDIG
];
1994 t
= expbuf
+ MAXEXPDIG
;
1997 *--t
= to_char(expo
% 10);
1998 } while ((expo
/= 10) > 9);
1999 *--t
= to_char(expo
);
2000 for (; t
< expbuf
+ MAXEXPDIG
; *p
++ = *t
++);
2004 * Exponents for decimal floating point conversions
2005 * (%[eEgG]) must be at least two characters long,
2006 * whereas exponents for hexadecimal conversions can
2007 * be only one character long.
2009 if (fmtch
== 'e' || fmtch
== 'E')
2011 *p
++ = to_char(expo
);
2015 #endif /* !NO_FLOATING_POINT */