1 /* vsprintf with automatic memory allocation.
2 Copyright (C) 1999, 2002-2021 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 3, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along
15 with this program; if not, see <https://www.gnu.org/licenses/>. */
17 /* This file can be parametrized with the following macros:
18 VASNPRINTF The name of the function being defined.
19 FCHAR_T The element type of the format string.
20 DCHAR_T The element type of the destination (result) string.
21 FCHAR_T_ONLY_ASCII Set to 1 to enable verification that all characters
22 in the format string are ASCII. MUST be set if
23 FCHAR_T and DCHAR_T are not the same type.
24 DIRECTIVE Structure denoting a format directive.
26 DIRECTIVES Structure denoting the set of format directives of a
27 format string. Depends on FCHAR_T.
28 PRINTF_PARSE Function that parses a format string.
30 DCHAR_CPY memcpy like function for DCHAR_T[] arrays.
31 DCHAR_SET memset like function for DCHAR_T[] arrays.
32 DCHAR_MBSNLEN mbsnlen like function for DCHAR_T[] arrays.
33 SNPRINTF The system's snprintf (or similar) function.
34 This may be either snprintf or swprintf.
35 TCHAR_T The element type of the argument and result string
36 of the said SNPRINTF function. This may be either
37 char or wchar_t. The code exploits that
38 sizeof (TCHAR_T) | sizeof (DCHAR_T) and
39 alignof (TCHAR_T) <= alignof (DCHAR_T).
40 DCHAR_IS_TCHAR Set to 1 if DCHAR_T and TCHAR_T are the same type.
41 DCHAR_CONV_FROM_ENCODING A function to convert from char[] to DCHAR[].
42 DCHAR_IS_UINT8_T Set to 1 if DCHAR_T is uint8_t.
43 DCHAR_IS_UINT16_T Set to 1 if DCHAR_T is uint16_t.
44 DCHAR_IS_UINT32_T Set to 1 if DCHAR_T is uint32_t.
45 ENABLE_UNISTDIO Set to 1 to enable the unistdio extensions.
46 ENABLE_WCHAR_FALLBACK Set to 1 to avoid EILSEQ during conversion of wide
47 characters (wchar_t) and wide character strings
48 (wchar_t[]) to multibyte sequences. The fallback is the
49 hexadecimal escape syntax (\unnnn or \Unnnnnnnn) or,
50 if wchar_t is not Unicode encoded, \wnnnn or \Wnnnnnnnn.
53 /* Tell glibc's <stdio.h> to provide a prototype for snprintf().
54 This must come before <config.h> because <config.h> may include
55 <features.h>, and once <features.h> has been included, it's too late. */
57 # define _GNU_SOURCE 1
69 # if WIDE_CHAR_VERSION
70 # include "vasnwprintf.h"
72 # include "vasnprintf.h"
76 #include <locale.h> /* localeconv() */
77 #include <stdio.h> /* snprintf(), sprintf() */
78 #include <stdlib.h> /* abort(), malloc(), realloc(), free() */
79 #include <string.h> /* memcpy(), strlen() */
80 #include <errno.h> /* errno */
81 #include <limits.h> /* CHAR_BIT */
82 #include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP */
84 # include <langinfo.h>
87 # if WIDE_CHAR_VERSION
88 # include "wprintf-parse.h"
90 # include "printf-parse.h"
94 /* Checked size_t computations. */
97 #include "attribute.h"
100 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
105 #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
107 # include "isnand-nolibm.h"
110 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE) && !defined IN_LIBINTL
112 # include "isnanl-nolibm.h"
116 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
118 # include "isnand-nolibm.h"
119 # include "printf-frexp.h"
122 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
124 # include "isnanl-nolibm.h"
125 # include "printf-frexpl.h"
129 /* Default parameters. */
131 # if WIDE_CHAR_VERSION
132 # define VASNPRINTF vasnwprintf
133 # define FCHAR_T wchar_t
134 # define DCHAR_T wchar_t
135 # define TCHAR_T wchar_t
136 # define DCHAR_IS_TCHAR 1
137 # define DIRECTIVE wchar_t_directive
138 # define DIRECTIVES wchar_t_directives
139 # define PRINTF_PARSE wprintf_parse
140 # define DCHAR_CPY wmemcpy
141 # define DCHAR_SET wmemset
143 # define VASNPRINTF vasnprintf
144 # define FCHAR_T char
145 # define DCHAR_T char
146 # define TCHAR_T char
147 # define DCHAR_IS_TCHAR 1
148 # define DIRECTIVE char_directive
149 # define DIRECTIVES char_directives
150 # define PRINTF_PARSE printf_parse
151 # define DCHAR_CPY memcpy
152 # define DCHAR_SET memset
155 #if WIDE_CHAR_VERSION
156 /* TCHAR_T is wchar_t. */
157 # define USE_SNPRINTF 1
158 # if HAVE_DECL__SNWPRINTF
159 /* On Windows, the function swprintf() has a different signature than
160 on Unix; we use the function _snwprintf() or - on mingw - snwprintf()
161 instead. The mingw function snwprintf() has fewer bugs than the
162 MSVCRT function _snwprintf(), so prefer that. */
163 # if defined __MINGW32__
164 # define SNPRINTF snwprintf
166 # define SNPRINTF _snwprintf
167 # define USE_MSVC__SNPRINTF 1
171 # define SNPRINTF swprintf
174 /* TCHAR_T is char. */
175 /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
176 But don't use it on BeOS, since BeOS snprintf produces no output if the
177 size argument is >= 0x3000000.
178 Also don't use it on Linux libc5, since there snprintf with size = 1
179 writes any output without bounds, like sprintf. */
180 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__ && !(__GNU_LIBRARY__ == 1)
181 # define USE_SNPRINTF 1
183 # define USE_SNPRINTF 0
185 # if HAVE_DECL__SNPRINTF
186 /* Windows. The mingw function snprintf() has fewer bugs than the MSVCRT
187 function _snprintf(), so prefer that. */
188 # if defined __MINGW32__
189 # define SNPRINTF snprintf
190 /* Here we need to call the native snprintf, not rpl_snprintf. */
193 /* MSVC versions < 14 did not have snprintf, only _snprintf. */
194 # define SNPRINTF _snprintf
195 # define USE_MSVC__SNPRINTF 1
199 # define SNPRINTF snprintf
200 /* Here we need to call the native snprintf, not rpl_snprintf. */
204 /* Here we need to call the native sprintf, not rpl_sprintf. */
207 /* GCC >= 4.0 with -Wall emits unjustified "... may be used uninitialized"
208 warnings in this file. Use -Dlint to suppress them. */
209 #if defined GCC_LINT || defined lint
210 # define IF_LINT(Code) Code
212 # define IF_LINT(Code) /* empty */
215 /* Avoid some warnings from "gcc -Wshadow".
216 This file doesn't use the exp() and remainder() functions. */
220 #define remainder rem
222 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF) && !WIDE_CHAR_VERSION
223 # if (HAVE_STRNLEN && !defined _AIX)
224 # define local_strnlen strnlen
226 # ifndef local_strnlen_defined
227 # define local_strnlen_defined 1
229 local_strnlen (const char *string, size_t maxlen)
231 const char *end = memchr (string, '\0', maxlen);
232 return end ? (size_t) (end - string) : maxlen;
238 #if (((!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF) && WIDE_CHAR_VERSION) || ((!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL)) && !WIDE_CHAR_VERSION && DCHAR_IS_TCHAR)) && HAVE_WCHAR_T
240 # define local_wcslen wcslen
242 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
243 a dependency towards this library, here is a local substitute.
244 Define this substitute only once, even if this file is included
245 twice in the same compilation unit. */
246 # ifndef local_wcslen_defined
247 # define local_wcslen_defined 1
249 local_wcslen (const wchar_t *s)
253 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
261 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF) && HAVE_WCHAR_T && WIDE_CHAR_VERSION
263 # define local_wcsnlen wcsnlen
265 # ifndef local_wcsnlen_defined
266 # define local_wcsnlen_defined 1
268 local_wcsnlen (const wchar_t *s, size_t maxlen)
272 for (ptr = s; maxlen > 0 && *ptr != (wchar_t) 0; ptr++, maxlen--)
280 #if (((!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL) || ENABLE_WCHAR_FALLBACK) && HAVE_WCHAR_T) || (ENABLE_WCHAR_FALLBACK && HAVE_WINT_T)) && !WIDE_CHAR_VERSION
281 # if ENABLE_WCHAR_FALLBACK
283 wctomb_fallback (char *s, wchar_t wc)
285 static char hex[16] = "0123456789ABCDEF";
288 if (sizeof (wchar_t) > 2 && wc > 0xffff)
290 # if __STDC_ISO_10646__ || (__GLIBC__ >= 2) || (defined _WIN32 || defined __CYGWIN__)
295 s[2] = hex[(wc & 0xf0000000U) >> 28];
296 s[3] = hex[(wc & 0xf000000U) >> 24];
297 s[4] = hex[(wc & 0xf00000U) >> 20];
298 s[5] = hex[(wc & 0xf0000U) >> 16];
299 s[6] = hex[(wc & 0xf000U) >> 12];
300 s[7] = hex[(wc & 0xf00U) >> 8];
301 s[8] = hex[(wc & 0xf0U) >> 4];
302 s[9] = hex[wc & 0xfU];
307 # if __STDC_ISO_10646__ || (__GLIBC__ >= 2) || (defined _WIN32 || defined __CYGWIN__)
312 s[2] = hex[(wc & 0xf000U) >> 12];
313 s[3] = hex[(wc & 0xf00U) >> 8];
314 s[4] = hex[(wc & 0xf0U) >> 4];
315 s[5] = hex[wc & 0xfU];
319 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
321 local_wcrtomb (char *s, wchar_t wc, mbstate_t *ps)
323 size_t count = wcrtomb (s, wc, ps);
324 if (count == (size_t)(-1))
325 count = wctomb_fallback (s, wc);
330 local_wctomb (char *s, wchar_t wc)
332 int count = wctomb (s, wc);
334 count = wctomb_fallback (s, wc);
337 # define local_wcrtomb(S, WC, PS) local_wctomb ((S), (WC))
340 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
341 # define local_wcrtomb(S, WC, PS) wcrtomb ((S), (WC), (PS))
343 # define local_wcrtomb(S, WC, PS) wctomb ((S), (WC))
348 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL
349 /* Determine the decimal-point character according to the current locale. */
350 # ifndef decimal_point_char_defined
351 # define decimal_point_char_defined 1
353 decimal_point_char (void)
356 /* Determine it in a multithread-safe way. We know nl_langinfo is
357 multithread-safe on glibc systems and Mac OS X systems, but is not required
358 to be multithread-safe by POSIX. sprintf(), however, is multithread-safe.
359 localeconv() is rarely multithread-safe. */
360 # if HAVE_NL_LANGINFO && (__GLIBC__ || defined __UCLIBC__ || (defined __APPLE__ && defined __MACH__))
361 point = nl_langinfo (RADIXCHAR);
364 sprintf (pointbuf, "%#.0f", 1.0);
365 point = &pointbuf[1];
367 point = localeconv () -> decimal_point;
369 /* The decimal point is always a single byte: either '.' or ','. */
370 return (point[0] != '\0' ? point[0] : '.');
375 #if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE && !defined IN_LIBINTL
377 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
379 is_infinite_or_zero (double x)
381 return isnand (x) || x + x == x;
386 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL
388 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
390 is_infinite_or_zerol (long double x)
392 return isnanl (x) || x + x == x;
397 #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
399 /* Converting 'long double' to decimal without rare rounding bugs requires
400 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
401 (and slower) algorithms. */
403 typedef unsigned int mp_limb_t;
404 # define GMP_LIMB_BITS 32
405 verify (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS);
407 typedef unsigned long long mp_twolimb_t;
408 # define GMP_TWOLIMB_BITS 64
409 verify (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS);
411 /* Representation of a bignum >= 0. */
415 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
418 /* Compute the product of two bignums >= 0.
419 Return the allocated memory in case of success, NULL in case of memory
420 allocation failure. */
422 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
429 if (src1.nlimbs <= src2.nlimbs)
443 /* Now 0 <= len1 <= len2. */
446 /* src1 or src2 is zero. */
448 dest->limbs = (mp_limb_t *) malloc (1);
452 /* Here 1 <= len1 <= len2. */
458 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
461 for (k = len2; k > 0; )
463 for (i = 0; i < len1; i++)
465 mp_limb_t digit1 = p1[i];
466 mp_twolimb_t carry = 0;
467 for (j = 0; j < len2; j++)
469 mp_limb_t digit2 = p2[j];
470 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
472 dp[i + j] = (mp_limb_t) carry;
473 carry = carry >> GMP_LIMB_BITS;
475 dp[i + len2] = (mp_limb_t) carry;
478 while (dlen > 0 && dp[dlen - 1] == 0)
486 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
487 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
489 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
491 Return the allocated memory in case of success, NULL in case of memory
492 allocation failure. */
494 divide (mpn_t a, mpn_t b, mpn_t *q)
497 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
498 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
499 If m<n, then q:=0 and r:=a.
500 If m>=n=1, perform a single-precision division:
503 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
504 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
505 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
506 Normalise [q[m-1],...,q[0]], yields q.
507 If m>=n>1, perform a multiple-precision division:
508 We have a/b < beta^(m-n+1).
509 s:=intDsize-1-(highest bit in b[n-1]), 0<=s<intDsize.
510 Shift a and b left by s bits, copying them. r:=a.
511 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
512 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
514 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
515 In case of overflow (q* >= beta) set q* := beta-1.
516 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
517 and c3 := b[n-2] * q*.
518 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
519 occurred. Furthermore 0 <= c3 < beta^2.
520 If there was overflow and
521 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
522 the next test can be skipped.}
523 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
524 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
526 Put r := r - b * q* * beta^j. In detail:
527 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
528 hence: u:=0, for i:=0 to n-1 do
530 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
531 u:=u div beta (+ 1, if carry in subtraction)
533 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
535 the carry u does not overflow.}
536 If a negative carry occurs, put q* := q* - 1
537 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
539 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
540 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
542 The room for q[j] can be allocated at the memory location of r[n+j].
543 Finally, round-to-even:
544 Shift r left by 1 bit.
545 If r > b or if r = b and q[0] is odd, q := q+1.
547 const mp_limb_t *a_ptr = a.limbs;
548 size_t a_len = a.nlimbs;
549 const mp_limb_t *b_ptr = b.limbs;
550 size_t b_len = b.nlimbs;
552 mp_limb_t *tmp_roomptr = NULL;
558 /* Allocate room for a_len+2 digits.
559 (Need a_len+1 digits for the real division and 1 more digit for the
560 final rounding of q.) */
561 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
566 while (a_len > 0 && a_ptr[a_len - 1] == 0)
573 /* Division by zero. */
575 if (b_ptr[b_len - 1] == 0)
581 /* Here m = a_len >= 0 and n = b_len > 0. */
585 /* m<n: trivial case. q=0, r := copy of a. */
588 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
589 q_ptr = roomptr + a_len;
594 /* n=1: single precision division.
595 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
599 mp_limb_t den = b_ptr[0];
600 mp_limb_t remainder = 0;
601 const mp_limb_t *sourceptr = a_ptr + a_len;
602 mp_limb_t *destptr = q_ptr + a_len;
604 for (count = a_len; count > 0; count--)
607 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
608 *--destptr = num / den;
609 remainder = num % den;
611 /* Normalise and store r. */
614 r_ptr[0] = remainder;
621 if (q_ptr[q_len - 1] == 0)
627 /* n>1: multiple precision division.
628 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
629 beta^(m-n-1) <= a/b < beta^(m-n+1). */
633 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
634 /* Determine s = GMP_LIMB_BITS - integer_length (msd).
635 Code copied from gnulib's integer_length.c. */
636 # if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) \
637 || (__clang_major__ >= 4)
638 s = __builtin_clz (msd);
640 # if defined DBL_EXPBIT0_WORD && defined DBL_EXPBIT0_BIT
641 if (GMP_LIMB_BITS <= DBL_MANT_BIT)
643 /* Use 'double' operations.
644 Assumes an IEEE 754 'double' implementation. */
645 # define DBL_EXP_MASK ((DBL_MAX_EXP - DBL_MIN_EXP) | 7)
646 # define DBL_EXP_BIAS (DBL_EXP_MASK / 2 - 1)
648 ((sizeof (double) + sizeof (unsigned int) - 1) / sizeof (unsigned int))
649 union { double value; unsigned int word[NWORDS]; } m;
651 /* Use a single integer to floating-point conversion. */
655 - (((m.word[DBL_EXPBIT0_WORD] >> DBL_EXPBIT0_BIT) & DBL_EXP_MASK)
691 /* 0 <= s < GMP_LIMB_BITS.
692 Copy b, shifting it left by s bits. */
695 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
696 if (tmp_roomptr == NULL)
702 const mp_limb_t *sourceptr = b_ptr;
703 mp_limb_t *destptr = tmp_roomptr;
704 mp_twolimb_t accu = 0;
706 for (count = b_len; count > 0; count--)
708 accu += (mp_twolimb_t) *sourceptr++ << s;
709 *destptr++ = (mp_limb_t) accu;
710 accu = accu >> GMP_LIMB_BITS;
712 /* accu must be zero, since that was how s was determined. */
718 /* Copy a, shifting it left by s bits, yields r.
720 At the beginning: r = roomptr[0..a_len],
721 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
725 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
730 const mp_limb_t *sourceptr = a_ptr;
731 mp_limb_t *destptr = r_ptr;
732 mp_twolimb_t accu = 0;
734 for (count = a_len; count > 0; count--)
736 accu += (mp_twolimb_t) *sourceptr++ << s;
737 *destptr++ = (mp_limb_t) accu;
738 accu = accu >> GMP_LIMB_BITS;
740 *destptr++ = (mp_limb_t) accu;
742 q_ptr = roomptr + b_len;
743 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
745 size_t j = a_len - b_len; /* m-n */
746 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
747 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
748 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
749 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
750 /* Division loop, traversed m-n+1 times.
751 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
756 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
758 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
760 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
761 | r_ptr[j + b_len - 1];
762 q_star = num / b_msd;
767 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
768 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
769 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
770 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
771 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
773 If yes, jump directly to the subtraction loop.
774 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
775 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
776 if (r_ptr[j + b_len] > b_msd
777 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
778 /* r[j+n] >= b[n-1]+1 or
779 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
784 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
786 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
787 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
788 mp_twolimb_t c3 = /* b[n-2] * q* */
789 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
790 /* While c2 < c3, increase c2 and decrease c3.
791 Consider c3-c2. While it is > 0, decrease it by
792 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
793 this can happen only twice. */
796 q_star = q_star - 1; /* q* := q* - 1 */
797 if (c3 - c2 > b_msdd)
798 q_star = q_star - 1; /* q* := q* - 1 */
804 /* Subtract r := r - b * q* * beta^j. */
807 const mp_limb_t *sourceptr = b_ptr;
808 mp_limb_t *destptr = r_ptr + j;
809 mp_twolimb_t carry = 0;
811 for (count = b_len; count > 0; count--)
813 /* Here 0 <= carry <= q*. */
816 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
817 + (mp_limb_t) ~(*destptr);
818 /* Here 0 <= carry <= beta*q* + beta-1. */
819 *destptr++ = ~(mp_limb_t) carry;
820 carry = carry >> GMP_LIMB_BITS; /* <= q* */
822 cr = (mp_limb_t) carry;
824 /* Subtract cr from r_ptr[j + b_len], then forget about
826 if (cr > r_ptr[j + b_len])
828 /* Subtraction gave a carry. */
829 q_star = q_star - 1; /* q* := q* - 1 */
832 const mp_limb_t *sourceptr = b_ptr;
833 mp_limb_t *destptr = r_ptr + j;
836 for (count = b_len; count > 0; count--)
838 mp_limb_t source1 = *sourceptr++;
839 mp_limb_t source2 = *destptr;
840 *destptr++ = source1 + source2 + carry;
843 ? source1 >= (mp_limb_t) ~source2
844 : source1 > (mp_limb_t) ~source2);
847 /* Forget about the carry and about r[j+n]. */
850 /* q* is determined. Store it as q[j]. */
859 if (q_ptr[q_len - 1] == 0)
861 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
862 b is shifted left by s bits. */
863 /* Shift r right by s bits. */
866 mp_limb_t ptr = r_ptr + r_len;
867 mp_twolimb_t accu = 0;
869 for (count = r_len; count > 0; count--)
871 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
872 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
873 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
878 while (r_len > 0 && r_ptr[r_len - 1] == 0)
881 /* Compare r << 1 with b. */
889 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
890 | (i < r_len ? r_ptr[i] << 1 : 0);
891 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
901 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
906 for (i = 0; i < q_len; i++)
907 if (++(q_ptr[i]) != 0)
912 if (tmp_roomptr != NULL)
919 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
921 Destroys the contents of a.
922 Return the allocated memory - containing the decimal digits in low-to-high
923 order, terminated with a NUL character - in case of success, NULL in case
924 of memory allocation failure. */
926 convert_to_decimal (mpn_t a, size_t extra_zeroes)
928 mp_limb_t *a_ptr = a.limbs;
929 size_t a_len = a.nlimbs;
930 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
931 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
932 /* We need extra_zeroes bytes for zeroes, followed by c_len bytes for the
933 digits of a, followed by 1 byte for the terminating NUL. */
934 char *c_ptr = (char *) malloc (xsum (xsum (extra_zeroes, c_len), 1));
938 for (; extra_zeroes > 0; extra_zeroes--)
942 /* Divide a by 10^9, in-place. */
943 mp_limb_t remainder = 0;
944 mp_limb_t *ptr = a_ptr + a_len;
946 for (count = a_len; count > 0; count--)
949 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
950 *ptr = num / 1000000000;
951 remainder = num % 1000000000;
953 /* Store the remainder as 9 decimal digits. */
954 for (count = 9; count > 0; count--)
956 *d_ptr++ = '0' + (remainder % 10);
957 remainder = remainder / 10;
960 if (a_ptr[a_len - 1] == 0)
963 /* Remove leading zeroes. */
964 while (d_ptr > c_ptr && d_ptr[-1] == '0')
966 /* But keep at least one zero. */
969 /* Terminate the string. */
975 # if NEED_PRINTF_LONG_DOUBLE
977 /* Assuming x is finite and >= 0:
978 write x as x = 2^e * m, where m is a bignum.
979 Return the allocated memory in case of success, NULL in case of memory
980 allocation failure. */
982 decode_long_double (long double x, int *ep, mpn_t *mp)
989 /* Allocate memory for result. */
990 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
991 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
994 /* Split into exponential part and mantissa. */
995 y = frexpl (x, &exp);
996 if (!(y >= 0.0L && y < 1.0L))
998 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * 2^LDBL_MANT_BIT), and the
999 latter is an integer. */
1000 /* Convert the mantissa (y * 2^LDBL_MANT_BIT) to a sequence of limbs.
1001 I'm not sure whether it's safe to cast a 'long double' value between
1002 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
1003 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
1005 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
1006 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
1009 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
1012 if (!(y >= 0.0L && y < 1.0L))
1014 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1017 if (!(y >= 0.0L && y < 1.0L))
1019 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1024 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
1027 if (!(y >= 0.0L && y < 1.0L))
1029 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
1033 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
1036 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1039 if (!(y >= 0.0L && y < 1.0L))
1041 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1044 if (!(y >= 0.0L && y < 1.0L))
1046 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1048 # if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess
1054 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
1057 *ep = exp - LDBL_MANT_BIT;
1063 # if NEED_PRINTF_DOUBLE
1065 /* Assuming x is finite and >= 0:
1066 write x as x = 2^e * m, where m is a bignum.
1067 Return the allocated memory in case of success, NULL in case of memory
1068 allocation failure. */
1070 decode_double (double x, int *ep, mpn_t *mp)
1077 /* Allocate memory for result. */
1078 m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
1079 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
1080 if (m.limbs == NULL)
1082 /* Split into exponential part and mantissa. */
1083 y = frexp (x, &exp);
1084 if (!(y >= 0.0 && y < 1.0))
1086 /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * 2^DBL_MANT_BIT), and the
1087 latter is an integer. */
1088 /* Convert the mantissa (y * 2^DBL_MANT_BIT) to a sequence of limbs.
1089 I'm not sure whether it's safe to cast a 'double' value between
1090 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
1091 'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
1093 # if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
1094 # if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
1097 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
1100 if (!(y >= 0.0 && y < 1.0))
1102 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1105 if (!(y >= 0.0 && y < 1.0))
1107 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1112 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
1115 if (!(y >= 0.0 && y < 1.0))
1117 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
1121 for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
1124 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1127 if (!(y >= 0.0 && y < 1.0))
1129 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1132 if (!(y >= 0.0 && y < 1.0))
1134 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1139 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
1142 *ep = exp - DBL_MANT_BIT;
1148 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
1149 Returns the decimal representation of round (x * 10^n).
1150 Return the allocated memory - containing the decimal digits in low-to-high
1151 order, terminated with a NUL character - in case of success, NULL in case
1152 of memory allocation failure. */
1154 scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
1157 size_t extra_zeroes;
1160 mp_limb_t *pow5_ptr;
1162 unsigned int s_limbs;
1163 unsigned int s_bits;
1171 /* x = 2^e * m, hence
1172 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
1173 = round (2^s * 5^n * m). */
1176 /* Factor out a common power of 10 if possible. */
1179 extra_zeroes = (s < n ? s : n);
1183 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1184 Before converting to decimal, we need to compute
1185 z = round (2^s * 5^n * m). */
1186 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1187 sign. 2.322 is slightly larger than log(5)/log(2). */
1188 abs_n = (n >= 0 ? n : -n);
1189 abs_s = (s >= 0 ? s : -s);
1190 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
1191 + abs_s / GMP_LIMB_BITS + 1)
1192 * sizeof (mp_limb_t));
1193 if (pow5_ptr == NULL)
1198 /* Initialize with 1. */
1201 /* Multiply with 5^|n|. */
1204 static mp_limb_t const small_pow5[13 + 1] =
1206 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1207 48828125, 244140625, 1220703125
1210 for (n13 = 0; n13 <= abs_n; n13 += 13)
1212 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
1214 mp_twolimb_t carry = 0;
1215 for (j = 0; j < pow5_len; j++)
1217 mp_limb_t digit2 = pow5_ptr[j];
1218 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
1219 pow5_ptr[j] = (mp_limb_t) carry;
1220 carry = carry >> GMP_LIMB_BITS;
1223 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
1226 s_limbs = abs_s / GMP_LIMB_BITS;
1227 s_bits = abs_s % GMP_LIMB_BITS;
1228 if (n >= 0 ? s >= 0 : s <= 0)
1230 /* Multiply with 2^|s|. */
1233 mp_limb_t *ptr = pow5_ptr;
1234 mp_twolimb_t accu = 0;
1236 for (count = pow5_len; count > 0; count--)
1238 accu += (mp_twolimb_t) *ptr << s_bits;
1239 *ptr++ = (mp_limb_t) accu;
1240 accu = accu >> GMP_LIMB_BITS;
1244 *ptr = (mp_limb_t) accu;
1251 for (count = pow5_len; count > 0;)
1254 pow5_ptr[s_limbs + count] = pow5_ptr[count];
1256 for (count = s_limbs; count > 0;)
1259 pow5_ptr[count] = 0;
1261 pow5_len += s_limbs;
1263 pow5.limbs = pow5_ptr;
1264 pow5.nlimbs = pow5_len;
1267 /* Multiply m with pow5. No division needed. */
1268 z_memory = multiply (m, pow5, &z);
1272 /* Divide m by pow5 and round. */
1273 z_memory = divide (m, pow5, &z);
1278 pow5.limbs = pow5_ptr;
1279 pow5.nlimbs = pow5_len;
1283 Multiply m with pow5, then divide by 2^|s|. */
1287 tmp_memory = multiply (m, pow5, &numerator);
1288 if (tmp_memory == NULL)
1294 /* Construct 2^|s|. */
1296 mp_limb_t *ptr = pow5_ptr + pow5_len;
1298 for (i = 0; i < s_limbs; i++)
1300 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1301 denominator.limbs = ptr;
1302 denominator.nlimbs = s_limbs + 1;
1304 z_memory = divide (numerator, denominator, &z);
1310 Multiply m with 2^s, then divide by pow5. */
1313 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1314 * sizeof (mp_limb_t));
1315 if (num_ptr == NULL)
1322 mp_limb_t *destptr = num_ptr;
1325 for (i = 0; i < s_limbs; i++)
1330 const mp_limb_t *sourceptr = m.limbs;
1331 mp_twolimb_t accu = 0;
1333 for (count = m.nlimbs; count > 0; count--)
1335 accu += (mp_twolimb_t) *sourceptr++ << s_bits;
1336 *destptr++ = (mp_limb_t) accu;
1337 accu = accu >> GMP_LIMB_BITS;
1340 *destptr++ = (mp_limb_t) accu;
1344 const mp_limb_t *sourceptr = m.limbs;
1346 for (count = m.nlimbs; count > 0; count--)
1347 *destptr++ = *sourceptr++;
1349 numerator.limbs = num_ptr;
1350 numerator.nlimbs = destptr - num_ptr;
1352 z_memory = divide (numerator, pow5, &z);
1359 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1361 if (z_memory == NULL)
1363 digits = convert_to_decimal (z, extra_zeroes);
1368 # if NEED_PRINTF_LONG_DOUBLE
1370 /* Assuming x is finite and >= 0, and n is an integer:
1371 Returns the decimal representation of round (x * 10^n).
1372 Return the allocated memory - containing the decimal digits in low-to-high
1373 order, terminated with a NUL character - in case of success, NULL in case
1374 of memory allocation failure. */
1376 scale10_round_decimal_long_double (long double x, int n)
1380 void *memory = decode_long_double (x, &e, &m);
1381 return scale10_round_decimal_decoded (e, m, memory, n);
1386 # if NEED_PRINTF_DOUBLE
1388 /* Assuming x is finite and >= 0, and n is an integer:
1389 Returns the decimal representation of round (x * 10^n).
1390 Return the allocated memory - containing the decimal digits in low-to-high
1391 order, terminated with a NUL character - in case of success, NULL in case
1392 of memory allocation failure. */
1394 scale10_round_decimal_double (double x, int n)
1398 void *memory = decode_double (x, &e, &m);
1399 return scale10_round_decimal_decoded (e, m, memory, n);
1404 # if NEED_PRINTF_LONG_DOUBLE
1406 /* Assuming x is finite and > 0:
1407 Return an approximation for n with 10^n <= x < 10^(n+1).
1408 The approximation is usually the right n, but may be off by 1 sometimes. */
1410 floorlog10l (long double x)
1417 /* Split into exponential part and mantissa. */
1418 y = frexpl (x, &exp);
1419 if (!(y >= 0.0L && y < 1.0L))
1425 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1427 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1428 exp -= GMP_LIMB_BITS;
1430 if (y < (1.0L / (1 << 16)))
1432 y *= 1.0L * (1 << 16);
1435 if (y < (1.0L / (1 << 8)))
1437 y *= 1.0L * (1 << 8);
1440 if (y < (1.0L / (1 << 4)))
1442 y *= 1.0L * (1 << 4);
1445 if (y < (1.0L / (1 << 2)))
1447 y *= 1.0L * (1 << 2);
1450 if (y < (1.0L / (1 << 1)))
1452 y *= 1.0L * (1 << 1);
1456 if (!(y >= 0.5L && y < 1.0L))
1458 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1461 if (z < 0.70710678118654752444)
1463 z *= 1.4142135623730950488;
1466 if (z < 0.8408964152537145431)
1468 z *= 1.1892071150027210667;
1471 if (z < 0.91700404320467123175)
1473 z *= 1.0905077326652576592;
1476 if (z < 0.9576032806985736469)
1478 z *= 1.0442737824274138403;
1481 /* Now 0.95 <= z <= 1.01. */
1483 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1484 Four terms are enough to get an approximation with error < 10^-7. */
1485 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1486 /* Finally multiply with log(2)/log(10), yields an approximation for
1488 l *= 0.30102999566398119523;
1489 /* Round down to the next integer. */
1490 return (int) l + (l < 0 ? -1 : 0);
1495 # if NEED_PRINTF_DOUBLE
1497 /* Assuming x is finite and > 0:
1498 Return an approximation for n with 10^n <= x < 10^(n+1).
1499 The approximation is usually the right n, but may be off by 1 sometimes. */
1501 floorlog10 (double x)
1508 /* Split into exponential part and mantissa. */
1509 y = frexp (x, &exp);
1510 if (!(y >= 0.0 && y < 1.0))
1516 while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1518 y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1519 exp -= GMP_LIMB_BITS;
1521 if (y < (1.0 / (1 << 16)))
1523 y *= 1.0 * (1 << 16);
1526 if (y < (1.0 / (1 << 8)))
1528 y *= 1.0 * (1 << 8);
1531 if (y < (1.0 / (1 << 4)))
1533 y *= 1.0 * (1 << 4);
1536 if (y < (1.0 / (1 << 2)))
1538 y *= 1.0 * (1 << 2);
1541 if (y < (1.0 / (1 << 1)))
1543 y *= 1.0 * (1 << 1);
1547 if (!(y >= 0.5 && y < 1.0))
1549 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1552 if (z < 0.70710678118654752444)
1554 z *= 1.4142135623730950488;
1557 if (z < 0.8408964152537145431)
1559 z *= 1.1892071150027210667;
1562 if (z < 0.91700404320467123175)
1564 z *= 1.0905077326652576592;
1567 if (z < 0.9576032806985736469)
1569 z *= 1.0442737824274138403;
1572 /* Now 0.95 <= z <= 1.01. */
1574 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1575 Four terms are enough to get an approximation with error < 10^-7. */
1576 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1577 /* Finally multiply with log(2)/log(10), yields an approximation for
1579 l *= 0.30102999566398119523;
1580 /* Round down to the next integer. */
1581 return (int) l + (l < 0 ? -1 : 0);
1586 /* Tests whether a string of digits consists of exactly PRECISION zeroes and
1587 a single '1' digit. */
1589 is_borderline (const char *digits, size_t precision)
1591 for (; precision > 0; precision--, digits++)
1597 return *digits == '\0';
1602 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF
1604 /* Use a different function name, to make it possible that the 'wchar_t'
1605 parametrization and the 'char' parametrization get compiled in the same
1606 translation unit. */
1607 # if WIDE_CHAR_VERSION
1608 # define MAX_ROOM_NEEDED wmax_room_needed
1610 # define MAX_ROOM_NEEDED max_room_needed
1613 /* Returns the number of TCHAR_T units needed as temporary space for the result
1614 of sprintf or SNPRINTF of a single conversion directive. */
1616 MAX_ROOM_NEEDED (const arguments *ap, size_t arg_index, FCHAR_T conversion,
1617 arg_type type, int flags, size_t width, int has_precision,
1618 size_t precision, int pad_ourselves)
1624 case 'd': case 'i': case 'u':
1625 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1627 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1628 * 0.30103 /* binary -> decimal */
1630 + 1; /* turn floor into ceil */
1631 else if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1633 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1634 * 0.30103 /* binary -> decimal */
1636 + 1; /* turn floor into ceil */
1639 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1640 * 0.30103 /* binary -> decimal */
1642 + 1; /* turn floor into ceil */
1643 if (tmp_length < precision)
1644 tmp_length = precision;
1645 /* Multiply by 2, as an estimate for FLAG_GROUP. */
1646 tmp_length = xsum (tmp_length, tmp_length);
1647 /* Add 1, to account for a leading sign. */
1648 tmp_length = xsum (tmp_length, 1);
1652 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1654 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1655 * 0.333334 /* binary -> octal */
1657 + 1; /* turn floor into ceil */
1658 else if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1660 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1661 * 0.333334 /* binary -> octal */
1663 + 1; /* turn floor into ceil */
1666 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1667 * 0.333334 /* binary -> octal */
1669 + 1; /* turn floor into ceil */
1670 if (tmp_length < precision)
1671 tmp_length = precision;
1672 /* Add 1, to account for a leading sign. */
1673 tmp_length = xsum (tmp_length, 1);
1677 if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT)
1679 (unsigned int) (sizeof (unsigned long long) * CHAR_BIT
1680 * 0.25 /* binary -> hexadecimal */
1682 + 1; /* turn floor into ceil */
1683 else if (type == TYPE_LONGINT || type == TYPE_ULONGINT)
1685 (unsigned int) (sizeof (unsigned long) * CHAR_BIT
1686 * 0.25 /* binary -> hexadecimal */
1688 + 1; /* turn floor into ceil */
1691 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1692 * 0.25 /* binary -> hexadecimal */
1694 + 1; /* turn floor into ceil */
1695 if (tmp_length < precision)
1696 tmp_length = precision;
1697 /* Add 2, to account for a leading sign or alternate form. */
1698 tmp_length = xsum (tmp_length, 2);
1702 if (type == TYPE_LONGDOUBLE)
1704 (unsigned int) (LDBL_MAX_EXP
1705 * 0.30103 /* binary -> decimal */
1706 * 2 /* estimate for FLAG_GROUP */
1708 + 1 /* turn floor into ceil */
1709 + 10; /* sign, decimal point etc. */
1712 (unsigned int) (DBL_MAX_EXP
1713 * 0.30103 /* binary -> decimal */
1714 * 2 /* estimate for FLAG_GROUP */
1716 + 1 /* turn floor into ceil */
1717 + 10; /* sign, decimal point etc. */
1718 tmp_length = xsum (tmp_length, precision);
1721 case 'e': case 'E': case 'g': case 'G':
1723 12; /* sign, decimal point, exponent etc. */
1724 tmp_length = xsum (tmp_length, precision);
1728 if (type == TYPE_LONGDOUBLE)
1730 (unsigned int) (LDBL_DIG
1731 * 0.831 /* decimal -> hexadecimal */
1733 + 1; /* turn floor into ceil */
1736 (unsigned int) (DBL_DIG
1737 * 0.831 /* decimal -> hexadecimal */
1739 + 1; /* turn floor into ceil */
1740 if (tmp_length < precision)
1741 tmp_length = precision;
1742 /* Account for sign, decimal point etc. */
1743 tmp_length = xsum (tmp_length, 12);
1747 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
1748 if (type == TYPE_WIDE_CHAR)
1750 tmp_length = MB_CUR_MAX;
1751 # if ENABLE_WCHAR_FALLBACK
1752 if (tmp_length < (sizeof (wchar_t) > 2 ? 10 : 6))
1753 tmp_length = (sizeof (wchar_t) > 2 ? 10 : 6);
1763 if (type == TYPE_WIDE_STRING)
1765 # if WIDE_CHAR_VERSION
1766 /* ISO C says about %ls in fwprintf:
1767 "If the precision is not specified or is greater than the size
1768 of the array, the array shall contain a null wide character."
1769 So if there is a precision, we must not use wcslen. */
1770 const wchar_t *arg = ap->arg[arg_index].a.a_wide_string;
1773 tmp_length = local_wcsnlen (arg, precision);
1775 tmp_length = local_wcslen (arg);
1777 /* ISO C says about %ls in fprintf:
1778 "If a precision is specified, no more than that many bytes are
1779 written (including shift sequences, if any), and the array
1780 shall contain a null wide character if, to equal the multibyte
1781 character sequence length given by the precision, the function
1782 would need to access a wide character one past the end of the
1784 So if there is a precision, we must not use wcslen. */
1785 /* This case has already been handled separately in VASNPRINTF. */
1792 # if WIDE_CHAR_VERSION
1793 /* ISO C says about %s in fwprintf:
1794 "If the precision is not specified or is greater than the size
1795 of the converted array, the converted array shall contain a
1796 null wide character."
1797 So if there is a precision, we must not use strlen. */
1798 /* This case has already been handled separately in VASNPRINTF. */
1801 /* ISO C says about %s in fprintf:
1802 "If the precision is not specified or greater than the size of
1803 the array, the array shall contain a null character."
1804 So if there is a precision, we must not use strlen. */
1805 const char *arg = ap->arg[arg_index].a.a_string;
1808 tmp_length = local_strnlen (arg, precision);
1810 tmp_length = strlen (arg);
1817 (unsigned int) (sizeof (void *) * CHAR_BIT
1818 * 0.25 /* binary -> hexadecimal */
1820 + 1 /* turn floor into ceil */
1821 + 2; /* account for leading 0x */
1830 # if ENABLE_UNISTDIO
1831 /* Padding considers the number of characters, therefore the number of
1832 elements after padding may be
1833 > max (tmp_length, width)
1835 <= tmp_length + width. */
1836 tmp_length = xsum (tmp_length, width);
1838 /* Padding considers the number of elements, says POSIX. */
1839 if (tmp_length < width)
1844 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
1852 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
1853 const FCHAR_T *format, va_list args)
1858 if (PRINTF_PARSE (format, &d, &a) < 0)
1859 /* errno is already set. */
1862 /* Frees the memory allocated by this function. Preserves errno. */
1864 if (d.dir != d.direct_alloc_dir) \
1866 if (a.arg != a.direct_alloc_arg) \
1869 if (PRINTF_FETCHARGS (args, &a) < 0)
1877 size_t buf_neededlength;
1879 TCHAR_T *buf_malloced;
1883 /* Output string accumulator. */
1888 /* Allocate a small buffer that will hold a directive passed to
1889 sprintf or snprintf. */
1891 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
1893 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
1895 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
1896 buf_malloced = NULL;
1901 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
1902 if (size_overflow_p (buf_memsize))
1903 goto out_of_memory_1;
1904 buf = (TCHAR_T *) malloc (buf_memsize);
1906 goto out_of_memory_1;
1910 if (resultbuf != NULL)
1913 allocated = *lengthp;
1922 result is either == resultbuf or == NULL or malloc-allocated.
1923 If length > 0, then result != NULL. */
1925 /* Ensures that allocated >= needed. Aborts through a jump to
1926 out_of_memory if needed is SIZE_MAX or otherwise too big. */
1927 #define ENSURE_ALLOCATION(needed) \
1928 if ((needed) > allocated) \
1930 size_t memory_size; \
1933 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
1934 if ((needed) > allocated) \
1935 allocated = (needed); \
1936 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
1937 if (size_overflow_p (memory_size)) \
1938 goto out_of_memory; \
1939 if (result == resultbuf || result == NULL) \
1940 memory = (DCHAR_T *) malloc (memory_size); \
1942 memory = (DCHAR_T *) realloc (result, memory_size); \
1943 if (memory == NULL) \
1944 goto out_of_memory; \
1945 if (result == resultbuf && length > 0) \
1946 DCHAR_CPY (memory, result, length); \
1950 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
1952 if (cp != dp->dir_start)
1954 size_t n = dp->dir_start - cp;
1955 size_t augmented_length = xsum (length, n);
1957 ENSURE_ALLOCATION (augmented_length);
1958 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
1959 need that the format string contains only ASCII characters
1960 if FCHAR_T and DCHAR_T are not the same type. */
1961 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
1963 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
1964 length = augmented_length;
1969 result[length++] = *cp++;
1976 /* Execute a single directive. */
1977 if (dp->conversion == '%')
1979 size_t augmented_length;
1981 if (!(dp->arg_index == ARG_NONE))
1983 augmented_length = xsum (length, 1);
1984 ENSURE_ALLOCATION (augmented_length);
1985 result[length] = '%';
1986 length = augmented_length;
1990 if (!(dp->arg_index != ARG_NONE))
1993 if (dp->conversion == 'n')
1995 switch (a.arg[dp->arg_index].type)
1997 case TYPE_COUNT_SCHAR_POINTER:
1998 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
2000 case TYPE_COUNT_SHORT_POINTER:
2001 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
2003 case TYPE_COUNT_INT_POINTER:
2004 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
2006 case TYPE_COUNT_LONGINT_POINTER:
2007 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
2009 case TYPE_COUNT_LONGLONGINT_POINTER:
2010 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
2017 /* The unistdio extensions. */
2018 else if (dp->conversion == 'U')
2020 arg_type type = a.arg[dp->arg_index].type;
2021 int flags = dp->flags;
2029 if (dp->width_start != dp->width_end)
2031 if (dp->width_arg_index != ARG_NONE)
2035 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2037 arg = a.arg[dp->width_arg_index].a.a_int;
2041 /* "A negative field width is taken as a '-' flag
2042 followed by a positive field width." */
2049 const FCHAR_T *digitp = dp->width_start;
2052 width = xsum (xtimes (width, 10), *digitp++ - '0');
2053 while (digitp != dp->width_end);
2060 if (dp->precision_start != dp->precision_end)
2062 if (dp->precision_arg_index != ARG_NONE)
2066 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2068 arg = a.arg[dp->precision_arg_index].a.a_int;
2069 /* "A negative precision is taken as if the precision
2079 const FCHAR_T *digitp = dp->precision_start + 1;
2082 while (digitp != dp->precision_end)
2083 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2090 case TYPE_U8_STRING:
2092 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
2093 const uint8_t *arg_end;
2098 /* Use only PRECISION characters, from the left. */
2101 for (; precision > 0; precision--)
2103 int count = u8_strmblen (arg_end);
2108 if (!(result == resultbuf || result == NULL))
2110 if (buf_malloced != NULL)
2111 free (buf_malloced);
2122 /* Use the entire string, and count the number of
2128 int count = u8_strmblen (arg_end);
2133 if (!(result == resultbuf || result == NULL))
2135 if (buf_malloced != NULL)
2136 free (buf_malloced);
2147 /* Use the entire string. */
2148 arg_end = arg + u8_strlen (arg);
2149 /* The number of characters doesn't matter. */
2153 if (characters < width && !(dp->flags & FLAG_LEFT))
2155 size_t n = width - characters;
2156 ENSURE_ALLOCATION (xsum (length, n));
2157 DCHAR_SET (result + length, ' ', n);
2161 # if DCHAR_IS_UINT8_T
2163 size_t n = arg_end - arg;
2164 ENSURE_ALLOCATION (xsum (length, n));
2165 DCHAR_CPY (result + length, arg, n);
2170 DCHAR_T *converted = result + length;
2171 size_t converted_len = allocated - length;
2173 /* Convert from UTF-8 to locale encoding. */
2175 u8_conv_to_encoding (locale_charset (),
2176 iconveh_question_mark,
2177 arg, arg_end - arg, NULL,
2178 converted, &converted_len);
2180 /* Convert from UTF-8 to UTF-16/UTF-32. */
2182 U8_TO_DCHAR (arg, arg_end - arg,
2183 converted, &converted_len);
2185 if (converted == NULL)
2187 if (!(result == resultbuf || result == NULL))
2189 if (buf_malloced != NULL)
2190 free (buf_malloced);
2194 if (converted != result + length)
2196 ENSURE_ALLOCATION (xsum (length, converted_len));
2197 DCHAR_CPY (result + length, converted, converted_len);
2200 length += converted_len;
2204 if (characters < width && (dp->flags & FLAG_LEFT))
2206 size_t n = width - characters;
2207 ENSURE_ALLOCATION (xsum (length, n));
2208 DCHAR_SET (result + length, ' ', n);
2214 case TYPE_U16_STRING:
2216 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
2217 const uint16_t *arg_end;
2222 /* Use only PRECISION characters, from the left. */
2225 for (; precision > 0; precision--)
2227 int count = u16_strmblen (arg_end);
2232 if (!(result == resultbuf || result == NULL))
2234 if (buf_malloced != NULL)
2235 free (buf_malloced);
2246 /* Use the entire string, and count the number of
2252 int count = u16_strmblen (arg_end);
2257 if (!(result == resultbuf || result == NULL))
2259 if (buf_malloced != NULL)
2260 free (buf_malloced);
2271 /* Use the entire string. */
2272 arg_end = arg + u16_strlen (arg);
2273 /* The number of characters doesn't matter. */
2277 if (characters < width && !(dp->flags & FLAG_LEFT))
2279 size_t n = width - characters;
2280 ENSURE_ALLOCATION (xsum (length, n));
2281 DCHAR_SET (result + length, ' ', n);
2285 # if DCHAR_IS_UINT16_T
2287 size_t n = arg_end - arg;
2288 ENSURE_ALLOCATION (xsum (length, n));
2289 DCHAR_CPY (result + length, arg, n);
2294 DCHAR_T *converted = result + length;
2295 size_t converted_len = allocated - length;
2297 /* Convert from UTF-16 to locale encoding. */
2299 u16_conv_to_encoding (locale_charset (),
2300 iconveh_question_mark,
2301 arg, arg_end - arg, NULL,
2302 converted, &converted_len);
2304 /* Convert from UTF-16 to UTF-8/UTF-32. */
2306 U16_TO_DCHAR (arg, arg_end - arg,
2307 converted, &converted_len);
2309 if (converted == NULL)
2311 if (!(result == resultbuf || result == NULL))
2313 if (buf_malloced != NULL)
2314 free (buf_malloced);
2318 if (converted != result + length)
2320 ENSURE_ALLOCATION (xsum (length, converted_len));
2321 DCHAR_CPY (result + length, converted, converted_len);
2324 length += converted_len;
2328 if (characters < width && (dp->flags & FLAG_LEFT))
2330 size_t n = width - characters;
2331 ENSURE_ALLOCATION (xsum (length, n));
2332 DCHAR_SET (result + length, ' ', n);
2338 case TYPE_U32_STRING:
2340 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
2341 const uint32_t *arg_end;
2346 /* Use only PRECISION characters, from the left. */
2349 for (; precision > 0; precision--)
2351 int count = u32_strmblen (arg_end);
2356 if (!(result == resultbuf || result == NULL))
2358 if (buf_malloced != NULL)
2359 free (buf_malloced);
2370 /* Use the entire string, and count the number of
2376 int count = u32_strmblen (arg_end);
2381 if (!(result == resultbuf || result == NULL))
2383 if (buf_malloced != NULL)
2384 free (buf_malloced);
2395 /* Use the entire string. */
2396 arg_end = arg + u32_strlen (arg);
2397 /* The number of characters doesn't matter. */
2401 if (characters < width && !(dp->flags & FLAG_LEFT))
2403 size_t n = width - characters;
2404 ENSURE_ALLOCATION (xsum (length, n));
2405 DCHAR_SET (result + length, ' ', n);
2409 # if DCHAR_IS_UINT32_T
2411 size_t n = arg_end - arg;
2412 ENSURE_ALLOCATION (xsum (length, n));
2413 DCHAR_CPY (result + length, arg, n);
2418 DCHAR_T *converted = result + length;
2419 size_t converted_len = allocated - length;
2421 /* Convert from UTF-32 to locale encoding. */
2423 u32_conv_to_encoding (locale_charset (),
2424 iconveh_question_mark,
2425 arg, arg_end - arg, NULL,
2426 converted, &converted_len);
2428 /* Convert from UTF-32 to UTF-8/UTF-16. */
2430 U32_TO_DCHAR (arg, arg_end - arg,
2431 converted, &converted_len);
2433 if (converted == NULL)
2435 if (!(result == resultbuf || result == NULL))
2437 if (buf_malloced != NULL)
2438 free (buf_malloced);
2442 if (converted != result + length)
2444 ENSURE_ALLOCATION (xsum (length, converted_len));
2445 DCHAR_CPY (result + length, converted, converted_len);
2448 length += converted_len;
2452 if (characters < width && (dp->flags & FLAG_LEFT))
2454 size_t n = width - characters;
2455 ENSURE_ALLOCATION (xsum (length, n));
2456 DCHAR_SET (result + length, ' ', n);
2467 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL) || ENABLE_WCHAR_FALLBACK) && HAVE_WCHAR_T
2468 else if (dp->conversion == 's'
2469 # if WIDE_CHAR_VERSION
2470 && a.arg[dp->arg_index].type != TYPE_WIDE_STRING
2472 && a.arg[dp->arg_index].type == TYPE_WIDE_STRING
2476 /* The normal handling of the 's' directive below requires
2477 allocating a temporary buffer. The determination of its
2478 length (tmp_length), in the case when a precision is
2479 specified, below requires a conversion between a char[]
2480 string and a wchar_t[] wide string. It could be done, but
2481 we have no guarantee that the implementation of sprintf will
2482 use the exactly same algorithm. Without this guarantee, it
2483 is possible to have buffer overrun bugs. In order to avoid
2484 such bugs, we implement the entire processing of the 's'
2485 directive ourselves. */
2486 int flags = dp->flags;
2494 if (dp->width_start != dp->width_end)
2496 if (dp->width_arg_index != ARG_NONE)
2500 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2502 arg = a.arg[dp->width_arg_index].a.a_int;
2506 /* "A negative field width is taken as a '-' flag
2507 followed by a positive field width." */
2514 const FCHAR_T *digitp = dp->width_start;
2517 width = xsum (xtimes (width, 10), *digitp++ - '0');
2518 while (digitp != dp->width_end);
2525 if (dp->precision_start != dp->precision_end)
2527 if (dp->precision_arg_index != ARG_NONE)
2531 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2533 arg = a.arg[dp->precision_arg_index].a.a_int;
2534 /* "A negative precision is taken as if the precision
2544 const FCHAR_T *digitp = dp->precision_start + 1;
2547 while (digitp != dp->precision_end)
2548 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2553 # if WIDE_CHAR_VERSION
2554 /* %s in vasnwprintf. See the specification of fwprintf. */
2556 const char *arg = a.arg[dp->arg_index].a.a_string;
2557 const char *arg_end;
2562 /* Use only as many bytes as needed to produce PRECISION
2563 wide characters, from the left. */
2566 memset (&state, '\0', sizeof (mbstate_t));
2570 for (; precision > 0; precision--)
2574 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2576 count = mblen (arg_end, MB_CUR_MAX);
2579 /* Found the terminating NUL. */
2583 /* Invalid or incomplete multibyte character. */
2584 if (!(result == resultbuf || result == NULL))
2586 if (buf_malloced != NULL)
2587 free (buf_malloced);
2598 /* Use the entire string, and count the number of wide
2602 memset (&state, '\0', sizeof (mbstate_t));
2610 count = mbrlen (arg_end, MB_CUR_MAX, &state);
2612 count = mblen (arg_end, MB_CUR_MAX);
2615 /* Found the terminating NUL. */
2619 /* Invalid or incomplete multibyte character. */
2620 if (!(result == resultbuf || result == NULL))
2622 if (buf_malloced != NULL)
2623 free (buf_malloced);
2634 /* Use the entire string. */
2635 arg_end = arg + strlen (arg);
2636 /* The number of characters doesn't matter. */
2640 if (characters < width && !(dp->flags & FLAG_LEFT))
2642 size_t n = width - characters;
2643 ENSURE_ALLOCATION (xsum (length, n));
2644 DCHAR_SET (result + length, ' ', n);
2648 if (has_precision || has_width)
2650 /* We know the number of wide characters in advance. */
2654 memset (&state, '\0', sizeof (mbstate_t));
2656 ENSURE_ALLOCATION (xsum (length, characters));
2657 for (remaining = characters; remaining > 0; remaining--)
2662 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2664 count = mbtowc (&wc, arg, arg_end - arg);
2667 /* mbrtowc not consistent with mbrlen, or mbtowc
2668 not consistent with mblen. */
2670 result[length++] = wc;
2673 if (!(arg == arg_end))
2680 memset (&state, '\0', sizeof (mbstate_t));
2682 while (arg < arg_end)
2687 count = mbrtowc (&wc, arg, arg_end - arg, &state);
2689 count = mbtowc (&wc, arg, arg_end - arg);
2692 /* mbrtowc not consistent with mbrlen, or mbtowc
2693 not consistent with mblen. */
2695 ENSURE_ALLOCATION (xsum (length, 1));
2696 result[length++] = wc;
2701 if (characters < width && (dp->flags & FLAG_LEFT))
2703 size_t n = width - characters;
2704 ENSURE_ALLOCATION (xsum (length, n));
2705 DCHAR_SET (result + length, ' ', n);
2710 /* %ls in vasnprintf. See the specification of fprintf. */
2712 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
2713 const wchar_t *arg_end;
2715 # if !DCHAR_IS_TCHAR
2716 /* This code assumes that TCHAR_T is 'char'. */
2717 verify (sizeof (TCHAR_T) == 1);
2726 /* Use only as many wide characters as needed to produce
2727 at most PRECISION bytes, from the left. */
2728 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2730 memset (&state, '\0', sizeof (mbstate_t));
2734 while (precision > 0)
2736 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2740 /* Found the terminating null wide character. */
2742 count = local_wcrtomb (cbuf, *arg_end, &state);
2745 /* Cannot convert. */
2746 if (!(result == resultbuf || result == NULL))
2748 if (buf_malloced != NULL)
2749 free (buf_malloced);
2754 if (precision < (unsigned int) count)
2757 characters += count;
2767 /* Use the entire string, and count the number of
2769 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2771 memset (&state, '\0', sizeof (mbstate_t));
2777 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2781 /* Found the terminating null wide character. */
2783 count = local_wcrtomb (cbuf, *arg_end, &state);
2786 /* Cannot convert. */
2787 if (!(result == resultbuf || result == NULL))
2789 if (buf_malloced != NULL)
2790 free (buf_malloced);
2796 characters += count;
2802 /* Use the entire string. */
2803 arg_end = arg + local_wcslen (arg);
2804 /* The number of bytes doesn't matter. */
2809 # if !DCHAR_IS_TCHAR
2810 /* Convert the string into a piece of temporary memory. */
2811 tmpsrc = (TCHAR_T *) malloc (characters * sizeof (TCHAR_T));
2815 TCHAR_T *tmpptr = tmpsrc;
2817 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2819 memset (&state, '\0', sizeof (mbstate_t));
2821 for (remaining = characters; remaining > 0; )
2823 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2828 count = local_wcrtomb (cbuf, *arg, &state);
2830 /* Inconsistency. */
2832 memcpy (tmpptr, cbuf, count);
2837 if (!(arg == arg_end))
2841 /* Convert from TCHAR_T[] to DCHAR_T[]. */
2843 DCHAR_CONV_FROM_ENCODING (locale_charset (),
2844 iconveh_question_mark,
2851 if (!(result == resultbuf || result == NULL))
2853 if (buf_malloced != NULL)
2854 free (buf_malloced);
2863 # if ENABLE_UNISTDIO
2864 /* Outside POSIX, it's preferable to compare the width
2865 against the number of _characters_ of the converted
2867 w = DCHAR_MBSNLEN (result + length, characters);
2869 /* The width is compared against the number of _bytes_
2870 of the converted value, says POSIX. */
2875 /* w doesn't matter. */
2878 if (w < width && !(dp->flags & FLAG_LEFT))
2880 size_t n = width - w;
2881 ENSURE_ALLOCATION (xsum (length, n));
2882 DCHAR_SET (result + length, ' ', n);
2887 if (has_precision || has_width)
2889 /* We know the number of bytes in advance. */
2891 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2893 memset (&state, '\0', sizeof (mbstate_t));
2895 ENSURE_ALLOCATION (xsum (length, characters));
2896 for (remaining = characters; remaining > 0; )
2898 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2903 count = local_wcrtomb (cbuf, *arg, &state);
2905 /* Inconsistency. */
2907 memcpy (result + length, cbuf, count);
2912 if (!(arg == arg_end))
2917 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
2919 memset (&state, '\0', sizeof (mbstate_t));
2921 while (arg < arg_end)
2923 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
2928 count = local_wcrtomb (cbuf, *arg, &state);
2931 /* Cannot convert. */
2932 if (!(result == resultbuf || result == NULL))
2934 if (buf_malloced != NULL)
2935 free (buf_malloced);
2940 ENSURE_ALLOCATION (xsum (length, count));
2941 memcpy (result + length, cbuf, count);
2947 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
2948 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
2950 length += tmpdst_len;
2953 if (w < width && (dp->flags & FLAG_LEFT))
2955 size_t n = width - w;
2956 ENSURE_ALLOCATION (xsum (length, n));
2957 DCHAR_SET (result + length, ' ', n);
2964 #if ENABLE_WCHAR_FALLBACK && HAVE_WINT_T && !WIDE_CHAR_VERSION
2965 else if (dp->conversion == 'c'
2966 && a.arg[dp->arg_index].type == TYPE_WIDE_CHAR)
2968 /* Implement the 'lc' directive ourselves, in order to provide
2969 the fallback that avoids EILSEQ. */
2970 int flags = dp->flags;
2976 if (dp->width_start != dp->width_end)
2978 if (dp->width_arg_index != ARG_NONE)
2982 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2984 arg = a.arg[dp->width_arg_index].a.a_int;
2988 /* "A negative field width is taken as a '-' flag
2989 followed by a positive field width." */
2996 const FCHAR_T *digitp = dp->width_start;
2999 width = xsum (xtimes (width, 10), *digitp++ - '0');
3000 while (digitp != dp->width_end);
3005 /* %lc in vasnprintf. See the specification of fprintf. */
3007 wchar_t arg = (wchar_t) a.arg[dp->arg_index].a.a_wide_char;
3009 # if !DCHAR_IS_TCHAR
3010 /* This code assumes that TCHAR_T is 'char'. */
3011 verify (sizeof (TCHAR_T) == 1);
3012 TCHAR_T tmpsrc[64]; /* Assume MB_CUR_MAX <= 64. */
3022 /* Count the number of bytes. */
3026 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
3028 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
3030 memset (&state, '\0', sizeof (mbstate_t));
3033 count = local_wcrtomb (cbuf, arg, &state);
3035 /* Inconsistency. */
3043 /* The number of bytes doesn't matter. */
3048 # if !DCHAR_IS_TCHAR
3049 /* Convert the string into a piece of temporary memory. */
3050 if (characters > 0) /* implies arg != 0 */
3052 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
3054 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
3056 memset (&state, '\0', sizeof (mbstate_t));
3059 count = local_wcrtomb (cbuf, arg, &state);
3061 /* Inconsistency. */
3063 memcpy (tmpsrc, cbuf, count);
3066 /* Convert from TCHAR_T[] to DCHAR_T[]. */
3068 DCHAR_CONV_FROM_ENCODING (locale_charset (),
3069 iconveh_question_mark,
3075 if (!(result == resultbuf || result == NULL))
3077 if (buf_malloced != NULL)
3078 free (buf_malloced);
3086 # if ENABLE_UNISTDIO
3087 /* Outside POSIX, it's preferable to compare the width
3088 against the number of _characters_ of the converted
3090 w = DCHAR_MBSNLEN (result + length, characters);
3092 /* The width is compared against the number of _bytes_
3093 of the converted value, says POSIX. */
3098 /* w doesn't matter. */
3101 if (w < width && !(dp->flags & FLAG_LEFT))
3103 size_t n = width - w;
3104 ENSURE_ALLOCATION (xsum (length, n));
3105 DCHAR_SET (result + length, ' ', n);
3112 /* We know the number of bytes in advance. */
3113 ENSURE_ALLOCATION (xsum (length, characters));
3114 if (characters > 0) /* implies arg != 0 */
3117 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
3119 memset (&state, '\0', sizeof (mbstate_t));
3122 count = local_wcrtomb (result + length, arg, &state);
3124 /* Inconsistency. */
3133 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
3135 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
3137 memset (&state, '\0', sizeof (mbstate_t));
3140 count = local_wcrtomb (cbuf, arg, &state);
3142 /* Inconsistency. */
3144 ENSURE_ALLOCATION (xsum (length, count));
3145 memcpy (result + length, cbuf, count);
3150 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
3151 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
3153 length += tmpdst_len;
3156 if (w < width && (dp->flags & FLAG_LEFT))
3158 size_t n = width - w;
3159 ENSURE_ALLOCATION (xsum (length, n));
3160 DCHAR_SET (result + length, ' ', n);
3166 #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL
3167 else if ((dp->conversion == 'a' || dp->conversion == 'A')
3168 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
3170 # if NEED_PRINTF_DOUBLE
3171 || a.arg[dp->arg_index].type == TYPE_DOUBLE
3173 # if NEED_PRINTF_LONG_DOUBLE
3174 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3180 arg_type type = a.arg[dp->arg_index].type;
3181 int flags = dp->flags;
3187 DCHAR_T tmpbuf[700];
3193 if (dp->width_start != dp->width_end)
3195 if (dp->width_arg_index != ARG_NONE)
3199 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3201 arg = a.arg[dp->width_arg_index].a.a_int;
3205 /* "A negative field width is taken as a '-' flag
3206 followed by a positive field width." */
3213 const FCHAR_T *digitp = dp->width_start;
3216 width = xsum (xtimes (width, 10), *digitp++ - '0');
3217 while (digitp != dp->width_end);
3223 if (dp->precision_start != dp->precision_end)
3225 if (dp->precision_arg_index != ARG_NONE)
3229 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3231 arg = a.arg[dp->precision_arg_index].a.a_int;
3232 /* "A negative precision is taken as if the precision
3242 const FCHAR_T *digitp = dp->precision_start + 1;
3245 while (digitp != dp->precision_end)
3246 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3251 /* Allocate a temporary buffer of sufficient size. */
3252 if (type == TYPE_LONGDOUBLE)
3254 (unsigned int) ((LDBL_DIG + 1)
3255 * 0.831 /* decimal -> hexadecimal */
3257 + 1; /* turn floor into ceil */
3260 (unsigned int) ((DBL_DIG + 1)
3261 * 0.831 /* decimal -> hexadecimal */
3263 + 1; /* turn floor into ceil */
3264 if (tmp_length < precision)
3265 tmp_length = precision;
3266 /* Account for sign, decimal point etc. */
3267 tmp_length = xsum (tmp_length, 12);
3269 if (tmp_length < width)
3272 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3274 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3278 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3280 if (size_overflow_p (tmp_memsize))
3281 /* Overflow, would lead to out of memory. */
3283 tmp = (DCHAR_T *) malloc (tmp_memsize);
3285 /* Out of memory. */
3291 if (type == TYPE_LONGDOUBLE)
3293 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE
3294 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3298 if (dp->conversion == 'A')
3300 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3304 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3310 DECL_LONG_DOUBLE_ROUNDING
3312 BEGIN_LONG_DOUBLE_ROUNDING ();
3314 if (signbit (arg)) /* arg < 0.0L or negative zero */
3322 else if (flags & FLAG_SHOWSIGN)
3324 else if (flags & FLAG_SPACE)
3327 if (arg > 0.0L && arg + arg == arg)
3329 if (dp->conversion == 'A')
3331 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3335 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3341 long double mantissa;
3344 mantissa = printf_frexpl (arg, &exponent);
3352 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
3354 /* Round the mantissa. */
3355 long double tail = mantissa;
3358 for (q = precision; ; q--)
3360 int digit = (int) tail;
3364 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
3373 for (q = precision; q > 0; q--)
3379 *p++ = dp->conversion - 'A' + 'X';
3384 digit = (int) mantissa;
3387 if ((flags & FLAG_ALT)
3388 || mantissa > 0.0L || precision > 0)
3390 *p++ = decimal_point_char ();
3391 /* This loop terminates because we assume
3392 that FLT_RADIX is a power of 2. */
3393 while (mantissa > 0.0L)
3396 digit = (int) mantissa;
3401 : dp->conversion - 10);
3405 while (precision > 0)
3412 *p++ = dp->conversion - 'A' + 'P';
3413 # if WIDE_CHAR_VERSION
3415 static const wchar_t decimal_format[] =
3416 { '%', '+', 'd', '\0' };
3417 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3422 if (sizeof (DCHAR_T) == 1)
3424 sprintf ((char *) p, "%+d", exponent);
3432 sprintf (expbuf, "%+d", exponent);
3433 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3439 END_LONG_DOUBLE_ROUNDING ();
3447 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
3448 double arg = a.arg[dp->arg_index].a.a_double;
3452 if (dp->conversion == 'A')
3454 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3458 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3465 if (signbit (arg)) /* arg < 0.0 or negative zero */
3473 else if (flags & FLAG_SHOWSIGN)
3475 else if (flags & FLAG_SPACE)
3478 if (arg > 0.0 && arg + arg == arg)
3480 if (dp->conversion == 'A')
3482 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3486 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3495 mantissa = printf_frexp (arg, &exponent);
3503 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
3505 /* Round the mantissa. */
3506 double tail = mantissa;
3509 for (q = precision; ; q--)
3511 int digit = (int) tail;
3515 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
3524 for (q = precision; q > 0; q--)
3530 *p++ = dp->conversion - 'A' + 'X';
3535 digit = (int) mantissa;
3538 if ((flags & FLAG_ALT)
3539 || mantissa > 0.0 || precision > 0)
3541 *p++ = decimal_point_char ();
3542 /* This loop terminates because we assume
3543 that FLT_RADIX is a power of 2. */
3544 while (mantissa > 0.0)
3547 digit = (int) mantissa;
3552 : dp->conversion - 10);
3556 while (precision > 0)
3563 *p++ = dp->conversion - 'A' + 'P';
3564 # if WIDE_CHAR_VERSION
3566 static const wchar_t decimal_format[] =
3567 { '%', '+', 'd', '\0' };
3568 SNPRINTF (p, 6 + 1, decimal_format, exponent);
3573 if (sizeof (DCHAR_T) == 1)
3575 sprintf ((char *) p, "%+d", exponent);
3583 sprintf (expbuf, "%+d", exponent);
3584 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
3595 /* The generated string now extends from tmp to p, with the
3596 zero padding insertion point being at pad_ptr. */
3601 size_t pad = width - count;
3602 DCHAR_T *end = p + pad;
3604 if (flags & FLAG_LEFT)
3606 /* Pad with spaces on the right. */
3607 for (; pad > 0; pad--)
3610 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
3612 /* Pad with zeroes. */
3617 for (; pad > 0; pad--)
3622 /* Pad with spaces on the left. */
3627 for (; pad > 0; pad--)
3636 if (count >= tmp_length)
3637 /* tmp_length was incorrectly calculated - fix the
3641 /* Make room for the result. */
3642 if (count >= allocated - length)
3644 size_t n = xsum (length, count);
3646 ENSURE_ALLOCATION (n);
3649 /* Append the result. */
3650 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
3656 #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL
3657 else if ((dp->conversion == 'f' || dp->conversion == 'F'
3658 || dp->conversion == 'e' || dp->conversion == 'E'
3659 || dp->conversion == 'g' || dp->conversion == 'G'
3660 || dp->conversion == 'a' || dp->conversion == 'A')
3662 # if NEED_PRINTF_DOUBLE
3663 || a.arg[dp->arg_index].type == TYPE_DOUBLE
3664 # elif NEED_PRINTF_INFINITE_DOUBLE
3665 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
3666 /* The systems (mingw) which produce wrong output
3667 for Inf, -Inf, and NaN also do so for -0.0.
3668 Therefore we treat this case here as well. */
3669 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
3671 # if NEED_PRINTF_LONG_DOUBLE
3672 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3673 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
3674 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
3675 /* Some systems produce wrong output for Inf,
3676 -Inf, and NaN. Some systems in this category
3677 (IRIX 5.3) also do so for -0.0. Therefore we
3678 treat this case here as well. */
3679 && is_infinite_or_zerol (a.arg[dp->arg_index].a.a_longdouble))
3683 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
3684 arg_type type = a.arg[dp->arg_index].type;
3686 int flags = dp->flags;
3692 DCHAR_T tmpbuf[700];
3698 if (dp->width_start != dp->width_end)
3700 if (dp->width_arg_index != ARG_NONE)
3704 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3706 arg = a.arg[dp->width_arg_index].a.a_int;
3710 /* "A negative field width is taken as a '-' flag
3711 followed by a positive field width." */
3718 const FCHAR_T *digitp = dp->width_start;
3721 width = xsum (xtimes (width, 10), *digitp++ - '0');
3722 while (digitp != dp->width_end);
3728 if (dp->precision_start != dp->precision_end)
3730 if (dp->precision_arg_index != ARG_NONE)
3734 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3736 arg = a.arg[dp->precision_arg_index].a.a_int;
3737 /* "A negative precision is taken as if the precision
3747 const FCHAR_T *digitp = dp->precision_start + 1;
3750 while (digitp != dp->precision_end)
3751 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3756 /* POSIX specifies the default precision to be 6 for %f, %F,
3757 %e, %E, but not for %g, %G. Implementations appear to use
3758 the same default precision also for %g, %G. But for %a, %A,
3759 the default precision is 0. */
3761 if (!(dp->conversion == 'a' || dp->conversion == 'A'))
3764 /* Allocate a temporary buffer of sufficient size. */
3765 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3766 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
3767 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
3768 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
3769 # elif NEED_PRINTF_LONG_DOUBLE
3770 tmp_length = LDBL_DIG + 1;
3771 # elif NEED_PRINTF_DOUBLE
3772 tmp_length = DBL_DIG + 1;
3776 if (tmp_length < precision)
3777 tmp_length = precision;
3778 # if NEED_PRINTF_LONG_DOUBLE
3779 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3780 if (type == TYPE_LONGDOUBLE)
3782 if (dp->conversion == 'f' || dp->conversion == 'F')
3784 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3785 if (!(isnanl (arg) || arg + arg == arg))
3787 /* arg is finite and nonzero. */
3788 int exponent = floorlog10l (arg < 0 ? -arg : arg);
3789 if (exponent >= 0 && tmp_length < exponent + precision)
3790 tmp_length = exponent + precision;
3794 # if NEED_PRINTF_DOUBLE
3795 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3796 if (type == TYPE_DOUBLE)
3798 if (dp->conversion == 'f' || dp->conversion == 'F')
3800 double arg = a.arg[dp->arg_index].a.a_double;
3801 if (!(isnand (arg) || arg + arg == arg))
3803 /* arg is finite and nonzero. */
3804 int exponent = floorlog10 (arg < 0 ? -arg : arg);
3805 if (exponent >= 0 && tmp_length < exponent + precision)
3806 tmp_length = exponent + precision;
3810 /* Account for sign, decimal point etc. */
3811 tmp_length = xsum (tmp_length, 12);
3813 if (tmp_length < width)
3816 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
3818 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
3822 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
3824 if (size_overflow_p (tmp_memsize))
3825 /* Overflow, would lead to out of memory. */
3827 tmp = (DCHAR_T *) malloc (tmp_memsize);
3829 /* Out of memory. */
3836 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
3837 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
3838 if (type == TYPE_LONGDOUBLE)
3841 long double arg = a.arg[dp->arg_index].a.a_longdouble;
3845 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3847 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
3851 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
3857 DECL_LONG_DOUBLE_ROUNDING
3859 BEGIN_LONG_DOUBLE_ROUNDING ();
3861 if (signbit (arg)) /* arg < 0.0L or negative zero */
3869 else if (flags & FLAG_SHOWSIGN)
3871 else if (flags & FLAG_SPACE)
3874 if (arg > 0.0L && arg + arg == arg)
3876 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
3878 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
3882 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
3887 # if NEED_PRINTF_LONG_DOUBLE
3890 if (dp->conversion == 'f' || dp->conversion == 'F')
3896 scale10_round_decimal_long_double (arg, precision);
3899 END_LONG_DOUBLE_ROUNDING ();
3902 ndigits = strlen (digits);
3904 if (ndigits > precision)
3908 *p++ = digits[ndigits];
3910 while (ndigits > precision);
3913 /* Here ndigits <= precision. */
3914 if ((flags & FLAG_ALT) || precision > 0)
3916 *p++ = decimal_point_char ();
3917 for (; precision > ndigits; precision--)
3922 *p++ = digits[ndigits];
3928 else if (dp->conversion == 'e' || dp->conversion == 'E')
3936 if ((flags & FLAG_ALT) || precision > 0)
3938 *p++ = decimal_point_char ();
3939 for (; precision > 0; precision--)
3950 exponent = floorlog10l (arg);
3955 scale10_round_decimal_long_double (arg,
3956 (int)precision - exponent);
3959 END_LONG_DOUBLE_ROUNDING ();
3962 ndigits = strlen (digits);
3964 if (ndigits == precision + 1)
3966 if (ndigits < precision
3967 || ndigits > precision + 2)
3968 /* The exponent was not guessed
3969 precisely enough. */
3972 /* None of two values of exponent is
3973 the right one. Prevent an endless
3977 if (ndigits == precision)
3983 /* Here ndigits = precision+1. */
3984 if (is_borderline (digits, precision))
3986 /* Maybe the exponent guess was too high
3987 and a smaller exponent can be reached
3988 by turning a 10...0 into 9...9x. */
3990 scale10_round_decimal_long_double (arg,
3991 (int)precision - exponent + 1);
3992 if (digits2 == NULL)
3995 END_LONG_DOUBLE_ROUNDING ();
3998 if (strlen (digits2) == precision + 1)
4007 /* Here ndigits = precision+1. */
4009 *p++ = digits[--ndigits];
4010 if ((flags & FLAG_ALT) || precision > 0)
4012 *p++ = decimal_point_char ();
4016 *p++ = digits[ndigits];
4023 *p++ = dp->conversion; /* 'e' or 'E' */
4024 # if WIDE_CHAR_VERSION
4026 static const wchar_t decimal_format[] =
4027 { '%', '+', '.', '2', 'd', '\0' };
4028 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4033 if (sizeof (DCHAR_T) == 1)
4035 sprintf ((char *) p, "%+.2d", exponent);
4043 sprintf (expbuf, "%+.2d", exponent);
4044 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4049 else if (dp->conversion == 'g' || dp->conversion == 'G')
4053 /* precision >= 1. */
4056 /* The exponent is 0, >= -4, < precision.
4057 Use fixed-point notation. */
4059 size_t ndigits = precision;
4060 /* Number of trailing zeroes that have to be
4063 (flags & FLAG_ALT ? 0 : precision - 1);
4067 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4069 *p++ = decimal_point_char ();
4070 while (ndigits > nzeroes)
4086 exponent = floorlog10l (arg);
4091 scale10_round_decimal_long_double (arg,
4092 (int)(precision - 1) - exponent);
4095 END_LONG_DOUBLE_ROUNDING ();
4098 ndigits = strlen (digits);
4100 if (ndigits == precision)
4102 if (ndigits < precision - 1
4103 || ndigits > precision + 1)
4104 /* The exponent was not guessed
4105 precisely enough. */
4108 /* None of two values of exponent is
4109 the right one. Prevent an endless
4113 if (ndigits < precision)
4119 /* Here ndigits = precision. */
4120 if (is_borderline (digits, precision - 1))
4122 /* Maybe the exponent guess was too high
4123 and a smaller exponent can be reached
4124 by turning a 10...0 into 9...9x. */
4126 scale10_round_decimal_long_double (arg,
4127 (int)(precision - 1) - exponent + 1);
4128 if (digits2 == NULL)
4131 END_LONG_DOUBLE_ROUNDING ();
4134 if (strlen (digits2) == precision)
4143 /* Here ndigits = precision. */
4145 /* Determine the number of trailing zeroes
4146 that have to be dropped. */
4148 if ((flags & FLAG_ALT) == 0)
4149 while (nzeroes < ndigits
4150 && digits[nzeroes] == '0')
4153 /* The exponent is now determined. */
4155 && exponent < (long)precision)
4157 /* Fixed-point notation:
4158 max(exponent,0)+1 digits, then the
4159 decimal point, then the remaining
4160 digits without trailing zeroes. */
4163 size_t ecount = exponent + 1;
4164 /* Note: count <= precision = ndigits. */
4165 for (; ecount > 0; ecount--)
4166 *p++ = digits[--ndigits];
4167 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4169 *p++ = decimal_point_char ();
4170 while (ndigits > nzeroes)
4173 *p++ = digits[ndigits];
4179 size_t ecount = -exponent - 1;
4181 *p++ = decimal_point_char ();
4182 for (; ecount > 0; ecount--)
4184 while (ndigits > nzeroes)
4187 *p++ = digits[ndigits];
4193 /* Exponential notation. */
4194 *p++ = digits[--ndigits];
4195 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4197 *p++ = decimal_point_char ();
4198 while (ndigits > nzeroes)
4201 *p++ = digits[ndigits];
4204 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
4205 # if WIDE_CHAR_VERSION
4207 static const wchar_t decimal_format[] =
4208 { '%', '+', '.', '2', 'd', '\0' };
4209 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4214 if (sizeof (DCHAR_T) == 1)
4216 sprintf ((char *) p, "%+.2d", exponent);
4224 sprintf (expbuf, "%+.2d", exponent);
4225 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4237 /* arg is finite. */
4243 if (dp->conversion == 'f' || dp->conversion == 'F')
4246 if ((flags & FLAG_ALT) || precision > 0)
4248 *p++ = decimal_point_char ();
4249 for (; precision > 0; precision--)
4253 else if (dp->conversion == 'e' || dp->conversion == 'E')
4256 if ((flags & FLAG_ALT) || precision > 0)
4258 *p++ = decimal_point_char ();
4259 for (; precision > 0; precision--)
4262 *p++ = dp->conversion; /* 'e' or 'E' */
4267 else if (dp->conversion == 'g' || dp->conversion == 'G')
4270 if (flags & FLAG_ALT)
4273 (precision > 0 ? precision - 1 : 0);
4274 *p++ = decimal_point_char ();
4275 for (; ndigits > 0; --ndigits)
4279 else if (dp->conversion == 'a' || dp->conversion == 'A')
4282 *p++ = dp->conversion - 'A' + 'X';
4285 if ((flags & FLAG_ALT) || precision > 0)
4287 *p++ = decimal_point_char ();
4288 for (; precision > 0; precision--)
4291 *p++ = dp->conversion - 'A' + 'P';
4300 END_LONG_DOUBLE_ROUNDING ();
4303 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4307 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4309 double arg = a.arg[dp->arg_index].a.a_double;
4313 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
4315 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
4319 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
4326 if (signbit (arg)) /* arg < 0.0 or negative zero */
4334 else if (flags & FLAG_SHOWSIGN)
4336 else if (flags & FLAG_SPACE)
4339 if (arg > 0.0 && arg + arg == arg)
4341 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
4343 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
4347 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
4352 # if NEED_PRINTF_DOUBLE
4355 if (dp->conversion == 'f' || dp->conversion == 'F')
4361 scale10_round_decimal_double (arg, precision);
4364 ndigits = strlen (digits);
4366 if (ndigits > precision)
4370 *p++ = digits[ndigits];
4372 while (ndigits > precision);
4375 /* Here ndigits <= precision. */
4376 if ((flags & FLAG_ALT) || precision > 0)
4378 *p++ = decimal_point_char ();
4379 for (; precision > ndigits; precision--)
4384 *p++ = digits[ndigits];
4390 else if (dp->conversion == 'e' || dp->conversion == 'E')
4398 if ((flags & FLAG_ALT) || precision > 0)
4400 *p++ = decimal_point_char ();
4401 for (; precision > 0; precision--)
4412 exponent = floorlog10 (arg);
4417 scale10_round_decimal_double (arg,
4418 (int)precision - exponent);
4421 ndigits = strlen (digits);
4423 if (ndigits == precision + 1)
4425 if (ndigits < precision
4426 || ndigits > precision + 2)
4427 /* The exponent was not guessed
4428 precisely enough. */
4431 /* None of two values of exponent is
4432 the right one. Prevent an endless
4436 if (ndigits == precision)
4442 /* Here ndigits = precision+1. */
4443 if (is_borderline (digits, precision))
4445 /* Maybe the exponent guess was too high
4446 and a smaller exponent can be reached
4447 by turning a 10...0 into 9...9x. */
4449 scale10_round_decimal_double (arg,
4450 (int)precision - exponent + 1);
4451 if (digits2 == NULL)
4456 if (strlen (digits2) == precision + 1)
4465 /* Here ndigits = precision+1. */
4467 *p++ = digits[--ndigits];
4468 if ((flags & FLAG_ALT) || precision > 0)
4470 *p++ = decimal_point_char ();
4474 *p++ = digits[ndigits];
4481 *p++ = dp->conversion; /* 'e' or 'E' */
4482 # if WIDE_CHAR_VERSION
4484 static const wchar_t decimal_format[] =
4485 /* Produce the same number of exponent digits
4486 as the native printf implementation. */
4487 # if defined _WIN32 && ! defined __CYGWIN__
4488 { '%', '+', '.', '3', 'd', '\0' };
4490 { '%', '+', '.', '2', 'd', '\0' };
4492 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4498 static const char decimal_format[] =
4499 /* Produce the same number of exponent digits
4500 as the native printf implementation. */
4501 # if defined _WIN32 && ! defined __CYGWIN__
4506 if (sizeof (DCHAR_T) == 1)
4508 sprintf ((char *) p, decimal_format, exponent);
4516 sprintf (expbuf, decimal_format, exponent);
4517 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4523 else if (dp->conversion == 'g' || dp->conversion == 'G')
4527 /* precision >= 1. */
4530 /* The exponent is 0, >= -4, < precision.
4531 Use fixed-point notation. */
4533 size_t ndigits = precision;
4534 /* Number of trailing zeroes that have to be
4537 (flags & FLAG_ALT ? 0 : precision - 1);
4541 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4543 *p++ = decimal_point_char ();
4544 while (ndigits > nzeroes)
4560 exponent = floorlog10 (arg);
4565 scale10_round_decimal_double (arg,
4566 (int)(precision - 1) - exponent);
4569 ndigits = strlen (digits);
4571 if (ndigits == precision)
4573 if (ndigits < precision - 1
4574 || ndigits > precision + 1)
4575 /* The exponent was not guessed
4576 precisely enough. */
4579 /* None of two values of exponent is
4580 the right one. Prevent an endless
4584 if (ndigits < precision)
4590 /* Here ndigits = precision. */
4591 if (is_borderline (digits, precision - 1))
4593 /* Maybe the exponent guess was too high
4594 and a smaller exponent can be reached
4595 by turning a 10...0 into 9...9x. */
4597 scale10_round_decimal_double (arg,
4598 (int)(precision - 1) - exponent + 1);
4599 if (digits2 == NULL)
4604 if (strlen (digits2) == precision)
4613 /* Here ndigits = precision. */
4615 /* Determine the number of trailing zeroes
4616 that have to be dropped. */
4618 if ((flags & FLAG_ALT) == 0)
4619 while (nzeroes < ndigits
4620 && digits[nzeroes] == '0')
4623 /* The exponent is now determined. */
4625 && exponent < (long)precision)
4627 /* Fixed-point notation:
4628 max(exponent,0)+1 digits, then the
4629 decimal point, then the remaining
4630 digits without trailing zeroes. */
4633 size_t ecount = exponent + 1;
4634 /* Note: ecount <= precision = ndigits. */
4635 for (; ecount > 0; ecount--)
4636 *p++ = digits[--ndigits];
4637 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4639 *p++ = decimal_point_char ();
4640 while (ndigits > nzeroes)
4643 *p++ = digits[ndigits];
4649 size_t ecount = -exponent - 1;
4651 *p++ = decimal_point_char ();
4652 for (; ecount > 0; ecount--)
4654 while (ndigits > nzeroes)
4657 *p++ = digits[ndigits];
4663 /* Exponential notation. */
4664 *p++ = digits[--ndigits];
4665 if ((flags & FLAG_ALT) || ndigits > nzeroes)
4667 *p++ = decimal_point_char ();
4668 while (ndigits > nzeroes)
4671 *p++ = digits[ndigits];
4674 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
4675 # if WIDE_CHAR_VERSION
4677 static const wchar_t decimal_format[] =
4678 /* Produce the same number of exponent digits
4679 as the native printf implementation. */
4680 # if defined _WIN32 && ! defined __CYGWIN__
4681 { '%', '+', '.', '3', 'd', '\0' };
4683 { '%', '+', '.', '2', 'd', '\0' };
4685 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4691 static const char decimal_format[] =
4692 /* Produce the same number of exponent digits
4693 as the native printf implementation. */
4694 # if defined _WIN32 && ! defined __CYGWIN__
4699 if (sizeof (DCHAR_T) == 1)
4701 sprintf ((char *) p, decimal_format, exponent);
4709 sprintf (expbuf, decimal_format, exponent);
4710 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4723 /* arg is finite. */
4729 if (dp->conversion == 'f' || dp->conversion == 'F')
4732 if ((flags & FLAG_ALT) || precision > 0)
4734 *p++ = decimal_point_char ();
4735 for (; precision > 0; precision--)
4739 else if (dp->conversion == 'e' || dp->conversion == 'E')
4742 if ((flags & FLAG_ALT) || precision > 0)
4744 *p++ = decimal_point_char ();
4745 for (; precision > 0; precision--)
4748 *p++ = dp->conversion; /* 'e' or 'E' */
4750 /* Produce the same number of exponent digits as
4751 the native printf implementation. */
4752 # if defined _WIN32 && ! defined __CYGWIN__
4758 else if (dp->conversion == 'g' || dp->conversion == 'G')
4761 if (flags & FLAG_ALT)
4764 (precision > 0 ? precision - 1 : 0);
4765 *p++ = decimal_point_char ();
4766 for (; ndigits > 0; --ndigits)
4778 /* The generated string now extends from tmp to p, with the
4779 zero padding insertion point being at pad_ptr. */
4784 size_t pad = width - count;
4785 DCHAR_T *end = p + pad;
4787 if (flags & FLAG_LEFT)
4789 /* Pad with spaces on the right. */
4790 for (; pad > 0; pad--)
4793 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4795 /* Pad with zeroes. */
4800 for (; pad > 0; pad--)
4805 /* Pad with spaces on the left. */
4810 for (; pad > 0; pad--)
4819 if (count >= tmp_length)
4820 /* tmp_length was incorrectly calculated - fix the
4824 /* Make room for the result. */
4825 if (count >= allocated - length)
4827 size_t n = xsum (length, count);
4829 ENSURE_ALLOCATION (n);
4832 /* Append the result. */
4833 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4841 arg_type type = a.arg[dp->arg_index].type;
4842 int flags = dp->flags;
4843 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4846 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4849 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
4853 #if NEED_PRINTF_UNBOUNDED_PRECISION
4856 # define prec_ourselves 0
4858 #if NEED_PRINTF_FLAG_LEFTADJUST
4859 # define pad_ourselves 1
4860 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4863 # define pad_ourselves 0
4866 unsigned int prefix_count;
4867 int prefixes[2] IF_LINT (= { 0 });
4871 TCHAR_T tmpbuf[700];
4875 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4878 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4880 if (dp->width_start != dp->width_end)
4882 if (dp->width_arg_index != ARG_NONE)
4886 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4888 arg = a.arg[dp->width_arg_index].a.a_int;
4892 /* "A negative field width is taken as a '-' flag
4893 followed by a positive field width." */
4900 const FCHAR_T *digitp = dp->width_start;
4903 width = xsum (xtimes (width, 10), *digitp++ - '0');
4904 while (digitp != dp->width_end);
4906 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
4912 #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION
4915 if (dp->precision_start != dp->precision_end)
4917 if (dp->precision_arg_index != ARG_NONE)
4921 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4923 arg = a.arg[dp->precision_arg_index].a.a_int;
4924 /* "A negative precision is taken as if the precision
4934 const FCHAR_T *digitp = dp->precision_start + 1;
4937 while (digitp != dp->precision_end)
4938 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
4944 /* Decide whether to handle the precision ourselves. */
4945 #if NEED_PRINTF_UNBOUNDED_PRECISION
4946 switch (dp->conversion)
4948 case 'd': case 'i': case 'u':
4950 case 'x': case 'X': case 'p':
4951 prec_ourselves = has_precision && (precision > 0);
4959 /* Decide whether to perform the padding ourselves. */
4960 #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
4961 switch (dp->conversion)
4963 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
4964 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
4965 to perform the padding after this conversion. Functions
4966 with unistdio extensions perform the padding based on
4967 character count rather than element count. */
4970 # if NEED_PRINTF_FLAG_ZERO
4971 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
4977 pad_ourselves = prec_ourselves;
4983 /* Allocate a temporary buffer of sufficient size for calling
4986 MAX_ROOM_NEEDED (&a, dp->arg_index, dp->conversion, type,
4987 flags, width, has_precision, precision,
4990 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
4994 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
4996 if (size_overflow_p (tmp_memsize))
4997 /* Overflow, would lead to out of memory. */
4999 tmp = (TCHAR_T *) malloc (tmp_memsize);
5001 /* Out of memory. */
5006 /* Construct the format string for calling snprintf or
5010 #if NEED_PRINTF_FLAG_GROUPING
5011 /* The underlying implementation doesn't support the ' flag.
5012 Produce no grouping characters in this case; this is
5013 acceptable because the grouping is locale dependent. */
5015 if (flags & FLAG_GROUP)
5018 if (flags & FLAG_LEFT)
5020 if (flags & FLAG_SHOWSIGN)
5022 if (flags & FLAG_SPACE)
5024 if (flags & FLAG_ALT)
5026 #if __GLIBC__ >= 2 && !defined __UCLIBC__
5027 if (flags & FLAG_LOCALIZED)
5032 if (flags & FLAG_ZERO)
5034 if (dp->width_start != dp->width_end)
5036 size_t n = dp->width_end - dp->width_start;
5037 /* The width specification is known to consist only
5038 of standard ASCII characters. */
5039 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
5041 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
5046 const FCHAR_T *mp = dp->width_start;
5053 if (!prec_ourselves)
5055 if (dp->precision_start != dp->precision_end)
5057 size_t n = dp->precision_end - dp->precision_start;
5058 /* The precision specification is known to consist only
5059 of standard ASCII characters. */
5060 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
5062 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
5067 const FCHAR_T *mp = dp->precision_start;
5077 case TYPE_LONGLONGINT:
5078 case TYPE_ULONGLONGINT:
5079 #if defined _WIN32 && ! defined __CYGWIN__
5091 case TYPE_WIDE_CHAR:
5094 case TYPE_WIDE_STRING:
5098 case TYPE_LONGDOUBLE:
5104 #if NEED_PRINTF_DIRECTIVE_F
5105 if (dp->conversion == 'F')
5109 *fbp = dp->conversion;
5111 # if ((HAVE_SNPRINTF_RETVAL_C99 && HAVE_SNPRINTF_TRUNCATION_C99) \
5112 || ((__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) \
5113 && !defined __UCLIBC__) \
5114 || (defined __APPLE__ && defined __MACH__) \
5115 || defined __ANDROID__ \
5116 || (defined _WIN32 && ! defined __CYGWIN__))
5117 /* On systems where we know that snprintf's return value
5118 conforms to ISO C 99 (HAVE_SNPRINTF_RETVAL_C99) and that
5119 snprintf always produces NUL-terminated strings
5120 (HAVE_SNPRINTF_TRUNCATION_C99), it is possible to avoid
5121 using %n. And it is desirable to do so, because more and
5122 more platforms no longer support %n, for "security reasons".
5123 In particular, the following platforms:
5124 - On glibc2 systems from 2004-10-18 or newer, the use of
5125 %n in format strings in writable memory may crash the
5126 program (if compiled with _FORTIFY_SOURCE=2).
5127 - On Mac OS X 10.13 or newer, the use of %n in format
5128 strings in writable memory by default crashes the
5130 - On Android, starting on 2018-03-07, the use of %n in
5131 format strings produces a fatal error (see
5132 <https://android.googlesource.com/platform/bionic/+/41398d03b7e8e0dfb951660ae713e682e9fc0336>).
5133 On these platforms, HAVE_SNPRINTF_RETVAL_C99 and
5134 HAVE_SNPRINTF_TRUNCATION_C99 are 1. We have listed them
5135 explicitly in the condition above, in case of cross-
5136 compilation (just to be sure). */
5137 /* On native Windows systems (such as mingw), we can avoid using
5139 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
5140 snprintf does not write more than the specified number
5141 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
5142 '4', '5', '6' into buf, not '4', '5', '\0'.)
5143 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
5144 allows us to recognize the case of an insufficient
5145 buffer size: it returns -1 in this case.
5146 On native Windows systems (such as mingw) where the OS is
5147 Windows Vista, the use of %n in format strings by default
5148 crashes the program. See
5149 <https://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
5150 <https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/set-printf-count-output>
5151 So we should avoid %n in this situation. */
5153 # else /* AIX <= 5.1, HP-UX, IRIX, OSF/1, Solaris <= 9, BeOS */
5162 /* Construct the arguments for calling snprintf or sprintf. */
5164 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
5166 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
5168 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
5170 if (!prec_ourselves && dp->precision_arg_index != ARG_NONE)
5172 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
5174 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
5178 /* The SNPRINTF result is appended after result[0..length].
5179 The latter is an array of DCHAR_T; SNPRINTF appends an
5180 array of TCHAR_T to it. This is possible because
5181 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
5182 alignof (TCHAR_T) <= alignof (DCHAR_T). */
5183 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
5184 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
5185 where an snprintf() with maxlen==1 acts like sprintf(). */
5186 ENSURE_ALLOCATION (xsum (length,
5187 (2 + TCHARS_PER_DCHAR - 1)
5188 / TCHARS_PER_DCHAR));
5189 /* Prepare checking whether snprintf returns the count
5191 *(TCHAR_T *) (result + length) = '\0';
5202 size_t maxlen = allocated - length;
5203 /* SNPRINTF can fail if its second argument is
5205 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
5206 maxlen = INT_MAX / TCHARS_PER_DCHAR;
5207 maxlen = maxlen * TCHARS_PER_DCHAR;
5208 # define SNPRINTF_BUF(arg) \
5209 switch (prefix_count) \
5212 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
5217 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
5219 prefixes[0], arg, &count); \
5222 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
5224 prefixes[0], prefixes[1], arg, \
5231 # define SNPRINTF_BUF(arg) \
5232 switch (prefix_count) \
5235 count = sprintf (tmp, buf, arg); \
5238 count = sprintf (tmp, buf, prefixes[0], arg); \
5241 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
5254 int arg = a.arg[dp->arg_index].a.a_schar;
5260 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
5266 int arg = a.arg[dp->arg_index].a.a_short;
5272 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
5278 int arg = a.arg[dp->arg_index].a.a_int;
5284 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
5290 long int arg = a.arg[dp->arg_index].a.a_longint;
5296 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
5300 case TYPE_LONGLONGINT:
5302 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
5306 case TYPE_ULONGLONGINT:
5308 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
5314 double arg = a.arg[dp->arg_index].a.a_double;
5318 case TYPE_LONGDOUBLE:
5320 long double arg = a.arg[dp->arg_index].a.a_longdouble;
5326 int arg = a.arg[dp->arg_index].a.a_char;
5331 case TYPE_WIDE_CHAR:
5333 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
5340 const char *arg = a.arg[dp->arg_index].a.a_string;
5345 case TYPE_WIDE_STRING:
5347 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
5354 void *arg = a.arg[dp->arg_index].a.a_pointer;
5363 /* Portability: Not all implementations of snprintf()
5364 are ISO C 99 compliant. Determine the number of
5365 bytes that snprintf() has produced or would have
5369 /* Verify that snprintf() has NUL-terminated its
5371 if ((unsigned int) count < maxlen
5372 && ((TCHAR_T *) (result + length)) [count] != '\0')
5374 /* Portability hack. */
5375 if (retcount > count)
5380 /* snprintf() doesn't understand the '%n'
5384 /* Don't use the '%n' directive; instead, look
5385 at the snprintf() return value. */
5391 /* Look at the snprintf() return value. */
5394 # if !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF
5395 /* HP-UX 10.20 snprintf() is doubly deficient:
5396 It doesn't understand the '%n' directive,
5397 *and* it returns -1 (rather than the length
5398 that would have been required) when the
5399 buffer is too small.
5400 But a failure at this point can also come
5401 from other reasons than a too small buffer,
5402 such as an invalid wide string argument to
5403 the %ls directive, or possibly an invalid
5404 floating-point argument. */
5406 MAX_ROOM_NEEDED (&a, dp->arg_index,
5407 dp->conversion, type, flags,
5410 precision, pad_ourselves);
5412 if (maxlen < tmp_length)
5414 /* Make more room. But try to do through
5415 this reallocation only once. */
5416 size_t bigger_need =
5419 TCHARS_PER_DCHAR - 1)
5420 / TCHARS_PER_DCHAR);
5421 /* And always grow proportionally.
5422 (There may be several arguments, each
5423 needing a little more room than the
5425 size_t bigger_need2 =
5426 xsum (xtimes (allocated, 2), 12);
5427 if (bigger_need < bigger_need2)
5428 bigger_need = bigger_need2;
5429 ENSURE_ALLOCATION (bigger_need);
5440 /* Attempt to handle failure. */
5443 /* SNPRINTF or sprintf failed. Use the errno that it
5447 if (dp->conversion == 'c' || dp->conversion == 's')
5453 if (!(result == resultbuf || result == NULL))
5455 if (buf_malloced != NULL)
5456 free (buf_malloced);
5463 /* Handle overflow of the allocated buffer.
5464 If such an overflow occurs, a C99 compliant snprintf()
5465 returns a count >= maxlen. However, a non-compliant
5466 snprintf() function returns only count = maxlen - 1. To
5467 cover both cases, test whether count >= maxlen - 1. */
5468 if ((unsigned int) count + 1 >= maxlen)
5470 /* If maxlen already has attained its allowed maximum,
5471 allocating more memory will not increase maxlen.
5472 Instead of looping, bail out. */
5473 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
5477 /* Need at least (count + 1) * sizeof (TCHAR_T)
5478 bytes. (The +1 is for the trailing NUL.)
5479 But ask for (count + 2) * sizeof (TCHAR_T)
5480 bytes, so that in the next round, we likely get
5481 maxlen > (unsigned int) count + 1
5482 and so we don't get here again.
5483 And allocate proportionally, to avoid looping
5484 eternally if snprintf() reports a too small
5488 ((unsigned int) count + 2
5489 + TCHARS_PER_DCHAR - 1)
5490 / TCHARS_PER_DCHAR),
5491 xtimes (allocated, 2));
5493 ENSURE_ALLOCATION (n);
5499 #if NEED_PRINTF_UNBOUNDED_PRECISION
5502 /* Handle the precision. */
5505 (TCHAR_T *) (result + length);
5509 size_t prefix_count;
5513 /* Put the additional zeroes after the sign. */
5515 && (*prec_ptr == '-' || *prec_ptr == '+'
5516 || *prec_ptr == ' '))
5518 /* Put the additional zeroes after the 0x prefix if
5519 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
5521 && prec_ptr[0] == '0'
5522 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
5525 move = count - prefix_count;
5526 if (precision > move)
5528 /* Insert zeroes. */
5529 size_t insert = precision - move;
5535 (count + insert + TCHARS_PER_DCHAR - 1)
5536 / TCHARS_PER_DCHAR);
5537 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5538 ENSURE_ALLOCATION (n);
5539 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
5540 prec_ptr = (TCHAR_T *) (result + length);
5543 prec_end = prec_ptr + count;
5544 prec_ptr += prefix_count;
5546 while (prec_end > prec_ptr)
5549 prec_end[insert] = prec_end[0];
5555 while (prec_end > prec_ptr);
5563 if (count >= tmp_length)
5564 /* tmp_length was incorrectly calculated - fix the
5570 /* Convert from TCHAR_T[] to DCHAR_T[]. */
5571 if (dp->conversion == 'c' || dp->conversion == 's')
5573 /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING
5575 The result string is not certainly ASCII. */
5576 const TCHAR_T *tmpsrc;
5579 /* This code assumes that TCHAR_T is 'char'. */
5580 verify (sizeof (TCHAR_T) == 1);
5582 tmpsrc = (TCHAR_T *) (result + length);
5587 DCHAR_CONV_FROM_ENCODING (locale_charset (),
5588 iconveh_question_mark,
5594 if (!(result == resultbuf || result == NULL))
5596 if (buf_malloced != NULL)
5597 free (buf_malloced);
5601 ENSURE_ALLOCATION (xsum (length, tmpdst_len));
5602 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
5608 /* The result string is ASCII.
5609 Simple 1:1 conversion. */
5611 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
5612 no-op conversion, in-place on the array starting
5613 at (result + length). */
5614 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
5617 const TCHAR_T *tmpsrc;
5622 if (result == resultbuf)
5624 tmpsrc = (TCHAR_T *) (result + length);
5625 /* ENSURE_ALLOCATION will not move tmpsrc
5626 (because it's part of resultbuf). */
5627 ENSURE_ALLOCATION (xsum (length, count));
5631 /* ENSURE_ALLOCATION will move the array
5632 (because it uses realloc(). */
5633 ENSURE_ALLOCATION (xsum (length, count));
5634 tmpsrc = (TCHAR_T *) (result + length);
5638 ENSURE_ALLOCATION (xsum (length, count));
5640 tmpdst = result + length;
5641 /* Copy backwards, because of overlapping. */
5644 for (n = count; n > 0; n--)
5645 *--tmpdst = *--tmpsrc;
5650 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
5651 /* Make room for the result. */
5652 if (count > allocated - length)
5654 /* Need at least count elements. But allocate
5657 xmax (xsum (length, count), xtimes (allocated, 2));
5659 ENSURE_ALLOCATION (n);
5663 /* Here count <= allocated - length. */
5665 /* Perform padding. */
5666 #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5667 if (pad_ourselves && has_width)
5670 # if ENABLE_UNISTDIO
5671 /* Outside POSIX, it's preferable to compare the width
5672 against the number of _characters_ of the converted
5674 w = DCHAR_MBSNLEN (result + length, count);
5676 /* The width is compared against the number of _bytes_
5677 of the converted value, says POSIX. */
5682 size_t pad = width - w;
5684 /* Make room for the result. */
5685 if (xsum (count, pad) > allocated - length)
5687 /* Need at least count + pad elements. But
5688 allocate proportionally. */
5690 xmax (xsum3 (length, count, pad),
5691 xtimes (allocated, 2));
5695 ENSURE_ALLOCATION (n);
5698 ENSURE_ALLOCATION (n);
5701 /* Here count + pad <= allocated - length. */
5704 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
5705 DCHAR_T * const rp = result + length;
5707 DCHAR_T * const rp = tmp;
5709 DCHAR_T *p = rp + count;
5710 DCHAR_T *end = p + pad;
5712 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
5713 if (dp->conversion == 'c'
5714 || dp->conversion == 's')
5715 /* No zero-padding for string directives. */
5720 pad_ptr = (*rp == '-' ? rp + 1 : rp);
5721 /* No zero-padding of "inf" and "nan". */
5722 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
5723 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
5726 /* The generated string now extends from rp to p,
5727 with the zero padding insertion point being at
5730 count = count + pad; /* = end - rp */
5732 if (flags & FLAG_LEFT)
5734 /* Pad with spaces on the right. */
5735 for (; pad > 0; pad--)
5738 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
5740 /* Pad with zeroes. */
5745 for (; pad > 0; pad--)
5750 /* Pad with spaces on the left. */
5755 for (; pad > 0; pad--)
5763 /* Here still count <= allocated - length. */
5765 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
5766 /* The snprintf() result did fit. */
5768 /* Append the sprintf() result. */
5769 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
5776 #if NEED_PRINTF_DIRECTIVE_F
5777 if (dp->conversion == 'F')
5779 /* Convert the %f result to upper case for %F. */
5780 DCHAR_T *rp = result + length;
5782 for (rc = count; rc > 0; rc--, rp++)
5783 if (*rp >= 'a' && *rp <= 'z')
5784 *rp = *rp - 'a' + 'A';
5792 #undef pad_ourselves
5793 #undef prec_ourselves
5798 /* Add the final NUL. */
5799 ENSURE_ALLOCATION (xsum (length, 1));
5800 result[length] = '\0';
5802 if (result != resultbuf && length + 1 < allocated)
5804 /* Shrink the allocated memory if possible. */
5807 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
5812 if (buf_malloced != NULL)
5813 free (buf_malloced);
5816 /* Note that we can produce a big string of a length > INT_MAX. POSIX
5817 says that snprintf() fails with errno = EOVERFLOW in this case, but
5818 that's only because snprintf() returns an 'int'. This function does
5819 not have this limitation. */
5824 if (!(result == resultbuf || result == NULL))
5826 if (buf_malloced != NULL)
5827 free (buf_malloced);
5834 if (!(result == resultbuf || result == NULL))
5836 if (buf_malloced != NULL)
5837 free (buf_malloced);
5845 #undef MAX_ROOM_NEEDED
5846 #undef TCHARS_PER_DCHAR
5854 #undef DCHAR_IS_TCHAR