2 * Copyright (c) 1990, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * $FreeBSD: src/lib/libc/stdio/vfwprintf.c,v 1.24 2005/04/16 22:36:51 das Exp $
37 * $NetBSD: vfwprintf.c,v 1.3 2005/06/15 09:31:27 he Exp $
38 * $DragonFly: src/lib/libc/stdio/vfwprintf.c,v 1.3 2006/03/02 18:05:30 joerg Exp $
42 * Actual wprintf innards.
44 * Avoid making gratuitous changes to this source file; it should be kept
45 * as close as possible to vfprintf.c for ease of maintenance.
48 #include "namespace.h"
49 #include <sys/types.h>
65 #include "un-namespace.h"
67 #include "libc_private.h"
69 #include "priv_stdio.h"
76 unsigned long ulongarg;
77 long long longlongarg;
78 unsigned long long ulonglongarg;
85 signed char *pschararg;
90 ptrdiff_t *pptrdiffarg;
93 #ifndef NO_FLOATING_POINT
95 long double longdoublearg;
102 * Type ids for argument type table.
105 T_UNUSED, TP_SHORT, T_INT, T_U_INT, TP_INT,
106 T_LONG, T_U_LONG, TP_LONG, T_LLONG, T_U_LLONG, TP_LLONG,
107 T_PTRDIFFT, TP_PTRDIFFT, T_SIZET, TP_SIZET,
108 T_INTMAXT, T_UINTMAXT, TP_INTMAXT, TP_VOID, TP_CHAR, TP_SCHAR,
109 T_DOUBLE, T_LONG_DOUBLE, T_WINT, TP_WCHAR
112 static int __sbprintf(FILE *, const wchar_t *, va_list);
113 static wint_t __xfputwc(wchar_t, FILE *);
114 static wchar_t *__ujtoa(uintmax_t, wchar_t *, int, int, const char *, int,
116 static wchar_t *__ultoa(u_long, wchar_t *, int, int, const char *, int,
118 static wchar_t *__mbsconv(char *, int);
119 static void __find_arguments(const wchar_t *, va_list, union arg **);
120 static void __grow_type_table(int, enum typeid **, int *);
123 * Helper function for `fprintf to unbuffered unix file': creates a
124 * temporary buffer. We only work on write-only files; this avoids
125 * worries about ungetc buffers and so forth.
128 __sbprintf(FILE *fp, const wchar_t *fmt, va_list ap)
132 unsigned char buf[BUFSIZ];
134 /* copy the important variables */
135 fake.pub._flags = fp->pub._flags & ~__SNBF;
136 fake.pub._fileno = fp->pub._fileno;
137 fake._cookie = fp->_cookie;
138 fake._write = fp->_write;
141 fake.fl_mutex = fp->fl_mutex;
142 fake.fl_owner = fp->fl_owner;
143 fake.fl_count = fp->fl_count;
144 memset(WCIO_GET(&fake), 0, sizeof(struct wchar_io_data));
146 /* set up the buffer */
147 fake._bf._base = fake.pub._p = buf;
148 fake._bf._size = fake.pub._w = sizeof(buf);
149 fake.pub._lbfsize = 0; /* not actually used, but Just In Case */
151 /* do the work, then copy any error status */
152 ret = __vfwprintf_unlocked(&fake, fmt, ap);
153 if (ret >= 0 && __fflush(&fake))
155 if (fake.pub._flags & __SERR)
156 fp->pub._flags |= __SERR;
161 * Like __fputwc, but handles fake string (__SSTR) files properly.
162 * File must already be locked.
165 __xfputwc(wchar_t wc, FILE *fp)
167 static const mbstate_t initial;
169 char buf[MB_LEN_MAX];
174 if ((fp->pub._flags & __SSTR) == 0)
175 return (__fputwc_unlock(wc, fp));
178 if ((len = wcrtomb(buf, wc, &mbs)) == (size_t)-1) {
179 fp->pub._flags |= __SERR;
187 return (__sfvwrite(fp, &uio) != EOF ? (wint_t)wc : WEOF);
191 * Macros for converting digits to letters and vice versa
193 #define to_digit(c) ((c) - '0')
194 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
195 #define to_char(n) (wchar_t)((n) + '0')
198 * Convert an unsigned long to ASCII for printf purposes, returning
199 * a pointer to the first character of the string representation.
200 * Octal numbers can be forced to have a leading zero; hex numbers
201 * use the given digits.
204 __ultoa(u_long val, wchar_t *endp, int base, int octzero, const char *xdigs,
205 int needgrp, char thousep, const char *grp)
212 * Handle the three cases separately, in the hope of getting
213 * better/faster code.
217 if (val < 10) { /* many numbers are 1 digit */
218 *--cp = to_char(val);
223 * On many machines, unsigned arithmetic is harder than
224 * signed arithmetic, so we do at most one unsigned mod and
225 * divide; this is sufficient to reduce the range of
226 * the incoming value to where signed arithmetic works.
228 if (val > LONG_MAX) {
229 *--cp = to_char(val % 10);
235 *--cp = to_char(sval % 10);
238 * If (*grp == CHAR_MAX) then no more grouping
239 * should be performed.
241 if (needgrp && ndig == *grp && *grp != CHAR_MAX &&
246 * If (*(grp+1) == '\0') then we have to
247 * use *grp character (last grouping rule)
250 if (*(grp+1) != '\0')
259 *--cp = to_char(val & 7);
262 if (octzero && *cp != '0')
268 *--cp = xdigs[(size_t)val & 15];
279 /* Identical to __ultoa, but for intmax_t. */
281 __ujtoa(uintmax_t val, wchar_t *endp, int base, int octzero,
282 const char *xdigs, int needgrp, char thousep, const char *grp)
288 /* quick test for small values; __ultoa is typically much faster */
289 /* (perhaps instead we should run until small, then call __ultoa?) */
290 if (val <= ULONG_MAX)
291 return (__ultoa((u_long)val, endp, base, octzero, xdigs,
292 needgrp, thousep, grp));
296 *--cp = to_char(val % 10);
300 if (val > INTMAX_MAX) {
301 *--cp = to_char(val % 10);
307 *--cp = to_char(sval % 10);
310 * If (*grp == CHAR_MAX) then no more grouping
311 * should be performed.
313 if (needgrp && *grp != CHAR_MAX && ndig == *grp &&
318 * If (*(grp+1) == '\0') then we have to
319 * use *grp character (last grouping rule)
322 if (*(grp+1) != '\0')
331 *--cp = to_char(val & 7);
334 if (octzero && *cp != '0')
340 *--cp = xdigs[(size_t)val & 15];
352 * Convert a multibyte character string argument for the %s format to a wide
353 * string representation. ``prec'' specifies the maximum number of bytes
354 * to output. If ``prec'' is greater than or equal to zero, we can't assume
355 * that the multibyte char. string ends in a null character.
358 __mbsconv(char *mbsarg, int prec)
360 static const mbstate_t initial;
362 wchar_t *convbuf, *wcp;
364 size_t insize, nchars, nconv;
370 * Supplied argument is a multibyte string; convert it to wide
375 * String is not guaranteed to be NUL-terminated. Find the
376 * number of characters to print.
379 insize = nchars = nconv = 0;
381 while (nchars != (size_t)prec) {
382 nconv = mbrlen(p, MB_CUR_MAX, &mbs);
383 if (nconv == 0 || nconv == (size_t)-1 ||
390 if (nconv == (size_t)-1 || nconv == (size_t)-2)
393 insize = strlen(mbsarg);
396 * Allocate buffer for the result and perform the conversion,
397 * converting at most `size' bytes of the input multibyte string to
398 * wide characters for printing.
400 convbuf = malloc((insize + 1) * sizeof(*convbuf));
407 while (insize != 0) {
408 nconv = mbrtowc(wcp, p, insize, &mbs);
409 if (nconv == 0 || nconv == (size_t)-1 || nconv == (size_t)-2)
415 if (nconv == (size_t)-1 || nconv == (size_t)-2) {
428 vfwprintf(FILE * __restrict fp, const wchar_t * __restrict fmt0, va_list ap)
433 ret = __vfwprintf_unlocked(fp, fmt0, ap);
438 #ifndef NO_FLOATING_POINT
441 #define freedtoa __freedtoa
449 static int exponent(wchar_t *, int, wchar_t);
450 static wchar_t *cvt(double, int, int, char *, int *, int, int *, char **);
452 #endif /* !NO_FLOATING_POINT */
455 * The size of the buffer we use as scratch space for integer
456 * conversions, among other things. Technically, we would need the
457 * most space for base 10 conversions with thousands' grouping
458 * characters between each pair of digits. 100 bytes is a
459 * conservative overestimate even for a 128-bit uintmax_t.
463 #define STATIC_ARG_TBL_SIZE 8 /* Size of static argument table. */
466 * Flags used during conversion.
468 #define ALT 0x001 /* alternate form */
469 #define LADJUST 0x004 /* left adjustment */
470 #define LONGDBL 0x008 /* long double */
471 #define LONGINT 0x010 /* long integer */
472 #define LLONGINT 0x020 /* quad_t integer */
473 #define SHORTINT 0x040 /* short integer */
474 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
475 #define FPT 0x100 /* Floating point number */
476 #define GROUPING 0x200 /* use grouping ("'" flag) */
477 /* C99 additional size modifiers: */
478 #define SIZET 0x400 /* size_t */
479 #define PTRDIFFT 0x800 /* ptrdiff_t */
480 #define INTMAXT 0x1000 /* intmax_t */
481 #define CHARINT 0x2000 /* print char using int format */
484 * Non-MT-safe version
487 __vfwprintf_unlocked(FILE *fp, const wchar_t *fmt0, va_list ap)
489 wchar_t *fmt; /* format string */
490 wchar_t ch; /* character from fmt */
491 int n, n2, n3; /* handy integer (short term usage) */
492 wchar_t *cp; /* handy char pointer (short term usage) */
493 int flags; /* flags as above */
494 int ret; /* return value accumulator */
495 int width; /* width from format (%8d), or 0 */
496 int prec; /* precision from format; <0 for N/A */
497 wchar_t sign; /* sign prefix (' ', '+', '-', or \0) */
498 char thousands_sep; /* locale specific thousands separator */
499 const char *grouping; /* locale specific numeric grouping rules */
500 #ifndef NO_FLOATING_POINT
502 * We can decompose the printed representation of floating
503 * point numbers into several parts, some of which may be empty:
505 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
508 * A: 'sign' holds this value if present; '\0' otherwise
509 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
510 * C: cp points to the string MMMNNN. Leading and trailing
511 * zeros are not in the string and must be added.
512 * D: expchar holds this character; '\0' if no exponent, e.g. %f
513 * F: at least two digits for decimal, at least one digit for hex
515 const char *decimal_point; /* locale specific decimal point */
517 int signflag; /* true if float is negative */
518 union { /* floating point arguments %[aAeEfFgG] */
522 char *dtoaend; /* pointer to end of converted digits */
524 double _double; /* double precision arguments %[eEfgG] */
525 char softsign; /* temporary negative sign for floats */
527 int expt; /* integer value of exponent */
528 char expchar; /* exponent character: [eEpP\0] */
529 int expsize; /* character count for expstr */
530 char *dtoaresult; /* buffer allocated by dtoa */
531 int lead; /* sig figs before decimal or group sep */
532 int ndig; /* actual number of digits returned by dtoa */
533 wchar_t expstr[MAXEXPDIG+2]; /* buffer for exponent string: e+ZZZ */
534 int nseps; /* number of group separators with ' */
535 int nrepeats; /* number of repeats of the last group */
537 u_long ulval; /* integer arguments %[diouxX] */
538 uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */
539 int base; /* base for [diouxX] conversion */
540 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
541 int realsz; /* field size expanded by dprec, sign, etc */
542 int size; /* size of converted field or string */
543 int prsize; /* max size of printed field */
544 const char *xdigs; /* digits for [xX] conversion */
545 wchar_t buf[BUF]; /* buffer with space for digits of uintmax_t */
546 wchar_t ox[2]; /* space for 0x hex-prefix */
547 union arg *argtable; /* args, built due to positional arg */
548 union arg statargtable [STATIC_ARG_TBL_SIZE];
549 int nextarg; /* 1-based argument index */
550 va_list orgap; /* original argument pointer */
551 wchar_t *convbuf; /* multibyte to wide conversion result */
554 * Choose PADSIZE to trade efficiency vs. size. If larger printf
555 * fields occur frequently, increase PADSIZE and make the initialisers
558 #define PADSIZE 16 /* pad chunk size */
559 static wchar_t blanks[PADSIZE] =
560 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
561 static wchar_t zeroes[PADSIZE] =
562 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
564 static const char xdigs_lower[16] = "0123456789abcdef";
565 static const char xdigs_upper[16] = "0123456789ABCDEF";
568 * BEWARE, these `goto error' on error, PRINT uses `n2' and
571 #define PRINT(ptr, len) do { \
572 for (n3 = 0; n3 < (len); n3++) \
573 __xfputwc((ptr)[n3], fp); \
574 } while (/*CONSTCOND*/0)
575 #define PAD(howmany, with) do { \
576 if ((n = (howmany)) > 0) { \
577 while (n > PADSIZE) { \
578 PRINT(with, PADSIZE); \
583 } while (/*CONSTCOND*/0)
584 #define PRINTANDPAD(p, ep, len, with) do { \
590 PAD((len) - (n2 > 0 ? n2 : 0), (with)); \
591 } while(/*CONSTCOND*/0)
594 * Get the argument indexed by nextarg. If the argument table is
595 * built, use it to get the argument. If its not, get the next
596 * argument (and arguments must be gotten sequentially).
598 #define GETARG(type) \
599 ((/*CONSTCOND*/argtable != NULL) ? *((type*)(void*)(&argtable[nextarg++])) : \
600 (nextarg++, va_arg(ap, type)))
603 * To extend shorts properly, we need both signed and unsigned
604 * argument extraction methods.
607 (flags&LONGINT ? GETARG(long) : \
608 flags&SHORTINT ? (long)(short)GETARG(int) : \
609 flags&CHARINT ? (long)(signed char)GETARG(int) : \
612 (flags&LONGINT ? GETARG(u_long) : \
613 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
614 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
615 (u_long)GETARG(u_int))
616 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
618 (flags&INTMAXT ? GETARG(intmax_t) : \
619 flags&SIZET ? (intmax_t)GETARG(size_t) : \
620 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
621 (intmax_t)GETARG(quad_t))
623 (flags&INTMAXT ? GETARG(uintmax_t) : \
624 flags&SIZET ? (uintmax_t)GETARG(size_t) : \
625 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
626 (uintmax_t)GETARG(u_quad_t))
629 * Get * arguments, including the form *nn$. Preserve the nextarg
630 * that the argument can be gotten once the type is determined.
632 #define GETASTER(val) \
635 while (is_digit(*cp)) { \
636 n2 = 10 * n2 + to_digit(*cp); \
640 int hold = nextarg; \
641 if (argtable == NULL) { \
642 argtable = statargtable; \
643 __find_arguments (fmt0, orgap, &argtable); \
646 val = GETARG (int); \
650 val = GETARG (int); \
654 thousands_sep = '\0';
656 #ifndef NO_FLOATING_POINT
658 decimal_point = localeconv()->decimal_point;
659 expsize = 0; /* XXXGCC -Wuninitialized [sh3,m68000] */
662 /* sorry, fwprintf(read_only_file, L"") returns WEOF, not 0 */
668 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
669 if ((fp->pub._flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
670 fp->pub._fileno >= 0)
671 return (__sbprintf(fp, fmt0, ap));
673 fmt = __DECONST(wchar_t *, fmt0);
680 * Scan the format for conversions (`%' character).
683 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
685 if ((n = fmt - cp) != 0) {
686 if ((unsigned)ret + n > INT_MAX) {
695 fmt++; /* skip over '%' */
705 nseps = nrepeats = 0;
711 reswitch: switch (ch) {
714 * ``If the space and + flags both appear, the space
715 * flag will be ignored.''
726 * ``A negative field width argument is taken as a
727 * - flag followed by a positive field width.''
729 * They don't exclude field widths read from args.
744 thousands_sep = *(localeconv()->thousands_sep);
745 grouping = localeconv()->grouping;
748 if ((ch = *fmt++) == '*') {
753 while (is_digit(ch)) {
754 prec = 10 * prec + to_digit(ch);
760 * ``Note that 0 is taken as a flag, not as the
761 * beginning of a field width.''
766 case '1': case '2': case '3': case '4':
767 case '5': case '6': case '7': case '8': case '9':
770 n = 10 * n + to_digit(ch);
772 } while (is_digit(ch));
775 if (argtable == NULL) {
776 argtable = statargtable;
777 __find_arguments (fmt0, orgap,
784 #ifndef NO_FLOATING_POINT
790 if (flags & SHORTINT) {
800 if (flags & LONGINT) {
807 flags |= LLONGINT; /* not necessarily */
820 *(cp = buf) = (wchar_t)GETARG(wint_t);
822 *(cp = buf) = (wchar_t)btowc(GETARG(int));
831 if (flags & INTMAX_SIZE) {
833 if ((intmax_t)ujval < 0) {
839 if ((long)ulval < 0) {
846 #ifndef NO_FLOATING_POINT
861 if (flags & LONGDBL) {
862 fparg.ldbl = GETARG(long double);
864 __hldtoa(fparg.ldbl, xdigs, prec,
865 &expt, &signflag, &dtoaend);
867 fparg.dbl = GETARG(double);
869 __hdtoa(fparg.dbl, xdigs, prec,
870 &expt, &signflag, &dtoaend);
874 prec = dtoaend - dtoaresult;
879 ndig = dtoaend - dtoaresult;
880 cp = convbuf = __mbsconv(dtoaresult, -1);
881 freedtoa(dtoaresult);
886 if (prec < 0) /* account for digit before decpt */
897 expchar = ch - ('g' - 'e');
905 if (flags & LONGDBL) {
906 fparg.ldbl = GETARG(long double);
908 __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
909 &expt, &signflag, &dtoaend);
911 fparg.dbl = GETARG(double);
913 dtoa(fparg.dbl, expchar ? 2 : 3, prec,
914 &expt, &signflag, &dtoaend);
918 ndig = dtoaend - dtoaresult;
919 cp = convbuf = __mbsconv(dtoaresult, -1);
920 freedtoa(dtoaresult);
924 if (expt == INT_MAX) { /* inf or nan */
926 cp = (ch >= 'a') ? L"nan" : L"NAN";
929 cp = (ch >= 'a') ? L"inf" : L"INF";
942 } else if ((ch == 'g' || ch == 'G') && prec == 0) {
946 if (flags & LONGDBL) {
947 _double = (double) GETARG(long double);
949 _double = GETARG(double);
952 /* do this before tricky precision changes */
953 if (isinf(_double)) {
956 if (ch == 'E' || ch == 'F' || ch == 'G')
963 if (isnan(_double)) {
964 if (ch == 'E' || ch == 'F' || ch == 'G')
973 if (dtoaresult != NULL) {
977 cp = cvt(_double, prec, flags, &softsign,
978 &expt, ch, &ndig, &dtoaresult);
983 if (ch == 'g' || ch == 'G') {
984 if (expt > -4 && expt <= prec) {
985 /* Make %[gG] smell like %[fF] */
995 * Make %[gG] smell like %[eE], but
996 * trim trailing zeroes if no # flag.
1003 expsize = exponent(expstr, expt - 1, expchar);
1004 size = expsize + prec;
1005 if (prec > 1 || flags & ALT)
1008 /* space for digits before decimal point */
1013 /* space for decimal pt and following digits */
1014 if (prec || flags & ALT)
1016 if (grouping && expt > 0) {
1017 /* space for thousands' grouping */
1018 nseps = nrepeats = 0;
1020 while (*grouping != CHAR_MAX) {
1021 if (lead <= *grouping)
1024 if (*(grouping+1)) {
1030 size += nseps + nrepeats;
1035 #endif /* !NO_FLOATING_POINT */
1038 * Assignment-like behavior is specified if the
1039 * value overflows or is otherwise unrepresentable.
1040 * C99 says to use `signed char' for %hhn conversions.
1042 if (flags & LLONGINT)
1043 *GETARG(quad_t *) = ret;
1044 else if (flags & SIZET)
1045 *GETARG(ssize_t *) = (ssize_t)ret;
1046 else if (flags & PTRDIFFT)
1047 *GETARG(ptrdiff_t *) = ret;
1048 else if (flags & INTMAXT)
1049 *GETARG(intmax_t *) = ret;
1050 else if (flags & LONGINT)
1051 *GETARG(long *) = ret;
1052 else if (flags & SHORTINT)
1053 *GETARG(short *) = ret;
1054 else if (flags & CHARINT)
1055 *GETARG(signed char *) = ret;
1057 *GETARG(int *) = ret;
1058 continue; /* no output */
1063 if (flags & INTMAX_SIZE)
1071 * ``The argument shall be a pointer to void. The
1072 * value of the pointer is converted to a sequence
1073 * of printable characters, in an implementation-
1077 ujval = (uintmax_t)(uintptr_t)GETARG(void *);
1079 xdigs = xdigs_lower;
1080 flags = flags | INTMAXT;
1087 if (flags & LONGINT) {
1088 if ((cp = GETARG(wchar_t *)) == NULL)
1093 if (convbuf != NULL)
1095 if ((mbp = GETARG(char *)) == NULL)
1098 convbuf = __mbsconv(mbp, prec);
1099 if (convbuf == NULL) {
1100 fp->pub._flags |= __SERR;
1109 * can't use wcslen; can only look for the
1110 * NUL in the first `prec' characters, and
1111 * wcslen() will go further.
1113 wchar_t *p = wmemchr(cp, 0, (size_t)prec);
1129 if (flags & INTMAX_SIZE)
1136 xdigs = xdigs_upper;
1139 xdigs = xdigs_lower;
1141 if (flags & INTMAX_SIZE)
1146 /* leading 0x/X only if non-zero */
1148 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
1152 /* unsigned conversions */
1153 nosign: sign = '\0';
1155 * ``... diouXx conversions ... if a precision is
1156 * specified, the 0 flag will be ignored.''
1159 number: if ((dprec = prec) >= 0)
1163 * ``The result of converting a zero value with an
1164 * explicit precision of zero is no characters.''
1167 * ``The C Standard is clear enough as is. The call
1168 * printf("%#.0o", 0) should print 0.''
1169 * -- Defect Report #151
1172 if (flags & INTMAX_SIZE) {
1173 if (ujval != 0 || prec != 0 ||
1174 (flags & ALT && base == 8))
1175 cp = __ujtoa(ujval, cp, base,
1177 flags & GROUPING, thousands_sep,
1180 if (ulval != 0 || prec != 0 ||
1181 (flags & ALT && base == 8))
1182 cp = __ultoa(ulval, cp, base,
1184 flags & GROUPING, thousands_sep,
1187 size = buf + BUF - cp;
1188 if (size > BUF) /* should never happen */
1191 default: /* "%?" prints ?, unless ? is NUL */
1194 /* pretend it was %c with argument ch */
1203 * All reasonable formats wind up here. At this point, `cp'
1204 * points to a string which (if not flags&LADJUST) should be
1205 * padded out to `width' places. If flags&ZEROPAD, it should
1206 * first be prefixed by any sign or other prefix; otherwise,
1207 * it should be blank padded before the prefix is emitted.
1208 * After any left-hand padding and prefixing, emit zeroes
1209 * required by a decimal [diouxX] precision, then print the
1210 * string proper, then emit zeroes required by any leftover
1211 * floating precision; finally, if LADJUST, pad with blanks.
1213 * Compute actual size, so we know how much to pad.
1214 * size excludes decimal prec; realsz includes it.
1216 realsz = dprec > size ? dprec : size;
1222 prsize = width > realsz ? width : realsz;
1223 if ((unsigned)ret + prsize > INT_MAX) {
1228 /* right-adjusting blank padding */
1229 if ((flags & (LADJUST|ZEROPAD)) == 0)
1230 PAD(width - realsz, blanks);
1236 if (ox[1]) { /* ox[1] is either x, X, or \0 */
1241 /* right-adjusting zero padding */
1242 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1243 PAD(width - realsz, zeroes);
1245 /* leading zeroes from decimal precision */
1246 PAD(dprec - size, zeroes);
1248 /* the string or number proper */
1249 #ifndef NO_FLOATING_POINT
1250 if ((flags & FPT) == 0) {
1252 } else { /* glue together f_p fragments */
1253 if (!expchar) { /* %[fF] or sufficiently short %[gG] */
1256 if (prec || flags & ALT)
1257 PRINT(decimal_point, 1);
1259 /* already handled initial 0's */
1262 PRINTANDPAD(cp, convbuf + ndig, lead, zeroes);
1265 while (nseps>0 || nrepeats>0) {
1272 PRINT(&thousands_sep,
1279 if (cp > convbuf + ndig)
1280 cp = convbuf + ndig;
1282 if (prec || flags & ALT) {
1283 buf[0] = *decimal_point;
1287 PRINTANDPAD(cp, convbuf + ndig, prec, zeroes);
1288 } else { /* %[eE] or sufficiently long %[gG] */
1289 if (prec > 1 || flags & ALT) {
1291 buf[1] = *decimal_point;
1294 PAD(prec - ndig, zeroes);
1297 PRINT(expstr, expsize);
1303 /* left-adjusting padding (always blank) */
1304 if (flags & LADJUST)
1305 PAD(width - realsz, blanks);
1307 /* finally, adjust ret */
1312 #ifndef NO_FLOATING_POINT
1313 if (dtoaresult != NULL)
1317 if (convbuf != NULL)
1321 if ((argtable != NULL) && (argtable != statargtable))
1328 * Find all arguments when a positional parameter is encountered. Returns a
1329 * table, indexed by argument number, of pointers to each arguments. The
1330 * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1331 * It will be replaces with a malloc-ed one if it overflows.
1334 __find_arguments (const wchar_t *fmt0, va_list ap, union arg **argtable)
1336 wchar_t *fmt; /* format string */
1337 wchar_t ch; /* character from fmt */
1338 int n, n2; /* handy integer (short term usage) */
1339 wchar_t *cp; /* handy char pointer (short term usage) */
1340 int flags; /* flags as above */
1341 enum typeid *typetable; /* table of types */
1342 enum typeid stattypetable [STATIC_ARG_TBL_SIZE];
1343 int tablesize; /* current size of type table */
1344 int tablemax; /* largest used index in table */
1345 int nextarg; /* 1-based argument index */
1348 * Add an argument type to the table, expanding if necessary.
1350 #define ADDTYPE(type) \
1351 /*LINTED null effect*/ \
1352 (void)((nextarg >= tablesize) ? \
1353 __grow_type_table(nextarg, &typetable, &tablesize) : (void)0, \
1354 (nextarg > tablemax) ? tablemax = nextarg : 0, \
1355 typetable[nextarg++] = type)
1358 (void)((flags&INTMAXT) ? ADDTYPE(T_INTMAXT) : \
1359 ((flags&SIZET) ? ADDTYPE(T_SIZET) : \
1360 ((flags&PTRDIFFT) ? ADDTYPE(T_PTRDIFFT) : \
1361 ((flags&LLONGINT) ? ADDTYPE(T_LLONG) : \
1362 ((flags&LONGINT) ? ADDTYPE(T_LONG) : ADDTYPE(T_INT))))))
1365 (void)((flags&INTMAXT) ? ADDTYPE(T_UINTMAXT) : \
1366 ((flags&SIZET) ? ADDTYPE(T_SIZET) : \
1367 ((flags&PTRDIFFT) ? ADDTYPE(T_PTRDIFFT) : \
1368 ((flags&LLONGINT) ? ADDTYPE(T_U_LLONG) : \
1369 ((flags&LONGINT) ? ADDTYPE(T_U_LONG) : ADDTYPE(T_U_INT))))))
1372 * Add * arguments to the type array.
1374 #define ADDASTER() \
1377 while (is_digit(*cp)) { \
1378 n2 = 10 * n2 + to_digit(*cp); \
1382 int hold = nextarg; \
1390 fmt = __DECONST(wchar_t *, fmt0);
1391 typetable = stattypetable;
1392 tablesize = STATIC_ARG_TBL_SIZE;
1395 for (n = 0; n < STATIC_ARG_TBL_SIZE; n++)
1396 typetable[n] = T_UNUSED;
1399 * Scan the format for conversions (`%' character).
1402 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
1406 fmt++; /* skip over '%' */
1411 reswitch: switch (ch) {
1423 if ((ch = *fmt++) == '*') {
1427 while (is_digit(ch)) {
1433 case '1': case '2': case '3': case '4':
1434 case '5': case '6': case '7': case '8': case '9':
1437 n = 10 * n + to_digit(ch);
1439 } while (is_digit(ch));
1445 #ifndef NO_FLOATING_POINT
1451 if (flags & SHORTINT) {
1461 if (flags & LONGINT) {
1468 flags |= LLONGINT; /* not necessarily */
1480 if (flags & LONGINT)
1492 #ifndef NO_FLOATING_POINT
1500 if (flags & LONGDBL)
1501 ADDTYPE(T_LONG_DOUBLE);
1505 #endif /* !NO_FLOATING_POINT */
1507 if (flags & INTMAXT)
1508 ADDTYPE(TP_INTMAXT);
1509 else if (flags & PTRDIFFT)
1510 ADDTYPE(TP_PTRDIFFT);
1511 else if (flags & SIZET)
1513 else if (flags & LLONGINT)
1515 else if (flags & LONGINT)
1517 else if (flags & SHORTINT)
1519 else if (flags & CHARINT)
1523 continue; /* no output */
1537 if (flags & LONGINT)
1550 default: /* "%?" prints ?, unless ? is NUL */
1558 * Build the argument table.
1560 if (tablemax >= STATIC_ARG_TBL_SIZE) {
1561 *argtable = (union arg *)
1562 malloc (sizeof (union arg) * (tablemax + 1));
1565 (*argtable) [0].intarg = 0;
1566 for (n = 1; n <= tablemax; n++) {
1567 switch (typetable [n]) {
1568 case T_UNUSED: /* whoops! */
1569 (*argtable) [n].intarg = va_arg (ap, int);
1572 (*argtable) [n].pschararg = va_arg (ap, signed char *);
1575 (*argtable) [n].pshortarg = va_arg (ap, short *);
1578 (*argtable) [n].intarg = va_arg (ap, int);
1581 (*argtable) [n].uintarg = va_arg (ap, unsigned int);
1584 (*argtable) [n].pintarg = va_arg (ap, int *);
1587 (*argtable) [n].longarg = va_arg (ap, long);
1590 (*argtable) [n].ulongarg = va_arg (ap, unsigned long);
1593 (*argtable) [n].plongarg = va_arg (ap, long *);
1596 (*argtable) [n].longlongarg = va_arg (ap, quad_t);
1599 (*argtable) [n].ulonglongarg = va_arg (ap, u_quad_t);
1602 (*argtable) [n].plonglongarg = va_arg (ap, quad_t *);
1605 (*argtable) [n].ptrdiffarg = va_arg (ap, ptrdiff_t);
1608 (*argtable) [n].pptrdiffarg = va_arg (ap, ptrdiff_t *);
1611 (*argtable) [n].sizearg = va_arg (ap, size_t);
1614 (*argtable) [n].psizearg = va_arg (ap, size_t *);
1617 (*argtable) [n].intmaxarg = va_arg (ap, intmax_t);
1620 (*argtable) [n].uintmaxarg = va_arg (ap, uintmax_t);
1623 (*argtable) [n].pintmaxarg = va_arg (ap, intmax_t *);
1625 #ifndef NO_FLOATING_POINT
1627 (*argtable) [n].doublearg = va_arg (ap, double);
1630 (*argtable) [n].longdoublearg = va_arg (ap, long double);
1634 (*argtable) [n].pchararg = va_arg (ap, char *);
1637 (*argtable) [n].pvoidarg = va_arg (ap, void *);
1640 (*argtable) [n].wintarg = va_arg (ap, wint_t);
1643 (*argtable) [n].pwchararg = va_arg (ap, wchar_t *);
1648 if ((typetable != NULL) && (typetable != stattypetable))
1653 * Increase the size of the type table.
1656 __grow_type_table (int nextarg, enum typeid **typetable, int *tablesize)
1658 enum typeid *const oldtable = *typetable;
1659 const int oldsize = *tablesize;
1660 enum typeid *newtable;
1661 int n, newsize = oldsize * 2;
1663 if (newsize < nextarg + 1)
1664 newsize = nextarg + 1;
1665 if (oldsize == STATIC_ARG_TBL_SIZE) {
1666 if ((newtable = malloc(newsize * sizeof(enum typeid))) == NULL)
1667 abort(); /* XXX handle better */
1668 bcopy(oldtable, newtable, oldsize * sizeof(enum typeid));
1670 newtable = realloc(oldtable, newsize * sizeof(enum typeid));
1671 if (newtable == NULL)
1672 abort(); /* XXX handle better */
1674 for (n = oldsize; n < newsize; n++)
1675 newtable[n] = T_UNUSED;
1677 *typetable = newtable;
1678 *tablesize = newsize;
1682 #ifndef NO_FLOATING_POINT
1683 extern char *__dtoa (double, int, int, int *, int *, char **, char **);
1686 cvt(double value, int ndigits, int flags, char *sign, int *decpt, int ch,
1687 int *length, char **dtoaresult)
1690 char *digits, *bp, *rve;
1691 static wchar_t buf[512];
1693 _DIAGASSERT(decpt != NULL);
1694 _DIAGASSERT(length != NULL);
1695 _DIAGASSERT(sign != NULL);
1698 mode = 3; /* ndigits after the decimal point */
1700 /* To obtain ndigits after the decimal point for the 'e'
1701 * and 'E' formats, round to ndigits + 1 significant
1704 if (ch == 'e' || ch == 'E') {
1707 mode = 2; /* ndigits significant digits */
1710 digits = __dtoa(value, mode, ndigits, decpt, &dsgn, &rve, dtoaresult);
1716 if ((ch != 'g' && ch != 'G') || flags & ALT) { /* Print trailing zeros */
1717 bp = digits + ndigits;
1719 if (*digits == '0' && value)
1720 *decpt = -ndigits + 1;
1723 if (value == 0) /* kludge for __dtoa irregularity */
1728 *length = rve - digits;
1729 mbstowcs(buf, digits, sizeof(buf)/sizeof(buf[0]));
1733 exponent(wchar_t *p0, int expo, wchar_t fmtch)
1736 wchar_t expbuf[MAXEXPDIG];
1746 t = expbuf + MAXEXPDIG;
1749 *--t = to_char(expo % 10);
1750 } while ((expo /= 10) > 9);
1751 *--t = to_char(expo);
1752 for (; t < expbuf + MAXEXPDIG; *p++ = *t++);
1756 * Exponents for decimal floating point conversions
1757 * (%[eEgG]) must be at least two characters long,
1758 * whereas exponents for hexadecimal conversions can
1759 * be only one character long.
1761 if (fmtch == 'e' || fmtch == 'E')
1763 *p++ = to_char(expo);
1767 #endif /* !NO_FLOATING_POINT */