1 /* $NetBSD: vfwprintf.c,v 1.23 2010/12/16 17:42:27 wiz 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.23 2010/12/16 17:42:27 wiz 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
);
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
;
174 /* set up the buffer */
175 fake
._bf
._base
= fake
._p
= buf
;
176 fake
._bf
._size
= fake
._w
= sizeof(buf
);
177 fake
._lbfsize
= 0; /* not actually used, but Just In Case */
179 /* do the work, then copy any error status */
180 ret
= WDECL(__vf
,printf_unlocked
)(&fake
, fmt
, ap
);
181 if (ret
>= 0 && fflush(&fake
))
183 if (fake
._flags
& __SERR
)
184 fp
->_flags
|= __SERR
;
190 * Like __fputwc, but handles fake string (__SSTR) files properly.
191 * File must already be locked.
194 __xfputwc(wchar_t wc
, FILE *fp
)
196 static const mbstate_t initial
;
198 char buf
[MB_LEN_MAX
];
203 if ((fp
->_flags
& __SSTR
) == 0)
204 return (__fputwc_unlock(wc
, fp
));
207 if ((len
= wcrtomb(buf
, wc
, &mbs
)) == (size_t)-1) {
208 fp
->_flags
|= __SERR
;
209 return (END_OF_FILE
);
216 return (__sfvwrite(fp
, &uio
) != EOF
? (wint_t)wc
: END_OF_FILE
);
220 * Flush out all the vectors defined by the given uio,
221 * then reset it so that it can be reused.
224 __sprint(FILE *fp
, struct __suio
*uio
)
228 _DIAGASSERT(fp
!= NULL
);
229 _DIAGASSERT(uio
!= NULL
);
231 if (uio
->uio_resid
== 0) {
235 err
= __sfvwrite(fp
, uio
);
243 * Macros for converting digits to letters and vice versa
245 #define to_digit(c) ((c) - '0')
246 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
247 #define to_char(n) (CHAR_T)((n) + '0')
250 * Convert an unsigned long to ASCII for printf purposes, returning
251 * a pointer to the first character of the string representation.
252 * Octal numbers can be forced to have a leading zero; hex numbers
253 * use the given digits.
256 __ultoa(u_long val
, CHAR_T
*endp
, int base
, int octzero
, const char *xdigs
,
257 int needgrp
, char thousep
, const char *grp
)
264 * Handle the three cases separately, in the hope of getting
265 * better/faster code.
269 if (val
< 10) { /* many numbers are 1 digit */
270 *--cp
= to_char(val
);
275 * On many machines, unsigned arithmetic is harder than
276 * signed arithmetic, so we do at most one unsigned mod and
277 * divide; this is sufficient to reduce the range of
278 * the incoming value to where signed arithmetic works.
280 if (val
> LONG_MAX
) {
281 *--cp
= to_char(val
% 10);
287 *--cp
= to_char(sval
% 10);
290 * If (*grp == CHAR_MAX) then no more grouping
291 * should be performed.
293 if (needgrp
&& ndig
== *grp
&& *grp
!= CHAR_MAX
298 * If (*(grp+1) == '\0') then we have to
299 * use *grp character (last grouping rule)
302 if (*(grp
+1) != '\0')
311 *--cp
= to_char(val
& 7);
314 if (octzero
&& *cp
!= '0')
320 *--cp
= xdigs
[(size_t)val
& 15];
331 /* Identical to __ultoa, but for intmax_t. */
333 __ujtoa(uintmax_t val
, CHAR_T
*endp
, int base
, int octzero
,
334 const char *xdigs
, int needgrp
, char thousep
, const char *grp
)
340 /* quick test for small values; __ultoa is typically much faster */
341 /* (perhaps instead we should run until small, then call __ultoa?) */
342 if (val
<= ULONG_MAX
)
343 return (__ultoa((u_long
)val
, endp
, base
, octzero
, xdigs
,
344 needgrp
, thousep
, grp
));
348 *--cp
= to_char(val
% 10);
352 if (val
> INTMAX_MAX
) {
353 *--cp
= to_char(val
% 10);
359 *--cp
= to_char(sval
% 10);
362 * If (*grp == CHAR_MAX) then no more grouping
363 * should be performed.
365 if (needgrp
&& *grp
!= CHAR_MAX
&& ndig
== *grp
370 * If (*(grp+1) == '\0') then we have to
371 * use *grp character (last grouping rule)
374 if (*(grp
+1) != '\0')
383 *--cp
= to_char(val
& 7);
386 if (octzero
&& *cp
!= '0')
392 *--cp
= xdigs
[(size_t)val
& 15];
405 * Convert a multibyte character string argument for the %s format to a wide
406 * string representation. ``prec'' specifies the maximum number of bytes
407 * to output. If ``prec'' is greater than or equal to zero, we can't assume
408 * that the multibyte char. string ends in a null character.
411 __mbsconv(char *mbsarg
, int prec
)
413 static const mbstate_t initial
;
415 wchar_t *convbuf
, *wcp
;
417 size_t insize
, nchars
, nconv
;
423 * Supplied argument is a multibyte string; convert it to wide
428 * String is not guaranteed to be NUL-terminated. Find the
429 * number of characters to print.
432 insize
= nchars
= nconv
= 0;
434 while (nchars
!= (size_t)prec
) {
435 nconv
= mbrlen(p
, MB_CUR_MAX
, &mbs
);
436 if (nconv
== 0 || nconv
== (size_t)-1 ||
443 if (nconv
== (size_t)-1 || nconv
== (size_t)-2)
446 insize
= strlen(mbsarg
);
449 * Allocate buffer for the result and perform the conversion,
450 * converting at most `size' bytes of the input multibyte string to
451 * wide characters for printing.
453 convbuf
= malloc((insize
+ 1) * sizeof(*convbuf
));
460 while (insize
!= 0) {
461 nconv
= mbrtowc(wcp
, p
, insize
, &mbs
);
462 if (nconv
== 0 || nconv
== (size_t)-1 || nconv
== (size_t)-2)
468 if (nconv
== (size_t)-1 || nconv
== (size_t)-2) {
478 * Convert a wide-character string argument for the %ls format to a multibyte
479 * string representation. If not -1, prec specifies the maximum number of
480 * bytes to output, and also means that we can't assume that the wide-char.
481 * string ends is null-terminated.
484 __wcsconv(wchar_t *wcsarg
, int prec
)
486 static const mbstate_t initial
;
488 char buf
[MB_LEN_MAX
];
493 /* Allocate space for the maximum number of bytes we could output. */
497 nbytes
= wcsrtombs(NULL
, (const wchar_t **)&p
, 0, &mbs
);
498 if (nbytes
== (size_t)-1)
502 * Optimisation: if the output precision is small enough,
503 * just allocate enough memory for the maximum instead of
504 * scanning the string.
513 clen
= wcrtomb(buf
, *p
++, &mbs
);
514 if (clen
== 0 || clen
== (size_t)-1 ||
515 nbytes
+ clen
> (size_t)prec
)
521 if ((convbuf
= malloc(nbytes
+ 1)) == NULL
)
524 /* Fill the output buffer. */
527 if ((nbytes
= wcsrtombs(convbuf
, (const wchar_t **)&p
,
528 nbytes
, &mbs
)) == (size_t)-1) {
532 convbuf
[nbytes
] = '\0';
541 WDECL(vf
,printf
)(FILE * __restrict fp
, const CHAR_T
* __restrict fmt0
, va_list ap
)
546 ret
= WDECL(__vf
,printf_unlocked
)(fp
, fmt0
, ap
);
551 #ifndef NO_FLOATING_POINT
559 static int exponent(CHAR_T
*, int, int);
561 static char *cvt(double, int, int, char *, int *, int, int *);
564 #endif /* !NO_FLOATING_POINT */
567 * The size of the buffer we use as scratch space for integer
568 * conversions, among other things. Technically, we would need the
569 * most space for base 10 conversions with thousands' grouping
570 * characters between each pair of digits. 100 bytes is a
571 * conservative overestimate even for a 128-bit uintmax_t.
575 #define STATIC_ARG_TBL_SIZE 8 /* Size of static argument table. */
578 * Flags used during conversion.
580 #define ALT 0x001 /* alternate form */
581 #define LADJUST 0x004 /* left adjustment */
582 #define LONGDBL 0x008 /* long double */
583 #define LONGINT 0x010 /* long integer */
584 #define LLONGINT 0x020 /* long long integer */
585 #define SHORTINT 0x040 /* short integer */
586 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
587 #define FPT 0x100 /* Floating point number */
588 #define GROUPING 0x200 /* use grouping ("'" flag) */
589 /* C99 additional size modifiers: */
590 #define SIZET 0x400 /* size_t */
591 #define PTRDIFFT 0x800 /* ptrdiff_t */
592 #define INTMAXT 0x1000 /* intmax_t */
593 #define CHARINT 0x2000 /* print char using int format */
596 * Non-MT-safe version
599 WDECL(__vf
,printf_unlocked
)(FILE *fp
, const CHAR_T
*fmt0
, va_list ap
)
601 CHAR_T
*fmt
; /* format string */
602 int ch
; /* character from fmt */
603 int n
, n2
; /* handy integer (short term usage) */
604 CHAR_T
*cp
; /* handy char pointer (short term usage) */
605 int flags
; /* flags as above */
606 int ret
; /* return value accumulator */
607 int width
; /* width from format (%8d), or 0 */
608 int prec
; /* precision from format; <0 for N/A */
609 CHAR_T sign
; /* sign prefix (' ', '+', '-', or \0) */
610 char thousands_sep
; /* locale specific thousands separator */
611 const char *grouping
; /* locale specific numeric grouping rules */
612 #ifndef NO_FLOATING_POINT
614 * We can decompose the printed representation of floating
615 * point numbers into several parts, some of which may be empty:
617 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
620 * A: 'sign' holds this value if present; '\0' otherwise
621 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
622 * C: cp points to the string MMMNNN. Leading and trailing
623 * zeros are not in the string and must be added.
624 * D: expchar holds this character; '\0' if no exponent, e.g. %f
625 * F: at least two digits for decimal, at least one digit for hex
627 char *decimal_point
; /* locale specific decimal point */
629 int signflag
; /* true if float is negative */
630 union { /* floating point arguments %[aAeEfFgG] */
634 char *dtoaend
; /* pointer to end of converted digits */
636 double _double
; /* double precision arguments %[eEfgG] */
637 char softsign
; /* temporary negative sign for floats */
639 char *dtoaresult
; /* buffer allocated by dtoa */
640 int expt
; /* integer value of exponent */
641 char expchar
; /* exponent character: [eEpP\0] */
642 int expsize
; /* character count for expstr */
643 int lead
; /* sig figs before decimal or group sep */
644 int ndig
; /* actual number of digits returned by dtoa */
645 CHAR_T expstr
[MAXEXPDIG
+2]; /* buffer for exponent string: e+ZZZ */
646 int nseps
; /* number of group separators with ' */
647 int nrepeats
; /* number of repeats of the last group */
649 u_long ulval
; /* integer arguments %[diouxX] */
650 uintmax_t ujval
; /* %j, %ll, %q, %t, %z integers */
651 int base
; /* base for [diouxX] conversion */
652 int dprec
; /* a copy of prec if [diouxX], 0 otherwise */
653 int realsz
; /* field size expanded by dprec, sign, etc */
654 int size
; /* size of converted field or string */
655 int prsize
; /* max size of printed field */
656 const char *xdigs
; /* digits for %[xX] conversion */
659 struct __siov
*iovp
; /* for PRINT macro */
660 struct __suio uio
; /* output information: summary */
661 struct __siov iov
[NIOV
];/* ... and individual io vectors */
665 CHAR_T buf
[BUF
]; /* buffer with space for digits of uintmax_t */
666 CHAR_T ox
[2]; /* space for 0x hex-prefix */
667 union arg
*argtable
; /* args, built due to positional arg */
668 union arg statargtable
[STATIC_ARG_TBL_SIZE
];
669 int nextarg
; /* 1-based argument index */
670 va_list orgap
; /* original argument pointer */
671 CHAR_T
*convbuf
; /* multibyte to wide conversion result */
674 * Choose PADSIZE to trade efficiency vs. size. If larger printf
675 * fields occur frequently, increase PADSIZE and make the initialisers
678 #define PADSIZE 16 /* pad chunk size */
679 static CHAR_T blanks
[PADSIZE
] =
680 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
681 static CHAR_T zeroes
[PADSIZE
] =
682 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
684 static const char xdigs_lower
[16] = "0123456789abcdef";
685 static const char xdigs_upper
[16] = "0123456789ABCDEF";
688 * BEWARE, these `goto error' on error, PRINT uses `n2' and
692 #define PRINT(ptr, len) do { \
693 for (n3 = 0; n3 < (len); n3++) \
694 __xfputwc((ptr)[n3], fp); \
695 } while (/*CONSTCOND*/0)
698 #define PRINT(ptr, len) do { \
699 iovp->iov_base = __UNCONST(ptr); \
700 iovp->iov_len = (len); \
701 uio.uio_resid += (len); \
703 if (++uio.uio_iovcnt >= NIOV) { \
704 if (__sprint(fp, &uio)) \
708 } while (/*CONSTCOND*/0)
709 #define FLUSH() do { \
710 if (uio.uio_resid && __sprint(fp, &uio)) \
712 uio.uio_iovcnt = 0; \
714 } while (/*CONSTCOND*/0)
717 #define PAD(howmany, with) do { \
718 if ((n = (howmany)) > 0) { \
719 while (n > PADSIZE) { \
720 PRINT(with, PADSIZE); \
725 } while (/*CONSTCOND*/0)
726 #define PRINTANDPAD(p, ep, len, with) do { \
732 PAD((len) - (n2 > 0 ? n2 : 0), (with)); \
733 } while(/*CONSTCOND*/0)
736 * Get the argument indexed by nextarg. If the argument table is
737 * built, use it to get the argument. If its not, get the next
738 * argument (and arguments must be gotten sequentially).
740 #define GETARG(type) \
741 ((/*CONSTCOND*/argtable != NULL) ? *((type*)(void*)(&argtable[nextarg++])) : \
742 (nextarg++, va_arg(ap, type)))
745 * To extend shorts properly, we need both signed and unsigned
746 * argument extraction methods.
749 (flags&LONGINT ? GETARG(long) : \
750 flags&SHORTINT ? (long)(short)GETARG(int) : \
751 flags&CHARINT ? (long)(signed char)GETARG(int) : \
754 (flags&LONGINT ? GETARG(u_long) : \
755 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
756 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
757 (u_long)GETARG(u_int))
758 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
760 (flags&INTMAXT ? GETARG(intmax_t) : \
761 flags&SIZET ? (intmax_t)GETARG(ssize_t) : \
762 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
763 (intmax_t)GETARG(long long))
765 (flags&INTMAXT ? GETARG(uintmax_t) : \
766 flags&SIZET ? (uintmax_t)GETARG(size_t) : \
767 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
768 (uintmax_t)GETARG(unsigned long long))
771 * Get * arguments, including the form *nn$. Preserve the nextarg
772 * that the argument can be gotten once the type is determined.
774 #define GETASTER(val) \
777 while (is_digit(*cp)) { \
778 n2 = 10 * n2 + to_digit(*cp); \
782 int hold = nextarg; \
783 if (argtable == NULL) { \
784 argtable = statargtable; \
785 if (__find_arguments(fmt0, orgap, &argtable) == -1) \
789 val = GETARG (int); \
793 val = GETARG (int); \
796 _DIAGASSERT(fp
!= NULL
);
797 _DIAGASSERT(fmt0
!= NULL
);
799 _SET_ORIENTATION(fp
, -1);
801 ndig
= -1; /* XXX gcc */
803 thousands_sep
= '\0';
805 #ifndef NO_FLOATING_POINT
806 decimal_point
= localeconv()->decimal_point
;
807 expsize
= 0; /* XXXGCC -Wuninitialized [sh3,m68000] */
810 /* sorry, f{w,}printf(read_only_file, L"") returns {W,}EOF, not 0 */
813 return (END_OF_FILE
);
816 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
817 if ((fp
->_flags
& (__SNBF
|__SWR
|__SRW
)) == (__SNBF
|__SWR
) &&
819 return (__sbprintf(fp
, fmt0
, ap
));
821 fmt
= (CHAR_T
*)__UNCONST(fmt0
);
826 uio
.uio_iov
= iovp
= iov
;
833 * Scan the format for conversions (`%' character).
836 const CHAR_T
*result
;
838 for (cp
= fmt
; (ch
= *fmt
) != '\0' && ch
!= '%'; fmt
++)
840 if ((n
= fmt
- cp
) != 0) {
841 if ((unsigned)ret
+ n
> INT_MAX
) {
850 fmt
++; /* skip over '%' */
860 nseps
= nrepeats
= 0;
866 reswitch
: switch (ch
) {
869 * ``If the space and + flags both appear, the space
870 * flag will be ignored.''
881 * ``A negative field width argument is taken as a
882 * - flag followed by a positive field width.''
884 * They don't exclude field widths read from args.
899 thousands_sep
= *(localeconv()->thousands_sep
);
900 grouping
= localeconv()->grouping
;
901 /* If the locale doesn't define the above, use sane
902 * defaults - otherwise silly things happen! */
903 if (thousands_sep
== 0)
905 if (!grouping
|| !*grouping
)
909 if ((ch
= *fmt
++) == '*') {
914 while (is_digit(ch
)) {
915 prec
= 10 * prec
+ to_digit(ch
);
921 * ``Note that 0 is taken as a flag, not as the
922 * beginning of a field width.''
927 case '1': case '2': case '3': case '4':
928 case '5': case '6': case '7': case '8': case '9':
931 n
= 10 * n
+ to_digit(ch
);
933 } while (is_digit(ch
));
936 if (argtable
== NULL
) {
937 argtable
= statargtable
;
938 if (__find_arguments(fmt0
, orgap
,
946 #ifndef NO_FLOATING_POINT
952 if (flags
& SHORTINT
) {
962 if (flags
& LONGINT
) {
969 flags
|= LLONGINT
; /* not necessarily */
982 if (flags
& LONGINT
) {
983 static const mbstate_t initial
;
988 mbseqlen
= wcrtomb(buf
,
989 (wchar_t)GETARG(wint_t), &mbs
);
990 if (mbseqlen
== (size_t)-1) {
991 fp
->_flags
|= __SERR
;
994 size
= (int)mbseqlen
;
1000 if (flags
& LONGINT
)
1001 *buf
= (wchar_t)GETARG(wint_t);
1003 *buf
= (wchar_t)btowc(GETARG(int));
1014 if (flags
& INTMAX_SIZE
) {
1016 if ((intmax_t)ujval
< 0) {
1022 if ((long)ulval
< 0) {
1029 #ifndef NO_FLOATING_POINT
1035 xdigs
= xdigs_lower
;
1039 xdigs
= xdigs_upper
;
1044 if (flags
& LONGDBL
) {
1045 fparg
.ldbl
= GETARG(long double);
1047 __hldtoa(fparg
.ldbl
, xdigs
, prec
,
1048 &expt
, &signflag
, &dtoaend
);
1050 fparg
.dbl
= GETARG(double);
1052 __hdtoa(fparg
.dbl
, xdigs
, prec
,
1053 &expt
, &signflag
, &dtoaend
);
1055 if (dtoaresult
== NULL
)
1059 prec
= dtoaend
- dtoaresult
;
1060 if (expt
== INT_MAX
)
1062 ndig
= dtoaend
- dtoaresult
;
1063 if (convbuf
!= NULL
)
1066 result
= convbuf
= __mbsconv(dtoaresult
, -1);
1069 result
= convbuf
= strdup(dtoaresult
);
1073 __freedtoa(dtoaresult
);
1078 if (prec
< 0) /* account for digit before decpt */
1089 expchar
= ch
- ('g' - 'e');
1095 if (flags
& LONGDBL
) {
1096 fparg
.ldbl
= GETARG(long double);
1098 __ldtoa(&fparg
.ldbl
, expchar
? 2 : 3, prec
,
1099 &expt
, &signflag
, &dtoaend
);
1101 fparg
.dbl
= GETARG(double);
1103 __dtoa(fparg
.dbl
, expchar
? 2 : 3, prec
,
1104 &expt
, &signflag
, &dtoaend
);
1108 if (dtoaresult
== NULL
)
1110 ndig
= dtoaend
- dtoaresult
;
1111 if (convbuf
!= NULL
)
1114 result
= convbuf
= __mbsconv(dtoaresult
, -1);
1117 result
= convbuf
= strdup(dtoaresult
);
1121 __freedtoa(dtoaresult
);
1125 if (expt
== INT_MAX
) { /* inf or nan */
1126 if (*result
== 'N') {
1127 result
= (ch
>= 'a') ? STRCONST("nan") :
1131 result
= (ch
>= 'a') ? STRCONST("inf") :
1146 } else if ((ch
== 'g' || ch
== 'G') && prec
== 0) {
1150 if (flags
& LONGDBL
) {
1151 _double
= (double) GETARG(long double);
1153 _double
= GETARG(double);
1156 /* do this before tricky precision changes */
1157 if (isinf(_double
)) {
1160 if (ch
== 'E' || ch
== 'F' || ch
== 'G')
1161 result
= STRCONST("INF");
1163 result
= STRCONST("inf");
1168 if (isnan(_double
)) {
1169 if (ch
== 'E' || ch
== 'F' || ch
== 'G')
1170 result
= STRCONST("NAN");
1172 result
= STRCONST("nan");
1179 dtoaresult
= cvt(_double
, prec
, flags
, &softsign
,
1181 if (dtoaresult
== NULL
)
1183 if (convbuf
!= NULL
)
1186 result
= convbuf
= __mbsconv(dtoaresult
, -1);
1189 result
= convbuf
= strdup(dtoaresult
);
1193 __freedtoa(dtoaresult
);
1198 if (ch
== 'g' || ch
== 'G') {
1199 if (expt
> -4 && expt
<= prec
) {
1200 /* Make %[gG] smell like %[fF] */
1210 * Make %[gG] smell like %[eE], but
1211 * trim trailing zeroes if no # flag.
1218 expsize
= exponent(expstr
, expt
- 1, expchar
);
1219 size
= expsize
+ prec
;
1220 if (prec
> 1 || flags
& ALT
)
1223 /* space for digits before decimal point */
1228 /* space for decimal pt and following digits */
1229 if (prec
|| flags
& ALT
)
1231 if (grouping
&& expt
> 0) {
1232 /* space for thousands' grouping */
1233 nseps
= nrepeats
= 0;
1235 while (*grouping
!= CHAR_MAX
) {
1236 if (lead
<= *grouping
)
1239 if (*(grouping
+1)) {
1245 size
+= nseps
+ nrepeats
;
1250 #endif /* !NO_FLOATING_POINT */
1253 * Assignment-like behavior is specified if the
1254 * value overflows or is otherwise unrepresentable.
1255 * C99 says to use `signed char' for %hhn conversions.
1257 if (flags
& LLONGINT
)
1258 *GETARG(long long *) = ret
;
1259 else if (flags
& SIZET
)
1260 *GETARG(ssize_t
*) = (ssize_t
)ret
;
1261 else if (flags
& PTRDIFFT
)
1262 *GETARG(ptrdiff_t *) = ret
;
1263 else if (flags
& INTMAXT
)
1264 *GETARG(intmax_t *) = ret
;
1265 else if (flags
& LONGINT
)
1266 *GETARG(long *) = ret
;
1267 else if (flags
& SHORTINT
)
1268 *GETARG(short *) = ret
;
1269 else if (flags
& CHARINT
)
1270 *GETARG(signed char *) = ret
;
1272 *GETARG(int *) = ret
;
1273 continue; /* no output */
1278 if (flags
& INTMAX_SIZE
)
1286 * ``The argument shall be a pointer to void. The
1287 * value of the pointer is converted to a sequence
1288 * of printable characters, in an implementation-
1292 ujval
= (uintmax_t)(uintptr_t)GETARG(void *);
1294 xdigs
= xdigs_lower
;
1295 flags
= flags
| INTMAXT
;
1302 if ((flags
& LONGINT
) != MULTI
) {
1303 if ((result
= GETARG(CHAR_T
*)) == NULL
)
1304 result
= STRCONST("(null)");
1308 if (convbuf
!= NULL
)
1310 if ((mc
= GETARG(MCHAR_T
*)) == NULL
)
1311 result
= STRCONST("(null)");
1313 convbuf
= SCONV(mc
, prec
);
1314 if (convbuf
== NULL
) {
1315 fp
->_flags
|= __SERR
;
1324 * can't use STRLEN; can only look for the
1325 * NUL in the first `prec' characters, and
1326 * STRLEN() will go further.
1328 CHAR_T
*p
= MEMCHR(result
, 0, (size_t)prec
);
1337 size
= STRLEN(result
);
1344 if (flags
& INTMAX_SIZE
)
1351 xdigs
= xdigs_upper
;
1354 xdigs
= xdigs_lower
;
1356 if (flags
& INTMAX_SIZE
)
1361 /* leading 0x/X only if non-zero */
1363 (flags
& INTMAX_SIZE
? ujval
!= 0 : ulval
!= 0))
1367 /* unsigned conversions */
1368 nosign
: sign
= '\0';
1370 * ``... diouXx conversions ... if a precision is
1371 * specified, the 0 flag will be ignored.''
1374 number
: if ((dprec
= prec
) >= 0)
1378 * ``The result of converting a zero value with an
1379 * explicit precision of zero is no characters.''
1382 * ``The C Standard is clear enough as is. The call
1383 * printf("%#.0o", 0) should print 0.''
1384 * -- Defect Report #151
1386 result
= cp
= buf
+ BUF
;
1387 if (flags
& INTMAX_SIZE
) {
1388 if (ujval
!= 0 || prec
!= 0 ||
1389 (flags
& ALT
&& base
== 8))
1390 result
= __ujtoa(ujval
, cp
, base
,
1392 flags
& GROUPING
, thousands_sep
,
1395 if (ulval
!= 0 || prec
!= 0 ||
1396 (flags
& ALT
&& base
== 8))
1397 result
= __ultoa(ulval
, cp
, base
,
1399 flags
& GROUPING
, thousands_sep
,
1402 size
= buf
+ BUF
- result
;
1403 if (size
> BUF
) /* should never happen */
1406 default: /* "%?" prints ?, unless ? is NUL */
1409 /* pretend it was %c with argument ch */
1418 * All reasonable formats wind up here. At this point, `result'
1419 * points to a string which (if not flags&LADJUST) should be
1420 * padded out to `width' places. If flags&ZEROPAD, it should
1421 * first be prefixed by any sign or other prefix; otherwise,
1422 * it should be blank padded before the prefix is emitted.
1423 * After any left-hand padding and prefixing, emit zeroes
1424 * required by a decimal [diouxX] precision, then print the
1425 * string proper, then emit zeroes required by any leftover
1426 * floating precision; finally, if LADJUST, pad with blanks.
1428 * Compute actual size, so we know how much to pad.
1429 * size excludes decimal prec; realsz includes it.
1431 realsz
= dprec
> size
? dprec
: size
;
1437 prsize
= width
> realsz
? width
: realsz
;
1438 if ((unsigned)ret
+ prsize
> INT_MAX
) {
1443 /* right-adjusting blank padding */
1444 if ((flags
& (LADJUST
|ZEROPAD
)) == 0)
1445 PAD(width
- realsz
, blanks
);
1451 if (ox
[1]) { /* ox[1] is either x, X, or \0 */
1456 /* right-adjusting zero padding */
1457 if ((flags
& (LADJUST
|ZEROPAD
)) == ZEROPAD
)
1458 PAD(width
- realsz
, zeroes
);
1460 /* leading zeroes from decimal precision */
1461 PAD(dprec
- size
, zeroes
);
1463 /* the string or number proper */
1464 #ifndef NO_FLOATING_POINT
1465 if ((flags
& FPT
) == 0) {
1466 PRINT(result
, size
);
1467 } else { /* glue together f_p fragments */
1468 if (!expchar
) { /* %[fF] or sufficiently short %[gG] */
1471 if (prec
|| flags
& ALT
)
1472 PRINT(decimal_point
, 1);
1474 /* already handled initial 0's */
1477 PRINTANDPAD(result
, convbuf
+ ndig
,
1481 while (nseps
>0 || nrepeats
>0) {
1488 PRINT(&thousands_sep
,
1493 result
+= *grouping
;
1495 if (result
> convbuf
+ ndig
)
1496 result
= convbuf
+ ndig
;
1498 if (prec
|| flags
& ALT
) {
1499 buf
[0] = *decimal_point
;
1503 PRINTANDPAD(result
, convbuf
+ ndig
, prec
,
1505 } else { /* %[eE] or sufficiently long %[gG] */
1506 if (prec
> 1 || flags
& ALT
) {
1508 buf
[1] = *decimal_point
;
1510 PRINT(result
, ndig
-1);
1511 PAD(prec
- ndig
, zeroes
);
1514 PRINT(expstr
, expsize
);
1518 PRINT(result
, size
);
1520 /* left-adjusting padding (always blank) */
1521 if (flags
& LADJUST
)
1522 PAD(width
- realsz
, blanks
);
1524 /* finally, adjust ret */
1532 if (convbuf
!= NULL
)
1536 if ((argtable
!= NULL
) && (argtable
!= statargtable
))
1547 * Find all arguments when a positional parameter is encountered. Returns a
1548 * table, indexed by argument number, of pointers to each arguments. The
1549 * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1550 * It will be replaces with a malloc-ed one if it overflows.
1553 __find_arguments(const CHAR_T
*fmt0
, va_list ap
, union arg
**argtable
)
1555 CHAR_T
*fmt
; /* format string */
1556 int ch
; /* character from fmt */
1557 int n
, n2
; /* handy integer (short term usage) */
1558 CHAR_T
*cp
; /* handy char pointer (short term usage) */
1559 int flags
; /* flags as above */
1560 enum typeid *typetable
; /* table of types */
1561 enum typeid stattypetable
[STATIC_ARG_TBL_SIZE
];
1562 int tablesize
; /* current size of type table */
1563 int tablemax
; /* largest used index in table */
1564 int nextarg
; /* 1-based argument index */
1567 * Add an argument type to the table, expanding if necessary.
1569 #define ADDTYPE(type) \
1571 if (nextarg >= tablesize) \
1572 if (__grow_type_table(nextarg, &typetable, \
1573 &tablesize) == -1) \
1575 if (nextarg > tablemax) \
1576 tablemax = nextarg; \
1577 typetable[nextarg++] = type; \
1578 } while (/*CONSTCOND*/0)
1582 if (flags & INTMAXT) \
1583 ADDTYPE(T_INTMAXT); \
1584 else if (flags & SIZET) \
1585 ADDTYPE(T_SSIZET); \
1586 else if (flags & PTRDIFFT) \
1587 ADDTYPE(T_PTRDIFFT); \
1588 else if (flags & LLONGINT) \
1590 else if (flags & LONGINT) \
1594 } while (/*CONSTCOND*/0)
1598 if (flags & INTMAXT) \
1599 ADDTYPE(T_UINTMAXT); \
1600 else if (flags & SIZET) \
1602 else if (flags & PTRDIFFT) \
1603 ADDTYPE(T_PTRDIFFT); \
1604 else if (flags & LLONGINT) \
1605 ADDTYPE(T_U_LLONG); \
1606 else if (flags & LONGINT) \
1607 ADDTYPE(T_U_LONG); \
1610 } while (/*CONSTCOND*/0)
1612 * Add * arguments to the type array.
1614 #define ADDASTER() \
1617 while (is_digit(*cp)) { \
1618 n2 = 10 * n2 + to_digit(*cp); \
1622 int hold = nextarg; \
1630 fmt
= (CHAR_T
*)__UNCONST(fmt0
);
1631 typetable
= stattypetable
;
1632 tablesize
= STATIC_ARG_TBL_SIZE
;
1635 for (n
= 0; n
< STATIC_ARG_TBL_SIZE
; n
++)
1636 typetable
[n
] = T_UNUSED
;
1639 * Scan the format for conversions (`%' character).
1642 for (cp
= fmt
; (ch
= *fmt
) != '\0' && ch
!= '%'; fmt
++)
1646 fmt
++; /* skip over '%' */
1651 reswitch
: switch (ch
) {
1663 if ((ch
= *fmt
++) == '*') {
1667 while (is_digit(ch
)) {
1673 case '1': case '2': case '3': case '4':
1674 case '5': case '6': case '7': case '8': case '9':
1677 n
= 10 * n
+ to_digit(ch
);
1679 } while (is_digit(ch
));
1685 #ifndef NO_FLOATING_POINT
1691 if (flags
& SHORTINT
) {
1701 if (flags
& LONGINT
) {
1708 flags
|= LLONGINT
; /* not necessarily */
1720 if (flags
& LONGINT
)
1732 #ifndef NO_FLOATING_POINT
1740 if (flags
& LONGDBL
)
1741 ADDTYPE(T_LONG_DOUBLE
);
1745 #endif /* !NO_FLOATING_POINT */
1747 if (flags
& INTMAXT
)
1748 ADDTYPE(TP_INTMAXT
);
1749 else if (flags
& PTRDIFFT
)
1750 ADDTYPE(TP_PTRDIFFT
);
1751 else if (flags
& SIZET
)
1753 else if (flags
& LLONGINT
)
1755 else if (flags
& LONGINT
)
1757 else if (flags
& SHORTINT
)
1759 else if (flags
& CHARINT
)
1763 continue; /* no output */
1777 if (flags
& LONGINT
)
1790 default: /* "%?" prints ?, unless ? is NUL */
1798 * Build the argument table.
1800 if (tablemax
>= STATIC_ARG_TBL_SIZE
) {
1801 *argtable
= (union arg
*)
1802 malloc (sizeof (union arg
) * (tablemax
+ 1));
1803 if (*argtable
== NULL
)
1807 (*argtable
) [0].intarg
= 0;
1808 for (n
= 1; n
<= tablemax
; n
++) {
1809 switch (typetable
[n
]) {
1810 case T_UNUSED
: /* whoops! */
1811 (*argtable
) [n
].intarg
= va_arg (ap
, int);
1814 (*argtable
) [n
].pschararg
= va_arg (ap
, signed char *);
1817 (*argtable
) [n
].pshortarg
= va_arg (ap
, short *);
1820 (*argtable
) [n
].intarg
= va_arg (ap
, int);
1823 (*argtable
) [n
].uintarg
= va_arg (ap
, unsigned int);
1826 (*argtable
) [n
].pintarg
= va_arg (ap
, int *);
1829 (*argtable
) [n
].longarg
= va_arg (ap
, long);
1832 (*argtable
) [n
].ulongarg
= va_arg (ap
, unsigned long);
1835 (*argtable
) [n
].plongarg
= va_arg (ap
, long *);
1838 (*argtable
) [n
].longlongarg
= va_arg (ap
, long long);
1841 (*argtable
) [n
].ulonglongarg
= va_arg (ap
, unsigned long long);
1844 (*argtable
) [n
].plonglongarg
= va_arg (ap
, long long *);
1847 (*argtable
) [n
].ptrdiffarg
= va_arg (ap
, ptrdiff_t);
1850 (*argtable
) [n
].pptrdiffarg
= va_arg (ap
, ptrdiff_t *);
1853 (*argtable
) [n
].ssizearg
= va_arg (ap
, ssize_t
);
1856 (*argtable
) [n
].sizearg
= va_arg (ap
, size_t);
1859 (*argtable
) [n
].psizearg
= va_arg (ap
, size_t *);
1862 (*argtable
) [n
].intmaxarg
= va_arg (ap
, intmax_t);
1865 (*argtable
) [n
].uintmaxarg
= va_arg (ap
, uintmax_t);
1868 (*argtable
) [n
].pintmaxarg
= va_arg (ap
, intmax_t *);
1871 #ifndef NO_FLOATING_POINT
1872 (*argtable
) [n
].doublearg
= va_arg (ap
, double);
1876 #ifndef NO_FLOATING_POINT
1877 (*argtable
) [n
].longdoublearg
= va_arg (ap
, long double);
1881 (*argtable
) [n
].pchararg
= va_arg (ap
, char *);
1884 (*argtable
) [n
].pvoidarg
= va_arg (ap
, void *);
1887 (*argtable
) [n
].wintarg
= va_arg (ap
, wint_t);
1890 (*argtable
) [n
].pwchararg
= va_arg (ap
, wchar_t *);
1895 if ((typetable
!= NULL
) && (typetable
!= stattypetable
))
1901 * Increase the size of the type table.
1904 __grow_type_table (int nextarg
, enum typeid **typetable
, int *tablesize
)
1906 enum typeid *const oldtable
= *typetable
;
1907 const int oldsize
= *tablesize
;
1908 enum typeid *newtable
;
1909 int n
, newsize
= oldsize
* 2;
1911 if (newsize
< nextarg
+ 1)
1912 newsize
= nextarg
+ 1;
1913 if (oldsize
== STATIC_ARG_TBL_SIZE
) {
1914 if ((newtable
= malloc(newsize
* sizeof(enum typeid))) == NULL
)
1916 memcpy(newtable
, oldtable
, oldsize
* sizeof(enum typeid));
1918 newtable
= realloc(oldtable
, newsize
* sizeof(enum typeid));
1919 if (newtable
== NULL
) {
1924 for (n
= oldsize
; n
< newsize
; n
++)
1925 newtable
[n
] = T_UNUSED
;
1927 *typetable
= newtable
;
1928 *tablesize
= newsize
;
1933 #ifndef NO_FLOATING_POINT
1936 cvt(double value
, int ndigits
, int flags
, char *sign
, int *decpt
, int ch
,
1940 char *digits
, *bp
, *rve
;
1942 _DIAGASSERT(decpt
!= NULL
);
1943 _DIAGASSERT(length
!= NULL
);
1944 _DIAGASSERT(sign
!= NULL
);
1947 mode
= 3; /* ndigits after the decimal point */
1949 /* To obtain ndigits after the decimal point for the 'e'
1950 * and 'E' formats, round to ndigits + 1 significant
1953 if (ch
== 'e' || ch
== 'E') {
1956 mode
= 2; /* ndigits significant digits */
1959 digits
= __dtoa(value
, mode
, ndigits
, decpt
, &dsgn
, &rve
);
1967 if ((ch
!= 'g' && ch
!= 'G') || flags
& ALT
) { /* Print trailing zeros */
1968 bp
= digits
+ ndigits
;
1970 if (*digits
== '0' && value
)
1971 *decpt
= -ndigits
+ 1;
1974 if (value
== 0) /* kludge for __dtoa irregularity */
1979 *length
= rve
- digits
;
1985 exponent(CHAR_T
*p0
, int expo
, int fmtch
)
1988 CHAR_T expbuf
[MAXEXPDIG
];
1998 t
= expbuf
+ MAXEXPDIG
;
2001 *--t
= to_char(expo
% 10);
2002 } while ((expo
/= 10) > 9);
2003 *--t
= to_char(expo
);
2004 for (; t
< expbuf
+ MAXEXPDIG
; *p
++ = *t
++);
2008 * Exponents for decimal floating point conversions
2009 * (%[eEgG]) must be at least two characters long,
2010 * whereas exponents for hexadecimal conversions can
2011 * be only one character long.
2013 if (fmtch
== 'e' || fmtch
== 'E')
2015 *p
++ = to_char(expo
);
2019 #endif /* !NO_FLOATING_POINT */