]>
git.proxmox.com Git - mirror_edk2.git/blob - StdLib/LibC/Stdio/vfwprintf.c
3c5332ac4aab50d5c7cb68b498832b8c41a89654
2 Implementation of internals for printf and wprintf.
4 Copyright (c) 2010 - 2011, Intel Corporation. All rights reserved.<BR>
5 This program and the accompanying materials are licensed and made available
6 under the terms and conditions of the BSD License that accompanies this
7 distribution. The full text of the license may be found at
8 http://opensource.org/licenses/bsd-license.
10 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
13 Copyright (c) 1990, 1993
14 The Regents of the University of California. All rights reserved.
16 This code is derived from software contributed to Berkeley by
19 Redistribution and use in source and binary forms, with or without
20 modification, are permitted provided that the following conditions
22 - Redistributions of source code must retain the above copyright
23 notice, this list of conditions and the following disclaimer.
24 - Redistributions in binary form must reproduce the above copyright
25 notice, this list of conditions and the following disclaimer in the
26 documentation and/or other materials provided with the distribution.
27 - Neither the name of the University nor the names of its contributors
28 may be used to endorse or promote products derived from this software
29 without specific prior written permission.
31 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
32 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
33 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
35 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
36 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
37 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
38 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
39 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
41 POSSIBILITY OF SUCH DAMAGE.
43 NetBSD: vfwprintf.c,v 1.9.2.1.4.1 2008/04/08 21:10:55 jdc Exp
44 vfprintf.c 8.1 (Berkeley) 6/4/93
46 #include <LibConfig.h>
48 #include "namespace.h"
49 #include <sys/types.h>
65 #include "reentrant.h"
71 // Keep compiler quiet about conversions from larger to smaller types.
72 #pragma warning ( disable : 4244 )
77 #define CHAR_T wchar_t
78 #define STRLEN(a) wcslen(a)
79 #define MEMCHR(a, b, c) wmemchr(a, b, c)
80 #define SCONV(a, b) __mbsconv(a, b)
81 #define STRCONST(a) L ## a
82 #define WDECL(a, b) a ## w ## b
83 #define END_OF_FILE WEOF
86 #define MCHAR_T wchar_t
88 #define STRLEN(a) strlen(a)
89 #define MEMCHR(a, b, c) memchr(a, b, c)
90 #define SCONV(a, b) __wcsconv(a, b)
92 #define WDECL(a, b) a ## b
93 #define END_OF_FILE EOF
101 unsigned long ulongarg
;
102 long long longlongarg
;
103 unsigned long long ulonglongarg
;
104 ptrdiff_t ptrdiffarg
;
107 uintmax_t uintmaxarg
;
110 signed char *pschararg
;
114 long long *plonglongarg
;
115 ptrdiff_t *pptrdiffarg
;
117 intmax_t *pintmaxarg
;
118 #ifndef NO_FLOATING_POINT
120 long double longdoublearg
;
127 * Type ids for argument type table.
130 T_UNUSED
, TP_SHORT
, T_INT
, T_U_INT
, TP_INT
,
131 T_LONG
, T_U_LONG
, TP_LONG
, T_LLONG
, T_U_LLONG
,
132 TP_LLONG
, T_PTRDIFFT
, TP_PTRDIFFT
, T_SIZET
, TP_SIZET
,
133 T_INTMAXT
, T_UINTMAXT
, TP_INTMAXT
, TP_VOID
, TP_CHAR
,
134 TP_SCHAR
, T_DOUBLE
, T_LONG_DOUBLE
, T_WINT
, TP_WCHAR
137 static int __sbprintf(FILE *, const CHAR_T
*, va_list);
138 static CHAR_T
*__ujtoa(uintmax_t, CHAR_T
*, int, int, const char *, int,
140 static CHAR_T
*__ultoa(u_long
, CHAR_T
*, int, int, const char *, int,
143 static CHAR_T
*__mbsconv(char *, int);
144 static wint_t __xfputwc(CHAR_T
, FILE *);
146 static char *__wcsconv(wchar_t *, int);
147 static int __sprint(FILE *, struct __suio
*);
149 static int __find_arguments(const CHAR_T
*, va_list, union arg
**);
150 static int __grow_type_table(int, enum typeid **, int *);
153 * Helper function for `fprintf to unbuffered unix file': creates a
154 * temporary buffer. We only work on write-only files; this avoids
155 * worries about ungetc buffers and so forth.
158 __sbprintf(FILE *fp
, const CHAR_T
*fmt
, va_list ap
)
162 struct __sfileext fakeext
;
163 unsigned char buf
[BUFSIZ
];
165 _DIAGASSERT(fp
!= NULL
);
166 _DIAGASSERT(fmt
!= NULL
);
172 _FILEEXT_SETUP(&fake
, &fakeext
);
174 /* copy the important variables */
175 fake
._flags
= fp
->_flags
& ~__SNBF
;
176 fake
._file
= fp
->_file
;
177 fake
._cookie
= fp
->_cookie
;
178 fake
._write
= fp
->_write
;
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
)(&fake
, 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
)
202 static const mbstate_t initial
= { 0 };
204 char buf
[MB_LEN_MAX
];
209 if ((fp
->_flags
& __SSTR
) == 0)
210 return (__fputwc_unlock(wc
, fp
));
213 if ((len
= wcrtomb(buf
, wc
, &mbs
)) == (size_t)-1) {
214 fp
->_flags
|= __SERR
;
215 return (END_OF_FILE
);
218 uio
.uio_resid
= (int)len
;
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
);
241 if (uio
->uio_resid
== 0) {
245 err
= __sfvwrite(fp
, uio
);
253 * Macros for converting digits to letters and vice versa
255 #define to_digit(c) ((c) - '0')
256 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
257 #define to_char(n) (CHAR_T)((n) + '0')
260 * Convert an unsigned long to ASCII for printf purposes, returning
261 * a pointer to the first character of the string representation.
262 * Octal numbers can be forced to have a leading zero; hex numbers
263 * use the given digits.
266 __ultoa(u_long val
, CHAR_T
*endp
, int base
, int octzero
, const char *xdigs
,
267 int needgrp
, char thousep
, const char *grp
)
274 * Handle the three cases separately, in the hope of getting
275 * better/faster code.
279 if (val
< 10) { /* many numbers are 1 digit */
280 *--cp
= to_char(val
);
285 * On many machines, unsigned arithmetic is harder than
286 * signed arithmetic, so we do at most one unsigned mod and
287 * divide; this is sufficient to reduce the range of
288 * the incoming value to where signed arithmetic works.
290 if (val
> LONG_MAX
) {
291 *--cp
= to_char(val
% 10);
293 sval
= (LONGN
)(val
/ 10);
297 *--cp
= to_char(sval
% 10);
300 * If (*grp == CHAR_MAX) then no more grouping
301 * should be performed.
303 if (needgrp
&& ndig
== *grp
&& *grp
!= CHAR_MAX
308 * If (*(grp+1) == '\0') then we have to
309 * use *grp character (last grouping rule)
312 if (*(grp
+1) != '\0')
321 *--cp
= to_char(val
& 7);
324 if (octzero
&& *cp
!= '0')
330 *--cp
= xdigs
[(size_t)val
& 15];
341 /* Identical to __ultoa, but for intmax_t. */
343 __ujtoa(uintmax_t val
, CHAR_T
*endp
, int base
, int octzero
,
344 const char *xdigs
, int needgrp
, char thousep
, const char *grp
)
350 /* quick test for small values; __ultoa is typically much faster */
351 /* (perhaps instead we should run until small, then call __ultoa?) */
352 if (val
<= ULONG_MAX
)
353 return (__ultoa((u_long
)val
, endp
, base
, octzero
, xdigs
,
354 needgrp
, thousep
, grp
));
358 *--cp
= to_char(val
% 10);
362 if (val
> INTMAX_MAX
) {
363 *--cp
= to_char(val
% 10);
369 *--cp
= to_char(sval
% 10);
372 * If (*grp == CHAR_MAX) then no more grouping
373 * should be performed.
375 if (needgrp
&& *grp
!= CHAR_MAX
&& ndig
== *grp
380 * If (*(grp+1) == '\0') then we have to
381 * use *grp character (last grouping rule)
384 if (*(grp
+1) != '\0')
393 *--cp
= to_char(val
& 7);
396 if (octzero
&& *cp
!= '0')
402 *--cp
= xdigs
[(size_t)val
& 15];
415 * Convert a multibyte character string argument for the %s format to a wide
416 * string representation. ``prec'' specifies the maximum number of bytes
417 * to output. If ``prec'' is greater than or equal to zero, we can't assume
418 * that the multibyte char. string ends in a null character.
421 __mbsconv(char *mbsarg
, int prec
)
423 static const mbstate_t initial
= { 0 };
425 wchar_t *convbuf
, *wcp
;
427 size_t insize
, nchars
, nconv
;
433 * Supplied argument is a multibyte string; convert it to wide
438 * String is not guaranteed to be NUL-terminated. Find the
439 * number of characters to print.
442 insize
= nchars
= nconv
= 0;
444 while (nchars
!= (size_t)prec
) {
445 nconv
= mbrlen(p
, MB_CUR_MAX
, &mbs
);
446 if (nconv
== 0 || nconv
== (size_t)-1 ||
453 if (nconv
== (size_t)-1 || nconv
== (size_t)-2)
456 insize
= strlen(mbsarg
);
459 * Allocate buffer for the result and perform the conversion,
460 * converting at most `size' bytes of the input multibyte string to
461 * wide characters for printing.
463 convbuf
= malloc((insize
+ 1) * sizeof(*convbuf
));
470 while (insize
!= 0) {
471 nconv
= mbrtowc(wcp
, p
, insize
, &mbs
);
472 if (nconv
== 0 || nconv
== (size_t)-1 || nconv
== (size_t)-2)
478 if (nconv
== (size_t)-1 || nconv
== (size_t)-2) {
488 * Convert a wide character string argument for the %ls format to a multibyte
489 * string representation. If not -1, prec specifies the maximum number of
490 * bytes to output, and also means that we can't assume that the wide char.
491 * string ends is null-terminated.
494 __wcsconv(wchar_t *wcsarg
, int prec
)
496 static const mbstate_t initial
= { 0 };
498 char buf
[MB_LEN_MAX
];
503 /* Allocate space for the maximum number of bytes we could output. */
507 nbytes
= wcsrtombs(NULL
, (const wchar_t **)&p
, 0, &mbs
);
508 if (nbytes
== (size_t)-1)
512 * Optimisation: if the output precision is small enough,
513 * just allocate enough memory for the maximum instead of
514 * scanning the string.
523 clen
= wcrtomb(buf
, *p
++, &mbs
);
524 if (clen
== 0 || clen
== (size_t)-1 ||
525 nbytes
+ clen
> (size_t)prec
)
531 if ((convbuf
= malloc(nbytes
+ 1)) == NULL
)
534 /* Fill the output buffer. */
537 if ((nbytes
= wcsrtombs(convbuf
, (const wchar_t **)&p
,
538 nbytes
, &mbs
)) == (size_t)-1) {
542 convbuf
[nbytes
] = '\0';
551 WDECL(vf
,printf
)(FILE * __restrict fp
, const CHAR_T
* __restrict fmt0
, va_list ap
)
560 ret
= WDECL(__vf
,printf_unlocked
)(fp
, fmt0
, ap
);
565 #ifndef NO_FLOATING_POINT
573 static int exponent(CHAR_T
*, int, int);
575 static char *cvt(double, int, int, char *, int *, int, int *);
578 #endif /* !NO_FLOATING_POINT */
581 * The size of the buffer we use as scratch space for integer
582 * conversions, among other things. Technically, we would need the
583 * most space for base 10 conversions with thousands' grouping
584 * characters between each pair of digits. 100 bytes is a
585 * conservative overestimate even for a 128-bit uintmax_t.
589 #define STATIC_ARG_TBL_SIZE 8 /* Size of static argument table. */
592 * Flags used during conversion.
594 #define ALT 0x001 /* alternate form */
595 #define LADJUST 0x004 /* left adjustment */
596 #define LONGDBL 0x008 /* long double */
597 #define LONGINT 0x010 /* long integer */
598 #define LLONGINT 0x020 /* long long integer */
599 #define SHORTINT 0x040 /* short integer */
600 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
601 #define FPT 0x100 /* Floating point number */
602 #define GROUPING 0x200 /* use grouping ("'" flag) */
603 /* C99 additional size modifiers: */
604 #define SIZET 0x400 /* size_t */
605 #define PTRDIFFT 0x800 /* ptrdiff_t */
606 #define INTMAXT 0x1000 /* intmax_t */
607 #define CHARINT 0x2000 /* print char using int format */
610 * Non-MT-safe version
613 WDECL(__vf
,printf_unlocked
)(FILE *fp
, const CHAR_T
*fmt0
, va_list ap
)
615 CHAR_T
*fmt
; /* format string */
616 int ch
; /* character from fmt */
617 int n
, n2
; /* handy integer (short term usage) */
618 CHAR_T
*cp
; /* handy char pointer (short term usage) */
619 int flags
; /* flags as above */
620 int ret
; /* return value accumulator (number of items converted)*/
621 int width
; /* width from format (%8d), or 0 */
622 int prec
; /* precision from format; <0 for N/A */
623 CHAR_T sign
; /* sign prefix (' ', '+', '-', or \0) */
624 char thousands_sep
; /* locale specific thousands separator */
625 const char *grouping
; /* locale specific numeric grouping rules */
626 #ifndef NO_FLOATING_POINT
628 * We can decompose the printed representation of floating
629 * point numbers into several parts, some of which may be empty:
631 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
634 * A: 'sign' holds this value if present; '\0' otherwise
635 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
636 * C: cp points to the string MMMNNN. Leading and trailing
637 * zeros are not in the string and must be added.
638 * D: expchar holds this character; '\0' if no exponent, e.g. %f
639 * F: at least two digits for decimal, at least one digit for hex
641 char *decimal_point
; /* locale specific decimal point */
643 int signflag
; /* true if float is negative */
644 union { /* floating point arguments %[aAeEfFgG] */
648 char *dtoaend
; /* pointer to end of converted digits */
650 double _double
; /* double precision arguments %[eEfgG] */
651 char softsign
; /* temporary negative sign for floats */
653 char *dtoaresult
; /* buffer allocated by dtoa */
654 int expt
= 0; /* integer value of exponent */
655 char expchar
; /* exponent character: [eEpP\0] */
656 int expsize
; /* character count for expstr */
657 int lead
; /* sig figs before decimal or group sep */
658 int ndig
; /* actual number of digits returned by dtoa */
659 CHAR_T expstr
[MAXEXPDIG
+2]; /* buffer for exponent string: e+ZZZ */
660 int nseps
; /* number of group separators with ' */
661 int nrepeats
; /* number of repeats of the last group */
663 u_long ulval
; /* integer arguments %[diouxX] */
664 uintmax_t ujval
; /* %j, %ll, %q, %t, %z integers */
665 int base
; /* base for [diouxX] conversion */
666 int dprec
; /* a copy of prec if [diouxX], 0 otherwise */
667 int realsz
; /* field size expanded by dprec, sign, etc */
668 int size
; /* size of converted field or string */
669 int prsize
; /* max size of printed field */
670 const char *xdigs
; /* digits for %[xX] conversion */
673 struct __siov
*iovp
; /* for PRINT macro */
674 struct __suio uio
; /* output information: summary */
675 struct __siov iov
[NIOV
];/* ... and individual io vectors */
679 CHAR_T buf
[BUF
]; /* buffer with space for digits of uintmax_t */
680 CHAR_T ox
[2]; /* space for 0x hex-prefix */
681 union arg
*argtable
; /* args, built due to positional arg */
682 union arg statargtable
[STATIC_ARG_TBL_SIZE
];
683 int nextarg
; /* 1-based argument index */
684 va_list orgap
; /* original argument pointer */
685 CHAR_T
*convbuf
; /* multibyte to wide conversion result */
688 * Choose PADSIZE to trade efficiency vs. size. If larger printf
689 * fields occur frequently, increase PADSIZE and make the initialisers
692 #define PADSIZE 16 /* pad chunk size */
693 static CHAR_T blanks
[PADSIZE
] =
694 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
695 static CHAR_T zeroes
[PADSIZE
] =
696 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
698 static const char xdigs_lower
[17] = "0123456789abcdef";
699 static const char xdigs_upper
[17] = "0123456789ABCDEF";
702 * BEWARE, these `goto error' on error, PRINT uses `n2' and
706 #define PRINT(ptr, len) do { \
707 for (n3 = 0; n3 < (len); n3++) \
708 __xfputwc((ptr)[n3], fp); \
709 } while (/*CONSTCOND*/0)
712 #define PRINT(ptr, len) do { \
713 iovp->iov_base = __UNCONST(ptr); \
714 iovp->iov_len = (len); \
715 uio.uio_resid += (len); \
717 if (++uio.uio_iovcnt >= NIOV) { \
718 if (__sprint(fp, &uio)) \
722 } while (/*CONSTCOND*/0)
723 #define FLUSH() do { \
724 if (uio.uio_resid && __sprint(fp, &uio)) \
726 uio.uio_iovcnt = 0; \
728 } while (/*CONSTCOND*/0)
731 #define PAD(howmany, with) do { \
732 if ((n = (howmany)) > 0) { \
733 while (n > PADSIZE) { \
734 PRINT(with, PADSIZE); \
739 } while (/*CONSTCOND*/0)
740 #define PRINTANDPAD(p, ep, len, with) do { \
746 PAD((len) - (n2 > 0 ? n2 : 0), (with)); \
747 } while(/*CONSTCOND*/0)
750 * Get the argument indexed by nextarg. If the argument table is
751 * built, use it to get the argument. If its not, get the next
752 * argument (and arguments must be gotten sequentially).
754 #define GETARG(type) \
755 ((/*CONSTCOND*/argtable != NULL) ? *((type*)(void*)(&argtable[nextarg++])) : \
756 (nextarg++, va_arg(ap, type)))
759 * To extend shorts properly, we need both signed and unsigned
760 * argument extraction methods.
763 ((long)(flags&LONGINT ? GETARG(long) : \
764 flags&SHORTINT ? (short)GETARG(int) : \
765 flags&CHARINT ? (signed char)GETARG(int) : \
769 ((u_long)(flags&LONGINT ? GETARG(u_long) : \
770 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
771 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
772 (u_long)GETARG(u_int)))
774 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
777 (flags&INTMAXT ? GETARG(intmax_t) : \
778 flags&SIZET ? (intmax_t)GETARG(size_t) : \
779 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
780 (intmax_t)GETARG(long long))
783 (flags&INTMAXT ? GETARG(uintmax_t) : \
784 flags&SIZET ? (uintmax_t)GETARG(size_t) : \
785 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
786 (uintmax_t)GETARG(unsigned long long))
789 * Get * arguments, including the form *nn$. Preserve the nextarg
790 * that the argument can be gotten once the type is determined.
792 #define GETASTER(val) \
795 while (is_digit(*cp)) { \
796 n2 = 10 * n2 + to_digit(*cp); \
800 int hold = nextarg; \
801 if (argtable == NULL) { \
802 argtable = statargtable; \
803 if (__find_arguments(fmt0, orgap, &argtable) == -1) \
807 val = GETARG (int); \
811 val = GETARG (int); \
814 _DIAGASSERT(fp
!= NULL
);
815 _DIAGASSERT(fmt0
!= NULL
);
821 _SET_ORIENTATION(fp
, -1);
823 ndig
= -1; /* XXX gcc */
825 thousands_sep
= '\0';
827 #ifndef NO_FLOATING_POINT
828 decimal_point
= localeconv()->decimal_point
;
829 expsize
= 0; /* XXXGCC -Wuninitialized [sh3,m68000] */
832 /* sorry, f{w,}printf(read_only_file, L"") returns {W,}EOF, not 0 */
835 return (END_OF_FILE
);
838 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
839 if ((fp
->_flags
& (__SNBF
|__SWR
|__SRW
)) == (__SNBF
|__SWR
) &&
841 return (__sbprintf(fp
, fmt0
, ap
));
843 fmt
= (CHAR_T
*)__UNCONST(fmt0
);
848 uio
.uio_iov
= iovp
= iov
;
855 * Scan the format for conversions (`%' character).
859 const CHAR_T
*result
;
861 for (cp
= fmt
; (ch
= *fmt
) != '\0' && ch
!= '%'; fmt
++)
863 if ((n
= (int)(fmt
- cp
)) != 0) {
864 if ((unsigned)ret
+ n
> INT_MAX
) {
873 fmt
++; /* skip over '%' */
883 nseps
= nrepeats
= 0;
889 reswitch
: switch (ch
) {
892 * ``If the space and + flags both appear, the space
893 * flag will be ignored.''
904 * ``A negative field width argument is taken as a
905 * - flag followed by a positive field width.''
907 * They don't exclude field widths read from args.
922 thousands_sep
= *(localeconv()->thousands_sep
);
923 grouping
= localeconv()->grouping
;
926 if ((ch
= *fmt
++) == '*') {
931 while (is_digit(ch
)) {
932 prec
= 10 * prec
+ to_digit(ch
);
938 * ``Note that 0 is taken as a flag, not as the
939 * beginning of a field width.''
944 case '1': case '2': case '3': case '4':
945 case '5': case '6': case '7': case '8': case '9':
948 n
= 10 * n
+ to_digit(ch
);
950 } while (is_digit(ch
));
953 if (argtable
== NULL
) {
954 argtable
= statargtable
;
955 if (__find_arguments(fmt0
, orgap
,
963 #ifndef NO_FLOATING_POINT
969 if (flags
& SHORTINT
) {
979 if (flags
& LONGINT
) {
986 flags
|= LLONGINT
; /* not necessarily */
999 if (flags
& LONGINT
) {
1000 static const mbstate_t initial
= { 0 };
1005 mbseqlen
= wcrtomb(buf
,
1006 (wchar_t)GETARG(wint_t), &mbs
);
1007 if (mbseqlen
== (size_t)-1) {
1008 fp
->_flags
|= __SERR
;
1011 size
= (int)mbseqlen
;
1013 *buf
= (char)(GETARG(int));
1017 if (flags
& LONGINT
)
1018 *buf
= (wchar_t)GETARG(wint_t);
1020 *buf
= (wchar_t)btowc(GETARG(int));
1031 if (flags
& INTMAX_SIZE
) {
1033 if ((intmax_t)ujval
< 0) {
1034 ujval
= (uintmax_t)(-((intmax_t)ujval
));
1039 if ((long)ulval
< 0) {
1040 ulval
= (u_long
)(-((long)ulval
));
1046 #ifndef NO_FLOATING_POINT
1052 xdigs
= xdigs_lower
;
1056 xdigs
= xdigs_upper
;
1061 if (flags
& LONGDBL
) {
1062 fparg
.ldbl
= GETARG(long double);
1064 __hldtoa(fparg
.ldbl
, xdigs
, prec
,
1065 &expt
, &signflag
, &dtoaend
);
1067 fparg
.dbl
= GETARG(double);
1069 __hdtoa(fparg
.dbl
, xdigs
, prec
,
1070 &expt
, &signflag
, &dtoaend
);
1072 if (dtoaresult
== NULL
)
1076 prec
= dtoaend
- dtoaresult
;
1077 if (expt
== INT_MAX
)
1079 ndig
= dtoaend
- dtoaresult
;
1080 if (convbuf
!= NULL
)
1083 result
= convbuf
= __mbsconv(dtoaresult
, -1);
1086 result
= convbuf
= strdup(dtoaresult
);
1090 __freedtoa(dtoaresult
);
1095 if (prec
< 0) /* account for digit before decpt */
1106 expchar
= ch
- ('g' - 'e');
1112 if (flags
& LONGDBL
) {
1113 fparg
.ldbl
= GETARG(long double);
1115 __ldtoa(&fparg
.ldbl
, expchar
? 2 : 3, prec
,
1116 &expt
, &signflag
, &dtoaend
);
1118 fparg
.dbl
= GETARG(double);
1120 __dtoa(fparg
.dbl
, expchar
? 2 : 3, prec
,
1121 &expt
, &signflag
, &dtoaend
);
1125 if (dtoaresult
== NULL
)
1127 ndig
= dtoaend
- dtoaresult
;
1128 if (convbuf
!= NULL
)
1131 result
= convbuf
= __mbsconv(dtoaresult
, -1);
1134 result
= convbuf
= strdup(dtoaresult
);
1138 __freedtoa(dtoaresult
);
1142 if (expt
== INT_MAX
) { /* inf or nan */
1143 if (*result
== 'N') {
1144 result
= (ch
>= 'a') ? STRCONST("nan") :
1148 result
= (ch
>= 'a') ? STRCONST("inf") :
1160 // if (prec == -1) {
1162 // } else if ((ch == 'g' || ch == 'G') && prec == 0) {
1168 if (prec
< 0) /* account for digit before decpt */
1169 prec
= DEFPREC
/* + 1*/ ;
1179 expchar
= ch
- ('g' - 'e');
1186 if (flags
& LONGDBL
) {
1187 _double
= (double) GETARG(long double);
1189 _double
= GETARG(double);
1192 /* do this before tricky precision changes */
1193 if (isinf(_double
)) {
1196 if (ch
== 'E' || ch
== 'F' || ch
== 'G')
1197 result
= STRCONST("INF");
1199 result
= STRCONST("inf");
1203 if (isnan(_double
)) {
1204 if (ch
== 'E' || ch
== 'F' || ch
== 'G')
1205 result
= STRCONST("NAN");
1207 result
= STRCONST("nan");
1213 dtoaresult
= cvt(_double
, prec
, flags
, &softsign
, &expt
, ch
, &ndig
);
1214 if (dtoaresult
== NULL
)
1216 if (convbuf
!= NULL
)
1219 result
= convbuf
= __mbsconv(dtoaresult
, -1);
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 (*grouping
!= CHAR_MAX
) {
1269 if (lead
<= *grouping
)
1272 if (*(grouping
+1)) {
1278 size
+= nseps
+ nrepeats
;
1283 #endif /* !NO_FLOATING_POINT */
1286 * Assignment-like behavior is specified if the
1287 * value overflows or is otherwise unrepresentable.
1288 * C99 says to use `signed char' for %hhn conversions.
1290 if (flags
& LLONGINT
)
1291 *GETARG(long long *) = ret
;
1292 else if (flags
& SIZET
)
1293 *GETARG(ssize_t
*) = (ssize_t
)ret
;
1294 else if (flags
& PTRDIFFT
)
1295 *GETARG(ptrdiff_t *) = ret
;
1296 else if (flags
& INTMAXT
)
1297 *GETARG(intmax_t *) = ret
;
1298 else if (flags
& LONGINT
)
1299 *GETARG(long *) = ret
;
1300 else if (flags
& SHORTINT
)
1301 *GETARG(short *) = ret
;
1302 else if (flags
& CHARINT
)
1303 *GETARG(signed char *) = ret
;
1305 *GETARG(int *) = ret
;
1306 continue; /* no output */
1311 if (flags
& INTMAX_SIZE
)
1319 * ``The argument shall be a pointer to void. The
1320 * value of the pointer is converted to a sequence
1321 * of printable characters, in an implementation-
1325 ujval
= (uintmax_t)GETARG(void *);
1327 xdigs
= xdigs_lower
;
1328 flags
= flags
| INTMAXT
;
1335 if ((flags
& LONGINT
) != MULTI
) {
1336 if ((result
= GETARG(CHAR_T
*)) == NULL
)
1337 result
= STRCONST("(null)");
1341 if (convbuf
!= NULL
)
1343 if ((mc
= GETARG(MCHAR_T
*)) == NULL
)
1344 result
= STRCONST("(null)");
1346 convbuf
= SCONV(mc
, prec
);
1347 if (convbuf
== NULL
) {
1348 fp
->_flags
|= __SERR
;
1357 * can't use STRLEN; can only look for the
1358 * NUL in the first `prec' characters, and
1359 * STRLEN() will go further.
1361 CHAR_T
*p
= MEMCHR(result
, 0, (size_t)prec
);
1370 size
= (int)STRLEN(result
);
1377 if (flags
& INTMAX_SIZE
)
1384 xdigs
= xdigs_upper
;
1387 xdigs
= xdigs_lower
;
1389 if (flags
& INTMAX_SIZE
)
1394 /* leading 0x/X only if non-zero */
1396 (flags
& INTMAX_SIZE
? ujval
!= 0 : ulval
!= 0))
1400 /* unsigned conversions */
1401 nosign
: sign
= '\0';
1403 * ``... diouXx conversions ... if a precision is
1404 * specified, the 0 flag will be ignored.''
1407 number
: if ((dprec
= prec
) >= 0)
1411 * ``The result of converting a zero value with an
1412 * explicit precision of zero is no characters.''
1415 * ``The C Standard is clear enough as is. The call
1416 * printf("%#.0o", 0) should print 0.''
1417 * -- Defect Report #151
1419 result
= cp
= buf
+ BUF
;
1420 if (flags
& INTMAX_SIZE
) {
1421 if (ujval
!= 0 || prec
!= 0 ||
1422 (flags
& ALT
&& base
== 8))
1424 result
= __ujtoa(ujval
, cp
, base
,
1426 flags
& GROUPING
, thousands_sep
,
1430 if (ulval
!= 0 || prec
!= 0 ||
1431 (flags
& ALT
&& base
== 8))
1432 result
= __ultoa(ulval
, cp
, base
,
1434 flags
& GROUPING
, thousands_sep
,
1437 size
= buf
+ BUF
- result
;
1438 if (size
> BUF
) /* should never happen */
1441 default: /* "%?" prints ?, unless ? is NUL */
1444 /* pretend it was %c with argument ch */
1453 * All reasonable formats wind up here. At this point, `result'
1454 * points to a string which (if not flags&LADJUST) should be
1455 * padded out to `width' places. If flags&ZEROPAD, it should
1456 * first be prefixed by any sign or other prefix; otherwise,
1457 * it should be blank padded before the prefix is emitted.
1458 * After any left-hand padding and prefixing, emit zeroes
1459 * required by a decimal [diouxX] precision, then print the
1460 * string proper, then emit zeroes required by any leftover
1461 * floating precision; finally, if LADJUST, pad with blanks.
1463 * Compute actual size, so we know how much to pad.
1464 * size excludes decimal prec; realsz includes it.
1466 realsz
= dprec
> size
? dprec
: size
;
1472 prsize
= width
> realsz
? width
: realsz
;
1473 if ((unsigned)ret
+ prsize
> INT_MAX
) {
1478 /* right-adjusting blank padding */
1479 if ((flags
& (LADJUST
|ZEROPAD
)) == 0)
1480 PAD(width
- realsz
, blanks
);
1486 if (ox
[1]) { /* ox[1] is either x, X, or \0 */
1491 /* right-adjusting zero padding */
1492 if ((flags
& (LADJUST
|ZEROPAD
)) == ZEROPAD
)
1493 PAD(width
- realsz
, zeroes
);
1495 /* leading zeroes from decimal precision */
1496 PAD(dprec
- size
, zeroes
);
1498 /* the string or number proper */
1499 #ifndef NO_FLOATING_POINT
1500 if ((flags
& FPT
) == 0) {
1501 PRINT(result
, size
);
1502 } else { /* glue together f_p fragments */
1503 if (!expchar
) { /* %[fF] or sufficiently short %[gG] */
1506 if (prec
|| flags
& ALT
)
1507 PRINT(decimal_point
, 1);
1509 /* already handled initial 0's */
1512 PRINTANDPAD(result
, convbuf
+ ndig
,
1516 while (nseps
>0 || nrepeats
>0) {
1523 PRINT(&thousands_sep
,
1528 result
+= *grouping
;
1530 if (result
> convbuf
+ ndig
)
1531 result
= convbuf
+ ndig
;
1533 if (prec
|| flags
& ALT
) {
1534 buf
[0] = *decimal_point
;
1538 PRINTANDPAD(result
, convbuf
+ ndig
, prec
,
1540 } else { /* %[eE] or sufficiently long %[gG] */
1541 if (prec
> 1 || flags
& ALT
) {
1543 buf
[1] = *decimal_point
;
1545 PRINT(result
, ndig
-1);
1546 PAD(prec
- ndig
, zeroes
);
1549 PRINT(expstr
, expsize
);
1553 PRINT(result
, size
);
1555 /* left-adjusting padding (always blank) */
1556 if (flags
& LADJUST
)
1557 PAD(width
- realsz
, blanks
);
1559 /* finally, adjust ret */
1567 if (convbuf
!= NULL
)
1571 if ((argtable
!= NULL
) && (argtable
!= statargtable
))
1582 * Find all arguments when a positional parameter is encountered. Returns a
1583 * table, indexed by argument number, of pointers to each arguments. The
1584 * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1585 * It will be replaces with a malloc-ed one if it overflows.
1588 __find_arguments(const CHAR_T
*fmt0
, va_list ap
, union arg
**argtable
)
1590 CHAR_T
*fmt
; /* format string */
1591 int ch
; /* character from fmt */
1592 int n
, n2
; /* handy integer (short term usage) */
1593 CHAR_T
*cp
; /* handy char pointer (short term usage) */
1594 int flags
; /* flags as above */
1595 enum typeid *typetable
; /* table of types */
1596 enum typeid stattypetable
[STATIC_ARG_TBL_SIZE
];
1597 int tablesize
; /* current size of type table */
1598 int tablemax
; /* largest used index in table */
1599 int nextarg
; /* 1-based argument index */
1602 * Add an argument type to the table, expanding if necessary.
1604 #define ADDTYPE(type) \
1606 if (nextarg >= tablesize) \
1607 if (__grow_type_table(nextarg, &typetable, \
1608 &tablesize) == -1) \
1610 if (nextarg > tablemax) \
1611 tablemax = nextarg; \
1612 typetable[nextarg++] = type; \
1613 } while (/*CONSTCOND*/0)
1617 if (flags & INTMAXT) \
1618 ADDTYPE(T_INTMAXT); \
1619 else if (flags & SIZET) \
1621 else if (flags & PTRDIFFT) \
1622 ADDTYPE(T_PTRDIFFT); \
1623 else if (flags & LLONGINT) \
1625 else if (flags & LONGINT) \
1629 } while (/*CONSTCOND*/0)
1633 if (flags & INTMAXT) \
1634 ADDTYPE(T_UINTMAXT); \
1635 else if (flags & SIZET) \
1637 else if (flags & PTRDIFFT) \
1638 ADDTYPE(T_PTRDIFFT); \
1639 else if (flags & LLONGINT) \
1640 ADDTYPE(T_U_LLONG); \
1641 else if (flags & LONGINT) \
1642 ADDTYPE(T_U_LONG); \
1645 } while (/*CONSTCOND*/0)
1647 * Add * arguments to the type array.
1649 #define ADDASTER() \
1652 while (is_digit(*cp)) { \
1653 n2 = 10 * n2 + to_digit(*cp); \
1657 int hold = nextarg; \
1665 fmt
= (CHAR_T
*)__UNCONST(fmt0
);
1666 typetable
= stattypetable
;
1667 tablesize
= STATIC_ARG_TBL_SIZE
;
1670 for (n
= 0; n
< STATIC_ARG_TBL_SIZE
; n
++)
1671 typetable
[n
] = T_UNUSED
;
1674 * Scan the format for conversions (`%' character).
1677 for (cp
= fmt
; (ch
= *fmt
) != '\0' && ch
!= '%'; fmt
++)
1681 fmt
++; /* skip over '%' */
1686 reswitch
: switch (ch
) {
1698 if ((ch
= *fmt
++) == '*') {
1702 while (is_digit(ch
)) {
1708 case '1': case '2': case '3': case '4':
1709 case '5': case '6': case '7': case '8': case '9':
1712 n
= 10 * n
+ to_digit(ch
);
1714 } while (is_digit(ch
));
1720 #ifndef NO_FLOATING_POINT
1726 if (flags
& SHORTINT
) {
1736 if (flags
& LONGINT
) {
1743 flags
|= LLONGINT
; /* not necessarily */
1755 if (flags
& LONGINT
)
1767 #ifndef NO_FLOATING_POINT
1775 if (flags
& LONGDBL
)
1776 ADDTYPE(T_LONG_DOUBLE
);
1780 #endif /* !NO_FLOATING_POINT */
1782 if (flags
& INTMAXT
)
1783 ADDTYPE(TP_INTMAXT
);
1784 else if (flags
& PTRDIFFT
)
1785 ADDTYPE(TP_PTRDIFFT
);
1786 else if (flags
& SIZET
)
1788 else if (flags
& LLONGINT
)
1790 else if (flags
& LONGINT
)
1792 else if (flags
& SHORTINT
)
1794 else if (flags
& CHARINT
)
1798 continue; /* no output */
1812 if (flags
& LONGINT
)
1825 default: /* "%?" prints ?, unless ? is NUL */
1833 * Build the argument table.
1835 if (tablemax
>= STATIC_ARG_TBL_SIZE
) {
1836 *argtable
= (union arg
*)
1837 malloc (sizeof (union arg
) * (tablemax
+ 1));
1838 if (*argtable
== NULL
)
1842 (*argtable
) [0].intarg
= 0;
1843 for (n
= 1; n
<= tablemax
; n
++) {
1844 switch (typetable
[n
]) {
1845 case T_UNUSED
: /* whoops! */
1846 (*argtable
) [n
].intarg
= va_arg (ap
, int);
1849 (*argtable
) [n
].pschararg
= va_arg (ap
, signed char *);
1852 (*argtable
) [n
].pshortarg
= va_arg (ap
, short *);
1855 (*argtable
) [n
].intarg
= va_arg (ap
, int);
1858 (*argtable
) [n
].uintarg
= va_arg (ap
, unsigned int);
1861 (*argtable
) [n
].pintarg
= va_arg (ap
, int *);
1864 (*argtable
) [n
].longarg
= va_arg (ap
, long);
1867 (*argtable
) [n
].ulongarg
= va_arg (ap
, unsigned long);
1870 (*argtable
) [n
].plongarg
= va_arg (ap
, long *);
1873 (*argtable
) [n
].longlongarg
= va_arg (ap
, long long);
1876 (*argtable
) [n
].ulonglongarg
= va_arg (ap
, unsigned long long);
1879 (*argtable
) [n
].plonglongarg
= va_arg (ap
, long long *);
1882 (*argtable
) [n
].ptrdiffarg
= va_arg (ap
, ptrdiff_t);
1885 (*argtable
) [n
].pptrdiffarg
= va_arg (ap
, ptrdiff_t *);
1888 (*argtable
) [n
].sizearg
= va_arg (ap
, size_t);
1891 (*argtable
) [n
].psizearg
= va_arg (ap
, size_t *);
1894 (*argtable
) [n
].intmaxarg
= va_arg (ap
, intmax_t);
1897 (*argtable
) [n
].uintmaxarg
= va_arg (ap
, uintmax_t);
1900 (*argtable
) [n
].pintmaxarg
= va_arg (ap
, intmax_t *);
1903 #ifndef NO_FLOATING_POINT
1904 (*argtable
) [n
].doublearg
= va_arg (ap
, double);
1908 #ifndef NO_FLOATING_POINT
1909 (*argtable
) [n
].longdoublearg
= va_arg (ap
, long double);
1913 (*argtable
) [n
].pchararg
= va_arg (ap
, char *);
1916 (*argtable
) [n
].pvoidarg
= va_arg (ap
, void *);
1919 (*argtable
) [n
].wintarg
= va_arg (ap
, wint_t);
1922 (*argtable
) [n
].pwchararg
= va_arg (ap
, wchar_t *);
1927 if ((typetable
!= NULL
) && (typetable
!= stattypetable
))
1933 * Increase the size of the type table.
1936 __grow_type_table (int nextarg
, enum typeid **typetable
, int *tablesize
)
1938 enum typeid *const oldtable
= *typetable
;
1939 const int oldsize
= *tablesize
;
1940 enum typeid *newtable
;
1941 int n
, newsize
= oldsize
* 2;
1943 if (newsize
< nextarg
+ 1)
1944 newsize
= nextarg
+ 1;
1945 if (oldsize
== STATIC_ARG_TBL_SIZE
) {
1946 if ((newtable
= malloc(newsize
* sizeof(enum typeid))) == NULL
)
1948 memcpy(newtable
, oldtable
, oldsize
* sizeof(enum typeid));
1950 newtable
= realloc(oldtable
, newsize
* sizeof(enum typeid));
1951 if (newtable
== NULL
) {
1956 for (n
= oldsize
; n
< newsize
; n
++)
1957 newtable
[n
] = T_UNUSED
;
1959 *typetable
= newtable
;
1960 *tablesize
= newsize
;
1965 #ifndef NO_FLOATING_POINT
1968 cvt(double value
, int ndigits
, int flags
, char *sign
, int *decpt
, int ch
,
1972 char *digits
, *bp
, *rve
;
1974 _DIAGASSERT(decpt
!= NULL
);
1975 _DIAGASSERT(length
!= NULL
);
1976 _DIAGASSERT(sign
!= NULL
);
1979 mode
= 3; /* ndigits after the decimal point */
1981 /* To obtain ndigits after the decimal point for the 'e'
1982 * and 'E' formats, round to ndigits + 1 significant
1985 if (ch
== 'e' || ch
== 'E') {
1988 mode
= 2; /* ndigits significant digits */
1991 digits
= __dtoa(value
, mode
, ndigits
, decpt
, &dsgn
, &rve
);
1999 if ((ch
!= 'g' && ch
!= 'G') || flags
& ALT
) { /* Print trailing zeros */
2000 bp
= digits
+ ndigits
;
2002 if (*digits
== '0' && value
)
2003 *decpt
= -ndigits
+ 1;
2006 if (value
== 0) /* kludge for __dtoa irregularity */
2011 *length
= rve
- digits
;
2017 exponent(CHAR_T
*p0
, int expo
, int fmtch
)
2020 CHAR_T expbuf
[MAXEXPDIG
];
2030 t
= expbuf
+ MAXEXPDIG
;
2033 *--t
= to_char(expo
% 10);
2034 } while ((expo
/= 10) > 9);
2035 *--t
= to_char(expo
);
2036 for (; t
< expbuf
+ MAXEXPDIG
; *p
++ = *t
++);
2040 * Exponents for decimal floating point conversions
2041 * (%[eEgG]) must be at least two characters long,
2042 * whereas exponents for hexadecimal conversions can
2043 * be only one character long.
2045 if (fmtch
== 'e' || fmtch
== 'E')
2047 *p
++ = to_char(expo
);
2051 #endif /* !NO_FLOATING_POINT */