Debian Codegraph @

lib/vasnprintf.c

raw
1 /* vsprintf with automatic memory allocation.
2 Copyright (C) 1999, 2002-2024 Free Software Foundation, Inc.
3
4 This file is free software: you can redistribute it and/or modify
5 it under the terms of the GNU Lesser General Public License as
6 published by the Free Software Foundation; either version 2.1 of the
7 License, or (at your option) any later version.
8
9 This file 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 Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
16
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.
25 Depends on FCHAR_T.
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.
29 Depends on FCHAR_T.
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.
51 */
52
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. */
56 #ifndef _GNU_SOURCE
57 # define _GNU_SOURCE 1
58 #endif
59
60 #ifndef VASNPRINTF
61 # include <config.h>
62 #endif
63
64 /* As of GCC 11.2.1, gcc -Wanalyzer-too-complex reports that main's
65 use of CHECK macros expands to code that is too complicated for gcc
66 -fanalyzer. Suppress the resulting bogus warnings. */
67 #if _GL_GNUC_PREREQ (10, 0)
68 # pragma GCC diagnostic ignored "-Wanalyzer-null-argument"
69 #endif
70
71 #include <alloca.h>
72
73 /* Specification. */
74 #ifndef VASNPRINTF
75 # if WIDE_CHAR_VERSION
76 # include "vasnwprintf.h"
77 # else
78 # include "vasnprintf.h"
79 # endif
80 #endif
81
82 #include <locale.h> /* localeconv() */
83 #include <stdint.h> /* PTRDIFF_MAX */
84 #include <stdio.h> /* snprintf(), sprintf() */
85 #include <stdlib.h> /* abort(), malloc(), realloc(), free() */
86 #include <string.h> /* memcpy(), strlen() */
87 #include <wchar.h> /* mbstate_t, mbrtowc(), mbrlen(), wcrtomb(), mbszero() */
88 #include <errno.h> /* errno */
89 #include <limits.h> /* CHAR_BIT, INT_MAX, INT_WIDTH, LONG_WIDTH */
90 #include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP, LDBL_MANT_DIG */
91 #if HAVE_NL_LANGINFO
92 # include <langinfo.h>
93 #endif
94 #ifndef VASNPRINTF
95 # if WIDE_CHAR_VERSION
96 # include "wprintf-parse.h"
97 # else
98 # include "printf-parse.h"
99 # endif
100 #endif
101
102 /* Checked size_t computations. */
103 #include "xsize.h"
104
105 #include "attribute.h"
106
107 #if NEED_PRINTF_DOUBLE || NEED_PRINTF_LONG_DOUBLE || (NEED_WPRINTF_DIRECTIVE_LA && WIDE_CHAR_VERSION)
108 # include <math.h>
109 # include "float+.h"
110 #endif
111
112 #if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
113 # include <math.h>
114 # include "isnand-nolibm.h"
115 #endif
116
117 #if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || (NEED_WPRINTF_DIRECTIVE_LA && WIDE_CHAR_VERSION)
118 # include <math.h>
119 # include "isnanl-nolibm.h"
120 # include "fpucw.h"
121 #endif
122
123 #if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
124 # include <math.h>
125 # include "isnand-nolibm.h"
126 # include "printf-frexp.h"
127 #endif
128
129 #if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || (NEED_WPRINTF_DIRECTIVE_LA && WIDE_CHAR_VERSION)
130 # include <math.h>
131 # include "isnanl-nolibm.h"
132 # include "printf-frexpl.h"
133 # include "fpucw.h"
134 #endif
135
136 /* Default parameters. */
137 #ifndef VASNPRINTF
138 # if WIDE_CHAR_VERSION
139 # define VASNPRINTF vasnwprintf
140 # define FCHAR_T wchar_t
141 # define DCHAR_T wchar_t
142 # define DIRECTIVE wchar_t_directive
143 # define DIRECTIVES wchar_t_directives
144 # define PRINTF_PARSE wprintf_parse
145 # define DCHAR_CPY wmemcpy
146 # define DCHAR_SET wmemset
147 # else
148 # define VASNPRINTF vasnprintf
149 # define FCHAR_T char
150 # define DCHAR_T char
151 # define TCHAR_T char
152 # define DCHAR_IS_TCHAR 1
153 # define DIRECTIVE char_directive
154 # define DIRECTIVES char_directives
155 # define PRINTF_PARSE printf_parse
156 # define DCHAR_CPY memcpy
157 # define DCHAR_SET memset
158 # endif
159 #endif
160 #if WIDE_CHAR_VERSION
161 /* DCHAR_T is wchar_t. */
162 # if HAVE_DECL__SNWPRINTF || (HAVE_SWPRINTF && HAVE_WORKING_SWPRINTF)
163 # define TCHAR_T wchar_t
164 # define DCHAR_IS_TCHAR 1
165 # define USE_SNPRINTF 1
166 # if HAVE_DECL__SNWPRINTF
167 /* On Windows, the function swprintf() has a different signature than
168 on Unix; we use the function _snwprintf() or - on mingw - snwprintf()
169 instead. The mingw function snwprintf() has fewer bugs than the
170 MSVCRT function _snwprintf(), so prefer that. */
171 # if defined __MINGW32__
172 # define SNPRINTF snwprintf
173 # else
174 # define SNPRINTF _snwprintf
175 # define USE_MSVC__SNPRINTF 1
176 # endif
177 # else
178 /* Unix. */
179 # define SNPRINTF swprintf
180 # endif
181 # else
182 /* Old platforms such as NetBSD 3.0, OpenBSD 3.8, HP-UX 11.00, IRIX 6.5. */
183 # define TCHAR_T char
184 # endif
185 #endif
186 #if !WIDE_CHAR_VERSION || !DCHAR_IS_TCHAR
187 /* TCHAR_T is char. */
188 /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'.
189 But don't use it on BeOS, since BeOS snprintf produces no output if the
190 size argument is >= 0x3000000.
191 Also don't use it on Linux libc5, since there snprintf with size = 1
192 writes any output without bounds, like sprintf. */
193 # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__ && !(__GNU_LIBRARY__ == 1)
194 # define USE_SNPRINTF 1
195 # else
196 # define USE_SNPRINTF 0
197 # endif
198 # if HAVE_DECL__SNPRINTF
199 /* Windows. The mingw function snprintf() has fewer bugs than the MSVCRT
200 function _snprintf(), so prefer that. */
201 # if defined __MINGW32__
202 # define SNPRINTF snprintf
203 /* Here we need to call the native snprintf, not rpl_snprintf. */
204 # undef snprintf
205 # else
206 /* MSVC versions < 14 did not have snprintf, only _snprintf. */
207 # define SNPRINTF _snprintf
208 # define USE_MSVC__SNPRINTF 1
209 # endif
210 # else
211 /* Unix. */
212 # define SNPRINTF snprintf
213 /* Here we need to call the native snprintf, not rpl_snprintf. */
214 # undef snprintf
215 # endif
216 #endif
217 /* Here we need to call the native sprintf, not rpl_sprintf. */
218 #undef sprintf
219
220 /* GCC >= 4.0 with -Wall emits unjustified "... may be used uninitialized"
221 warnings in this file. Use -Dlint to suppress them. */
222 #if defined GCC_LINT || defined lint
223 # define IF_LINT(Code) Code
224 #else
225 # define IF_LINT(Code) /* empty */
226 #endif
227
228 /* Avoid some warnings from "gcc -Wshadow".
229 This file doesn't use the exp() and remainder() functions. */
230 #undef exp
231 #define exp expo
232 #undef remainder
233 #define remainder rem
234
235 #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || (PTRDIFF_MAX > INT_MAX)) && !WIDE_CHAR_VERSION
236 # if (HAVE_STRNLEN && !defined _AIX)
237 # define local_strnlen strnlen
238 # else
239 # ifndef local_strnlen_defined
240 # define local_strnlen_defined 1
241 static size_t
242 local_strnlen (const char *string, size_t maxlen)
243 {
244 const char *end = memchr (string, '\0', maxlen);
245 return end ? (size_t) (end - string) : maxlen;
246 }
247 # endif
248 # endif
249 #endif
250
251 #if ((!USE_SNPRINTF || WIDE_CHAR_VERSION || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || (PTRDIFF_MAX > INT_MAX) || !DCHAR_IS_TCHAR || NEED_WPRINTF_DIRECTIVE_LC) && WIDE_CHAR_VERSION) || ((!USE_SNPRINTF || (PTRDIFF_MAX > INT_MAX) || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || NEED_PRINTF_DIRECTIVE_LS) && !WIDE_CHAR_VERSION && DCHAR_IS_TCHAR)
252 # if HAVE_WCSLEN
253 # define local_wcslen wcslen
254 # else
255 /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid
256 a dependency towards this library, here is a local substitute.
257 Define this substitute only once, even if this file is included
258 twice in the same compilation unit. */
259 # ifndef local_wcslen_defined
260 # define local_wcslen_defined 1
261 static size_t
262 local_wcslen (const wchar_t *s)
263 {
264 const wchar_t *ptr;
265
266 for (ptr = s; *ptr != (wchar_t) 0; ptr++)
267 ;
268 return ptr - s;
269 }
270 # endif
271 # endif
272 #endif
273
274 #if (!USE_SNPRINTF || (WIDE_CHAR_VERSION && DCHAR_IS_TCHAR) || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF) && WIDE_CHAR_VERSION
275 # if HAVE_WCSNLEN && HAVE_DECL_WCSNLEN
276 # define local_wcsnlen wcsnlen
277 # else
278 # ifndef local_wcsnlen_defined
279 # define local_wcsnlen_defined 1
280 static size_t
281 local_wcsnlen (const wchar_t *s, size_t maxlen)
282 {
283 const wchar_t *ptr;
284
285 for (ptr = s; maxlen > 0 && *ptr != (wchar_t) 0; ptr++, maxlen--)
286 ;
287 return ptr - s;
288 }
289 # endif
290 # endif
291 #endif
292
293 #if ((!USE_SNPRINTF || (PTRDIFF_MAX > INT_MAX) || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || NEED_PRINTF_DIRECTIVE_LS || ENABLE_WCHAR_FALLBACK) || ((NEED_PRINTF_DIRECTIVE_LC || ENABLE_WCHAR_FALLBACK) && HAVE_WINT_T)) && !WIDE_CHAR_VERSION
294 # if ENABLE_WCHAR_FALLBACK
295 static size_t
296 wctomb_fallback (char *s, wchar_t wc)
297 {
298 static char const hex[16] = "0123456789ABCDEF";
299
300 s[0] = '\\';
301 if (sizeof (wchar_t) > 2 && wc > 0xffff)
302 {
303 # if __STDC_ISO_10646__ || (__GLIBC__ >= 2) || (defined _WIN32 || defined __CYGWIN__)
304 s[1] = 'U';
305 # else
306 s[1] = 'W';
307 # endif
308 s[2] = hex[(wc & 0xf0000000U) >> 28];
309 s[3] = hex[(wc & 0xf000000U) >> 24];
310 s[4] = hex[(wc & 0xf00000U) >> 20];
311 s[5] = hex[(wc & 0xf0000U) >> 16];
312 s[6] = hex[(wc & 0xf000U) >> 12];
313 s[7] = hex[(wc & 0xf00U) >> 8];
314 s[8] = hex[(wc & 0xf0U) >> 4];
315 s[9] = hex[wc & 0xfU];
316 return 10;
317 }
318 else
319 {
320 # if __STDC_ISO_10646__ || (__GLIBC__ >= 2) || (defined _WIN32 || defined __CYGWIN__)
321 s[1] = 'u';
322 # else
323 s[1] = 'w';
324 # endif
325 s[2] = hex[(wc & 0xf000U) >> 12];
326 s[3] = hex[(wc & 0xf00U) >> 8];
327 s[4] = hex[(wc & 0xf0U) >> 4];
328 s[5] = hex[wc & 0xfU];
329 return 6;
330 }
331 }
332 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
333 static size_t
334 local_wcrtomb (char *s, wchar_t wc, mbstate_t *ps)
335 {
336 size_t count = wcrtomb (s, wc, ps);
337 if (count == (size_t)(-1))
338 count = wctomb_fallback (s, wc);
339 return count;
340 }
341 # else
342 static int
343 local_wctomb (char *s, wchar_t wc)
344 {
345 int count = wctomb (s, wc);
346 if (count < 0)
347 count = wctomb_fallback (s, wc);
348 return count;
349 }
350 # define local_wcrtomb(S, WC, PS) local_wctomb ((S), (WC))
351 # endif
352 # else
353 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
354 # define local_wcrtomb(S, WC, PS) wcrtomb ((S), (WC), (PS))
355 # else
356 # define local_wcrtomb(S, WC, PS) wctomb ((S), (WC))
357 # endif
358 # endif
359 #endif
360
361 #if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE || (NEED_WPRINTF_DIRECTIVE_LA && WIDE_CHAR_VERSION)
362 /* Determine the decimal-point character according to the current locale. */
363 # ifndef decimal_point_char_defined
364 # define decimal_point_char_defined 1
365 static char
366 decimal_point_char (void)
367 {
368 const char *point;
369 /* Determine it in a multithread-safe way. We know nl_langinfo is
370 multithread-safe on glibc systems and Mac OS X systems, but is not required
371 to be multithread-safe by POSIX. sprintf(), however, is multithread-safe.
372 localeconv() is rarely multithread-safe. */
373 # if HAVE_NL_LANGINFO && (__GLIBC__ || defined __UCLIBC__ || (defined __APPLE__ && defined __MACH__))
374 point = nl_langinfo (RADIXCHAR);
375 # elif 1
376 char pointbuf[5];
377 sprintf (pointbuf, "%#.0f", 1.0);
378 point = &pointbuf[1];
379 # else
380 point = localeconv () -> decimal_point;
381 # endif
382 /* The decimal point is always a single byte: either '.' or ','. */
383 return (point[0] != '\0' ? point[0] : '.');
384 }
385 # endif
386 #endif
387
388 #if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE
389
390 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
391 static int
392 is_infinite_or_zero (double x)
393 {
394 return isnand (x) || x + x == x;
395 }
396
397 #endif
398
399 #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE
400
401 /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */
402 static int
403 is_infinite_or_zerol (long double x)
404 {
405 return isnanl (x) || x + x == x;
406 }
407
408 #endif
409
410 #if NEED_PRINTF_LONG_DOUBLE
411
412 /* Like frexpl, except that it supports even "unsupported" numbers. */
413 # if (LDBL_MANT_DIG == 64 && (defined __ia64 || (defined __x86_64__ || defined __amd64__) || (defined __i386 || defined __i386__ || defined _I386 || defined _M_IX86 || defined _X86_))) && (defined __APPLE__ && defined __MACH__)
414 /* Don't assume that frexpl can handle pseudo-denormals; it does not on
415 macOS 12/x86_64. Therefore test for a pseudo-denormal explicitly. */
416
417 static
418 long double safe_frexpl (long double x, int *exp)
419 {
420 union
421 {
422 long double value;
423 struct { unsigned int mant_word[2]; unsigned short sign_exp_word; } r;
424 }
425 u;
426 u.value = x;
427 if (u.r.sign_exp_word == 0 && (u.r.mant_word[1] & 0x80000000u) != 0)
428 {
429 /* Pseudo-Denormal. */
430 *exp = LDBL_MIN_EXP;
431 u.r.sign_exp_word = 1 - LDBL_MIN_EXP;
432 return u.value;
433 }
434 else
435 return frexpl (x, exp);
436 }
437
438 # else
439 # define safe_frexpl frexpl
440 # endif
441
442 #endif
443
444 #if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE
445
446 /* An indicator for a failed memory allocation. */
447 # define NOMEM_PTR ((void *) (-1))
448
449 /* Converting 'long double' to decimal without rare rounding bugs requires
450 real bignums. We use the naming conventions of GNU gmp, but vastly simpler
451 (and slower) algorithms. */
452
453 typedef unsigned int mp_limb_t;
454 # define GMP_LIMB_BITS 32
455 static_assert (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS);
456
457 typedef unsigned long long mp_twolimb_t;
458 # define GMP_TWOLIMB_BITS 64
459 static_assert (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS);
460
461 /* Representation of a bignum >= 0. */
462 typedef struct
463 {
464 size_t nlimbs;
465 mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */
466 } mpn_t;
467
468 /* Compute the product of two bignums >= 0.
469 Return the allocated memory (possibly NULL) in case of success, NOMEM_PTR
470 in case of memory allocation failure. */
471 static void *
472 multiply (mpn_t src1, mpn_t src2, mpn_t *dest)
473 {
474 const mp_limb_t *p1;
475 const mp_limb_t *p2;
476 size_t len1;
477 size_t len2;
478
479 if (src1.nlimbs <= src2.nlimbs)
480 {
481 len1 = src1.nlimbs;
482 p1 = src1.limbs;
483 len2 = src2.nlimbs;
484 p2 = src2.limbs;
485 }
486 else
487 {
488 len1 = src2.nlimbs;
489 p1 = src2.limbs;
490 len2 = src1.nlimbs;
491 p2 = src1.limbs;
492 }
493 /* Now 0 <= len1 <= len2. */
494 if (len1 == 0)
495 {
496 /* src1 or src2 is zero. */
497 dest->nlimbs = 0;
498 dest->limbs = NULL;
499 }
500 else
501 {
502 /* Here 1 <= len1 <= len2. */
503 size_t dlen;
504 mp_limb_t *dp;
505 size_t k, i, j;
506
507 dlen = len1 + len2;
508 dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t));
509 if (dp == NULL)
510 return NOMEM_PTR;
511 for (k = len2; k > 0; )
512 dp[--k] = 0;
513 for (i = 0; i < len1; i++)
514 {
515 mp_limb_t digit1 = p1[i];
516 mp_twolimb_t carry = 0;
517 for (j = 0; j < len2; j++)
518 {
519 mp_limb_t digit2 = p2[j];
520 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
521 carry += dp[i + j];
522 dp[i + j] = (mp_limb_t) carry;
523 carry = carry >> GMP_LIMB_BITS;
524 }
525 dp[i + len2] = (mp_limb_t) carry;
526 }
527 /* Normalise. */
528 while (dlen > 0 && dp[dlen - 1] == 0)
529 dlen--;
530 dest->nlimbs = dlen;
531 dest->limbs = dp;
532 }
533 return dest->limbs;
534 }
535
536 /* Compute the quotient of a bignum a >= 0 and a bignum b > 0.
537 a is written as a = q * b + r with 0 <= r < b. q is the quotient, r
538 the remainder.
539 Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd,
540 q is incremented.
541 Return the allocated memory (possibly NULL) in case of success, NOMEM_PTR
542 in case of memory allocation failure. */
543 static void *
544 divide (mpn_t a, mpn_t b, mpn_t *q)
545 {
546 /* Algorithm:
547 First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]
548 with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).
549 If m<n, then q:=0 and r:=a.
550 If m>=n=1, perform a single-precision division:
551 r:=0, j:=m,
552 while j>0 do
553 {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =
554 = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta}
555 j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j].
556 Normalise [q[m-1],...,q[0]], yields q.
557 If m>=n>1, perform a multiple-precision division:
558 We have a/b < beta^(m-n+1).
559 s:=intDsize-1-(highest bit in b[n-1]), 0<=s<intDsize.
560 Shift a and b left by s bits, copying them. r:=a.
561 r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2.
562 For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}
563 Compute q* :
564 q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).
565 In case of overflow (q* >= beta) set q* := beta-1.
566 Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]
567 and c3 := b[n-2] * q*.
568 {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow
569 occurred. Furthermore 0 <= c3 < beta^2.
570 If there was overflow and
571 r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,
572 the next test can be skipped.}
573 While c3 > c2, {Here 0 <= c2 < c3 < beta^2}
574 Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].
575 If q* > 0:
576 Put r := r - b * q* * beta^j. In detail:
577 [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].
578 hence: u:=0, for i:=0 to n-1 do
579 u := u + q* * b[i],
580 r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),
581 u:=u div beta (+ 1, if carry in subtraction)
582 r[n+j]:=r[n+j]-u.
583 {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1
584 < q* + 1 <= beta,
585 the carry u does not overflow.}
586 If a negative carry occurs, put q* := q* - 1
587 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].
588 Set q[j] := q*.
589 Normalise [q[m-n],..,q[0]]; this yields the quotient q.
590 Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the
591 rest r.
592 The room for q[j] can be allocated at the memory location of r[n+j].
593 Finally, round-to-even:
594 Shift r left by 1 bit.
595 If r > b or if r = b and q[0] is odd, q := q+1.
596 */
597 const mp_limb_t *a_ptr = a.limbs;
598 size_t a_len = a.nlimbs;
599 const mp_limb_t *b_ptr = b.limbs;
600 size_t b_len = b.nlimbs;
601 mp_limb_t *roomptr;
602 mp_limb_t *tmp_roomptr = NULL;
603 mp_limb_t *q_ptr;
604 size_t q_len;
605 mp_limb_t *r_ptr;
606 size_t r_len;
607
608 /* Allocate room for a_len+2 digits.
609 (Need a_len+1 digits for the real division and 1 more digit for the
610 final rounding of q.) */
611 roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
612 if (roomptr == NULL)
613 return NOMEM_PTR;
614
615 /* Normalise a. */
616 while (a_len > 0 && a_ptr[a_len - 1] == 0)
617 a_len--;
618
619 /* Normalise b. */
620 for (;;)
621 {
622 if (b_len == 0)
623 /* Division by zero. */
624 abort ();
625 if (b_ptr[b_len - 1] == 0)
626 b_len--;
627 else
628 break;
629 }
630
631 /* Here m = a_len >= 0 and n = b_len > 0. */
632
633 if (a_len < b_len)
634 {
635 /* m<n: trivial case. q=0, r := copy of a. */
636 r_ptr = roomptr;
637 r_len = a_len;
638 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
639 q_ptr = roomptr + a_len;
640 q_len = 0;
641 }
642 else if (b_len == 1)
643 {
644 /* n=1: single precision division.
645 beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */
646 r_ptr = roomptr;
647 q_ptr = roomptr + 1;
648 {
649 mp_limb_t den = b_ptr[0];
650 mp_limb_t remainder = 0;
651 const mp_limb_t *sourceptr = a_ptr + a_len;
652 mp_limb_t *destptr = q_ptr + a_len;
653 size_t count;
654 for (count = a_len; count > 0; count--)
655 {
656 mp_twolimb_t num =
657 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;
658 *--destptr = num / den;
659 remainder = num % den;
660 }
661 /* Normalise and store r. */
662 if (remainder > 0)
663 {
664 r_ptr[0] = remainder;
665 r_len = 1;
666 }
667 else
668 r_len = 0;
669 /* Normalise q. */
670 q_len = a_len;
671 if (q_ptr[q_len - 1] == 0)
672 q_len--;
673 }
674 }
675 else
676 {
677 /* n>1: multiple precision division.
678 beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>
679 beta^(m-n-1) <= a/b < beta^(m-n+1). */
680 /* Determine s. */
681 size_t s;
682 {
683 mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */
684 /* Determine s = GMP_LIMB_BITS - integer_length (msd).
685 Code copied from gnulib's integer_length.c. */
686 # if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) \
687 || (__clang_major__ >= 4)
688 s = __builtin_clz (msd);
689 # else
690 # if defined DBL_EXPBIT0_WORD && defined DBL_EXPBIT0_BIT
691 if (GMP_LIMB_BITS <= DBL_MANT_BIT)
692 {
693 /* Use 'double' operations.
694 Assumes an IEEE 754 'double' implementation. */
695 # define DBL_EXP_MASK ((DBL_MAX_EXP - DBL_MIN_EXP) | 7)
696 # define DBL_EXP_BIAS (DBL_EXP_MASK / 2 - 1)
697 # define NWORDS \
698 ((sizeof (double) + sizeof (unsigned int) - 1) / sizeof (unsigned int))
699 union { double value; unsigned int word[NWORDS]; } m;
700
701 /* Use a single integer to floating-point conversion. */
702 m.value = msd;
703
704 s = GMP_LIMB_BITS
705 - (((m.word[DBL_EXPBIT0_WORD] >> DBL_EXPBIT0_BIT) & DBL_EXP_MASK)
706 - DBL_EXP_BIAS);
707 }
708 else
709 # undef NWORDS
710 # endif
711 {
712 s = 31;
713 if (msd >= 0x10000)
714 {
715 msd = msd >> 16;
716 s -= 16;
717 }
718 if (msd >= 0x100)
719 {
720 msd = msd >> 8;
721 s -= 8;
722 }
723 if (msd >= 0x10)
724 {
725 msd = msd >> 4;
726 s -= 4;
727 }
728 if (msd >= 0x4)
729 {
730 msd = msd >> 2;
731 s -= 2;
732 }
733 if (msd >= 0x2)
734 {
735 msd = msd >> 1;
736 s -= 1;
737 }
738 }
739 # endif
740 }
741 /* 0 <= s < GMP_LIMB_BITS.
742 Copy b, shifting it left by s bits. */
743 if (s > 0)
744 {
745 tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));
746 if (tmp_roomptr == NULL)
747 {
748 free (roomptr);
749 return NOMEM_PTR;
750 }
751 {
752 const mp_limb_t *sourceptr = b_ptr;
753 mp_limb_t *destptr = tmp_roomptr;
754 mp_twolimb_t accu = 0;
755 size_t count;
756 for (count = b_len; count > 0; count--)
757 {
758 accu += (mp_twolimb_t) *sourceptr++ << s;
759 *destptr++ = (mp_limb_t) accu;
760 accu = accu >> GMP_LIMB_BITS;
761 }
762 /* accu must be zero, since that was how s was determined. */
763 if (accu != 0)
764 abort ();
765 }
766 b_ptr = tmp_roomptr;
767 }
768 /* Copy a, shifting it left by s bits, yields r.
769 Memory layout:
770 At the beginning: r = roomptr[0..a_len],
771 at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */
772 r_ptr = roomptr;
773 if (s == 0)
774 {
775 memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));
776 r_ptr[a_len] = 0;
777 }
778 else
779 {
780 const mp_limb_t *sourceptr = a_ptr;
781 mp_limb_t *destptr = r_ptr;
782 mp_twolimb_t accu = 0;
783 size_t count;
784 for (count = a_len; count > 0; count--)
785 {
786 accu += (mp_twolimb_t) *sourceptr++ << s;
787 *destptr++ = (mp_limb_t) accu;
788 accu = accu >> GMP_LIMB_BITS;
789 }
790 *destptr++ = (mp_limb_t) accu;
791 }
792 q_ptr = roomptr + b_len;
793 q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */
794 {
795 size_t j = a_len - b_len; /* m-n */
796 mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */
797 mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */
798 mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */
799 ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;
800 /* Division loop, traversed m-n+1 times.
801 j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */
802 for (;;)
803 {
804 mp_limb_t q_star;
805 mp_limb_t c1;
806 if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */
807 {
808 /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */
809 mp_twolimb_t num =
810 ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)
811 | r_ptr[j + b_len - 1];
812 q_star = num / b_msd;
813 c1 = num % b_msd;
814 }
815 else
816 {
817 /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */
818 q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */
819 /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta
820 <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta
821 <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)
822 {<= beta !}.
823 If yes, jump directly to the subtraction loop.
824 (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta
825 <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */
826 if (r_ptr[j + b_len] > b_msd
827 || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)
828 /* r[j+n] >= b[n-1]+1 or
829 r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a
830 carry. */
831 goto subtract;
832 }
833 /* q_star = q*,
834 c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */
835 {
836 mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */
837 ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2];
838 mp_twolimb_t c3 = /* b[n-2] * q* */
839 (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star;
840 /* While c2 < c3, increase c2 and decrease c3.
841 Consider c3-c2. While it is > 0, decrease it by
842 b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2
843 this can happen only twice. */
844 if (c3 > c2)
845 {
846 q_star = q_star - 1; /* q* := q* - 1 */
847 if (c3 - c2 > b_msdd)
848 q_star = q_star - 1; /* q* := q* - 1 */
849 }
850 }
851 if (q_star > 0)
852 subtract:
853 {
854 /* Subtract r := r - b * q* * beta^j. */
855 mp_limb_t cr;
856 {
857 const mp_limb_t *sourceptr = b_ptr;
858 mp_limb_t *destptr = r_ptr + j;
859 mp_twolimb_t carry = 0;
860 size_t count;
861 for (count = b_len; count > 0; count--)
862 {
863 /* Here 0 <= carry <= q*. */
864 carry =
865 carry
866 + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++
867 + (mp_limb_t) ~(*destptr);
868 /* Here 0 <= carry <= beta*q* + beta-1. */
869 *destptr++ = ~(mp_limb_t) carry;
870 carry = carry >> GMP_LIMB_BITS; /* <= q* */
871 }
872 cr = (mp_limb_t) carry;
873 }
874 /* Subtract cr from r_ptr[j + b_len], then forget about
875 r_ptr[j + b_len]. */
876 if (cr > r_ptr[j + b_len])
877 {
878 /* Subtraction gave a carry. */
879 q_star = q_star - 1; /* q* := q* - 1 */
880 /* Add b back. */
881 {
882 const mp_limb_t *sourceptr = b_ptr;
883 mp_limb_t *destptr = r_ptr + j;
884 mp_limb_t carry = 0;
885 size_t count;
886 for (count = b_len; count > 0; count--)
887 {
888 mp_limb_t source1 = *sourceptr++;
889 mp_limb_t source2 = *destptr;
890 *destptr++ = source1 + source2 + carry;
891 carry =
892 (carry
893 ? source1 >= (mp_limb_t) ~source2
894 : source1 > (mp_limb_t) ~source2);
895 }
896 }
897 /* Forget about the carry and about r[j+n]. */
898 }
899 }
900 /* q* is determined. Store it as q[j]. */
901 q_ptr[j] = q_star;
902 if (j == 0)
903 break;
904 j--;
905 }
906 }
907 r_len = b_len;
908 /* Normalise q. */
909 if (q_ptr[q_len - 1] == 0)
910 q_len--;
911 # if 0 /* Not needed here, since we need r only to compare it with b/2, and
912 b is shifted left by s bits. */
913 /* Shift r right by s bits. */
914 if (s > 0)
915 {
916 mp_limb_t ptr = r_ptr + r_len;
917 mp_twolimb_t accu = 0;
918 size_t count;
919 for (count = r_len; count > 0; count--)
920 {
921 accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;
922 accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);
923 *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);
924 }
925 }
926 # endif
927 /* Normalise r. */
928 while (r_len > 0 && r_ptr[r_len - 1] == 0)
929 r_len--;
930 }
931 /* Compare r << 1 with b. */
932 if (r_len > b_len)
933 goto increment_q;
934 {
935 size_t i;
936 for (i = b_len;;)
937 {
938 mp_limb_t r_i =
939 (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)
940 | (i < r_len ? r_ptr[i] << 1 : 0);
941 mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);
942 if (r_i > b_i)
943 goto increment_q;
944 if (r_i < b_i)
945 goto keep_q;
946 if (i == 0)
947 break;
948 i--;
949 }
950 }
951 if (q_len > 0 && ((q_ptr[0] & 1) != 0))
952 /* q is odd. */
953 increment_q:
954 {
955 size_t i;
956 for (i = 0; i < q_len; i++)
957 if (++(q_ptr[i]) != 0)
958 goto keep_q;
959 q_ptr[q_len++] = 1;
960 }
961 keep_q:
962 free (tmp_roomptr);
963 q->limbs = q_ptr;
964 q->nlimbs = q_len;
965 return roomptr;
966 }
967
968 /* Avoid pointless GCC warning "argument 1 value '18446744073709551615' exceeds
969 maximum object size 9223372036854775807", triggered by the use of xsum as
970 argument of malloc. */
971 # if _GL_GNUC_PREREQ (7, 0)
972 # pragma GCC diagnostic push
973 # pragma GCC diagnostic ignored "-Walloc-size-larger-than="
974 # endif
975
976 /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal
977 representation.
978 Destroys the contents of a.
979 Return the allocated memory - containing the decimal digits in low-to-high
980 order, terminated with a NUL character - in case of success, NULL in case
981 of memory allocation failure. */
982 static char *
983 convert_to_decimal (mpn_t a, size_t extra_zeroes)
984 {
985 mp_limb_t *a_ptr = a.limbs;
986 size_t a_len = a.nlimbs;
987 /* 0.03345 is slightly larger than log(2)/(9*log(10)). */
988 size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1);
989 /* We need extra_zeroes bytes for zeroes, followed by c_len bytes for the
990 digits of a, followed by 1 byte for the terminating NUL. */
991 char *c_ptr = (char *) malloc (xsum (xsum (extra_zeroes, c_len), 1));
992 if (c_ptr != NULL)
993 {
994 char *d_ptr = c_ptr;
995 for (; extra_zeroes > 0; extra_zeroes--)
996 *d_ptr++ = '0';
997 while (a_len > 0)
998 {
999 /* Divide a by 10^9, in-place. */
1000 mp_limb_t remainder = 0;
1001 mp_limb_t *ptr = a_ptr + a_len;
1002 size_t count;
1003 for (count = a_len; count > 0; count--)
1004 {
1005 mp_twolimb_t num =
1006 ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr;
1007 *ptr = num / 1000000000;
1008 remainder = num % 1000000000;
1009 }
1010 /* Store the remainder as 9 decimal digits. */
1011 for (count = 9; count > 0; count--)
1012 {
1013 *d_ptr++ = '0' + (remainder % 10);
1014 remainder = remainder / 10;
1015 }
1016 /* Normalize a. */
1017 if (a_ptr[a_len - 1] == 0)
1018 a_len--;
1019 }
1020 /* Remove leading zeroes. */
1021 while (d_ptr > c_ptr && d_ptr[-1] == '0')
1022 d_ptr--;
1023 /* But keep at least one zero. */
1024 if (d_ptr == c_ptr)
1025 *d_ptr++ = '0';
1026 /* Terminate the string. */
1027 *d_ptr = '\0';
1028 }
1029 return c_ptr;
1030 }
1031
1032 # if _GL_GNUC_PREREQ (7, 0)
1033 # pragma GCC diagnostic pop
1034 # endif
1035
1036 # if NEED_PRINTF_LONG_DOUBLE
1037
1038 /* Assuming x is finite and >= 0:
1039 write x as x = 2^e * m, where m is a bignum.
1040 Return the allocated memory in case of success, NULL in case of memory
1041 allocation failure. */
1042 static void *
1043 decode_long_double (long double x, int *ep, mpn_t *mp)
1044 {
1045 mpn_t m;
1046 int exp;
1047 long double y;
1048 size_t i;
1049
1050 /* Allocate memory for result. */
1051 m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
1052 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
1053 if (m.limbs == NULL)
1054 return NULL;
1055 /* Split into exponential part and mantissa. */
1056 y = safe_frexpl (x, &exp);
1057 if (!(y >= 0.0L && y < 1.0L))
1058 abort ();
1059 /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * 2^LDBL_MANT_BIT), and the
1060 latter is an integer. */
1061 /* Convert the mantissa (y * 2^LDBL_MANT_BIT) to a sequence of limbs.
1062 I'm not sure whether it's safe to cast a 'long double' value between
1063 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
1064 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int',
1065 doesn't matter). */
1066 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0
1067 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
1068 {
1069 mp_limb_t hi, lo;
1070 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2));
1071 hi = (int) y;
1072 y -= hi;
1073 if (!(y >= 0.0L && y < 1.0L))
1074 abort ();
1075 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1076 lo = (int) y;
1077 y -= lo;
1078 if (!(y >= 0.0L && y < 1.0L))
1079 abort ();
1080 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1081 }
1082 # else
1083 {
1084 mp_limb_t d;
1085 y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS);
1086 d = (int) y;
1087 y -= d;
1088 if (!(y >= 0.0L && y < 1.0L))
1089 abort ();
1090 m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d;
1091 }
1092 # endif
1093 # endif
1094 for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
1095 {
1096 mp_limb_t hi, lo;
1097 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1098 hi = (int) y;
1099 y -= hi;
1100 if (!(y >= 0.0L && y < 1.0L))
1101 abort ();
1102 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1103 lo = (int) y;
1104 y -= lo;
1105 if (!(y >= 0.0L && y < 1.0L))
1106 abort ();
1107 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1108 }
1109 # if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess
1110 precision. */
1111 if (!(y == 0.0L))
1112 abort ();
1113 # endif
1114 /* Normalise. */
1115 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
1116 m.nlimbs--;
1117 *mp = m;
1118 *ep = exp - LDBL_MANT_BIT;
1119 return m.limbs;
1120 }
1121
1122 # endif
1123
1124 # if NEED_PRINTF_DOUBLE
1125
1126 /* Assuming x is finite and >= 0:
1127 write x as x = 2^e * m, where m is a bignum.
1128 Return the allocated memory in case of success, NULL in case of memory
1129 allocation failure. */
1130 static void *
1131 decode_double (double x, int *ep, mpn_t *mp)
1132 {
1133 mpn_t m;
1134 int exp;
1135 double y;
1136 size_t i;
1137
1138 /* Allocate memory for result. */
1139 m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
1140 m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
1141 if (m.limbs == NULL)
1142 return NULL;
1143 /* Split into exponential part and mantissa. */
1144 y = frexp (x, &exp);
1145 if (!(y >= 0.0 && y < 1.0))
1146 abort ();
1147 /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * 2^DBL_MANT_BIT), and the
1148 latter is an integer. */
1149 /* Convert the mantissa (y * 2^DBL_MANT_BIT) to a sequence of limbs.
1150 I'm not sure whether it's safe to cast a 'double' value between
1151 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only
1152 'double' values between 0 and 2^16 (to 'unsigned int' or 'int',
1153 doesn't matter). */
1154 # if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0
1155 # if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2
1156 {
1157 mp_limb_t hi, lo;
1158 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2));
1159 hi = (int) y;
1160 y -= hi;
1161 if (!(y >= 0.0 && y < 1.0))
1162 abort ();
1163 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1164 lo = (int) y;
1165 y -= lo;
1166 if (!(y >= 0.0 && y < 1.0))
1167 abort ();
1168 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1169 }
1170 # else
1171 {
1172 mp_limb_t d;
1173 y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS);
1174 d = (int) y;
1175 y -= d;
1176 if (!(y >= 0.0 && y < 1.0))
1177 abort ();
1178 m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d;
1179 }
1180 # endif
1181 # endif
1182 for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; )
1183 {
1184 mp_limb_t hi, lo;
1185 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1186 hi = (int) y;
1187 y -= hi;
1188 if (!(y >= 0.0 && y < 1.0))
1189 abort ();
1190 y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2);
1191 lo = (int) y;
1192 y -= lo;
1193 if (!(y >= 0.0 && y < 1.0))
1194 abort ();
1195 m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo;
1196 }
1197 if (!(y == 0.0))
1198 abort ();
1199 /* Normalise. */
1200 while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0)
1201 m.nlimbs--;
1202 *mp = m;
1203 *ep = exp - DBL_MANT_BIT;
1204 return m.limbs;
1205 }
1206
1207 # endif
1208
1209 /* Assuming x = 2^e * m is finite and >= 0, and n is an integer:
1210 Returns the decimal representation of round (x * 10^n).
1211 Return the allocated memory - containing the decimal digits in low-to-high
1212 order, terminated with a NUL character - in case of success, NULL in case
1213 of memory allocation failure. */
1214 static char *
1215 scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
1216 {
1217 int s;
1218 size_t extra_zeroes;
1219 unsigned int abs_n;
1220 unsigned int abs_s;
1221 mp_limb_t *pow5_ptr;
1222 size_t pow5_len;
1223 unsigned int s_limbs;
1224 unsigned int s_bits;
1225 mpn_t pow5;
1226 mpn_t z;
1227 void *z_memory;
1228 char *digits;
1229
1230 /* x = 2^e * m, hence
1231 y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
1232 = round (2^s * 5^n * m). */
1233 s = e + n;
1234 extra_zeroes = 0;
1235 /* Factor out a common power of 10 if possible. */
1236 if (s > 0 && n > 0)
1237 {
1238 extra_zeroes = (s < n ? s : n);
1239 s -= extra_zeroes;
1240 n -= extra_zeroes;
1241 }
1242 /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes.
1243 Before converting to decimal, we need to compute
1244 z = round (2^s * 5^n * m). */
1245 /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
1246 sign. 2.322 is slightly larger than log(5)/log(2). */
1247 abs_n = (n >= 0 ? n : -n);
1248 abs_s = (s >= 0 ? s : -s);
1249 pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
1250 + abs_s / GMP_LIMB_BITS + 1)
1251 * sizeof (mp_limb_t));
1252 if (pow5_ptr == NULL)
1253 {
1254 free (memory);
1255 return NULL;
1256 }
1257 /* Initialize with 1. */
1258 pow5_ptr[0] = 1;
1259 pow5_len = 1;
1260 /* Multiply with 5^|n|. */
1261 if (abs_n > 0)
1262 {
1263 static mp_limb_t const small_pow5[13 + 1] =
1264 {
1265 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
1266 48828125, 244140625, 1220703125
1267 };
1268 unsigned int n13;
1269 for (n13 = 0; n13 <= abs_n; n13 += 13)
1270 {
1271 mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13];
1272 size_t j;
1273 mp_twolimb_t carry = 0;
1274 for (j = 0; j < pow5_len; j++)
1275 {
1276 mp_limb_t digit2 = pow5_ptr[j];
1277 carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2;
1278 pow5_ptr[j] = (mp_limb_t) carry;
1279 carry = carry >> GMP_LIMB_BITS;
1280 }
1281 if (carry > 0)
1282 pow5_ptr[pow5_len++] = (mp_limb_t) carry;
1283 }
1284 }
1285 s_limbs = abs_s / GMP_LIMB_BITS;
1286 s_bits = abs_s % GMP_LIMB_BITS;
1287 if (n >= 0 ? s >= 0 : s <= 0)
1288 {
1289 /* Multiply with 2^|s|. */
1290 if (s_bits > 0)
1291 {
1292 mp_limb_t *ptr = pow5_ptr;
1293 mp_twolimb_t accu = 0;
1294 size_t count;
1295 for (count = pow5_len; count > 0; count--)
1296 {
1297 accu += (mp_twolimb_t) *ptr << s_bits;
1298 *ptr++ = (mp_limb_t) accu;
1299 accu = accu >> GMP_LIMB_BITS;
1300 }
1301 if (accu > 0)
1302 {
1303 *ptr = (mp_limb_t) accu;
1304 pow5_len++;
1305 }
1306 }
1307 if (s_limbs > 0)
1308 {
1309 size_t count;
1310 for (count = pow5_len; count > 0;)
1311 {
1312 count--;
1313 pow5_ptr[s_limbs + count] = pow5_ptr[count];
1314 }
1315 for (count = s_limbs; count > 0;)
1316 {
1317 count--;
1318 pow5_ptr[count] = 0;
1319 }
1320 pow5_len += s_limbs;
1321 }
1322 pow5.limbs = pow5_ptr;
1323 pow5.nlimbs = pow5_len;
1324 if (n >= 0)
1325 {
1326 /* Multiply m with pow5. No division needed. */
1327 z_memory = multiply (m, pow5, &z);
1328 }
1329 else
1330 {
1331 /* Divide m by pow5 and round. */
1332 z_memory = divide (m, pow5, &z);
1333 }
1334 }
1335 else
1336 {
1337 pow5.limbs = pow5_ptr;
1338 pow5.nlimbs = pow5_len;
1339 if (n >= 0)
1340 {
1341 /* n >= 0, s < 0.
1342 Multiply m with pow5, then divide by 2^|s|. */
1343 mpn_t numerator;
1344 mpn_t denominator;
1345 void *tmp_memory;
1346 tmp_memory = multiply (m, pow5, &numerator);
1347 if (tmp_memory == NOMEM_PTR)
1348 {
1349 free (pow5_ptr);
1350 free (memory);
1351 return NULL;
1352 }
1353 /* Construct 2^|s|. */
1354 {
1355 mp_limb_t *ptr = pow5_ptr + pow5_len;
1356 size_t i;
1357 for (i = 0; i < s_limbs; i++)
1358 ptr[i] = 0;
1359 ptr[s_limbs] = (mp_limb_t) 1 << s_bits;
1360 denominator.limbs = ptr;
1361 denominator.nlimbs = s_limbs + 1;
1362 }
1363 z_memory = divide (numerator, denominator, &z);
1364 free (tmp_memory);
1365 }
1366 else
1367 {
1368 /* n < 0, s > 0.
1369 Multiply m with 2^s, then divide by pow5. */
1370 mpn_t numerator;
1371 mp_limb_t *num_ptr;
1372 num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1)
1373 * sizeof (mp_limb_t));
1374 if (num_ptr == NULL)
1375 {
1376 free (pow5_ptr);
1377 free (memory);
1378 return NULL;
1379 }
1380 {
1381 mp_limb_t *destptr = num_ptr;
1382 {
1383 size_t i;
1384 for (i = 0; i < s_limbs; i++)
1385 *destptr++ = 0;
1386 }
1387 if (s_bits > 0)
1388 {
1389 const mp_limb_t *sourceptr = m.limbs;
1390 mp_twolimb_t accu = 0;
1391 size_t count;
1392 for (count = m.nlimbs; count > 0; count--)
1393 {
1394 accu += (mp_twolimb_t) *sourceptr++ << s_bits;
1395 *destptr++ = (mp_limb_t) accu;
1396 accu = accu >> GMP_LIMB_BITS;
1397 }
1398 if (accu > 0)
1399 *destptr++ = (mp_limb_t) accu;
1400 }
1401 else
1402 {
1403 const mp_limb_t *sourceptr = m.limbs;
1404 size_t count;
1405 for (count = m.nlimbs; count > 0; count--)
1406 *destptr++ = *sourceptr++;
1407 }
1408 numerator.limbs = num_ptr;
1409 numerator.nlimbs = destptr - num_ptr;
1410 }
1411 z_memory = divide (numerator, pow5, &z);
1412 free (num_ptr);
1413 }
1414 }
1415 free (pow5_ptr);
1416 free (memory);
1417
1418 /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */
1419
1420 if (z_memory == NOMEM_PTR)
1421 return NULL;
1422 digits = convert_to_decimal (z, extra_zeroes);
1423 free (z_memory);
1424 return digits;
1425 }
1426
1427 # if NEED_PRINTF_LONG_DOUBLE
1428
1429 /* Assuming x is finite and >= 0, and n is an integer:
1430 Returns the decimal representation of round (x * 10^n).
1431 Return the allocated memory - containing the decimal digits in low-to-high
1432 order, terminated with a NUL character - in case of success, NULL in case
1433 of memory allocation failure. */
1434 static char *
1435 scale10_round_decimal_long_double (long double x, int n)
1436 {
1437 int e;
1438 mpn_t m;
1439 void *memory = decode_long_double (x, &e, &m);
1440 if (memory != NULL)
1441 return scale10_round_decimal_decoded (e, m, memory, n);
1442 else
1443 return NULL;
1444 }
1445
1446 # endif
1447
1448 # if NEED_PRINTF_DOUBLE
1449
1450 /* Assuming x is finite and >= 0, and n is an integer:
1451 Returns the decimal representation of round (x * 10^n).
1452 Return the allocated memory - containing the decimal digits in low-to-high
1453 order, terminated with a NUL character - in case of success, NULL in case
1454 of memory allocation failure. */
1455 static char *
1456 scale10_round_decimal_double (double x, int n)
1457 {
1458 int e;
1459 mpn_t m;
1460 void *memory = decode_double (x, &e, &m);
1461 if (memory != NULL)
1462 return scale10_round_decimal_decoded (e, m, memory, n);
1463 else
1464 return NULL;
1465 }
1466
1467 # endif
1468
1469 # if NEED_PRINTF_LONG_DOUBLE
1470
1471 /* Assuming x is finite and > 0:
1472 Return an approximation for n with 10^n <= x < 10^(n+1).
1473 The approximation is usually the right n, but may be off by 1 sometimes. */
1474 static int
1475 floorlog10l (long double x)
1476 {
1477 int exp;
1478 long double y;
1479 double z;
1480 double l;
1481
1482 /* Split into exponential part and mantissa. */
1483 y = safe_frexpl (x, &exp);
1484 if (!(y >= 0.0L && y < 1.0L))
1485 abort ();
1486 if (y == 0.0L)
1487 return INT_MIN;
1488 if (y < 0.5L)
1489 {
1490 while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1491 {
1492 y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1493 exp -= GMP_LIMB_BITS;
1494 }
1495 if (y < (1.0L / (1 << 16)))
1496 {
1497 y *= 1.0L * (1 << 16);
1498 exp -= 16;
1499 }
1500 if (y < (1.0L / (1 << 8)))
1501 {
1502 y *= 1.0L * (1 << 8);
1503 exp -= 8;
1504 }
1505 if (y < (1.0L / (1 << 4)))
1506 {
1507 y *= 1.0L * (1 << 4);
1508 exp -= 4;
1509 }
1510 if (y < (1.0L / (1 << 2)))
1511 {
1512 y *= 1.0L * (1 << 2);
1513 exp -= 2;
1514 }
1515 if (y < (1.0L / (1 << 1)))
1516 {
1517 y *= 1.0L * (1 << 1);
1518 exp -= 1;
1519 }
1520 }
1521 if (!(y >= 0.5L && y < 1.0L))
1522 abort ();
1523 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1524 l = exp;
1525 z = y;
1526 if (z < 0.70710678118654752444)
1527 {
1528 z *= 1.4142135623730950488;
1529 l -= 0.5;
1530 }
1531 if (z < 0.8408964152537145431)
1532 {
1533 z *= 1.1892071150027210667;
1534 l -= 0.25;
1535 }
1536 if (z < 0.91700404320467123175)
1537 {
1538 z *= 1.0905077326652576592;
1539 l -= 0.125;
1540 }
1541 if (z < 0.9576032806985736469)
1542 {
1543 z *= 1.0442737824274138403;
1544 l -= 0.0625;
1545 }
1546 /* Now 0.95 <= z <= 1.01. */
1547 z = 1 - z;
1548 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1549 Four terms are enough to get an approximation with error < 10^-7. */
1550 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1551 /* Finally multiply with log(2)/log(10), yields an approximation for
1552 log10(x). */
1553 l *= 0.30102999566398119523;
1554 /* Round down to the next integer. */
1555 return (int) l + (l < 0 ? -1 : 0);
1556 }
1557
1558 # endif
1559
1560 # if NEED_PRINTF_DOUBLE
1561
1562 /* Assuming x is finite and > 0:
1563 Return an approximation for n with 10^n <= x < 10^(n+1).
1564 The approximation is usually the right n, but may be off by 1 sometimes. */
1565 static int
1566 floorlog10 (double x)
1567 {
1568 int exp;
1569 double y;
1570 double z;
1571 double l;
1572
1573 /* Split into exponential part and mantissa. */
1574 y = frexp (x, &exp);
1575 if (!(y >= 0.0 && y < 1.0))
1576 abort ();
1577 if (y == 0.0)
1578 return INT_MIN;
1579 if (y < 0.5)
1580 {
1581 while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2))))
1582 {
1583 y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2));
1584 exp -= GMP_LIMB_BITS;
1585 }
1586 if (y < (1.0 / (1 << 16)))
1587 {
1588 y *= 1.0 * (1 << 16);
1589 exp -= 16;
1590 }
1591 if (y < (1.0 / (1 << 8)))
1592 {
1593 y *= 1.0 * (1 << 8);
1594 exp -= 8;
1595 }
1596 if (y < (1.0 / (1 << 4)))
1597 {
1598 y *= 1.0 * (1 << 4);
1599 exp -= 4;
1600 }
1601 if (y < (1.0 / (1 << 2)))
1602 {
1603 y *= 1.0 * (1 << 2);
1604 exp -= 2;
1605 }
1606 if (y < (1.0 / (1 << 1)))
1607 {
1608 y *= 1.0 * (1 << 1);
1609 exp -= 1;
1610 }
1611 }
1612 if (!(y >= 0.5 && y < 1.0))
1613 abort ();
1614 /* Compute an approximation for l = log2(x) = exp + log2(y). */
1615 l = exp;
1616 z = y;
1617 if (z < 0.70710678118654752444)
1618 {
1619 z *= 1.4142135623730950488;
1620 l -= 0.5;
1621 }
1622 if (z < 0.8408964152537145431)
1623 {
1624 z *= 1.1892071150027210667;
1625 l -= 0.25;
1626 }
1627 if (z < 0.91700404320467123175)
1628 {
1629 z *= 1.0905077326652576592;
1630 l -= 0.125;
1631 }
1632 if (z < 0.9576032806985736469)
1633 {
1634 z *= 1.0442737824274138403;
1635 l -= 0.0625;
1636 }
1637 /* Now 0.95 <= z <= 1.01. */
1638 z = 1 - z;
1639 /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...)
1640 Four terms are enough to get an approximation with error < 10^-7. */
1641 l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25)));
1642 /* Finally multiply with log(2)/log(10), yields an approximation for
1643 log10(x). */
1644 l *= 0.30102999566398119523;
1645 /* Round down to the next integer. */
1646 return (int) l + (l < 0 ? -1 : 0);
1647 }
1648
1649 # endif
1650
1651 /* Tests whether a string of digits consists of exactly PRECISION zeroes and
1652 a single '1' digit. */
1653 static int
1654 is_borderline (const char *digits, size_t precision)
1655 {
1656 for (; precision > 0; precision--, digits++)
1657 if (*digits != '0')
1658 return 0;
1659 if (*digits != '1')
1660 return 0;
1661 digits++;
1662 return *digits == '\0';
1663 }
1664
1665 #endif
1666
1667 #if !USE_SNPRINTF || (WIDE_CHAR_VERSION && DCHAR_IS_TCHAR) || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF
1668
1669 /* Use a different function name, to make it possible that the 'wchar_t'
1670 parametrization and the 'char' parametrization get compiled in the same
1671 translation unit. */
1672 # if WIDE_CHAR_VERSION
1673 # define MAX_ROOM_NEEDED wmax_room_needed
1674 # else
1675 # define MAX_ROOM_NEEDED max_room_needed
1676 # endif
1677
1678 /* Returns the number of TCHAR_T units needed as temporary space for the result
1679 of sprintf or SNPRINTF of a single conversion directive. */
1680 static size_t
1681 MAX_ROOM_NEEDED (const arguments *ap, size_t arg_index, FCHAR_T conversion,
1682 arg_type type, int flags, size_t width, int has_precision,
1683 size_t precision, int pad_ourselves)
1684 {
1685 size_t tmp_length;
1686
1687 switch (conversion)
1688 {
1689 case 'd': case 'i': case 'u':
1690 switch (type)
1691 {
1692 default:
1693 tmp_length =
1694 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1695 * 0.30103 /* binary -> decimal */
1696 )
1697 + 1; /* turn floor into ceil */
1698 break;
1699 case TYPE_LONGINT:
1700 tmp_length =
1701 (unsigned int) (sizeof (long int) * CHAR_BIT
1702 * 0.30103 /* binary -> decimal */
1703 )
1704 + 1; /* turn floor into ceil */
1705 break;
1706 case TYPE_ULONGINT:
1707 tmp_length =
1708 (unsigned int) (sizeof (unsigned long int) * CHAR_BIT
1709 * 0.30103 /* binary -> decimal */
1710 )
1711 + 1; /* turn floor into ceil */
1712 break;
1713 case TYPE_LONGLONGINT:
1714 tmp_length =
1715 (unsigned int) (sizeof (long long int) * CHAR_BIT
1716 * 0.30103 /* binary -> decimal */
1717 )
1718 + 1; /* turn floor into ceil */
1719 break;
1720 case TYPE_ULONGLONGINT:
1721 tmp_length =
1722 (unsigned int) (sizeof (unsigned long long int) * CHAR_BIT
1723 * 0.30103 /* binary -> decimal */
1724 )
1725 + 1; /* turn floor into ceil */
1726 break;
1727 case TYPE_INT8_T:
1728 tmp_length =
1729 (unsigned int) (sizeof (int8_t) * CHAR_BIT
1730 * 0.30103 /* binary -> decimal */
1731 )
1732 + 1; /* turn floor into ceil */
1733 break;
1734 case TYPE_UINT8_T:
1735 tmp_length =
1736 (unsigned int) (sizeof (uint8_t) * CHAR_BIT
1737 * 0.30103 /* binary -> decimal */
1738 )
1739 + 1; /* turn floor into ceil */
1740 break;
1741 case TYPE_INT16_T:
1742 tmp_length =
1743 (unsigned int) (sizeof (int16_t) * CHAR_BIT
1744 * 0.30103 /* binary -> decimal */
1745 )
1746 + 1; /* turn floor into ceil */
1747 break;
1748 case TYPE_UINT16_T:
1749 tmp_length =
1750 (unsigned int) (sizeof (uint16_t) * CHAR_BIT
1751 * 0.30103 /* binary -> decimal */
1752 )
1753 + 1; /* turn floor into ceil */
1754 break;
1755 case TYPE_INT32_T:
1756 tmp_length =
1757 (unsigned int) (sizeof (int32_t) * CHAR_BIT
1758 * 0.30103 /* binary -> decimal */
1759 )
1760 + 1; /* turn floor into ceil */
1761 break;
1762 case TYPE_UINT32_T:
1763 tmp_length =
1764 (unsigned int) (sizeof (uint32_t) * CHAR_BIT
1765 * 0.30103 /* binary -> decimal */
1766 )
1767 + 1; /* turn floor into ceil */
1768 break;
1769 case TYPE_INT64_T:
1770 tmp_length =
1771 (unsigned int) (sizeof (int64_t) * CHAR_BIT
1772 * 0.30103 /* binary -> decimal */
1773 )
1774 + 1; /* turn floor into ceil */
1775 break;
1776 case TYPE_UINT64_T:
1777 tmp_length =
1778 (unsigned int) (sizeof (uint64_t) * CHAR_BIT
1779 * 0.30103 /* binary -> decimal */
1780 )
1781 + 1; /* turn floor into ceil */
1782 break;
1783 case TYPE_INT_FAST8_T:
1784 tmp_length =
1785 (unsigned int) (sizeof (int_fast8_t) * CHAR_BIT
1786 * 0.30103 /* binary -> decimal */
1787 )
1788 + 1; /* turn floor into ceil */
1789 break;
1790 case TYPE_UINT_FAST8_T:
1791 tmp_length =
1792 (unsigned int) (sizeof (uint_fast8_t) * CHAR_BIT
1793 * 0.30103 /* binary -> decimal */
1794 )
1795 + 1; /* turn floor into ceil */
1796 break;
1797 case TYPE_INT_FAST16_T:
1798 tmp_length =
1799 (unsigned int) (sizeof (int_fast16_t) * CHAR_BIT
1800 * 0.30103 /* binary -> decimal */
1801 )
1802 + 1; /* turn floor into ceil */
1803 break;
1804 case TYPE_UINT_FAST16_T:
1805 tmp_length =
1806 (unsigned int) (sizeof (uint_fast16_t) * CHAR_BIT
1807 * 0.30103 /* binary -> decimal */
1808 )
1809 + 1; /* turn floor into ceil */
1810 break;
1811 case TYPE_INT_FAST32_T:
1812 tmp_length =
1813 (unsigned int) (sizeof (int_fast32_t) * CHAR_BIT
1814 * 0.30103 /* binary -> decimal */
1815 )
1816 + 1; /* turn floor into ceil */
1817 break;
1818 case TYPE_UINT_FAST32_T:
1819 tmp_length =
1820 (unsigned int) (sizeof (uint_fast32_t) * CHAR_BIT
1821 * 0.30103 /* binary -> decimal */
1822 )
1823 + 1; /* turn floor into ceil */
1824 break;
1825 case TYPE_INT_FAST64_T:
1826 tmp_length =
1827 (unsigned int) (sizeof (int_fast64_t) * CHAR_BIT
1828 * 0.30103 /* binary -> decimal */
1829 )
1830 + 1; /* turn floor into ceil */
1831 break;
1832 case TYPE_UINT_FAST64_T:
1833 tmp_length =
1834 (unsigned int) (sizeof (uint_fast64_t) * CHAR_BIT
1835 * 0.30103 /* binary -> decimal */
1836 )
1837 + 1; /* turn floor into ceil */
1838 break;
1839 }
1840 if (tmp_length < precision)
1841 tmp_length = precision;
1842 /* Multiply by 2, as an estimate for FLAG_GROUP. */
1843 tmp_length = xsum (tmp_length, tmp_length);
1844 /* Add 1, to account for a leading sign. */
1845 tmp_length = xsum (tmp_length, 1);
1846 break;
1847
1848 case 'b':
1849 #if SUPPORT_GNU_PRINTF_DIRECTIVES \
1850 || (__GLIBC__ + (__GLIBC_MINOR__ >= 35) > 2)
1851 case 'B':
1852 #endif
1853 switch (type)
1854 {
1855 default:
1856 tmp_length =
1857 (unsigned int) (sizeof (unsigned int) * CHAR_BIT)
1858 + 1; /* turn floor into ceil */
1859 break;
1860 case TYPE_ULONGINT:
1861 tmp_length =
1862 (unsigned int) (sizeof (unsigned long int) * CHAR_BIT)
1863 + 1; /* turn floor into ceil */
1864 break;
1865 case TYPE_ULONGLONGINT:
1866 tmp_length =
1867 (unsigned int) (sizeof (unsigned long long int) * CHAR_BIT)
1868 + 1; /* turn floor into ceil */
1869 break;
1870 case TYPE_UINT8_T:
1871 tmp_length =
1872 (unsigned int) (sizeof (uint8_t) * CHAR_BIT)
1873 + 1; /* turn floor into ceil */
1874 break;
1875 case TYPE_UINT16_T:
1876 tmp_length =
1877 (unsigned int) (sizeof (uint16_t) * CHAR_BIT)
1878 + 1; /* turn floor into ceil */
1879 break;
1880 case TYPE_UINT32_T:
1881 tmp_length =
1882 (unsigned int) (sizeof (uint32_t) * CHAR_BIT)
1883 + 1; /* turn floor into ceil */
1884 break;
1885 case TYPE_UINT64_T:
1886 tmp_length =
1887 (unsigned int) (sizeof (uint64_t) * CHAR_BIT)
1888 + 1; /* turn floor into ceil */
1889 break;
1890 case TYPE_UINT_FAST8_T:
1891 tmp_length =
1892 (unsigned int) (sizeof (uint_fast8_t) * CHAR_BIT)
1893 + 1; /* turn floor into ceil */
1894 break;
1895 case TYPE_UINT_FAST16_T:
1896 tmp_length =
1897 (unsigned int) (sizeof (uint_fast16_t) * CHAR_BIT)
1898 + 1; /* turn floor into ceil */
1899 break;
1900 case TYPE_UINT_FAST32_T:
1901 tmp_length =
1902 (unsigned int) (sizeof (uint_fast32_t) * CHAR_BIT)
1903 + 1; /* turn floor into ceil */
1904 break;
1905 case TYPE_UINT_FAST64_T:
1906 tmp_length =
1907 (unsigned int) (sizeof (uint_fast64_t) * CHAR_BIT)
1908 + 1; /* turn floor into ceil */
1909 break;
1910 }
1911 if (tmp_length < precision)
1912 tmp_length = precision;
1913 /* Add 2, to account for a prefix from the alternate form. */
1914 tmp_length = xsum (tmp_length, 2);
1915 break;
1916
1917 case 'o':
1918 switch (type)
1919 {
1920 default:
1921 tmp_length =
1922 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
1923 * 0.333334 /* binary -> octal */
1924 )
1925 + 1; /* turn floor into ceil */
1926 break;
1927 case TYPE_ULONGINT:
1928 tmp_length =
1929 (unsigned int) (sizeof (unsigned long int) * CHAR_BIT
1930 * 0.333334 /* binary -> octal */
1931 )
1932 + 1; /* turn floor into ceil */
1933 break;
1934 case TYPE_ULONGLONGINT:
1935 tmp_length =
1936 (unsigned int) (sizeof (unsigned long long int) * CHAR_BIT
1937 * 0.333334 /* binary -> octal */
1938 )
1939 + 1; /* turn floor into ceil */
1940 break;
1941 case TYPE_UINT8_T:
1942 tmp_length =
1943 (unsigned int) (sizeof (uint8_t) * CHAR_BIT
1944 * 0.333334 /* binary -> octal */
1945 )
1946 + 1; /* turn floor into ceil */
1947 break;
1948 case TYPE_UINT16_T:
1949 tmp_length =
1950 (unsigned int) (sizeof (uint16_t) * CHAR_BIT
1951 * 0.333334 /* binary -> octal */
1952 )
1953 + 1; /* turn floor into ceil */
1954 break;
1955 case TYPE_UINT32_T:
1956 tmp_length =
1957 (unsigned int) (sizeof (uint32_t) * CHAR_BIT
1958 * 0.333334 /* binary -> octal */
1959 )
1960 + 1; /* turn floor into ceil */
1961 break;
1962 case TYPE_UINT64_T:
1963 tmp_length =
1964 (unsigned int) (sizeof (uint64_t) * CHAR_BIT
1965 * 0.333334 /* binary -> octal */
1966 )
1967 + 1; /* turn floor into ceil */
1968 break;
1969 case TYPE_UINT_FAST8_T:
1970 tmp_length =
1971 (unsigned int) (sizeof (uint_fast8_t) * CHAR_BIT
1972 * 0.333334 /* binary -> octal */
1973 )
1974 + 1; /* turn floor into ceil */
1975 break;
1976 case TYPE_UINT_FAST16_T:
1977 tmp_length =
1978 (unsigned int) (sizeof (uint_fast16_t) * CHAR_BIT
1979 * 0.333334 /* binary -> octal */
1980 )
1981 + 1; /* turn floor into ceil */
1982 break;
1983 case TYPE_UINT_FAST32_T:
1984 tmp_length =
1985 (unsigned int) (sizeof (uint_fast32_t) * CHAR_BIT
1986 * 0.333334 /* binary -> octal */
1987 )
1988 + 1; /* turn floor into ceil */
1989 break;
1990 case TYPE_UINT_FAST64_T:
1991 tmp_length =
1992 (unsigned int) (sizeof (uint_fast64_t) * CHAR_BIT
1993 * 0.333334 /* binary -> octal */
1994 )
1995 + 1; /* turn floor into ceil */
1996 break;
1997 }
1998 if (tmp_length < precision)
1999 tmp_length = precision;
2000 /* Add 1, to account for a leading sign. */
2001 tmp_length = xsum (tmp_length, 1);
2002 break;
2003
2004 case 'x': case 'X':
2005 switch (type)
2006 {
2007 default:
2008 tmp_length =
2009 (unsigned int) (sizeof (unsigned int) * CHAR_BIT
2010 * 0.25 /* binary -> hexadecimal */
2011 )
2012 + 1; /* turn floor into ceil */
2013 break;
2014 case TYPE_ULONGINT:
2015 tmp_length =
2016 (unsigned int) (sizeof (unsigned long int) * CHAR_BIT
2017 * 0.25 /* binary -> hexadecimal */
2018 )
2019 + 1; /* turn floor into ceil */
2020 break;
2021 case TYPE_ULONGLONGINT:
2022 tmp_length =
2023 (unsigned int) (sizeof (unsigned long long int) * CHAR_BIT
2024 * 0.25 /* binary -> hexadecimal */
2025 )
2026 + 1; /* turn floor into ceil */
2027 break;
2028 case TYPE_UINT8_T:
2029 tmp_length =
2030 (unsigned int) (sizeof (uint8_t) * CHAR_BIT
2031 * 0.25 /* binary -> hexadecimal */
2032 )
2033 + 1; /* turn floor into ceil */
2034 break;
2035 case TYPE_UINT16_T:
2036 tmp_length =
2037 (unsigned int) (sizeof (uint16_t) * CHAR_BIT
2038 * 0.25 /* binary -> hexadecimal */
2039 )
2040 + 1; /* turn floor into ceil */
2041 break;
2042 case TYPE_UINT32_T:
2043 tmp_length =
2044 (unsigned int) (sizeof (uint32_t) * CHAR_BIT
2045 * 0.25 /* binary -> hexadecimal */
2046 )
2047 + 1; /* turn floor into ceil */
2048 break;
2049 case TYPE_UINT64_T:
2050 tmp_length =
2051 (unsigned int) (sizeof (uint64_t) * CHAR_BIT
2052 * 0.25 /* binary -> hexadecimal */
2053 )
2054 + 1; /* turn floor into ceil */
2055 break;
2056 case TYPE_UINT_FAST8_T:
2057 tmp_length =
2058 (unsigned int) (sizeof (uint_fast8_t) * CHAR_BIT
2059 * 0.25 /* binary -> hexadecimal */
2060 )
2061 + 1; /* turn floor into ceil */
2062 break;
2063 case TYPE_UINT_FAST16_T:
2064 tmp_length =
2065 (unsigned int) (sizeof (uint_fast16_t) * CHAR_BIT
2066 * 0.25 /* binary -> hexadecimal */
2067 )
2068 + 1; /* turn floor into ceil */
2069 break;
2070 case TYPE_UINT_FAST32_T:
2071 tmp_length =
2072 (unsigned int) (sizeof (uint_fast32_t) * CHAR_BIT
2073 * 0.25 /* binary -> hexadecimal */
2074 )
2075 + 1; /* turn floor into ceil */
2076 break;
2077 case TYPE_UINT_FAST64_T:
2078 tmp_length =
2079 (unsigned int) (sizeof (uint_fast64_t) * CHAR_BIT
2080 * 0.25 /* binary -> hexadecimal */
2081 )
2082 + 1; /* turn floor into ceil */
2083 break;
2084 }
2085 if (tmp_length < precision)
2086 tmp_length = precision;
2087 /* Add 2, to account for a prefix from the alternate form. */
2088 tmp_length = xsum (tmp_length, 2);
2089 break;
2090
2091 case 'f': case 'F':
2092 if (type == TYPE_LONGDOUBLE)
2093 tmp_length =
2094 (unsigned int) (LDBL_MAX_EXP
2095 * 0.30103 /* binary -> decimal */
2096 * 2 /* estimate for FLAG_GROUP */
2097 )
2098 + 1 /* turn floor into ceil */
2099 + 10; /* sign, decimal point etc. */
2100 else
2101 tmp_length =
2102 (unsigned int) (DBL_MAX_EXP
2103 * 0.30103 /* binary -> decimal */
2104 * 2 /* estimate for FLAG_GROUP */
2105 )
2106 + 1 /* turn floor into ceil */
2107 + 10; /* sign, decimal point etc. */
2108 tmp_length = xsum (tmp_length, precision);
2109 break;
2110
2111 case 'e': case 'E': case 'g': case 'G':
2112 tmp_length =
2113 12; /* sign, decimal point, exponent etc. */
2114 tmp_length = xsum (tmp_length, precision);
2115 break;
2116
2117 case 'a': case 'A':
2118 if (type == TYPE_LONGDOUBLE)
2119 tmp_length =
2120 (unsigned int) (LDBL_DIG
2121 * 0.831 /* decimal -> hexadecimal */
2122 )
2123 + 1; /* turn floor into ceil */
2124 else
2125 tmp_length =
2126 (unsigned int) (DBL_DIG
2127 * 0.831 /* decimal -> hexadecimal */
2128 )
2129 + 1; /* turn floor into ceil */
2130 if (tmp_length < precision)
2131 tmp_length = precision;
2132 /* Account for sign, decimal point etc. */
2133 tmp_length = xsum (tmp_length, 12);
2134 break;
2135
2136 case 'c':
2137 # if HAVE_WINT_T && !WIDE_CHAR_VERSION
2138 if (type == TYPE_WIDE_CHAR)
2139 {
2140 tmp_length = MB_CUR_MAX;
2141 # if ENABLE_WCHAR_FALLBACK
2142 if (tmp_length < (sizeof (wchar_t) > 2 ? 10 : 6))
2143 tmp_length = (sizeof (wchar_t) > 2 ? 10 : 6);
2144 # endif
2145 }
2146 else
2147 # endif
2148 tmp_length = 1;
2149 break;
2150
2151 case 's':
2152 if (type == TYPE_WIDE_STRING)
2153 {
2154 # if WIDE_CHAR_VERSION
2155 /* ISO C says about %ls in fwprintf:
2156 "If the precision is not specified or is greater than the size
2157 of the array, the array shall contain a null wide character."
2158 So if there is a precision, we must not use wcslen. */
2159 const wchar_t *arg = ap->arg[arg_index].a.a_wide_string;
2160
2161 if (has_precision)
2162 tmp_length = local_wcsnlen (arg, precision);
2163 else
2164 tmp_length = local_wcslen (arg);
2165 # else
2166 /* ISO C says about %ls in fprintf:
2167 "If a precision is specified, no more than that many bytes are
2168 written (including shift sequences, if any), and the array
2169 shall contain a null wide character if, to equal the multibyte
2170 character sequence length given by the precision, the function
2171 would need to access a wide character one past the end of the
2172 array."
2173 So if there is a precision, we must not use wcslen. */
2174 /* This case has already been handled separately in VASNPRINTF. */
2175 abort ();
2176 # endif
2177 }
2178 else
2179 {
2180 # if WIDE_CHAR_VERSION
2181 /* ISO C says about %s in fwprintf:
2182 "If the precision is not specified or is greater than the size
2183 of the converted array, the converted array shall contain a
2184 null wide character."
2185 So if there is a precision, we must not use strlen. */
2186 /* This case has already been handled separately in VASNPRINTF. */
2187 abort ();
2188 # else
2189 /* ISO C says about %s in fprintf:
2190 "If the precision is not specified or greater than the size of
2191 the array, the array shall contain a null character."
2192 So if there is a precision, we must not use strlen. */
2193 const char *arg = ap->arg[arg_index].a.a_string;
2194
2195 if (has_precision)
2196 tmp_length = local_strnlen (arg, precision);
2197 else
2198 tmp_length = strlen (arg);
2199 # endif
2200 }
2201 break;
2202
2203 case 'p':
2204 tmp_length =
2205 (unsigned int) (sizeof (void *) * CHAR_BIT
2206 * 0.25 /* binary -> hexadecimal */
2207 )
2208 + 1 /* turn floor into ceil */
2209 + 2; /* account for leading 0x */
2210 break;
2211
2212 default:
2213 abort ();
2214 }
2215
2216 if (!pad_ourselves)
2217 {
2218 # if ENABLE_UNISTDIO
2219 /* Padding considers the number of characters, therefore the number of
2220 elements after padding may be
2221 > max (tmp_length, width)
2222 but is certainly
2223 <= tmp_length + width. */
2224 tmp_length = xsum (tmp_length, width);
2225 # else
2226 /* Padding considers the number of elements, says POSIX. */
2227 if (tmp_length < width)
2228 tmp_length = width;
2229 # endif
2230 }
2231
2232 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
2233
2234 return tmp_length;
2235 }
2236
2237 #endif
2238
2239 DCHAR_T *
2240 VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
2241 const FCHAR_T *format, va_list args)
2242 {
2243 DIRECTIVES d;
2244 arguments a;
2245
2246 if (PRINTF_PARSE (format, &d, &a) < 0)
2247 /* errno is already set. */
2248 return NULL;
2249
2250 /* Frees the memory allocated by this function. Preserves errno. */
2251 #define CLEANUP() \
2252 if (d.dir != d.direct_alloc_dir) \
2253 free (d.dir); \
2254 if (a.arg != a.direct_alloc_arg) \
2255 free (a.arg);
2256
2257 if (PRINTF_FETCHARGS (args, &a) < 0)
2258 goto fail_1_with_EINVAL;
2259
2260 {
2261 size_t buf_neededlength;
2262 TCHAR_T *buf;
2263 TCHAR_T *buf_malloced;
2264 const FCHAR_T *cp;
2265 size_t i;
2266 DIRECTIVE *dp;
2267 /* Output string accumulator. */
2268 DCHAR_T *result;
2269 size_t allocated;
2270 size_t length;
2271
2272 /* Allocate a small buffer that will hold a directive passed to
2273 sprintf or snprintf. */
2274 buf_neededlength =
2275 xsum4 (7, d.max_width_length, d.max_precision_length, 6);
2276 #if HAVE_ALLOCA
2277 if (buf_neededlength < 4000 / sizeof (TCHAR_T))
2278 {
2279 buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T));
2280 buf_malloced = NULL;
2281 }
2282 else
2283 #endif
2284 {
2285 size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T));
2286 if (size_overflow_p (buf_memsize))
2287 goto out_of_memory_1;
2288 buf = (TCHAR_T *) malloc (buf_memsize);
2289 if (buf == NULL)
2290 goto out_of_memory_1;
2291 buf_malloced = buf;
2292 }
2293
2294 result = resultbuf;
2295 allocated = (resultbuf != NULL ? *lengthp : 0);
2296 length = 0;
2297 /* Invariants:
2298 result is either == resultbuf or malloc-allocated.
2299 If result == NULL, resultbuf is == NULL as well.
2300 If length > 0, then result != NULL. */
2301
2302 /* Ensures that allocated >= needed. Aborts through a jump to
2303 out_of_memory if needed is SIZE_MAX or otherwise too big. */
2304 #define ENSURE_ALLOCATION_ELSE(needed, oom_statement) \
2305 if ((needed) > allocated) \
2306 { \
2307 size_t memory_size; \
2308 DCHAR_T *memory; \
2309 \
2310 allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
2311 if ((needed) > allocated) \
2312 allocated = (needed); \
2313 memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
2314 if (size_overflow_p (memory_size)) \
2315 oom_statement \
2316 if (result == resultbuf) \
2317 memory = (DCHAR_T *) malloc (memory_size); \
2318 else \
2319 memory = (DCHAR_T *) realloc (result, memory_size); \
2320 if (memory == NULL) \
2321 oom_statement \
2322 if (result == resultbuf && length > 0) \
2323 DCHAR_CPY (memory, result, length); \
2324 result = memory; \
2325 }
2326 #define ENSURE_ALLOCATION(needed) \
2327 ENSURE_ALLOCATION_ELSE((needed), goto out_of_memory; )
2328
2329 for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++)
2330 {
2331 if (cp != dp->dir_start)
2332 {
2333 size_t n = dp->dir_start - cp;
2334 size_t augmented_length = xsum (length, n);
2335
2336 ENSURE_ALLOCATION (augmented_length);
2337 /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we
2338 need that the format string contains only ASCII characters
2339 if FCHAR_T and DCHAR_T are not the same type. */
2340 if (sizeof (FCHAR_T) == sizeof (DCHAR_T))
2341 {
2342 DCHAR_CPY (result + length, (const DCHAR_T *) cp, n);
2343 length = augmented_length;
2344 }
2345 else
2346 {
2347 do
2348 result[length++] = *cp++;
2349 while (--n > 0);
2350 }
2351 }
2352 if (i == d.count)
2353 break;
2354
2355 /* Execute a single directive. */
2356 if (dp->conversion == '%')
2357 {
2358 size_t augmented_length;
2359
2360 if (!(dp->arg_index == ARG_NONE))
2361 abort ();
2362 augmented_length = xsum (length, 1);
2363 ENSURE_ALLOCATION (augmented_length);
2364 result[length] = '%';
2365 length = augmented_length;
2366 }
2367 else
2368 {
2369 if (!(dp->arg_index != ARG_NONE))
2370 abort ();
2371
2372 if (dp->conversion == 'n')
2373 {
2374 #if NEED_PRINTF_WITH_N_DIRECTIVE
2375 switch (a.arg[dp->arg_index].type)
2376 {
2377 case TYPE_COUNT_SCHAR_POINTER:
2378 *a.arg[dp->arg_index].a.a_count_schar_pointer = length;
2379 break;
2380 case TYPE_COUNT_SHORT_POINTER:
2381 *a.arg[dp->arg_index].a.a_count_short_pointer = length;
2382 break;
2383 case TYPE_COUNT_INT_POINTER:
2384 *a.arg[dp->arg_index].a.a_count_int_pointer = length;
2385 break;
2386 case TYPE_COUNT_LONGINT_POINTER:
2387 *a.arg[dp->arg_index].a.a_count_longint_pointer = length;
2388 break;
2389 case TYPE_COUNT_LONGLONGINT_POINTER:
2390 *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length;
2391 break;
2392 case TYPE_COUNT_INT8_T_POINTER:
2393 *a.arg[dp->arg_index].a.a_count_int8_t_pointer = length;
2394 break;
2395 case TYPE_COUNT_INT16_T_POINTER:
2396 *a.arg[dp->arg_index].a.a_count_int16_t_pointer = length;
2397 break;
2398 case TYPE_COUNT_INT32_T_POINTER:
2399 *a.arg[dp->arg_index].a.a_count_int32_t_pointer = length;
2400 break;
2401 case TYPE_COUNT_INT64_T_POINTER:
2402 *a.arg[dp->arg_index].a.a_count_int64_t_pointer = length;
2403 break;
2404 case TYPE_COUNT_INT_FAST8_T_POINTER:
2405 *a.arg[dp->arg_index].a.a_count_int_fast8_t_pointer = length;
2406 break;
2407 case TYPE_COUNT_INT_FAST16_T_POINTER:
2408 *a.arg[dp->arg_index].a.a_count_int_fast16_t_pointer = length;
2409 break;
2410 case TYPE_COUNT_INT_FAST32_T_POINTER:
2411 *a.arg[dp->arg_index].a.a_count_int_fast32_t_pointer = length;
2412 break;
2413 case TYPE_COUNT_INT_FAST64_T_POINTER:
2414 *a.arg[dp->arg_index].a.a_count_int_fast64_t_pointer = length;
2415 break;
2416 default:
2417 abort ();
2418 }
2419 #else
2420 abort ();
2421 #endif
2422 }
2423 #if ENABLE_UNISTDIO
2424 /* The unistdio extensions. */
2425 else if (dp->conversion == 'U')
2426 {
2427 arg_type type = a.arg[dp->arg_index].type;
2428 int flags = dp->flags;
2429 int has_width;
2430 size_t width;
2431 int has_precision;
2432 size_t precision;
2433
2434 has_width = 0;
2435 width = 0;
2436 if (dp->width_start != dp->width_end)
2437 {
2438 if (dp->width_arg_index != ARG_NONE)
2439 {
2440 int arg;
2441
2442 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2443 abort ();
2444 arg = a.arg[dp->width_arg_index].a.a_int;
2445 width = arg;
2446 if (arg < 0)
2447 {
2448 /* "A negative field width is taken as a '-' flag
2449 followed by a positive field width." */
2450 flags |= FLAG_LEFT;
2451 width = -width;
2452 }
2453 }
2454 else
2455 {
2456 const FCHAR_T *digitp = dp->width_start;
2457
2458 do
2459 width = xsum (xtimes (width, 10), *digitp++ - '0');
2460 while (digitp != dp->width_end);
2461 }
2462 if (width > (size_t) INT_MAX)
2463 goto overflow;
2464 has_width = 1;
2465 }
2466
2467 has_precision = 0;
2468 precision = 0;
2469 if (dp->precision_start != dp->precision_end)
2470 {
2471 if (dp->precision_arg_index != ARG_NONE)
2472 {
2473 int arg;
2474
2475 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2476 abort ();
2477 arg = a.arg[dp->precision_arg_index].a.a_int;
2478 /* "A negative precision is taken as if the precision
2479 were omitted." */
2480 if (arg >= 0)
2481 {
2482 precision = arg;
2483 has_precision = 1;
2484 }
2485 }
2486 else
2487 {
2488 const FCHAR_T *digitp = dp->precision_start + 1;
2489
2490 precision = 0;
2491 while (digitp != dp->precision_end)
2492 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2493 has_precision = 1;
2494 }
2495 }
2496
2497 switch (type)
2498 {
2499 case TYPE_U8_STRING:
2500 {
2501 const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string;
2502 const uint8_t *arg_end;
2503 size_t characters;
2504
2505 if (has_precision)
2506 {
2507 /* Use only PRECISION characters, from the left. */
2508 arg_end = arg;
2509 characters = 0;
2510 for (; precision > 0; precision--)
2511 {
2512 int count = u8_strmblen (arg_end);
2513 if (count == 0)
2514 break;
2515 if (count < 0)
2516 goto fail_with_EILSEQ;
2517 arg_end += count;
2518 characters++;
2519 }
2520 }
2521 else if (has_width)
2522 {
2523 /* Use the entire string, and count the number of
2524 characters. */
2525 arg_end = arg;
2526 characters = 0;
2527 for (;;)
2528 {
2529 int count = u8_strmblen (arg_end);
2530 if (count == 0)
2531 break;
2532 if (count < 0)
2533 goto fail_with_EILSEQ;
2534 arg_end += count;
2535 characters++;
2536 }
2537 }
2538 else
2539 {
2540 /* Use the entire string. */
2541 arg_end = arg + u8_strlen (arg);
2542 /* The number of characters doesn't matter,
2543 because !has_width and therefore width==0. */
2544 characters = 0;
2545 }
2546
2547 if (characters < width && !(flags & FLAG_LEFT))
2548 {
2549 size_t n = width - characters;
2550 ENSURE_ALLOCATION (xsum (length, n));
2551 DCHAR_SET (result + length, ' ', n);
2552 length += n;
2553 }
2554
2555 # if DCHAR_IS_UINT8_T
2556 {
2557 size_t n = arg_end - arg;
2558 ENSURE_ALLOCATION (xsum (length, n));
2559 DCHAR_CPY (result + length, arg, n);
2560 length += n;
2561 }
2562 # else
2563 { /* Convert. */
2564 DCHAR_T *converted = result + length;
2565 size_t converted_len = allocated - length;
2566 # if DCHAR_IS_TCHAR
2567 /* Convert from UTF-8 to locale encoding. */
2568 converted =
2569 u8_conv_to_encoding (locale_charset (),
2570 iconveh_question_mark,
2571 arg, arg_end - arg, NULL,
2572 converted, &converted_len);
2573 # else
2574 /* Convert from UTF-8 to UTF-16/UTF-32. */
2575 converted =
2576 U8_TO_DCHAR (arg, arg_end - arg,
2577 converted, &converted_len);
2578 # endif
2579 if (converted == NULL)
2580 goto fail_with_errno;
2581 if (converted != result + length)
2582 {
2583 ENSURE_ALLOCATION_ELSE (xsum (length, converted_len),
2584 { free (converted); goto out_of_memory; });
2585 DCHAR_CPY (result + length, converted, converted_len);
2586 free (converted);
2587 }
2588 length += converted_len;
2589 }
2590 # endif
2591
2592 if (characters < width && (flags & FLAG_LEFT))
2593 {
2594 size_t n = width - characters;
2595 ENSURE_ALLOCATION (xsum (length, n));
2596 DCHAR_SET (result + length, ' ', n);
2597 length += n;
2598 }
2599 }
2600 break;
2601
2602 case TYPE_U16_STRING:
2603 {
2604 const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string;
2605 const uint16_t *arg_end;
2606 size_t characters;
2607
2608 if (has_precision)
2609 {
2610 /* Use only PRECISION characters, from the left. */
2611 arg_end = arg;
2612 characters = 0;
2613 for (; precision > 0; precision--)
2614 {
2615 int count = u16_strmblen (arg_end);
2616 if (count == 0)
2617 break;
2618 if (count < 0)
2619 goto fail_with_EILSEQ;
2620 arg_end += count;
2621 characters++;
2622 }
2623 }
2624 else if (has_width)
2625 {
2626 /* Use the entire string, and count the number of
2627 characters. */
2628 arg_end = arg;
2629 characters = 0;
2630 for (;;)
2631 {
2632 int count = u16_strmblen (arg_end);
2633 if (count == 0)
2634 break;
2635 if (count < 0)
2636 goto fail_with_EILSEQ;
2637 arg_end += count;
2638 characters++;
2639 }
2640 }
2641 else
2642 {
2643 /* Use the entire string. */
2644 arg_end = arg + u16_strlen (arg);
2645 /* The number of characters doesn't matter,
2646 because !has_width and therefore width==0. */
2647 characters = 0;
2648 }
2649
2650 if (characters < width && !(flags & FLAG_LEFT))
2651 {
2652 size_t n = width - characters;
2653 ENSURE_ALLOCATION (xsum (length, n));
2654 DCHAR_SET (result + length, ' ', n);
2655 length += n;
2656 }
2657
2658 # if DCHAR_IS_UINT16_T
2659 {
2660 size_t n = arg_end - arg;
2661 ENSURE_ALLOCATION (xsum (length, n));
2662 DCHAR_CPY (result + length, arg, n);
2663 length += n;
2664 }
2665 # else
2666 { /* Convert. */
2667 DCHAR_T *converted = result + length;
2668 size_t converted_len = allocated - length;
2669 # if DCHAR_IS_TCHAR
2670 /* Convert from UTF-16 to locale encoding. */
2671 converted =
2672 u16_conv_to_encoding (locale_charset (),
2673 iconveh_question_mark,
2674 arg, arg_end - arg, NULL,
2675 converted, &converted_len);
2676 # else
2677 /* Convert from UTF-16 to UTF-8/UTF-32. */
2678 converted =
2679 U16_TO_DCHAR (arg, arg_end - arg,
2680 converted, &converted_len);
2681 # endif
2682 if (converted == NULL)
2683 goto fail_with_errno;
2684 if (converted != result + length)
2685 {
2686 ENSURE_ALLOCATION_ELSE (xsum (length, converted_len),
2687 { free (converted); goto out_of_memory; });
2688 DCHAR_CPY (result + length, converted, converted_len);
2689 free (converted);
2690 }
2691 length += converted_len;
2692 }
2693 # endif
2694
2695 if (characters < width && (flags & FLAG_LEFT))
2696 {
2697 size_t n = width - characters;
2698 ENSURE_ALLOCATION (xsum (length, n));
2699 DCHAR_SET (result + length, ' ', n);
2700 length += n;
2701 }
2702 }
2703 break;
2704
2705 case TYPE_U32_STRING:
2706 {
2707 const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string;
2708 const uint32_t *arg_end;
2709 size_t characters;
2710
2711 if (has_precision)
2712 {
2713 /* Use only PRECISION characters, from the left. */
2714 arg_end = arg;
2715 characters = 0;
2716 for (; precision > 0; precision--)
2717 {
2718 int count = u32_strmblen (arg_end);
2719 if (count == 0)
2720 break;
2721 if (count < 0)
2722 goto fail_with_EILSEQ;
2723 arg_end += count;
2724 characters++;
2725 }
2726 }
2727 else if (has_width)
2728 {
2729 /* Use the entire string, and count the number of
2730 characters. */
2731 arg_end = arg;
2732 characters = 0;
2733 for (;;)
2734 {
2735 int count = u32_strmblen (arg_end);
2736 if (count == 0)
2737 break;
2738 if (count < 0)
2739 goto fail_with_EILSEQ;
2740 arg_end += count;
2741 characters++;
2742 }
2743 }
2744 else
2745 {
2746 /* Use the entire string. */
2747 arg_end = arg + u32_strlen (arg);
2748 /* The number of characters doesn't matter,
2749 because !has_width and therefore width==0. */
2750 characters = 0;
2751 }
2752
2753 if (characters < width && !(flags & FLAG_LEFT))
2754 {
2755 size_t n = width - characters;
2756 ENSURE_ALLOCATION (xsum (length, n));
2757 DCHAR_SET (result + length, ' ', n);
2758 length += n;
2759 }
2760
2761 # if DCHAR_IS_UINT32_T
2762 {
2763 size_t n = arg_end - arg;
2764 ENSURE_ALLOCATION (xsum (length, n));
2765 DCHAR_CPY (result + length, arg, n);
2766 length += n;
2767 }
2768 # else
2769 { /* Convert. */
2770 DCHAR_T *converted = result + length;
2771 size_t converted_len = allocated - length;
2772 # if DCHAR_IS_TCHAR
2773 /* Convert from UTF-32 to locale encoding. */
2774 converted =
2775 u32_conv_to_encoding (locale_charset (),
2776 iconveh_question_mark,
2777 arg, arg_end - arg, NULL,
2778 converted, &converted_len);
2779 # else
2780 /* Convert from UTF-32 to UTF-8/UTF-16. */
2781 converted =
2782 U32_TO_DCHAR (arg, arg_end - arg,
2783 converted, &converted_len);
2784 # endif
2785 if (converted == NULL)
2786 goto fail_with_errno;
2787 if (converted != result + length)
2788 {
2789 ENSURE_ALLOCATION_ELSE (xsum (length, converted_len),
2790 { free (converted); goto out_of_memory; });
2791 DCHAR_CPY (result + length, converted, converted_len);
2792 free (converted);
2793 }
2794 length += converted_len;
2795 }
2796 # endif
2797
2798 if (characters < width && (flags & FLAG_LEFT))
2799 {
2800 size_t n = width - characters;
2801 ENSURE_ALLOCATION (xsum (length, n));
2802 DCHAR_SET (result + length, ' ', n);
2803 length += n;
2804 }
2805 }
2806 break;
2807
2808 default:
2809 abort ();
2810 }
2811 }
2812 #endif
2813 #if !WIDE_CHAR_VERSION && (PTRDIFF_MAX > INT_MAX)
2814 else if (dp->conversion == 's'
2815 && a.arg[dp->arg_index].type != TYPE_WIDE_STRING)
2816 {
2817 /* %s in vasnprintf. See the specification of fprintf.
2818 We handle it ourselves here, because the string may be longer
2819 than INT_MAX characters, whence snprintf or sprintf would
2820 fail to process it. */
2821 int flags = dp->flags;
2822 int has_width;
2823 size_t width;
2824 int has_precision;
2825 size_t precision;
2826
2827 has_width = 0;
2828 width = 0;
2829 if (dp->width_start != dp->width_end)
2830 {
2831 if (dp->width_arg_index != ARG_NONE)
2832 {
2833 int arg;
2834
2835 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
2836 abort ();
2837 arg = a.arg[dp->width_arg_index].a.a_int;
2838 width = arg;
2839 if (arg < 0)
2840 {
2841 /* "A negative field width is taken as a '-' flag
2842 followed by a positive field width." */
2843 flags |= FLAG_LEFT;
2844 width = -width;
2845 }
2846 }
2847 else
2848 {
2849 const FCHAR_T *digitp = dp->width_start;
2850
2851 do
2852 width = xsum (xtimes (width, 10), *digitp++ - '0');
2853 while (digitp != dp->width_end);
2854 }
2855 if (width > (size_t) INT_MAX)
2856 goto overflow;
2857 has_width = 1;
2858 }
2859
2860 has_precision = 0;
2861 precision = 6;
2862 if (dp->precision_start != dp->precision_end)
2863 {
2864 if (dp->precision_arg_index != ARG_NONE)
2865 {
2866 int arg;
2867
2868 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
2869 abort ();
2870 arg = a.arg[dp->precision_arg_index].a.a_int;
2871 /* "A negative precision is taken as if the precision
2872 were omitted." */
2873 if (arg >= 0)
2874 {
2875 precision = arg;
2876 has_precision = 1;
2877 }
2878 }
2879 else
2880 {
2881 const FCHAR_T *digitp = dp->precision_start + 1;
2882
2883 precision = 0;
2884 while (digitp != dp->precision_end)
2885 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
2886 has_precision = 1;
2887 }
2888 }
2889
2890 {
2891 const char *arg = a.arg[dp->arg_index].a.a_string;
2892 size_t bytes;
2893 # if ENABLE_UNISTDIO && DCHAR_IS_TCHAR
2894 size_t characters;
2895 # endif
2896 # if !DCHAR_IS_TCHAR
2897 /* This code assumes that TCHAR_T is 'char'. */
2898 static_assert (sizeof (TCHAR_T) == 1);
2899 DCHAR_T *tmpdst;
2900 size_t tmpdst_len;
2901 # endif
2902 size_t w;
2903
2904 if (has_precision)
2905 {
2906 /* Use only at most PRECISION bytes, from the left. */
2907 bytes = local_strnlen (arg, precision);
2908 }
2909 else
2910 {
2911 /* Use the entire string, and count the number of
2912 bytes. */
2913 bytes = strlen (arg);
2914 }
2915
2916 # if ENABLE_UNISTDIO && DCHAR_IS_TCHAR
2917 if (has_width)
2918 characters = mbsnlen (arg, bytes);
2919 else
2920 {
2921 /* The number of characters doesn't matter,
2922 because !has_width and therefore width==0. */
2923 characters = 0;
2924 }
2925 # endif
2926
2927 # if !DCHAR_IS_TCHAR
2928 /* Convert from TCHAR_T[] to DCHAR_T[]. */
2929 tmpdst =
2930 DCHAR_CONV_FROM_ENCODING (locale_charset (),
2931 iconveh_question_mark,
2932 arg, bytes,
2933 NULL,
2934 NULL, &tmpdst_len);
2935 if (tmpdst == NULL)
2936 goto fail_with_errno;
2937 # endif
2938
2939 if (has_width)
2940 {
2941 # if ENABLE_UNISTDIO
2942 /* Outside POSIX, it's preferable to compare the width
2943 against the number of _characters_ of the converted
2944 value. */
2945 # if DCHAR_IS_TCHAR
2946 w = characters;
2947 # else
2948 w = DCHAR_MBSNLEN (tmpdst, tmpdst_len);
2949 # endif
2950 # else
2951 /* The width is compared against the number of _bytes_
2952 of the converted value, says POSIX. */
2953 w = bytes;
2954 # endif
2955 }
2956 else
2957 /* w doesn't matter. */
2958 w = 0;
2959
2960 {
2961 # if DCHAR_IS_TCHAR
2962 size_t total = bytes + (w < width ? width - w : 0);
2963 ENSURE_ALLOCATION (xsum (length, total));
2964 # else
2965 size_t total = tmpdst_len + (w < width ? width - w : 0);
2966 ENSURE_ALLOCATION_ELSE (xsum (length, total),
2967 { free (tmpdst); goto out_of_memory; });
2968 # endif
2969
2970 if (w < width && !(flags & FLAG_LEFT))
2971 {
2972 size_t n = width - w;
2973 DCHAR_SET (result + length, ' ', n);
2974 length += n;
2975 }
2976
2977 # if DCHAR_IS_TCHAR
2978 memcpy (result + length, arg, bytes);
2979 length += bytes;
2980 # else
2981 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
2982 free (tmpdst);
2983 length += tmpdst_len;
2984 # endif
2985
2986 if (w < width && (flags & FLAG_LEFT))
2987 {
2988 size_t n = width - w;
2989 DCHAR_SET (result + length, ' ', n);
2990 length += n;
2991 }
2992 }
2993 }
2994 }
2995 #endif
2996 #if WIDE_CHAR_VERSION && ((PTRDIFF_MAX > INT_MAX) || !DCHAR_IS_TCHAR || NEED_WPRINTF_DIRECTIVE_LC)
2997 else if ((dp->conversion == 's'
2998 && a.arg[dp->arg_index].type == TYPE_WIDE_STRING)
2999 || (dp->conversion == 'c'
3000 && a.arg[dp->arg_index].type == TYPE_WIDE_CHAR))
3001 {
3002 /* %ls or %lc in vasnwprintf. See the specification of
3003 fwprintf. */
3004 /* It would be silly to use snprintf ("%ls", ...) and then
3005 convert back the result from a char[] to a wchar_t[].
3006 Instead, just copy the argument wchar_t[] to the result. */
3007 int flags = dp->flags;
3008 size_t width;
3009
3010 width = 0;
3011 if (dp->width_start != dp->width_end)
3012 {
3013 if (dp->width_arg_index != ARG_NONE)
3014 {
3015 int arg;
3016
3017 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3018 abort ();
3019 arg = a.arg[dp->width_arg_index].a.a_int;
3020 width = arg;
3021 if (arg < 0)
3022 {
3023 /* "A negative field width is taken as a '-' flag
3024 followed by a positive field width." */
3025 flags |= FLAG_LEFT;
3026 width = -width;
3027 }
3028 }
3029 else
3030 {
3031 const FCHAR_T *digitp = dp->width_start;
3032
3033 do
3034 width = xsum (xtimes (width, 10), *digitp++ - '0');
3035 while (digitp != dp->width_end);
3036 }
3037 if (width > (size_t) INT_MAX)
3038 goto overflow;
3039 }
3040
3041 {
3042 const wchar_t *ls_arg;
3043 wchar_t lc_arg[1];
3044 size_t characters;
3045
3046 if (dp->conversion == 's')
3047 {
3048 int has_precision;
3049 size_t precision;
3050
3051 has_precision = 0;
3052 precision = 6;
3053 if (dp->precision_start != dp->precision_end)
3054 {
3055 if (dp->precision_arg_index != ARG_NONE)
3056 {
3057 int arg;
3058
3059 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3060 abort ();
3061 arg = a.arg[dp->precision_arg_index].a.a_int;
3062 /* "A negative precision is taken as if the precision
3063 were omitted." */
3064 if (arg >= 0)
3065 {
3066 precision = arg;
3067 has_precision = 1;
3068 }
3069 }
3070 else
3071 {
3072 const FCHAR_T *digitp = dp->precision_start + 1;
3073
3074 precision = 0;
3075 while (digitp != dp->precision_end)
3076 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3077 has_precision = 1;
3078 }
3079 }
3080
3081 ls_arg = a.arg[dp->arg_index].a.a_wide_string;
3082
3083 if (has_precision)
3084 {
3085 /* Use only at most PRECISION wide characters, from
3086 the left. */
3087 const wchar_t *ls_arg_end;
3088
3089 ls_arg_end = ls_arg;
3090 characters = 0;
3091 for (; precision > 0; precision--)
3092 {
3093 if (*ls_arg_end == 0)
3094 /* Found the terminating null wide character. */
3095 break;
3096 ls_arg_end++;
3097 characters++;
3098 }
3099 }
3100 else
3101 {
3102 /* Use the entire string, and count the number of wide
3103 characters. */
3104 characters = local_wcslen (ls_arg);
3105 }
3106 }
3107 else /* dp->conversion == 'c' */
3108 {
3109 lc_arg[0] = (wchar_t) a.arg[dp->arg_index].a.a_wide_char;
3110 ls_arg = lc_arg;
3111 characters = 1;
3112 }
3113
3114 {
3115 size_t total = (characters < width ? width : characters);
3116 ENSURE_ALLOCATION (xsum (length, total));
3117
3118 if (characters < width && !(flags & FLAG_LEFT))
3119 {
3120 size_t n = width - characters;
3121 DCHAR_SET (result + length, ' ', n);
3122 length += n;
3123 }
3124
3125 if (characters > 0)
3126 {
3127 DCHAR_CPY (result + length, ls_arg, characters);
3128 length += characters;
3129 }
3130
3131 if (characters < width && (flags & FLAG_LEFT))
3132 {
3133 size_t n = width - characters;
3134 DCHAR_SET (result + length, ' ', n);
3135 length += n;
3136 }
3137 }
3138 }
3139 }
3140 #endif
3141 #if WIDE_CHAR_VERSION || !USE_SNPRINTF || (PTRDIFF_MAX > INT_MAX) || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || NEED_PRINTF_DIRECTIVE_LS || ENABLE_WCHAR_FALLBACK
3142 else if (dp->conversion == 's'
3143 # if WIDE_CHAR_VERSION
3144 && a.arg[dp->arg_index].type != TYPE_WIDE_STRING
3145 # else
3146 && a.arg[dp->arg_index].type == TYPE_WIDE_STRING
3147 # endif
3148 )
3149 {
3150 /* The normal handling of the 's' directive below requires
3151 allocating a temporary buffer. The determination of its
3152 length (tmp_length), in the case when a precision is
3153 specified, below requires a conversion between a char[]
3154 string and a wchar_t[] wide string. It could be done, but
3155 we have no guarantee that the implementation of sprintf will
3156 use the exactly same algorithm. Without this guarantee, it
3157 is possible to have buffer overrun bugs. In order to avoid
3158 such bugs, we implement the entire processing of the 's'
3159 directive ourselves. */
3160 int flags = dp->flags;
3161 int has_width;
3162 size_t width;
3163 int has_precision;
3164 size_t precision;
3165
3166 has_width = 0;
3167 width = 0;
3168 if (dp->width_start != dp->width_end)
3169 {
3170 if (dp->width_arg_index != ARG_NONE)
3171 {
3172 int arg;
3173
3174 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3175 abort ();
3176 arg = a.arg[dp->width_arg_index].a.a_int;
3177 width = arg;
3178 if (arg < 0)
3179 {
3180 /* "A negative field width is taken as a '-' flag
3181 followed by a positive field width." */
3182 flags |= FLAG_LEFT;
3183 width = -width;
3184 }
3185 }
3186 else
3187 {
3188 const FCHAR_T *digitp = dp->width_start;
3189
3190 do
3191 width = xsum (xtimes (width, 10), *digitp++ - '0');
3192 while (digitp != dp->width_end);
3193 }
3194 if (width > (size_t) INT_MAX)
3195 goto overflow;
3196 has_width = 1;
3197 }
3198
3199 has_precision = 0;
3200 precision = 6;
3201 if (dp->precision_start != dp->precision_end)
3202 {
3203 if (dp->precision_arg_index != ARG_NONE)
3204 {
3205 int arg;
3206
3207 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3208 abort ();
3209 arg = a.arg[dp->precision_arg_index].a.a_int;
3210 /* "A negative precision is taken as if the precision
3211 were omitted." */
3212 if (arg >= 0)
3213 {
3214 precision = arg;
3215 has_precision = 1;
3216 }
3217 }
3218 else
3219 {
3220 const FCHAR_T *digitp = dp->precision_start + 1;
3221
3222 precision = 0;
3223 while (digitp != dp->precision_end)
3224 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
3225 has_precision = 1;
3226 }
3227 }
3228
3229 # if WIDE_CHAR_VERSION
3230 /* %s in vasnwprintf. See the specification of fwprintf. */
3231 {
3232 const char *arg = a.arg[dp->arg_index].a.a_string;
3233 const char *arg_end;
3234 size_t characters;
3235
3236 if (has_precision)
3237 {
3238 /* Use only as many bytes as needed to produce PRECISION
3239 wide characters, from the left. */
3240 # if HAVE_MBRTOWC
3241 mbstate_t state;
3242 mbszero (&state);
3243 # endif
3244 arg_end = arg;
3245 characters = 0;
3246 for (; precision > 0; precision--)
3247 {
3248 int count;
3249 # if HAVE_MBRTOWC
3250 count = mbrlen (arg_end, MB_CUR_MAX, &state);
3251 # else
3252 count = mblen (arg_end, MB_CUR_MAX);
3253 # endif
3254 if (count == 0)
3255 /* Found the terminating NUL. */
3256 break;
3257 if (count < 0)
3258 /* Invalid or incomplete multibyte character. */
3259 goto fail_with_EILSEQ;
3260 arg_end += count;
3261 characters++;
3262 }
3263 }
3264 else if (has_width)
3265 {
3266 /* Use the entire string, and count the number of wide
3267 characters. */
3268 # if HAVE_MBRTOWC
3269 mbstate_t state;
3270 mbszero (&state);
3271 # endif
3272 arg_end = arg;
3273 characters = 0;
3274 for (;;)
3275 {
3276 int count;
3277 # if HAVE_MBRTOWC
3278 count = mbrlen (arg_end, MB_CUR_MAX, &state);
3279 # else
3280 count = mblen (arg_end, MB_CUR_MAX);
3281 # endif
3282 if (count == 0)
3283 /* Found the terminating NUL. */
3284 break;
3285 if (count < 0)
3286 /* Invalid or incomplete multibyte character. */
3287 goto fail_with_EILSEQ;
3288 arg_end += count;
3289 characters++;
3290 }
3291 }
3292 else
3293 {
3294 /* Use the entire string. */
3295 arg_end = arg + strlen (arg);
3296 /* The number of characters doesn't matter. */
3297 characters = 0;
3298 }
3299
3300 if (characters < width && !(flags & FLAG_LEFT))
3301 {
3302 size_t n = width - characters;
3303 ENSURE_ALLOCATION (xsum (length, n));
3304 DCHAR_SET (result + length, ' ', n);
3305 length += n;
3306 }
3307
3308 if (has_precision || has_width)
3309 {
3310 /* We know the number of wide characters in advance. */
3311 size_t remaining;
3312 # if HAVE_MBRTOWC
3313 mbstate_t state;
3314 mbszero (&state);
3315 # endif
3316 ENSURE_ALLOCATION (xsum (length, characters));
3317 for (remaining = characters; remaining > 0; remaining--)
3318 {
3319 wchar_t wc;
3320 int count;
3321 # if HAVE_MBRTOWC
3322 count = mbrtowc (&wc, arg, arg_end - arg, &state);
3323 # else
3324 count = mbtowc (&wc, arg, arg_end - arg);
3325 # endif
3326 if (count <= 0)
3327 /* mbrtowc not consistent with mbrlen, or mbtowc
3328 not consistent with mblen. */
3329 abort ();
3330 result[length++] = wc;
3331 arg += count;
3332 }
3333 if (!(arg == arg_end))
3334 abort ();
3335 }
3336 else
3337 {
3338 # if HAVE_MBRTOWC
3339 mbstate_t state;
3340 mbszero (&state);
3341 # endif
3342 while (arg < arg_end)
3343 {
3344 wchar_t wc;
3345 int count;
3346 # if HAVE_MBRTOWC
3347 count = mbrtowc (&wc, arg, arg_end - arg, &state);
3348 # else
3349 count = mbtowc (&wc, arg, arg_end - arg);
3350 # endif
3351 if (count == 0)
3352 /* mbrtowc not consistent with strlen. */
3353 abort ();
3354 if (count < 0)
3355 /* Invalid or incomplete multibyte character. */
3356 goto fail_with_EILSEQ;
3357 ENSURE_ALLOCATION (xsum (length, 1));
3358 result[length++] = wc;
3359 arg += count;
3360 }
3361 }
3362
3363 if (characters < width && (flags & FLAG_LEFT))
3364 {
3365 size_t n = width - characters;
3366 ENSURE_ALLOCATION (xsum (length, n));
3367 DCHAR_SET (result + length, ' ', n);
3368 length += n;
3369 }
3370 }
3371 # else
3372 /* %ls in vasnprintf. See the specification of fprintf. */
3373 {
3374 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
3375 const wchar_t *arg_end;
3376 size_t bytes;
3377 # if ENABLE_UNISTDIO && DCHAR_IS_TCHAR
3378 size_t characters;
3379 # endif
3380 # if !DCHAR_IS_TCHAR
3381 /* This code assumes that TCHAR_T is 'char'. */
3382 static_assert (sizeof (TCHAR_T) == 1);
3383 DCHAR_T *tmpdst;
3384 size_t tmpdst_len;
3385 # endif
3386 size_t w;
3387
3388 if (has_precision)
3389 {
3390 /* Use only as many wide characters as needed to produce
3391 at most PRECISION bytes, from the left. */
3392 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
3393 mbstate_t state;
3394 mbszero (&state);
3395 # endif
3396 arg_end = arg;
3397 bytes = 0;
3398 # if ENABLE_UNISTDIO && DCHAR_IS_TCHAR
3399 characters = 0;
3400 # endif
3401 while (precision > 0)
3402 {
3403 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
3404 int count;
3405
3406 if (*arg_end == 0)
3407 /* Found the terminating null wide character. */
3408 break;
3409 count = local_wcrtomb (cbuf, *arg_end, &state);
3410 if (count < 0)
3411 /* Cannot convert. */
3412 goto fail_with_EILSEQ;
3413 if (precision < (unsigned int) count)
3414 break;
3415 arg_end++;
3416 bytes += count;
3417 # if ENABLE_UNISTDIO && DCHAR_IS_TCHAR
3418 characters += mbsnlen (cbuf, count);
3419 # endif
3420 precision -= count;
3421 }
3422 }
3423 # if DCHAR_IS_TCHAR
3424 else if (has_width)
3425 # else
3426 else
3427 # endif
3428 {
3429 /* Use the entire string, and count the number of
3430 bytes. */
3431 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
3432 mbstate_t state;
3433 mbszero (&state);
3434 # endif
3435 arg_end = arg;
3436 bytes = 0;
3437 # if ENABLE_UNISTDIO && DCHAR_IS_TCHAR
3438 characters = 0;
3439 # endif
3440 for (;;)
3441 {
3442 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
3443 int count;
3444
3445 if (*arg_end == 0)
3446 /* Found the terminating null wide character. */
3447 break;
3448 count = local_wcrtomb (cbuf, *arg_end, &state);
3449 if (count < 0)
3450 /* Cannot convert. */
3451 goto fail_with_EILSEQ;
3452 arg_end++;
3453 bytes += count;
3454 # if ENABLE_UNISTDIO && DCHAR_IS_TCHAR
3455 characters += mbsnlen (cbuf, count);
3456 # endif
3457 }
3458 }
3459 # if DCHAR_IS_TCHAR
3460 else
3461 {
3462 /* Use the entire string. */
3463 arg_end = arg + local_wcslen (arg);
3464 /* The number of bytes and characters doesn't matter,
3465 because !has_width and therefore width==0. */
3466 bytes = 0;
3467 # if ENABLE_UNISTDIO
3468 characters = 0;
3469 # endif
3470 }
3471 # endif
3472
3473 # if !DCHAR_IS_TCHAR
3474 {
3475 TCHAR_T *tmpsrc;
3476
3477 /* Convert the string into a piece of temporary memory. */
3478 tmpsrc = (TCHAR_T *) malloc (bytes * sizeof (TCHAR_T));
3479 if (tmpsrc == NULL)
3480 goto out_of_memory;
3481 {
3482 TCHAR_T *tmpptr = tmpsrc;
3483 size_t remaining;
3484 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
3485 mbstate_t state;
3486 mbszero (&state);
3487 # endif
3488 for (remaining = bytes; remaining > 0; )
3489 {
3490 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
3491 int count;
3492
3493 if (*arg == 0)
3494 abort ();
3495 count = local_wcrtomb (cbuf, *arg, &state);
3496 if (count <= 0)
3497 /* Inconsistency. */
3498 abort ();
3499 memcpy (tmpptr, cbuf, count);
3500 tmpptr += count;
3501 arg++;
3502 remaining -= count;
3503 }
3504 if (!(arg == arg_end))
3505 abort ();
3506 }
3507
3508 /* Convert from TCHAR_T[] to DCHAR_T[]. */
3509 tmpdst =
3510 DCHAR_CONV_FROM_ENCODING (locale_charset (),
3511 iconveh_question_mark,
3512 tmpsrc, bytes,
3513 NULL,
3514 NULL, &tmpdst_len);
3515 if (tmpdst == NULL)
3516 {
3517 free (tmpsrc);
3518 goto fail_with_errno;
3519 }
3520 free (tmpsrc);
3521 }
3522 # endif
3523
3524 if (has_width)
3525 {
3526 # if ENABLE_UNISTDIO
3527 /* Outside POSIX, it's preferable to compare the width
3528 against the number of _characters_ of the converted
3529 value. */
3530 # if DCHAR_IS_TCHAR
3531 w = characters;
3532 # else
3533 w = DCHAR_MBSNLEN (tmpdst, tmpdst_len);
3534 # endif
3535 # else
3536 /* The width is compared against the number of _bytes_
3537 of the converted value, says POSIX. */
3538 w = bytes;
3539 # endif
3540 }
3541 else
3542 /* w doesn't matter. */
3543 w = 0;
3544
3545 if (w < width && !(flags & FLAG_LEFT))
3546 {
3547 size_t n = width - w;
3548 # if DCHAR_IS_TCHAR
3549 ENSURE_ALLOCATION (xsum (length, n));
3550 # else
3551 ENSURE_ALLOCATION_ELSE (xsum (length, n),
3552 { free (tmpdst); goto out_of_memory; });
3553 # endif
3554 DCHAR_SET (result + length, ' ', n);
3555 length += n;
3556 }
3557
3558 # if DCHAR_IS_TCHAR
3559 if (has_precision || has_width)
3560 {
3561 /* We know the number of bytes in advance. */
3562 size_t remaining;
3563 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
3564 mbstate_t state;
3565 mbszero (&state);
3566 # endif
3567 ENSURE_ALLOCATION (xsum (length, bytes));
3568 for (remaining = bytes; remaining > 0; )
3569 {
3570 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
3571 int count;
3572
3573 if (*arg == 0)
3574 abort ();
3575 count = local_wcrtomb (cbuf, *arg, &state);
3576 if (count <= 0)
3577 /* Inconsistency. */
3578 abort ();
3579 memcpy (result + length, cbuf, count);
3580 length += count;
3581 arg++;
3582 remaining -= count;
3583 }
3584 if (!(arg == arg_end))
3585 abort ();
3586 }
3587 else
3588 {
3589 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
3590 mbstate_t state;
3591 mbszero (&state);
3592 # endif
3593 while (arg < arg_end)
3594 {
3595 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
3596 int count;
3597
3598 if (*arg == 0)
3599 abort ();
3600 count = local_wcrtomb (cbuf, *arg, &state);
3601 if (count <= 0)
3602 /* Cannot convert. */
3603 goto fail_with_EILSEQ;
3604 ENSURE_ALLOCATION (xsum (length, count));
3605 memcpy (result + length, cbuf, count);
3606 length += count;
3607 arg++;
3608 }
3609 }
3610 # else
3611 ENSURE_ALLOCATION_ELSE (xsum (length, tmpdst_len),
3612 { free (tmpdst); goto out_of_memory; });
3613 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
3614 free (tmpdst);
3615 length += tmpdst_len;
3616 # endif
3617
3618 if (w < width && (flags & FLAG_LEFT))
3619 {
3620 size_t n = width - w;
3621 ENSURE_ALLOCATION (xsum (length, n));
3622 DCHAR_SET (result + length, ' ', n);
3623 length += n;
3624 }
3625 }
3626 # endif
3627 }
3628 #endif
3629 #if (NEED_PRINTF_DIRECTIVE_LC || ENABLE_WCHAR_FALLBACK) && HAVE_WINT_T && !WIDE_CHAR_VERSION
3630 else if (dp->conversion == 'c'
3631 && a.arg[dp->arg_index].type == TYPE_WIDE_CHAR)
3632 {
3633 /* Implement the 'lc' directive ourselves, in order to provide
3634 a correct behaviour for the null wint_t argument and/or the
3635 fallback that avoids EILSEQ. */
3636 int flags = dp->flags;
3637 int has_width;
3638 size_t width;
3639
3640 has_width = 0;
3641 width = 0;
3642 if (dp->width_start != dp->width_end)
3643 {
3644 if (dp->width_arg_index != ARG_NONE)
3645 {
3646 int arg;
3647
3648 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3649 abort ();
3650 arg = a.arg[dp->width_arg_index].a.a_int;
3651 width = arg;
3652 if (arg < 0)
3653 {
3654 /* "A negative field width is taken as a '-' flag
3655 followed by a positive field width." */
3656 flags |= FLAG_LEFT;
3657 width = -width;
3658 }
3659 }
3660 else
3661 {
3662 const FCHAR_T *digitp = dp->width_start;
3663
3664 do
3665 width = xsum (xtimes (width, 10), *digitp++ - '0');
3666 while (digitp != dp->width_end);
3667 }
3668 if (width > (size_t) INT_MAX)
3669 goto overflow;
3670 has_width = 1;
3671 }
3672
3673 /* %lc in vasnprintf. See the specification of fprintf. */
3674 {
3675 wchar_t arg = (wchar_t) a.arg[dp->arg_index].a.a_wide_char;
3676 size_t bytes;
3677 # if ENABLE_UNISTDIO && DCHAR_IS_TCHAR
3678 size_t characters;
3679 # endif
3680 # if !DCHAR_IS_TCHAR
3681 /* This code assumes that TCHAR_T is 'char'. */
3682 static_assert (sizeof (TCHAR_T) == 1);
3683 DCHAR_T *tmpdst;
3684 size_t tmpdst_len;
3685 # endif
3686 size_t w;
3687
3688 # if DCHAR_IS_TCHAR
3689 if (has_width)
3690 # endif
3691 {
3692 /* Count the number of bytes. */
3693 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
3694 int count;
3695 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
3696 mbstate_t state;
3697 mbszero (&state);
3698 # endif
3699
3700 count = local_wcrtomb (cbuf, arg, &state);
3701 if (count < 0)
3702 /* Cannot convert. */
3703 goto fail_with_EILSEQ;
3704 bytes = count;
3705 # if ENABLE_UNISTDIO && DCHAR_IS_TCHAR
3706 characters = mbsnlen (cbuf, count);
3707 # endif
3708 }
3709 # if DCHAR_IS_TCHAR
3710 else
3711 {
3712 /* The number of bytes and characters doesn't matter,
3713 because !has_width and therefore width==0. */
3714 bytes = 0;
3715 # if ENABLE_UNISTDIO
3716 characters = 0;
3717 # endif
3718 }
3719 # endif
3720
3721 # if !DCHAR_IS_TCHAR
3722 {
3723 TCHAR_T tmpsrc[64]; /* Assume MB_CUR_MAX <= 64. */
3724
3725 /* Convert the string into a piece of temporary memory. */
3726 if (bytes > 0)
3727 {
3728 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
3729 int count;
3730 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
3731 mbstate_t state;
3732 mbszero (&state);
3733 # endif
3734
3735 count = local_wcrtomb (cbuf, arg, &state);
3736 if (count <= 0)
3737 /* Inconsistency. */
3738 abort ();
3739 memcpy (tmpsrc, cbuf, count);
3740 }
3741
3742 /* Convert from TCHAR_T[] to DCHAR_T[]. */
3743 tmpdst =
3744 DCHAR_CONV_FROM_ENCODING (locale_charset (),
3745 iconveh_question_mark,
3746 tmpsrc, bytes,
3747 NULL,
3748 NULL, &tmpdst_len);
3749 if (tmpdst == NULL)
3750 goto fail_with_errno;
3751 }
3752 # endif
3753
3754 if (has_width)
3755 {
3756 # if ENABLE_UNISTDIO
3757 /* Outside POSIX, it's preferable to compare the width
3758 against the number of _characters_ of the converted
3759 value. */
3760 # if DCHAR_IS_TCHAR
3761 w = characters;
3762 # else
3763 w = DCHAR_MBSNLEN (tmpdst, tmpdst_len);
3764 # endif
3765 # else
3766 /* The width is compared against the number of _bytes_
3767 of the converted value, says POSIX. */
3768 w = bytes;
3769 # endif
3770 }
3771 else
3772 /* w doesn't matter. */
3773 w = 0;
3774
3775 if (w < width && !(flags & FLAG_LEFT))
3776 {
3777 size_t n = width - w;
3778 # if DCHAR_IS_TCHAR
3779 ENSURE_ALLOCATION (xsum (length, n));
3780 # else
3781 ENSURE_ALLOCATION_ELSE (xsum (length, n),
3782 { free (tmpdst); goto out_of_memory; });
3783 # endif
3784 DCHAR_SET (result + length, ' ', n);
3785 length += n;
3786 }
3787
3788 # if DCHAR_IS_TCHAR
3789 if (has_width)
3790 {
3791 /* We know the number of bytes in advance. */
3792 ENSURE_ALLOCATION (xsum (length, bytes));
3793 if (bytes > 0)
3794 {
3795 int count;
3796 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
3797 mbstate_t state;
3798 mbszero (&state);
3799 # endif
3800
3801 count = local_wcrtomb (result + length, arg, &state);
3802 if (count <= 0)
3803 /* Inconsistency. */
3804 abort ();
3805 length += count;
3806 }
3807 }
3808 else
3809 {
3810 char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
3811 int count;
3812 # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
3813 mbstate_t state;
3814 mbszero (&state);
3815 # endif
3816
3817 count = local_wcrtomb (cbuf, arg, &state);
3818 if (count < 0)
3819 /* Cannot convert. */
3820 goto fail_with_EILSEQ;
3821 ENSURE_ALLOCATION (xsum (length, count));
3822 memcpy (result + length, cbuf, count);
3823 length += count;
3824 }
3825 # else
3826 ENSURE_ALLOCATION_ELSE (xsum (length, tmpdst_len),
3827 { free (tmpdst); goto out_of_memory; });
3828 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
3829 free (tmpdst);
3830 length += tmpdst_len;
3831 # endif
3832
3833 if (w < width && (flags & FLAG_LEFT))
3834 {
3835 size_t n = width - w;
3836 ENSURE_ALLOCATION (xsum (length, n));
3837 DCHAR_SET (result + length, ' ', n);
3838 length += n;
3839 }
3840 }
3841 }
3842 #endif
3843 #if NEED_WPRINTF_DIRECTIVE_C && WIDE_CHAR_VERSION
3844 else if (dp->conversion == 'c'
3845 && a.arg[dp->arg_index].type != TYPE_WIDE_CHAR)
3846 {
3847 /* Implement the 'c' directive ourselves, in order to avoid
3848 EILSEQ in the "C" locale. */
3849 int flags = dp->flags;
3850 size_t width;
3851
3852 width = 0;
3853 if (dp->width_start != dp->width_end)
3854 {
3855 if (dp->width_arg_index != ARG_NONE)
3856 {
3857 int arg;
3858
3859 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3860 abort ();
3861 arg = a.arg[dp->width_arg_index].a.a_int;
3862 width = arg;
3863 if (arg < 0)
3864 {
3865 /* "A negative field width is taken as a '-' flag
3866 followed by a positive field width." */
3867 flags |= FLAG_LEFT;
3868 width = -width;
3869 }
3870 }
3871 else
3872 {
3873 const FCHAR_T *digitp = dp->width_start;
3874
3875 do
3876 width = xsum (xtimes (width, 10), *digitp++ - '0');
3877 while (digitp != dp->width_end);
3878 }
3879 if (width > (size_t) INT_MAX)
3880 goto overflow;
3881 }
3882
3883 /* %c in vasnwprintf. See the specification of fwprintf. */
3884 {
3885 char arg = (char) a.arg[dp->arg_index].a.a_char;
3886 mbstate_t state;
3887 wchar_t wc;
3888
3889 mbszero (&state);
3890 int count = mbrtowc (&wc, &arg, 1, &state);
3891 if (count < 0)
3892 /* Invalid or incomplete multibyte character. */
3893 goto fail_with_EILSEQ;
3894
3895 {
3896 size_t total = (1 < width ? width : 1);
3897 ENSURE_ALLOCATION (xsum (length, total));
3898
3899 if (1 < width && !(flags & FLAG_LEFT))
3900 {
3901 size_t n = width - 1;
3902 DCHAR_SET (result + length, ' ', n);
3903 length += n;
3904 }
3905
3906 result[length++] = wc;
3907
3908 if (1 < width && (flags & FLAG_LEFT))
3909 {
3910 size_t n = width - 1;
3911 DCHAR_SET (result + length, ' ', n);
3912 length += n;
3913 }
3914 }
3915 }
3916 }
3917 #endif
3918 #if NEED_PRINTF_DIRECTIVE_B || NEED_PRINTF_DIRECTIVE_UPPERCASE_B
3919 else if (0
3920 # if NEED_PRINTF_DIRECTIVE_B
3921 || (dp->conversion == 'b')
3922 # endif
3923 # if NEED_PRINTF_DIRECTIVE_UPPERCASE_B
3924 || (dp->conversion == 'B')
3925 # endif
3926 )
3927 {
3928 arg_type type = a.arg[dp->arg_index].type;
3929 int flags = dp->flags;
3930 int has_width;
3931 size_t width;
3932 int has_precision;
3933 size_t precision;
3934 size_t tmp_length;
3935 size_t count;
3936 DCHAR_T tmpbuf[700];
3937 DCHAR_T *tmp;
3938 DCHAR_T *tmp_end;
3939 DCHAR_T *tmp_start;
3940 DCHAR_T *pad_ptr;
3941 DCHAR_T *p;
3942
3943 has_width = 0;
3944 width = 0;
3945 if (dp->width_start != dp->width_end)
3946 {
3947 if (dp->width_arg_index != ARG_NONE)
3948 {
3949 int arg;
3950
3951 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
3952 abort ();
3953 arg = a.arg[dp->width_arg_index].a.a_int;
3954 width = arg;
3955 if (arg < 0)
3956 {
3957 /* "A negative field width is taken as a '-' flag
3958 followed by a positive field width." */
3959 flags |= FLAG_LEFT;
3960 width = -width;
3961 }
3962 }
3963 else
3964 {
3965 const FCHAR_T *digitp = dp->width_start;
3966
3967 do
3968 width = xsum (xtimes (width, 10), *digitp++ - '0');
3969 while (digitp != dp->width_end);
3970 }
3971 if (width > (size_t) INT_MAX)
3972 goto overflow;
3973 has_width = 1;
3974 }
3975
3976 has_precision = 0;
3977 precision = 1;
3978 if (dp->precision_start != dp->precision_end)
3979 {
3980 if (dp->precision_arg_index != ARG_NONE)
3981 {
3982 int arg;
3983
3984 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
3985 abort ();
3986 arg = a.arg[dp->precision_arg_index].a.a_int;
3987 /* "A negative precision is taken as if the precision
3988 were omitted." */
3989 if (arg >= 0)
3990 {
3991 precision = arg;
3992 has_precision = 1;
3993 }
3994 }
3995 else
3996 {
3997 const FCHAR_T *digitp = dp->precision_start + 1;
3998
3999 precision = 0;
4000 while (digitp != dp->precision_end)
4001 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
4002 has_precision = 1;
4003 }
4004 }
4005
4006 /* Allocate a temporary buffer of sufficient size. */
4007 switch (type)
4008 {
4009 default:
4010 tmp_length =
4011 (unsigned int) (sizeof (unsigned int) * CHAR_BIT)
4012 + 1; /* turn floor into ceil */
4013 break;
4014 case TYPE_ULONGINT:
4015 tmp_length =
4016 (unsigned int) (sizeof (unsigned long int) * CHAR_BIT)
4017 + 1; /* turn floor into ceil */
4018 break;
4019 case TYPE_ULONGLONGINT:
4020 tmp_length =
4021 (unsigned int) (sizeof (unsigned long long int) * CHAR_BIT)
4022 + 1; /* turn floor into ceil */
4023 break;
4024 case TYPE_UINT8_T:
4025 tmp_length =
4026 (unsigned int) (sizeof (uint8_t) * CHAR_BIT)
4027 + 1; /* turn floor into ceil */
4028 break;
4029 case TYPE_UINT16_T:
4030 tmp_length =
4031 (unsigned int) (sizeof (uint16_t) * CHAR_BIT)
4032 + 1; /* turn floor into ceil */
4033 break;
4034 case TYPE_UINT32_T:
4035 tmp_length =
4036 (unsigned int) (sizeof (uint32_t) * CHAR_BIT)
4037 + 1; /* turn floor into ceil */
4038 break;
4039 case TYPE_UINT64_T:
4040 tmp_length =
4041 (unsigned int) (sizeof (uint64_t) * CHAR_BIT)
4042 + 1; /* turn floor into ceil */
4043 break;
4044 case TYPE_UINT_FAST8_T:
4045 tmp_length =
4046 (unsigned int) (sizeof (uint_fast8_t) * CHAR_BIT)
4047 + 1; /* turn floor into ceil */
4048 break;
4049 case TYPE_UINT_FAST16_T:
4050 tmp_length =
4051 (unsigned int) (sizeof (uint_fast16_t) * CHAR_BIT)
4052 + 1; /* turn floor into ceil */
4053 break;
4054 case TYPE_UINT_FAST32_T:
4055 tmp_length =
4056 (unsigned int) (sizeof (uint_fast32_t) * CHAR_BIT)
4057 + 1; /* turn floor into ceil */
4058 break;
4059 case TYPE_UINT_FAST64_T:
4060 tmp_length =
4061 (unsigned int) (sizeof (uint_fast64_t) * CHAR_BIT)
4062 + 1; /* turn floor into ceil */
4063 break;
4064 }
4065 if (tmp_length < precision)
4066 tmp_length = precision;
4067 /* Add 2, to account for a prefix from the alternate form. */
4068 tmp_length = xsum (tmp_length, 2);
4069
4070 if (tmp_length < width)
4071 tmp_length = width;
4072
4073 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
4074 tmp = tmpbuf;
4075 else
4076 {
4077 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
4078
4079 if (size_overflow_p (tmp_memsize))
4080 /* Overflow, would lead to out of memory. */
4081 goto out_of_memory;
4082 tmp = (DCHAR_T *) malloc (tmp_memsize);
4083 if (tmp == NULL)
4084 /* Out of memory. */
4085 goto out_of_memory;
4086 }
4087
4088 tmp_end = tmp + tmp_length;
4089
4090 unsigned long long arg;
4091 switch (type)
4092 {
4093 case TYPE_UCHAR:
4094 arg = a.arg[dp->arg_index].a.a_uchar;
4095 break;
4096 case TYPE_USHORT:
4097 arg = a.arg[dp->arg_index].a.a_ushort;
4098 break;
4099 case TYPE_UINT:
4100 arg = a.arg[dp->arg_index].a.a_uint;
4101 break;
4102 case TYPE_ULONGINT:
4103 arg = a.arg[dp->arg_index].a.a_ulongint;
4104 break;
4105 case TYPE_ULONGLONGINT:
4106 arg = a.arg[dp->arg_index].a.a_ulonglongint;
4107 break;
4108 case TYPE_UINT8_T:
4109 arg = a.arg[dp->arg_index].a.a_uint8_t;
4110 break;
4111 case TYPE_UINT16_T:
4112 arg = a.arg[dp->arg_index].a.a_uint16_t;
4113 break;
4114 case TYPE_UINT32_T:
4115 arg = a.arg[dp->arg_index].a.a_uint32_t;
4116 break;
4117 case TYPE_UINT64_T:
4118 arg = a.arg[dp->arg_index].a.a_uint64_t;
4119 break;
4120 case TYPE_UINT_FAST8_T:
4121 arg = a.arg[dp->arg_index].a.a_uint_fast8_t;
4122 break;
4123 case TYPE_UINT_FAST16_T:
4124 arg = a.arg[dp->arg_index].a.a_uint_fast16_t;
4125 break;
4126 case TYPE_UINT_FAST32_T:
4127 arg = a.arg[dp->arg_index].a.a_uint_fast32_t;
4128 break;
4129 case TYPE_UINT_FAST64_T:
4130 arg = a.arg[dp->arg_index].a.a_uint_fast64_t;
4131 break;
4132 default:
4133 abort ();
4134 }
4135 int need_prefix = ((flags & FLAG_ALT) && arg != 0);
4136
4137 p = tmp_end;
4138 /* "The result of converting a zero value with a precision
4139 of zero is no characters." */
4140 if (!(has_precision && precision == 0 && arg == 0))
4141 {
4142 do
4143 {
4144 *--p = '0' + (arg & 1);
4145 arg = arg >> 1;
4146 }
4147 while (arg != 0);
4148 }
4149
4150 if (has_precision)
4151 {
4152 DCHAR_T *digits_start = tmp_end - precision;
4153 while (p > digits_start)
4154 *--p = '0';
4155 }
4156
4157 pad_ptr = p;
4158
4159 if (need_prefix)
4160 {
4161 # if NEED_PRINTF_DIRECTIVE_B && !NEED_PRINTF_DIRECTIVE_UPPERCASE_B
4162 *--p = 'b';
4163 # elif NEED_PRINTF_DIRECTIVE_UPPERCASE_B && !NEED_PRINTF_DIRECTIVE_B
4164 *--p = 'B';
4165 # else
4166 *--p = dp->conversion;
4167 # endif
4168 *--p = '0';
4169 }
4170 tmp_start = p;
4171
4172 /* The generated string now extends from tmp_start to tmp_end,
4173 with the zero padding insertion point being at pad_ptr,
4174 tmp_start <= pad_ptr <= tmp_end. */
4175 count = tmp_end - tmp_start;
4176
4177 if (count < width)
4178 {
4179 size_t pad = width - count;
4180
4181 if (flags & FLAG_LEFT)
4182 {
4183 /* Pad with spaces on the right. */
4184 for (p = tmp_start; p < tmp_end; p++)
4185 *(p - pad) = *p;
4186 for (p = tmp_end - pad; p < tmp_end; p++)
4187 *p = ' ';
4188 }
4189 else if ((flags & FLAG_ZERO)
4190 /* Neither ISO C nor POSIX specify that the '0'
4191 flag is ignored when a width and a precision
4192 are both present. But most implementations
4193 do so. */
4194 && !(has_width && has_precision))
4195 {
4196 /* Pad with zeroes. */
4197 for (p = tmp_start; p < pad_ptr; p++)
4198 *(p - pad) = *p;
4199 for (p = pad_ptr - pad; p < pad_ptr; p++)
4200 *p = '0';
4201 }
4202 else
4203 {
4204 /* Pad with spaces on the left. */
4205 for (p = tmp_start - pad; p < tmp_start; p++)
4206 *p = ' ';
4207 }
4208
4209 tmp_start = tmp_start - pad;
4210 }
4211
4212 count = tmp_end - tmp_start;
4213
4214 if (count > tmp_length)
4215 /* tmp_length was incorrectly calculated - fix the
4216 code above! */
4217 abort ();
4218
4219 /* Make room for the result. */
4220 if (count >= allocated - length)
4221 {
4222 size_t n = xsum (length, count);
4223
4224 ENSURE_ALLOCATION_ELSE (n,
4225 { if (tmp != tmpbuf) free (tmp); goto out_of_memory; });
4226 }
4227
4228 /* Append the result. */
4229 memcpy (result + length, tmp_start, count * sizeof (DCHAR_T));
4230 if (tmp != tmpbuf)
4231 free (tmp);
4232 length += count;
4233 }
4234 #endif
4235 #if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE || (NEED_WPRINTF_DIRECTIVE_LA && WIDE_CHAR_VERSION)
4236 else if ((dp->conversion == 'a' || dp->conversion == 'A')
4237 # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE))
4238 && (0
4239 # if NEED_PRINTF_DOUBLE
4240 || a.arg[dp->arg_index].type == TYPE_DOUBLE
4241 # endif
4242 # if NEED_PRINTF_LONG_DOUBLE || (NEED_WPRINTF_DIRECTIVE_LA && WIDE_CHAR_VERSION)
4243 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
4244 # endif
4245 )
4246 # endif
4247 )
4248 {
4249 arg_type type = a.arg[dp->arg_index].type;
4250 int flags = dp->flags;
4251 size_t width;
4252 int has_precision;
4253 size_t precision;
4254 size_t tmp_length;
4255 size_t count;
4256 DCHAR_T tmpbuf[700];
4257 DCHAR_T *tmp;
4258 DCHAR_T *pad_ptr;
4259 DCHAR_T *p;
4260
4261 width = 0;
4262 if (dp->width_start != dp->width_end)
4263 {
4264 if (dp->width_arg_index != ARG_NONE)
4265 {
4266 int arg;
4267
4268 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4269 abort ();
4270 arg = a.arg[dp->width_arg_index].a.a_int;
4271 width = arg;
4272 if (arg < 0)
4273 {
4274 /* "A negative field width is taken as a '-' flag
4275 followed by a positive field width." */
4276 flags |= FLAG_LEFT;
4277 width = -width;
4278 }
4279 }
4280 else
4281 {
4282 const FCHAR_T *digitp = dp->width_start;
4283
4284 do
4285 width = xsum (xtimes (width, 10), *digitp++ - '0');
4286 while (digitp != dp->width_end);
4287 }
4288 if (width > (size_t) INT_MAX)
4289 goto overflow;
4290 }
4291
4292 has_precision = 0;
4293 precision = 0;
4294 if (dp->precision_start != dp->precision_end)
4295 {
4296 if (dp->precision_arg_index != ARG_NONE)
4297 {
4298 int arg;
4299
4300 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4301 abort ();
4302 arg = a.arg[dp->precision_arg_index].a.a_int;
4303 /* "A negative precision is taken as if the precision
4304 were omitted." */
4305 if (arg >= 0)
4306 {
4307 precision = arg;
4308 has_precision = 1;
4309 }
4310 }
4311 else
4312 {
4313 const FCHAR_T *digitp = dp->precision_start + 1;
4314
4315 precision = 0;
4316 while (digitp != dp->precision_end)
4317 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
4318 has_precision = 1;
4319 }
4320 }
4321
4322 /* Allocate a temporary buffer of sufficient size. */
4323 if (type == TYPE_LONGDOUBLE)
4324 tmp_length =
4325 (unsigned int) ((LDBL_DIG + 1)
4326 * 0.831 /* decimal -> hexadecimal */
4327 )
4328 + 1; /* turn floor into ceil */
4329 else
4330 tmp_length =
4331 (unsigned int) ((DBL_DIG + 1)
4332 * 0.831 /* decimal -> hexadecimal */
4333 )
4334 + 1; /* turn floor into ceil */
4335 if (tmp_length < precision)
4336 tmp_length = precision;
4337 /* Account for sign, decimal point etc. */
4338 tmp_length = xsum (tmp_length, 12);
4339
4340 if (tmp_length < width)
4341 tmp_length = width;
4342
4343 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
4344
4345 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
4346 tmp = tmpbuf;
4347 else
4348 {
4349 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
4350
4351 if (size_overflow_p (tmp_memsize))
4352 /* Overflow, would lead to out of memory. */
4353 goto out_of_memory;
4354 tmp = (DCHAR_T *) malloc (tmp_memsize);
4355 if (tmp == NULL)
4356 /* Out of memory. */
4357 goto out_of_memory;
4358 }
4359
4360 pad_ptr = NULL;
4361 p = tmp;
4362 if (type == TYPE_LONGDOUBLE)
4363 {
4364 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || (NEED_WPRINTF_DIRECTIVE_LA && WIDE_CHAR_VERSION)
4365 long double arg = a.arg[dp->arg_index].a.a_longdouble;
4366
4367 if (isnanl (arg))
4368 {
4369 if (dp->conversion == 'A')
4370 {
4371 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
4372 }
4373 else
4374 {
4375 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
4376 }
4377 }
4378 else
4379 {
4380 int sign = 0;
4381 DECL_LONG_DOUBLE_ROUNDING
4382
4383 BEGIN_LONG_DOUBLE_ROUNDING ();
4384
4385 if (signbit (arg)) /* arg < 0.0L or negative zero */
4386 {
4387 sign = -1;
4388 arg = -arg;
4389 }
4390
4391 if (sign < 0)
4392 *p++ = '-';
4393 else if (flags & FLAG_SHOWSIGN)
4394 *p++ = '+';
4395 else if (flags & FLAG_SPACE)
4396 *p++ = ' ';
4397
4398 if (arg > 0.0L && arg + arg == arg)
4399 {
4400 if (dp->conversion == 'A')
4401 {
4402 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
4403 }
4404 else
4405 {
4406 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
4407 }
4408 }
4409 else
4410 {
4411 int exponent;
4412 long double mantissa;
4413
4414 if (arg > 0.0L)
4415 mantissa = printf_frexpl (arg, &exponent);
4416 else
4417 {
4418 exponent = 0;
4419 mantissa = 0.0L;
4420 }
4421
4422 if (has_precision
4423 && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1)
4424 {
4425 /* Round the mantissa. */
4426 long double tail = mantissa;
4427 size_t q;
4428
4429 for (q = precision; ; q--)
4430 {
4431 int digit = (int) tail;
4432 tail -= digit;
4433 if (q == 0)
4434 {
4435 if (digit & 1 ? tail >= 0.5L : tail > 0.5L)
4436 tail = 1 - tail;
4437 else
4438 tail = - tail;
4439 break;
4440 }
4441 tail *= 16.0L;
4442 }
4443 if (tail != 0.0L)
4444 for (q = precision; q > 0; q--)
4445 tail *= 0.0625L;
4446 mantissa += tail;
4447 }
4448
4449 *p++ = '0';
4450 *p++ = dp->conversion - 'A' + 'X';
4451 pad_ptr = p;
4452 {
4453 int digit;
4454
4455 digit = (int) mantissa;
4456 mantissa -= digit;
4457 *p++ = '0' + digit;
4458 if ((flags & FLAG_ALT)
4459 || mantissa > 0.0L || precision > 0)
4460 {
4461 *p++ = decimal_point_char ();
4462 /* This loop terminates because we assume
4463 that FLT_RADIX is a power of 2. */
4464 while (mantissa > 0.0L)
4465 {
4466 mantissa *= 16.0L;
4467 digit = (int) mantissa;
4468 mantissa -= digit;
4469 *p++ = digit
4470 + (digit < 10
4471 ? '0'
4472 : dp->conversion - 10);
4473 if (precision > 0)
4474 precision--;
4475 }
4476 while (precision > 0)
4477 {
4478 *p++ = '0';
4479 precision--;
4480 }
4481 }
4482 }
4483 *p++ = dp->conversion - 'A' + 'P';
4484 # if WIDE_CHAR_VERSION && DCHAR_IS_TCHAR
4485 {
4486 static const wchar_t decimal_format[] =
4487 { '%', '+', 'd', '\0' };
4488 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4489 }
4490 while (*p != '\0')
4491 p++;
4492 # else
4493 if (sizeof (DCHAR_T) == 1)
4494 {
4495 sprintf ((char *) p, "%+d", exponent);
4496 while (*p != '\0')
4497 p++;
4498 }
4499 else
4500 {
4501 char expbuf[6 + 1];
4502 const char *ep;
4503 sprintf (expbuf, "%+d", exponent);
4504 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4505 p++;
4506 }
4507 # endif
4508 }
4509
4510 END_LONG_DOUBLE_ROUNDING ();
4511 }
4512 # else
4513 abort ();
4514 # endif
4515 }
4516 else
4517 {
4518 # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE
4519 double arg = a.arg[dp->arg_index].a.a_double;
4520
4521 if (isnand (arg))
4522 {
4523 if (dp->conversion == 'A')
4524 {
4525 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
4526 }
4527 else
4528 {
4529 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
4530 }
4531 }
4532 else
4533 {
4534 int sign = 0;
4535
4536 if (signbit (arg)) /* arg < 0.0 or negative zero */
4537 {
4538 sign = -1;
4539 arg = -arg;
4540 }
4541
4542 if (sign < 0)
4543 *p++ = '-';
4544 else if (flags & FLAG_SHOWSIGN)
4545 *p++ = '+';
4546 else if (flags & FLAG_SPACE)
4547 *p++ = ' ';
4548
4549 if (arg > 0.0 && arg + arg == arg)
4550 {
4551 if (dp->conversion == 'A')
4552 {
4553 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
4554 }
4555 else
4556 {
4557 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
4558 }
4559 }
4560 else
4561 {
4562 int exponent;
4563 double mantissa;
4564
4565 if (arg > 0.0)
4566 mantissa = printf_frexp (arg, &exponent);
4567 else
4568 {
4569 exponent = 0;
4570 mantissa = 0.0;
4571 }
4572
4573 if (has_precision
4574 && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1)
4575 {
4576 /* Round the mantissa. */
4577 double tail = mantissa;
4578 size_t q;
4579
4580 for (q = precision; ; q--)
4581 {
4582 int digit = (int) tail;
4583 tail -= digit;
4584 if (q == 0)
4585 {
4586 if (digit & 1 ? tail >= 0.5 : tail > 0.5)
4587 tail = 1 - tail;
4588 else
4589 tail = - tail;
4590 break;
4591 }
4592 tail *= 16.0;
4593 }
4594 if (tail != 0.0)
4595 for (q = precision; q > 0; q--)
4596 tail *= 0.0625;
4597 mantissa += tail;
4598 }
4599
4600 *p++ = '0';
4601 *p++ = dp->conversion - 'A' + 'X';
4602 pad_ptr = p;
4603 {
4604 int digit;
4605
4606 digit = (int) mantissa;
4607 mantissa -= digit;
4608 *p++ = '0' + digit;
4609 if ((flags & FLAG_ALT)
4610 || mantissa > 0.0 || precision > 0)
4611 {
4612 *p++ = decimal_point_char ();
4613 /* This loop terminates because we assume
4614 that FLT_RADIX is a power of 2. */
4615 while (mantissa > 0.0)
4616 {
4617 mantissa *= 16.0;
4618 digit = (int) mantissa;
4619 mantissa -= digit;
4620 *p++ = digit
4621 + (digit < 10
4622 ? '0'
4623 : dp->conversion - 10);
4624 if (precision > 0)
4625 precision--;
4626 }
4627 while (precision > 0)
4628 {
4629 *p++ = '0';
4630 precision--;
4631 }
4632 }
4633 }
4634 *p++ = dp->conversion - 'A' + 'P';
4635 # if WIDE_CHAR_VERSION && DCHAR_IS_TCHAR
4636 {
4637 static const wchar_t decimal_format[] =
4638 { '%', '+', 'd', '\0' };
4639 SNPRINTF (p, 6 + 1, decimal_format, exponent);
4640 }
4641 while (*p != '\0')
4642 p++;
4643 # else
4644 if (sizeof (DCHAR_T) == 1)
4645 {
4646 sprintf ((char *) p, "%+d", exponent);
4647 while (*p != '\0')
4648 p++;
4649 }
4650 else
4651 {
4652 char expbuf[6 + 1];
4653 const char *ep;
4654 sprintf (expbuf, "%+d", exponent);
4655 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
4656 p++;
4657 }
4658 # endif
4659 }
4660 }
4661 # else
4662 abort ();
4663 # endif
4664 }
4665
4666 /* The generated string now extends from tmp to p, with the
4667 zero padding insertion point being at pad_ptr. */
4668 count = p - tmp;
4669
4670 if (count < width)
4671 {
4672 size_t pad = width - count;
4673 DCHAR_T *end = p + pad;
4674
4675 if (flags & FLAG_LEFT)
4676 {
4677 /* Pad with spaces on the right. */
4678 for (; pad > 0; pad--)
4679 *p++ = ' ';
4680 }
4681 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
4682 {
4683 /* Pad with zeroes. */
4684 DCHAR_T *q = end;
4685
4686 while (p > pad_ptr)
4687 *--q = *--p;
4688 for (; pad > 0; pad--)
4689 *p++ = '0';
4690 }
4691 else
4692 {
4693 /* Pad with spaces on the left. */
4694 DCHAR_T *q = end;
4695
4696 while (p > tmp)
4697 *--q = *--p;
4698 for (; pad > 0; pad--)
4699 *p++ = ' ';
4700 }
4701
4702 p = end;
4703 }
4704
4705 count = p - tmp;
4706
4707 if (count >= tmp_length)
4708 /* tmp_length was incorrectly calculated - fix the
4709 code above! */
4710 abort ();
4711
4712 /* Make room for the result. */
4713 if (count >= allocated - length)
4714 {
4715 size_t n = xsum (length, count);
4716
4717 ENSURE_ALLOCATION_ELSE (n,
4718 { if (tmp != tmpbuf) free (tmp); goto out_of_memory; });
4719 }
4720
4721 /* Append the result. */
4722 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
4723 if (tmp != tmpbuf)
4724 free (tmp);
4725 length += count;
4726 }
4727 #endif
4728 #if NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE
4729 else if ((dp->conversion == 'f' || dp->conversion == 'F'
4730 || dp->conversion == 'e' || dp->conversion == 'E'
4731 || dp->conversion == 'g' || dp->conversion == 'G'
4732 || dp->conversion == 'a' || dp->conversion == 'A')
4733 && (0
4734 # if NEED_PRINTF_DOUBLE
4735 || a.arg[dp->arg_index].type == TYPE_DOUBLE
4736 # elif NEED_PRINTF_INFINITE_DOUBLE
4737 || (a.arg[dp->arg_index].type == TYPE_DOUBLE
4738 /* The systems (mingw) which produce wrong output
4739 for Inf, -Inf, and NaN also do so for -0.0.
4740 Therefore we treat this case here as well. */
4741 && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double))
4742 # endif
4743 # if NEED_PRINTF_LONG_DOUBLE
4744 || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
4745 # elif NEED_PRINTF_INFINITE_LONG_DOUBLE
4746 || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE
4747 /* Some systems produce wrong output for Inf,
4748 -Inf, and NaN. Some systems in this category
4749 (IRIX 5.3) also do so for -0.0. Therefore we
4750 treat this case here as well. */
4751 && is_infinite_or_zerol (a.arg[dp->arg_index].a.a_longdouble))
4752 # endif
4753 ))
4754 {
4755 # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE)
4756 arg_type type = a.arg[dp->arg_index].type;
4757 # endif
4758 int flags = dp->flags;
4759 size_t width;
4760 size_t count;
4761 int has_precision;
4762 size_t precision;
4763 size_t tmp_length;
4764 DCHAR_T tmpbuf[700];
4765 DCHAR_T *tmp;
4766 DCHAR_T *pad_ptr;
4767 DCHAR_T *p;
4768
4769 width = 0;
4770 if (dp->width_start != dp->width_end)
4771 {
4772 if (dp->width_arg_index != ARG_NONE)
4773 {
4774 int arg;
4775
4776 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
4777 abort ();
4778 arg = a.arg[dp->width_arg_index].a.a_int;
4779 width = arg;
4780 if (arg < 0)
4781 {
4782 /* "A negative field width is taken as a '-' flag
4783 followed by a positive field width." */
4784 flags |= FLAG_LEFT;
4785 width = -width;
4786 }
4787 }
4788 else
4789 {
4790 const FCHAR_T *digitp = dp->width_start;
4791
4792 do
4793 width = xsum (xtimes (width, 10), *digitp++ - '0');
4794 while (digitp != dp->width_end);
4795 }
4796 if (width > (size_t) INT_MAX)
4797 goto overflow;
4798 }
4799
4800 has_precision = 0;
4801 precision = 0;
4802 if (dp->precision_start != dp->precision_end)
4803 {
4804 if (dp->precision_arg_index != ARG_NONE)
4805 {
4806 int arg;
4807
4808 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
4809 abort ();
4810 arg = a.arg[dp->precision_arg_index].a.a_int;
4811 /* "A negative precision is taken as if the precision
4812 were omitted." */
4813 if (arg >= 0)
4814 {
4815 precision = arg;
4816 has_precision = 1;
4817 }
4818 }
4819 else
4820 {
4821 const FCHAR_T *digitp = dp->precision_start + 1;
4822
4823 precision = 0;
4824 while (digitp != dp->precision_end)
4825 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
4826 has_precision = 1;
4827 }
4828 }
4829
4830 /* POSIX specifies the default precision to be 6 for %f, %F,
4831 %e, %E, but not for %g, %G. Implementations appear to use
4832 the same default precision also for %g, %G. But for %a, %A,
4833 the default precision is 0. */
4834 if (!has_precision)
4835 if (!(dp->conversion == 'a' || dp->conversion == 'A'))
4836 precision = 6;
4837
4838 /* Allocate a temporary buffer of sufficient size. */
4839 # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
4840 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
4841 # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
4842 tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0);
4843 # elif NEED_PRINTF_LONG_DOUBLE
4844 tmp_length = LDBL_DIG + 1;
4845 # elif NEED_PRINTF_DOUBLE
4846 tmp_length = DBL_DIG + 1;
4847 # else
4848 tmp_length = 0;
4849 # endif
4850 if (tmp_length < precision)
4851 tmp_length = precision;
4852 # if NEED_PRINTF_LONG_DOUBLE
4853 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4854 if (type == TYPE_LONGDOUBLE)
4855 # endif
4856 if (dp->conversion == 'f' || dp->conversion == 'F')
4857 {
4858 long double arg = a.arg[dp->arg_index].a.a_longdouble;
4859 if (!(isnanl (arg) || arg + arg == arg))
4860 {
4861 /* arg is finite and nonzero. */
4862 int exponent = floorlog10l (arg < 0 ? -arg : arg);
4863 if (exponent >= 0 && tmp_length < exponent + precision)
4864 tmp_length = exponent + precision;
4865 }
4866 }
4867 # endif
4868 # if NEED_PRINTF_DOUBLE
4869 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
4870 if (type == TYPE_DOUBLE)
4871 # endif
4872 if (dp->conversion == 'f' || dp->conversion == 'F')
4873 {
4874 double arg = a.arg[dp->arg_index].a.a_double;
4875 if (!(isnand (arg) || arg + arg == arg))
4876 {
4877 /* arg is finite and nonzero. */
4878 int exponent = floorlog10 (arg < 0 ? -arg : arg);
4879 if (exponent >= 0 && tmp_length < exponent + precision)
4880 tmp_length = exponent + precision;
4881 }
4882 }
4883 # endif
4884 /* Account for sign, decimal point etc. */
4885 tmp_length = xsum (tmp_length, 12);
4886
4887 if (tmp_length < width)
4888 tmp_length = width;
4889
4890 tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
4891
4892 if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
4893 tmp = tmpbuf;
4894 else
4895 {
4896 size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T));
4897
4898 if (size_overflow_p (tmp_memsize))
4899 /* Overflow, would lead to out of memory. */
4900 goto out_of_memory;
4901 tmp = (DCHAR_T *) malloc (tmp_memsize);
4902 if (tmp == NULL)
4903 /* Out of memory. */
4904 goto out_of_memory;
4905 }
4906
4907 pad_ptr = NULL;
4908 p = tmp;
4909
4910 # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
4911 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
4912 if (type == TYPE_LONGDOUBLE)
4913 # endif
4914 {
4915 long double arg = a.arg[dp->arg_index].a.a_longdouble;
4916
4917 if (isnanl (arg))
4918 {
4919 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
4920 {
4921 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
4922 }
4923 else
4924 {
4925 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
4926 }
4927 }
4928 else
4929 {
4930 int sign = 0;
4931 DECL_LONG_DOUBLE_ROUNDING
4932
4933 BEGIN_LONG_DOUBLE_ROUNDING ();
4934
4935 if (signbit (arg)) /* arg < 0.0L or negative zero */
4936 {
4937 sign = -1;
4938 arg = -arg;
4939 }
4940
4941 if (sign < 0)
4942 *p++ = '-';
4943 else if (flags & FLAG_SHOWSIGN)
4944 *p++ = '+';
4945 else if (flags & FLAG_SPACE)
4946 *p++ = ' ';
4947
4948 if (arg > 0.0L && arg + arg == arg)
4949 {
4950 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
4951 {
4952 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
4953 }
4954 else
4955 {
4956 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
4957 }
4958 }
4959 else
4960 {
4961 # if NEED_PRINTF_LONG_DOUBLE
4962 pad_ptr = p;
4963
4964 if (dp->conversion == 'f' || dp->conversion == 'F')
4965 {
4966 char *digits;
4967 size_t ndigits;
4968
4969 digits =
4970 scale10_round_decimal_long_double (arg, precision);
4971 if (digits == NULL)
4972 {
4973 END_LONG_DOUBLE_ROUNDING ();
4974 goto out_of_memory;
4975 }
4976 ndigits = strlen (digits);
4977
4978 if (ndigits > precision)
4979 do
4980 {
4981 --ndigits;
4982 *p++ = digits[ndigits];
4983 }
4984 while (ndigits > precision);
4985 else
4986 *p++ = '0';
4987 /* Here ndigits <= precision. */
4988 if ((flags & FLAG_ALT) || precision > 0)
4989 {
4990 *p++ = decimal_point_char ();
4991 for (; precision > ndigits; precision--)
4992 *p++ = '0';
4993 while (ndigits > 0)
4994 {
4995 --ndigits;
4996 *p++ = digits[ndigits];
4997 }
4998 }
4999
5000 free (digits);
5001 }
5002 else if (dp->conversion == 'e' || dp->conversion == 'E')
5003 {
5004 int exponent;
5005
5006 if (arg == 0.0L)
5007 {
5008 exponent = 0;
5009 *p++ = '0';
5010 if ((flags & FLAG_ALT) || precision > 0)
5011 {
5012 *p++ = decimal_point_char ();
5013 for (; precision > 0; precision--)
5014 *p++ = '0';
5015 }
5016 }
5017 else
5018 {
5019 /* arg > 0.0L. */
5020 int adjusted;
5021 char *digits;
5022 size_t ndigits;
5023
5024 exponent = floorlog10l (arg);
5025 adjusted = 0;
5026 for (;;)
5027 {
5028 digits =
5029 scale10_round_decimal_long_double (arg,
5030 (int)precision - exponent);
5031 if (digits == NULL)
5032 {
5033 END_LONG_DOUBLE_ROUNDING ();
5034 goto out_of_memory;
5035 }
5036 ndigits = strlen (digits);
5037
5038 if (ndigits == precision + 1)
5039 break;
5040 if (ndigits < precision
5041 || ndigits > precision + 2)
5042 /* The exponent was not guessed
5043 precisely enough. */
5044 abort ();
5045 if (adjusted)
5046 /* None of two values of exponent is
5047 the right one. Prevent an endless
5048 loop. */
5049 abort ();
5050 free (digits);
5051 if (ndigits == precision)
5052 exponent -= 1;
5053 else
5054 exponent += 1;
5055 adjusted = 1;
5056 }
5057 /* Here ndigits = precision+1. */
5058 if (is_borderline (digits, precision))
5059 {
5060 /* Maybe the exponent guess was too high
5061 and a smaller exponent can be reached
5062 by turning a 10...0 into 9...9x. */
5063 char *digits2 =
5064 scale10_round_decimal_long_double (arg,
5065 (int)precision - exponent + 1);
5066 if (digits2 == NULL)
5067 {
5068 free (digits);
5069 END_LONG_DOUBLE_ROUNDING ();
5070 goto out_of_memory;
5071 }
5072 if (strlen (digits2) == precision + 1)
5073 {
5074 free (digits);
5075 digits = digits2;
5076 exponent -= 1;
5077 }
5078 else
5079 free (digits2);
5080 }
5081 /* Here ndigits = precision+1. */
5082
5083 *p++ = digits[--ndigits];
5084 if ((flags & FLAG_ALT) || precision > 0)
5085 {
5086 *p++ = decimal_point_char ();
5087 while (ndigits > 0)
5088 {
5089 --ndigits;
5090 *p++ = digits[ndigits];
5091 }
5092 }
5093
5094 free (digits);
5095 }
5096
5097 *p++ = dp->conversion; /* 'e' or 'E' */
5098 # if WIDE_CHAR_VERSION && DCHAR_IS_TCHAR
5099 {
5100 static const wchar_t decimal_format[] =
5101 { '%', '+', '.', '2', 'd', '\0' };
5102 SNPRINTF (p, 6 + 1, decimal_format, exponent);
5103 }
5104 while (*p != '\0')
5105 p++;
5106 # else
5107 if (sizeof (DCHAR_T) == 1)
5108 {
5109 sprintf ((char *) p, "%+.2d", exponent);
5110 while (*p != '\0')
5111 p++;
5112 }
5113 else
5114 {
5115 char expbuf[6 + 1];
5116 const char *ep;
5117 sprintf (expbuf, "%+.2d", exponent);
5118 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
5119 p++;
5120 }
5121 # endif
5122 }
5123 else if (dp->conversion == 'g' || dp->conversion == 'G')
5124 {
5125 if (precision == 0)
5126 precision = 1;
5127 /* precision >= 1. */
5128
5129 if (arg == 0.0L)
5130 /* The exponent is 0, >= -4, < precision.
5131 Use fixed-point notation. */
5132 {
5133 size_t ndigits = precision;
5134 /* Number of trailing zeroes that have to be
5135 dropped. */
5136 size_t nzeroes =
5137 (flags & FLAG_ALT ? 0 : precision - 1);
5138
5139 --ndigits;
5140 *p++ = '0';
5141 if ((flags & FLAG_ALT) || ndigits > nzeroes)
5142 {
5143 *p++ = decimal_point_char ();
5144 while (ndigits > nzeroes)
5145 {
5146 --ndigits;
5147 *p++ = '0';
5148 }
5149 }
5150 }
5151 else
5152 {
5153 /* arg > 0.0L. */
5154 int exponent;
5155 int adjusted;
5156 char *digits;
5157 size_t ndigits;
5158 size_t nzeroes;
5159
5160 exponent = floorlog10l (arg);
5161 adjusted = 0;
5162 for (;;)
5163 {
5164 digits =
5165 scale10_round_decimal_long_double (arg,
5166 (int)(precision - 1) - exponent);
5167 if (digits == NULL)
5168 {
5169 END_LONG_DOUBLE_ROUNDING ();
5170 goto out_of_memory;
5171 }
5172 ndigits = strlen (digits);
5173
5174 if (ndigits == precision)
5175 break;
5176 if (ndigits < precision - 1
5177 || ndigits > precision + 1)
5178 /* The exponent was not guessed
5179 precisely enough. */
5180 abort ();
5181 if (adjusted)
5182 /* None of two values of exponent is
5183 the right one. Prevent an endless
5184 loop. */
5185 abort ();
5186 free (digits);
5187 if (ndigits < precision)
5188 exponent -= 1;
5189 else
5190 exponent += 1;
5191 adjusted = 1;
5192 }
5193 /* Here ndigits = precision. */
5194 if (is_borderline (digits, precision - 1))
5195 {
5196 /* Maybe the exponent guess was too high
5197 and a smaller exponent can be reached
5198 by turning a 10...0 into 9...9x. */
5199 char *digits2 =
5200 scale10_round_decimal_long_double (arg,
5201 (int)(precision - 1) - exponent + 1);
5202 if (digits2 == NULL)
5203 {
5204 free (digits);
5205 END_LONG_DOUBLE_ROUNDING ();
5206 goto out_of_memory;
5207 }
5208 if (strlen (digits2) == precision)
5209 {
5210 free (digits);
5211 digits = digits2;
5212 exponent -= 1;
5213 }
5214 else
5215 free (digits2);
5216 }
5217 /* Here ndigits = precision. */
5218
5219 /* Determine the number of trailing zeroes
5220 that have to be dropped. */
5221 nzeroes = 0;
5222 if ((flags & FLAG_ALT) == 0)
5223 while (nzeroes < ndigits
5224 && digits[nzeroes] == '0')
5225 nzeroes++;
5226
5227 /* The exponent is now determined. */
5228 if (exponent >= -4
5229 && exponent < (long)precision)
5230 {
5231 /* Fixed-point notation:
5232 max(exponent,0)+1 digits, then the
5233 decimal point, then the remaining
5234 digits without trailing zeroes. */
5235 if (exponent >= 0)
5236 {
5237 size_t ecount = exponent + 1;
5238 /* Note: count <= precision = ndigits. */
5239 for (; ecount > 0; ecount--)
5240 *p++ = digits[--ndigits];
5241 if ((flags & FLAG_ALT) || ndigits > nzeroes)
5242 {
5243 *p++ = decimal_point_char ();
5244 while (ndigits > nzeroes)
5245 {
5246 --ndigits;
5247 *p++ = digits[ndigits];
5248 }
5249 }
5250 }
5251 else
5252 {
5253 size_t ecount = -exponent - 1;
5254 *p++ = '0';
5255 *p++ = decimal_point_char ();
5256 for (; ecount > 0; ecount--)
5257 *p++ = '0';
5258 while (ndigits > nzeroes)
5259 {
5260 --ndigits;
5261 *p++ = digits[ndigits];
5262 }
5263 }
5264 }
5265 else
5266 {
5267 /* Exponential notation. */
5268 *p++ = digits[--ndigits];
5269 if ((flags & FLAG_ALT) || ndigits > nzeroes)
5270 {
5271 *p++ = decimal_point_char ();
5272 while (ndigits > nzeroes)
5273 {
5274 --ndigits;
5275 *p++ = digits[ndigits];
5276 }
5277 }
5278 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
5279 # if WIDE_CHAR_VERSION && DCHAR_IS_TCHAR
5280 {
5281 static const wchar_t decimal_format[] =
5282 { '%', '+', '.', '2', 'd', '\0' };
5283 SNPRINTF (p, 6 + 1, decimal_format, exponent);
5284 }
5285 while (*p != '\0')
5286 p++;
5287 # else
5288 if (sizeof (DCHAR_T) == 1)
5289 {
5290 sprintf ((char *) p, "%+.2d", exponent);
5291 while (*p != '\0')
5292 p++;
5293 }
5294 else
5295 {
5296 char expbuf[6 + 1];
5297 const char *ep;
5298 sprintf (expbuf, "%+.2d", exponent);
5299 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
5300 p++;
5301 }
5302 # endif
5303 }
5304
5305 free (digits);
5306 }
5307 }
5308 else
5309 abort ();
5310 # else
5311 /* arg is finite. */
5312 if (!(arg == 0.0L))
5313 abort ();
5314
5315 pad_ptr = p;
5316
5317 if (dp->conversion == 'f' || dp->conversion == 'F')
5318 {
5319 *p++ = '0';
5320 if ((flags & FLAG_ALT) || precision > 0)
5321 {
5322 *p++ = decimal_point_char ();
5323 for (; precision > 0; precision--)
5324 *p++ = '0';
5325 }
5326 }
5327 else if (dp->conversion == 'e' || dp->conversion == 'E')
5328 {
5329 *p++ = '0';
5330 if ((flags & FLAG_ALT) || precision > 0)
5331 {
5332 *p++ = decimal_point_char ();
5333 for (; precision > 0; precision--)
5334 *p++ = '0';
5335 }
5336 *p++ = dp->conversion; /* 'e' or 'E' */
5337 *p++ = '+';
5338 *p++ = '0';
5339 *p++ = '0';
5340 }
5341 else if (dp->conversion == 'g' || dp->conversion == 'G')
5342 {
5343 *p++ = '0';
5344 if (flags & FLAG_ALT)
5345 {
5346 size_t ndigits =
5347 (precision > 0 ? precision - 1 : 0);
5348 *p++ = decimal_point_char ();
5349 for (; ndigits > 0; --ndigits)
5350 *p++ = '0';
5351 }
5352 }
5353 else if (dp->conversion == 'a' || dp->conversion == 'A')
5354 {
5355 *p++ = '0';
5356 *p++ = dp->conversion - 'A' + 'X';
5357 pad_ptr = p;
5358 *p++ = '0';
5359 if ((flags & FLAG_ALT) || precision > 0)
5360 {
5361 *p++ = decimal_point_char ();
5362 for (; precision > 0; precision--)
5363 *p++ = '0';
5364 }
5365 *p++ = dp->conversion - 'A' + 'P';
5366 *p++ = '+';
5367 *p++ = '0';
5368 }
5369 else
5370 abort ();
5371 # endif
5372 }
5373
5374 END_LONG_DOUBLE_ROUNDING ();
5375 }
5376 }
5377 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
5378 else
5379 # endif
5380 # endif
5381 # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
5382 {
5383 double arg = a.arg[dp->arg_index].a.a_double;
5384
5385 if (isnand (arg))
5386 {
5387 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
5388 {
5389 *p++ = 'N'; *p++ = 'A'; *p++ = 'N';
5390 }
5391 else
5392 {
5393 *p++ = 'n'; *p++ = 'a'; *p++ = 'n';
5394 }
5395 }
5396 else
5397 {
5398 int sign = 0;
5399
5400 if (signbit (arg)) /* arg < 0.0 or negative zero */
5401 {
5402 sign = -1;
5403 arg = -arg;
5404 }
5405
5406 if (sign < 0)
5407 *p++ = '-';
5408 else if (flags & FLAG_SHOWSIGN)
5409 *p++ = '+';
5410 else if (flags & FLAG_SPACE)
5411 *p++ = ' ';
5412
5413 if (arg > 0.0 && arg + arg == arg)
5414 {
5415 if (dp->conversion >= 'A' && dp->conversion <= 'Z')
5416 {
5417 *p++ = 'I'; *p++ = 'N'; *p++ = 'F';
5418 }
5419 else
5420 {
5421 *p++ = 'i'; *p++ = 'n'; *p++ = 'f';
5422 }
5423 }
5424 else
5425 {
5426 # if NEED_PRINTF_DOUBLE
5427 pad_ptr = p;
5428
5429 if (dp->conversion == 'f' || dp->conversion == 'F')
5430 {
5431 char *digits;
5432 size_t ndigits;
5433
5434 digits =
5435 scale10_round_decimal_double (arg, precision);
5436 if (digits == NULL)
5437 goto out_of_memory;
5438 ndigits = strlen (digits);
5439
5440 if (ndigits > precision)
5441 do
5442 {
5443 --ndigits;
5444 *p++ = digits[ndigits];
5445 }
5446 while (ndigits > precision);
5447 else
5448 *p++ = '0';
5449 /* Here ndigits <= precision. */
5450 if ((flags & FLAG_ALT) || precision > 0)
5451 {
5452 *p++ = decimal_point_char ();
5453 for (; precision > ndigits; precision--)
5454 *p++ = '0';
5455 while (ndigits > 0)
5456 {
5457 --ndigits;
5458 *p++ = digits[ndigits];
5459 }
5460 }
5461
5462 free (digits);
5463 }
5464 else if (dp->conversion == 'e' || dp->conversion == 'E')
5465 {
5466 int exponent;
5467
5468 if (arg == 0.0)
5469 {
5470 exponent = 0;
5471 *p++ = '0';
5472 if ((flags & FLAG_ALT) || precision > 0)
5473 {
5474 *p++ = decimal_point_char ();
5475 for (; precision > 0; precision--)
5476 *p++ = '0';
5477 }
5478 }
5479 else
5480 {
5481 /* arg > 0.0. */
5482 int adjusted;
5483 char *digits;
5484 size_t ndigits;
5485
5486 exponent = floorlog10 (arg);
5487 adjusted = 0;
5488 for (;;)
5489 {
5490 digits =
5491 scale10_round_decimal_double (arg,
5492 (int)precision - exponent);
5493 if (digits == NULL)
5494 goto out_of_memory;
5495 ndigits = strlen (digits);
5496
5497 if (ndigits == precision + 1)
5498 break;
5499 if (ndigits < precision
5500 || ndigits > precision + 2)
5501 /* The exponent was not guessed
5502 precisely enough. */
5503 abort ();
5504 if (adjusted)
5505 /* None of two values of exponent is
5506 the right one. Prevent an endless
5507 loop. */
5508 abort ();
5509 free (digits);
5510 if (ndigits == precision)
5511 exponent -= 1;
5512 else
5513 exponent += 1;
5514 adjusted = 1;
5515 }
5516 /* Here ndigits = precision+1. */
5517 if (is_borderline (digits, precision))
5518 {
5519 /* Maybe the exponent guess was too high
5520 and a smaller exponent can be reached
5521 by turning a 10...0 into 9...9x. */
5522 char *digits2 =
5523 scale10_round_decimal_double (arg,
5524 (int)precision - exponent + 1);
5525 if (digits2 == NULL)
5526 {
5527 free (digits);
5528 goto out_of_memory;
5529 }
5530 if (strlen (digits2) == precision + 1)
5531 {
5532 free (digits);
5533 digits = digits2;
5534 exponent -= 1;
5535 }
5536 else
5537 free (digits2);
5538 }
5539 /* Here ndigits = precision+1. */
5540
5541 *p++ = digits[--ndigits];
5542 if ((flags & FLAG_ALT) || precision > 0)
5543 {
5544 *p++ = decimal_point_char ();
5545 while (ndigits > 0)
5546 {
5547 --ndigits;
5548 *p++ = digits[ndigits];
5549 }
5550 }
5551
5552 free (digits);
5553 }
5554
5555 *p++ = dp->conversion; /* 'e' or 'E' */
5556 # if WIDE_CHAR_VERSION && DCHAR_IS_TCHAR
5557 {
5558 static const wchar_t decimal_format[] =
5559 /* Produce the same number of exponent digits
5560 as the native printf implementation. */
5561 # if defined _WIN32 && ! defined __CYGWIN__
5562 { '%', '+', '.', '3', 'd', '\0' };
5563 # else
5564 { '%', '+', '.', '2', 'd', '\0' };
5565 # endif
5566 SNPRINTF (p, 6 + 1, decimal_format, exponent);
5567 }
5568 while (*p != '\0')
5569 p++;
5570 # else
5571 {
5572 static const char decimal_format[] =
5573 /* Produce the same number of exponent digits
5574 as the native printf implementation. */
5575 # if defined _WIN32 && ! defined __CYGWIN__
5576 "%+.3d";
5577 # else
5578 "%+.2d";
5579 # endif
5580 if (sizeof (DCHAR_T) == 1)
5581 {
5582 sprintf ((char *) p, decimal_format, exponent);
5583 while (*p != '\0')
5584 p++;
5585 }
5586 else
5587 {
5588 char expbuf[6 + 1];
5589 const char *ep;
5590 sprintf (expbuf, decimal_format, exponent);
5591 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
5592 p++;
5593 }
5594 }
5595 # endif
5596 }
5597 else if (dp->conversion == 'g' || dp->conversion == 'G')
5598 {
5599 if (precision == 0)
5600 precision = 1;
5601 /* precision >= 1. */
5602
5603 if (arg == 0.0)
5604 /* The exponent is 0, >= -4, < precision.
5605 Use fixed-point notation. */
5606 {
5607 size_t ndigits = precision;
5608 /* Number of trailing zeroes that have to be
5609 dropped. */
5610 size_t nzeroes =
5611 (flags & FLAG_ALT ? 0 : precision - 1);
5612
5613 --ndigits;
5614 *p++ = '0';
5615 if ((flags & FLAG_ALT) || ndigits > nzeroes)
5616 {
5617 *p++ = decimal_point_char ();
5618 while (ndigits > nzeroes)
5619 {
5620 --ndigits;
5621 *p++ = '0';
5622 }
5623 }
5624 }
5625 else
5626 {
5627 /* arg > 0.0. */
5628 int exponent;
5629 int adjusted;
5630 char *digits;
5631 size_t ndigits;
5632 size_t nzeroes;
5633
5634 exponent = floorlog10 (arg);
5635 adjusted = 0;
5636 for (;;)
5637 {
5638 digits =
5639 scale10_round_decimal_double (arg,
5640 (int)(precision - 1) - exponent);
5641 if (digits == NULL)
5642 goto out_of_memory;
5643 ndigits = strlen (digits);
5644
5645 if (ndigits == precision)
5646 break;
5647 if (ndigits < precision - 1
5648 || ndigits > precision + 1)
5649 /* The exponent was not guessed
5650 precisely enough. */
5651 abort ();
5652 if (adjusted)
5653 /* None of two values of exponent is
5654 the right one. Prevent an endless
5655 loop. */
5656 abort ();
5657 free (digits);
5658 if (ndigits < precision)
5659 exponent -= 1;
5660 else
5661 exponent += 1;
5662 adjusted = 1;
5663 }
5664 /* Here ndigits = precision. */
5665 if (is_borderline (digits, precision - 1))
5666 {
5667 /* Maybe the exponent guess was too high
5668 and a smaller exponent can be reached
5669 by turning a 10...0 into 9...9x. */
5670 char *digits2 =
5671 scale10_round_decimal_double (arg,
5672 (int)(precision - 1) - exponent + 1);
5673 if (digits2 == NULL)
5674 {
5675 free (digits);
5676 goto out_of_memory;
5677 }
5678 if (strlen (digits2) == precision)
5679 {
5680 free (digits);
5681 digits = digits2;
5682 exponent -= 1;
5683 }
5684 else
5685 free (digits2);
5686 }
5687 /* Here ndigits = precision. */
5688
5689 /* Determine the number of trailing zeroes
5690 that have to be dropped. */
5691 nzeroes = 0;
5692 if ((flags & FLAG_ALT) == 0)
5693 while (nzeroes < ndigits
5694 && digits[nzeroes] == '0')
5695 nzeroes++;
5696
5697 /* The exponent is now determined. */
5698 if (exponent >= -4
5699 && exponent < (long)precision)
5700 {
5701 /* Fixed-point notation:
5702 max(exponent,0)+1 digits, then the
5703 decimal point, then the remaining
5704 digits without trailing zeroes. */
5705 if (exponent >= 0)
5706 {
5707 size_t ecount = exponent + 1;
5708 /* Note: ecount <= precision = ndigits. */
5709 for (; ecount > 0; ecount--)
5710 *p++ = digits[--ndigits];
5711 if ((flags & FLAG_ALT) || ndigits > nzeroes)
5712 {
5713 *p++ = decimal_point_char ();
5714 while (ndigits > nzeroes)
5715 {
5716 --ndigits;
5717 *p++ = digits[ndigits];
5718 }
5719 }
5720 }
5721 else
5722 {
5723 size_t ecount = -exponent - 1;
5724 *p++ = '0';
5725 *p++ = decimal_point_char ();
5726 for (; ecount > 0; ecount--)
5727 *p++ = '0';
5728 while (ndigits > nzeroes)
5729 {
5730 --ndigits;
5731 *p++ = digits[ndigits];
5732 }
5733 }
5734 }
5735 else
5736 {
5737 /* Exponential notation. */
5738 *p++ = digits[--ndigits];
5739 if ((flags & FLAG_ALT) || ndigits > nzeroes)
5740 {
5741 *p++ = decimal_point_char ();
5742 while (ndigits > nzeroes)
5743 {
5744 --ndigits;
5745 *p++ = digits[ndigits];
5746 }
5747 }
5748 *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */
5749 # if WIDE_CHAR_VERSION && DCHAR_IS_TCHAR
5750 {
5751 static const wchar_t decimal_format[] =
5752 /* Produce the same number of exponent digits
5753 as the native printf implementation. */
5754 # if defined _WIN32 && ! defined __CYGWIN__
5755 { '%', '+', '.', '3', 'd', '\0' };
5756 # else
5757 { '%', '+', '.', '2', 'd', '\0' };
5758 # endif
5759 SNPRINTF (p, 6 + 1, decimal_format, exponent);
5760 }
5761 while (*p != '\0')
5762 p++;
5763 # else
5764 {
5765 static const char decimal_format[] =
5766 /* Produce the same number of exponent digits
5767 as the native printf implementation. */
5768 # if defined _WIN32 && ! defined __CYGWIN__
5769 "%+.3d";
5770 # else
5771 "%+.2d";
5772 # endif
5773 if (sizeof (DCHAR_T) == 1)
5774 {
5775 sprintf ((char *) p, decimal_format, exponent);
5776 while (*p != '\0')
5777 p++;
5778 }
5779 else
5780 {
5781 char expbuf[6 + 1];
5782 const char *ep;
5783 sprintf (expbuf, decimal_format, exponent);
5784 for (ep = expbuf; (*p = *ep) != '\0'; ep++)
5785 p++;
5786 }
5787 }
5788 # endif
5789 }
5790
5791 free (digits);
5792 }
5793 }
5794 else
5795 abort ();
5796 # else
5797 /* arg is finite. */
5798 if (!(arg == 0.0))
5799 abort ();
5800
5801 pad_ptr = p;
5802
5803 if (dp->conversion == 'f' || dp->conversion == 'F')
5804 {
5805 *p++ = '0';
5806 if ((flags & FLAG_ALT) || precision > 0)
5807 {
5808 *p++ = decimal_point_char ();
5809 for (; precision > 0; precision--)
5810 *p++ = '0';
5811 }
5812 }
5813 else if (dp->conversion == 'e' || dp->conversion == 'E')
5814 {
5815 *p++ = '0';
5816 if ((flags & FLAG_ALT) || precision > 0)
5817 {
5818 *p++ = decimal_point_char ();
5819 for (; precision > 0; precision--)
5820 *p++ = '0';
5821 }
5822 *p++ = dp->conversion; /* 'e' or 'E' */
5823 *p++ = '+';
5824 /* Produce the same number of exponent digits as
5825 the native printf implementation. */
5826 # if defined _WIN32 && ! defined __CYGWIN__
5827 *p++ = '0';
5828 # endif
5829 *p++ = '0';
5830 *p++ = '0';
5831 }
5832 else if (dp->conversion == 'g' || dp->conversion == 'G')
5833 {
5834 *p++ = '0';
5835 if (flags & FLAG_ALT)
5836 {
5837 size_t ndigits =
5838 (precision > 0 ? precision - 1 : 0);
5839 *p++ = decimal_point_char ();
5840 for (; ndigits > 0; --ndigits)
5841 *p++ = '0';
5842 }
5843 }
5844 else
5845 abort ();
5846 # endif
5847 }
5848 }
5849 }
5850 # endif
5851
5852 /* The generated string now extends from tmp to p, with the
5853 zero padding insertion point being at pad_ptr. */
5854 count = p - tmp;
5855
5856 if (count < width)
5857 {
5858 size_t pad = width - count;
5859 DCHAR_T *end = p + pad;
5860
5861 if (flags & FLAG_LEFT)
5862 {
5863 /* Pad with spaces on the right. */
5864 for (; pad > 0; pad--)
5865 *p++ = ' ';
5866 }
5867 else if ((flags & FLAG_ZERO) && pad_ptr != NULL)
5868 {
5869 /* Pad with zeroes. */
5870 DCHAR_T *q = end;
5871
5872 while (p > pad_ptr)
5873 *--q = *--p;
5874 for (; pad > 0; pad--)
5875 *p++ = '0';
5876 }
5877 else
5878 {
5879 /* Pad with spaces on the left. */
5880 DCHAR_T *q = end;
5881
5882 while (p > tmp)
5883 *--q = *--p;
5884 for (; pad > 0; pad--)
5885 *p++ = ' ';
5886 }
5887
5888 p = end;
5889 }
5890
5891 count = p - tmp;
5892
5893 if (count >= tmp_length)
5894 /* tmp_length was incorrectly calculated - fix the
5895 code above! */
5896 abort ();
5897
5898 /* Make room for the result. */
5899 if (count >= allocated - length)
5900 {
5901 size_t n = xsum (length, count);
5902
5903 ENSURE_ALLOCATION_ELSE (n,
5904 { if (tmp != tmpbuf) free (tmp); goto out_of_memory; });
5905 }
5906
5907 /* Append the result. */
5908 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
5909 if (tmp != tmpbuf)
5910 free (tmp);
5911 length += count;
5912 }
5913 #endif
5914 else
5915 {
5916 arg_type type = a.arg[dp->arg_index].type;
5917 int flags = dp->flags;
5918 #if (WIDE_CHAR_VERSION && MUSL_LIBC) || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_FLAG_ALT_PRECISION_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5919 int has_width;
5920 #endif
5921 #if !USE_SNPRINTF || WIDE_CHAR_VERSION || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_FLAG_ALT_PRECISION_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5922 size_t width;
5923 #endif
5924 #if !USE_SNPRINTF || (WIDE_CHAR_VERSION && DCHAR_IS_TCHAR) || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || (WIDE_CHAR_VERSION && MUSL_LIBC) || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_FLAG_ALT_PRECISION_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5925 int has_precision;
5926 size_t precision;
5927 #endif
5928 #if NEED_PRINTF_FLAG_ALT_PRECISION_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5929 int prec_ourselves;
5930 #else
5931 # define prec_ourselves 0
5932 #endif
5933 #if (WIDE_CHAR_VERSION && MUSL_LIBC) || NEED_PRINTF_FLAG_LEFTADJUST
5934 # define pad_ourselves 1
5935 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_FLAG_ALT_PRECISION_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5936 int pad_ourselves;
5937 #else
5938 # define pad_ourselves 0
5939 #endif
5940 TCHAR_T *fbp;
5941 unsigned int prefix_count;
5942 int prefixes[2] IF_LINT (= { 0 });
5943 int orig_errno;
5944 #if !USE_SNPRINTF
5945 size_t tmp_length;
5946 TCHAR_T tmpbuf[700];
5947 TCHAR_T *tmp;
5948 #endif
5949
5950 #if (WIDE_CHAR_VERSION && MUSL_LIBC) || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_FLAG_ALT_PRECISION_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5951 has_width = 0;
5952 #endif
5953 #if !USE_SNPRINTF || WIDE_CHAR_VERSION || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_FLAG_ALT_PRECISION_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5954 width = 0;
5955 if (dp->width_start != dp->width_end)
5956 {
5957 if (dp->width_arg_index != ARG_NONE)
5958 {
5959 int arg;
5960
5961 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
5962 abort ();
5963 arg = a.arg[dp->width_arg_index].a.a_int;
5964 width = arg;
5965 if (arg < 0)
5966 {
5967 /* "A negative field width is taken as a '-' flag
5968 followed by a positive field width." */
5969 flags |= FLAG_LEFT;
5970 width = -width;
5971 }
5972 }
5973 else
5974 {
5975 const FCHAR_T *digitp = dp->width_start;
5976
5977 do
5978 width = xsum (xtimes (width, 10), *digitp++ - '0');
5979 while (digitp != dp->width_end);
5980 }
5981 if (width > (size_t) INT_MAX)
5982 goto overflow;
5983 # define WIDTH_IS_CHECKED 1
5984 # if (WIDE_CHAR_VERSION && MUSL_LIBC) || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_FLAG_ALT_PRECISION_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5985 has_width = 1;
5986 # endif
5987 }
5988 #endif
5989
5990 #if !USE_SNPRINTF || (WIDE_CHAR_VERSION && DCHAR_IS_TCHAR) || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || (WIDE_CHAR_VERSION && MUSL_LIBC) || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_FLAG_ALT_PRECISION_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
5991 has_precision = 0;
5992 precision = 6;
5993 if (dp->precision_start != dp->precision_end)
5994 {
5995 if (dp->precision_arg_index != ARG_NONE)
5996 {
5997 int arg;
5998
5999 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
6000 abort ();
6001 arg = a.arg[dp->precision_arg_index].a.a_int;
6002 /* "A negative precision is taken as if the precision
6003 were omitted." */
6004 if (arg >= 0)
6005 {
6006 precision = arg;
6007 has_precision = 1;
6008 }
6009 }
6010 else
6011 {
6012 const FCHAR_T *digitp = dp->precision_start + 1;
6013
6014 precision = 0;
6015 while (digitp != dp->precision_end)
6016 precision = xsum (xtimes (precision, 10), *digitp++ - '0');
6017 has_precision = 1;
6018 }
6019 }
6020 #endif
6021
6022 /* Decide whether to handle the precision ourselves. */
6023 #if NEED_PRINTF_FLAG_ALT_PRECISION_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
6024 switch (dp->conversion)
6025 {
6026 # if NEED_PRINTF_UNBOUNDED_PRECISION
6027 case 'd': case 'i': case 'u':
6028 case 'b':
6029 #if SUPPORT_GNU_PRINTF_DIRECTIVES \
6030 || (__GLIBC__ + (__GLIBC_MINOR__ >= 35) > 2)
6031 case 'B':
6032 #endif
6033 case 'o':
6034 prec_ourselves = has_precision && (precision > 0);
6035 break;
6036 # endif
6037 case 'x': case 'X': case 'p':
6038 prec_ourselves =
6039 has_precision
6040 && (0
6041 # if NEED_PRINTF_FLAG_ALT_PRECISION_ZERO
6042 || (precision == 0)
6043 # endif
6044 # if NEED_PRINTF_UNBOUNDED_PRECISION
6045 || (precision > 0)
6046 # endif
6047 );
6048 break;
6049 default:
6050 prec_ourselves = 0;
6051 break;
6052 }
6053 #endif
6054
6055 /* Decide whether to perform the padding ourselves. */
6056 #if !((WIDE_CHAR_VERSION && MUSL_LIBC) || NEED_PRINTF_FLAG_LEFTADJUST) && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_FLAG_ALT_PRECISION_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION)
6057 switch (dp->conversion)
6058 {
6059 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
6060 /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need
6061 to perform the padding after this conversion. Functions
6062 with unistdio extensions perform the padding based on
6063 character count rather than element count. */
6064 case 'c': case 's':
6065 # endif
6066 # if NEED_PRINTF_FLAG_ZERO
6067 case 'f': case 'F': case 'e': case 'E': case 'g': case 'G':
6068 case 'a': case 'A':
6069 # endif
6070 pad_ourselves = 1;
6071 break;
6072 default:
6073 pad_ourselves = prec_ourselves;
6074 break;
6075 }
6076 #endif
6077
6078 #if !USE_SNPRINTF
6079 /* Allocate a temporary buffer of sufficient size for calling
6080 sprintf. */
6081 tmp_length =
6082 MAX_ROOM_NEEDED (&a, dp->arg_index, dp->conversion, type,
6083 flags, width, has_precision, precision,
6084 pad_ourselves);
6085
6086 if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T))
6087 tmp = tmpbuf;
6088 else
6089 {
6090 size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T));
6091
6092 if (size_overflow_p (tmp_memsize))
6093 /* Overflow, would lead to out of memory. */
6094 goto out_of_memory;
6095 tmp = (TCHAR_T *) malloc (tmp_memsize);
6096 if (tmp == NULL)
6097 /* Out of memory. */
6098 goto out_of_memory;
6099 }
6100 #endif
6101
6102 /* Construct the format string for calling snprintf or
6103 sprintf. */
6104 fbp = buf;
6105 *fbp++ = '%';
6106 #if NEED_PRINTF_FLAG_GROUPING
6107 /* The underlying implementation doesn't support the ' flag.
6108 Produce no grouping characters in this case; this is
6109 acceptable because the grouping is locale dependent. */
6110 #else
6111 if (flags & FLAG_GROUP)
6112 *fbp++ = '\'';
6113 #endif
6114 if (flags & FLAG_LEFT)
6115 *fbp++ = '-';
6116 if (flags & FLAG_SHOWSIGN)
6117 *fbp++ = '+';
6118 if (flags & FLAG_SPACE)
6119 *fbp++ = ' ';
6120 if (flags & FLAG_ALT)
6121 *fbp++ = '#';
6122 #if __GLIBC__ >= 2 && !defined __UCLIBC__
6123 if (flags & FLAG_LOCALIZED)
6124 *fbp++ = 'I';
6125 #endif
6126 if (!pad_ourselves)
6127 {
6128 if (flags & FLAG_ZERO)
6129 *fbp++ = '0';
6130 if (dp->width_start != dp->width_end)
6131 {
6132 size_t n = dp->width_end - dp->width_start;
6133 #if !WIDTH_IS_CHECKED
6134 size_t width;
6135 /* Reject an out-of-range width.
6136 The underlying SNPRINTF already does this on some
6137 platforms (glibc, musl, macOS, FreeBSD, NetBSD,
6138 OpenBSD, Cygwin, Solaris, MSVC). However, on others
6139 (AIX, mingw), it doesn't; thus this vasnprintf
6140 invocation would succeed and produce a wrong result.
6141 So, this is redundant on some platforms, but it's a
6142 quick check anyway. */
6143 if (dp->width_arg_index != ARG_NONE)
6144 {
6145 int arg;
6146
6147 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
6148 abort ();
6149 arg = a.arg[dp->width_arg_index].a.a_int;
6150 width = arg;
6151 if (arg < 0)
6152 {
6153 /* "A negative field width is taken as a '-' flag
6154 followed by a positive field width." */
6155 width = -width;
6156 }
6157 }
6158 else
6159 {
6160 const FCHAR_T *digitp = dp->width_start;
6161
6162 width = 0;
6163 do
6164 width = xsum (xtimes (width, 10), *digitp++ - '0');
6165 while (digitp != dp->width_end);
6166 }
6167 if (width > (size_t) INT_MAX)
6168 goto overflow;
6169 #endif
6170 /* The width specification is known to consist only
6171 of standard ASCII characters. */
6172 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
6173 {
6174 memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T));
6175 fbp += n;
6176 }
6177 else
6178 {
6179 const FCHAR_T *mp = dp->width_start;
6180 do
6181 *fbp++ = *mp++;
6182 while (--n > 0);
6183 }
6184 }
6185 }
6186 if (!prec_ourselves)
6187 {
6188 if (dp->precision_start != dp->precision_end)
6189 {
6190 size_t n = dp->precision_end - dp->precision_start;
6191 /* The precision specification is known to consist only
6192 of standard ASCII characters. */
6193 if (sizeof (FCHAR_T) == sizeof (TCHAR_T))
6194 {
6195 memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T));
6196 fbp += n;
6197 }
6198 else
6199 {
6200 const FCHAR_T *mp = dp->precision_start;
6201 do
6202 *fbp++ = *mp++;
6203 while (--n > 0);
6204 }
6205 }
6206 }
6207
6208 switch (type)
6209 {
6210 case TYPE_LONGLONGINT:
6211 case TYPE_ULONGLONGINT:
6212 #if INT8_WIDTH > LONG_WIDTH
6213 case TYPE_INT8_T:
6214 #endif
6215 #if UINT8_WIDTH > LONG_WIDTH
6216 case TYPE_UINT8_T:
6217 #endif
6218 #if INT16_WIDTH > LONG_WIDTH
6219 case TYPE_INT16_T:
6220 #endif
6221 #if UINT16_WIDTH > LONG_WIDTH
6222 case TYPE_UINT16_T:
6223 #endif
6224 #if INT32_WIDTH > LONG_WIDTH
6225 case TYPE_INT32_T:
6226 #endif
6227 #if UINT32_WIDTH > LONG_WIDTH
6228 case TYPE_UINT32_T:
6229 #endif
6230 #if INT64_WIDTH > LONG_WIDTH
6231 case TYPE_INT64_T:
6232 #endif
6233 #if UINT64_WIDTH > LONG_WIDTH
6234 case TYPE_UINT64_T:
6235 #endif
6236 #if INT_FAST8_WIDTH > LONG_WIDTH
6237 case TYPE_INT_FAST8_T:
6238 #endif
6239 #if UINT_FAST8_WIDTH > LONG_WIDTH
6240 case TYPE_UINT_FAST8_T:
6241 #endif
6242 #if INT_FAST16_WIDTH > LONG_WIDTH
6243 case TYPE_INT_FAST16_T:
6244 #endif
6245 #if UINT_FAST16_WIDTH > LONG_WIDTH
6246 case TYPE_UINT_FAST16_T:
6247 #endif
6248 #if INT_FAST32_WIDTH > LONG_WIDTH
6249 case TYPE_INT3_FAST2_T:
6250 #endif
6251 #if UINT_FAST32_WIDTH > LONG_WIDTH
6252 case TYPE_UINT_FAST32_T:
6253 #endif
6254 #if INT_FAST64_WIDTH > LONG_WIDTH
6255 case TYPE_INT_FAST64_T:
6256 #endif
6257 #if UINT_FAST64_WIDTH > LONG_WIDTH
6258 case TYPE_UINT_FAST64_T:
6259 #endif
6260 #if defined _WIN32 && ! defined __CYGWIN__
6261 *fbp++ = 'I';
6262 *fbp++ = '6';
6263 *fbp++ = '4';
6264 break;
6265 #else
6266 *fbp++ = 'l';
6267 #endif
6268 FALLTHROUGH;
6269 case TYPE_LONGINT:
6270 case TYPE_ULONGINT:
6271 #if INT8_WIDTH > INT_WIDTH && INT8_WIDTH <= LONG_WIDTH
6272 case TYPE_INT8_T:
6273 #endif
6274 #if UINT8_WIDTH > INT_WIDTH && UINT8_WIDTH <= LONG_WIDTH
6275 case TYPE_UINT8_T:
6276 #endif
6277 #if INT16_WIDTH > INT_WIDTH && INT16_WIDTH <= LONG_WIDTH
6278 case TYPE_INT16_T:
6279 #endif
6280 #if UINT16_WIDTH > INT_WIDTH && UINT16_WIDTH <= LONG_WIDTH
6281 case TYPE_UINT16_T:
6282 #endif
6283 #if INT32_WIDTH > INT_WIDTH && INT32_WIDTH <= LONG_WIDTH
6284 case TYPE_INT32_T:
6285 #endif
6286 #if UINT32_WIDTH > INT_WIDTH && UINT32_WIDTH <= LONG_WIDTH
6287 case TYPE_UINT32_T:
6288 #endif
6289 #if INT64_WIDTH > INT_WIDTH && INT64_WIDTH <= LONG_WIDTH
6290 case TYPE_INT64_T:
6291 #endif
6292 #if UINT64_WIDTH > INT_WIDTH && UINT64_WIDTH <= LONG_WIDTH
6293 case TYPE_UINT64_T:
6294 #endif
6295 #if INT_FAST8_WIDTH > INT_WIDTH && INT_FAST8_WIDTH <= LONG_WIDTH
6296 case TYPE_INT_FAST8_T:
6297 #endif
6298 #if UINT_FAST8_WIDTH > INT_WIDTH && UINT_FAST8_WIDTH <= LONG_WIDTH
6299 case TYPE_UINT_FAST8_T:
6300 #endif
6301 #if INT_FAST16_WIDTH > INT_WIDTH && INT_FAST16_WIDTH <= LONG_WIDTH
6302 case TYPE_INT_FAST16_T:
6303 #endif
6304 #if UINT_FAST16_WIDTH > INT_WIDTH && UINT_FAST16_WIDTH <= LONG_WIDTH
6305 case TYPE_UINT_FAST16_T:
6306 #endif
6307 #if INT_FAST32_WIDTH > INT_WIDTH && INT_FAST32_WIDTH <= LONG_WIDTH
6308 case TYPE_INT_FAST32_T:
6309 #endif
6310 #if UINT_FAST32_WIDTH > INT_WIDTH && UINT_FAST32_WIDTH <= LONG_WIDTH
6311 case TYPE_UINT_FAST32_T:
6312 #endif
6313 #if INT_FAST64_WIDTH > INT_WIDTH && INT_FAST64_WIDTH <= LONG_WIDTH
6314 case TYPE_INT_FAST64_T:
6315 #endif
6316 #if UINT_FAST64_WIDTH > INT_WIDTH && UINT_FAST64_WIDTH <= LONG_WIDTH
6317 case TYPE_UINT_FAST64_T:
6318 #endif
6319 #if HAVE_WINT_T
6320 case TYPE_WIDE_CHAR:
6321 #endif
6322 case TYPE_WIDE_STRING:
6323 *fbp++ = 'l';
6324 break;
6325 case TYPE_LONGDOUBLE:
6326 *fbp++ = 'L';
6327 break;
6328 default:
6329 break;
6330 }
6331 #if NEED_PRINTF_DIRECTIVE_F
6332 if (dp->conversion == 'F')
6333 *fbp = 'f';
6334 else
6335 #endif
6336 *fbp = dp->conversion;
6337 #if USE_SNPRINTF
6338 /* Decide whether to pass %n in the format string
6339 to SNPRINTF. */
6340 # if (((!WIDE_CHAR_VERSION || !DCHAR_IS_TCHAR) \
6341 && (HAVE_SNPRINTF_RETVAL_C99 && HAVE_SNPRINTF_TRUNCATION_C99)) \
6342 || ((__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) \
6343 && !defined __UCLIBC__) \
6344 || (defined __APPLE__ && defined __MACH__) \
6345 || defined __OpenBSD__ \
6346 || defined __ANDROID__ \
6347 || (defined _WIN32 && ! defined __CYGWIN__)) \
6348 || (WIDE_CHAR_VERSION && MUSL_LIBC)
6349 /* We can avoid passing %n and instead rely on SNPRINTF's
6350 return value if
6351 - !WIDE_CHAR_VERSION || !DCHAR_IS_TCHAR, because otherwise,
6352 when WIDE_CHAR_VERSION && DCHAR_IS_TCHAR,
6353 snwprintf()/_snwprintf() (Windows) and swprintf() (Unix)
6354 don't return the needed buffer size,
6355 and
6356 - we're compiling for a system where we know
6357 - that snprintf's return value conforms to ISO C 99
6358 (HAVE_SNPRINTF_RETVAL_C99) and
6359 - that snprintf always produces NUL-terminated strings
6360 (HAVE_SNPRINTF_TRUNCATION_C99).
6361 And it is desirable to do so, because more and more platforms
6362 no longer support %n, for "security reasons". */
6363 /* On specific platforms, listed below, we *must* avoid %n.
6364 In the case
6365 !WIDE_CHAR_VERSION && HAVE_SNPRINTF_RETVAL_C99 && !USE_MSVC__SNPRINTF
6366 we can rely on the return value of snprintf instead. Whereas
6367 in the opposite case
6368 WIDE_CHAR_VERSION || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF
6369 we need to make room based on an estimation, computed by
6370 MAX_ROOM_NEEDED. */
6371 /* The following platforms forbid %n:
6372 - On glibc2 systems from 2004-10-18 or newer, the use of
6373 %n in format strings in writable memory may crash the
6374 program (if compiled with _FORTIFY_SOURCE=2).
6375 - On macOS 10.13 or newer, the use of %n in format
6376 strings in writable memory by default crashes the
6377 program.
6378 - On OpenBSD, since 2021-08-30, the use of %n in format
6379 strings produces an abort (see
6380 <https://cvsweb.openbsd.org/cgi-bin/cvsweb/src/lib/libc/stdio/vfprintf.c.diff?r1=1.79&r2=1.80&f=h>,
6381 <https://cvsweb.openbsd.org/cgi-bin/cvsweb/src/lib/libc/stdio/vfwprintf.c.diff?r1=1.20&r2=1.21&f=h>).
6382 - On Android, starting on 2018-03-07, the use of %n in
6383 format strings produces a fatal error (see
6384 <https://android.googlesource.com/platform/bionic/+/41398d03b7e8e0dfb951660ae713e682e9fc0336>).
6385 - On native Windows systems (such as mingw) where the OS is
6386 Windows Vista, the use of %n in format strings by default
6387 crashes the program. See
6388 <https://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and
6389 <https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/set-printf-count-output>
6390 On the first four of these platforms, if !WIDE_CHAR_VERSION,
6391 it is not a big deal to avoid %n, because on these platforms,
6392 HAVE_SNPRINTF_RETVAL_C99 and HAVE_SNPRINTF_TRUNCATION_C99 are
6393 1.
6394 On native Windows, if !WIDE_CHAR_VERSION, it's not a big deal
6395 either because:
6396 - Although the gl_SNPRINTF_TRUNCATION_C99 test fails,
6397 snprintf does not write more than the specified number
6398 of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes
6399 '4', '5', '6' into buf, not '4', '5', '\0'.)
6400 - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf
6401 allows us to recognize the case of an insufficient
6402 buffer size: it returns -1 in this case. */
6403 /* Additionally, in the WIDE_CHAR_VERSION case, we cannot use %n
6404 on musl libc because we would run into an swprintf() bug.
6405 See <https://www.openwall.com/lists/musl/2023/03/19/1>. */
6406 fbp[1] = '\0';
6407 # else /* AIX <= 5.1, HP-UX, IRIX, OSF/1, Solaris <= 9, BeOS */
6408 fbp[1] = '%';
6409 fbp[2] = 'n';
6410 fbp[3] = '\0';
6411 # endif
6412 #else
6413 fbp[1] = '\0';
6414 #endif
6415
6416 /* Construct the arguments for calling snprintf or sprintf. */
6417 prefix_count = 0;
6418 if (!pad_ourselves && dp->width_arg_index != ARG_NONE)
6419 {
6420 if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
6421 abort ();
6422 prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int;
6423 }
6424 if (!prec_ourselves && dp->precision_arg_index != ARG_NONE)
6425 {
6426 if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
6427 abort ();
6428 prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int;
6429 }
6430
6431 #if USE_SNPRINTF
6432 /* The SNPRINTF result is appended after result[0..length].
6433 The latter is an array of DCHAR_T; SNPRINTF appends an
6434 array of TCHAR_T to it. This is possible because
6435 sizeof (TCHAR_T) divides sizeof (DCHAR_T) and
6436 alignof (TCHAR_T) <= alignof (DCHAR_T). */
6437 # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T))
6438 /* Ensure that maxlen below will be >= 2. Needed on BeOS,
6439 where an snprintf() with maxlen==1 acts like sprintf(). */
6440 ENSURE_ALLOCATION (xsum (length,
6441 (2 + TCHARS_PER_DCHAR - 1)
6442 / TCHARS_PER_DCHAR));
6443 /* Prepare checking whether snprintf returns the count
6444 via %n. */
6445 *(TCHAR_T *) (result + length) = '\0';
6446 #endif
6447
6448 orig_errno = errno;
6449
6450 for (;;)
6451 {
6452 int count = -1;
6453
6454 #if USE_SNPRINTF
6455 int retcount = 0;
6456 size_t maxlen = allocated - length;
6457 /* SNPRINTF can fail if its second argument is
6458 > INT_MAX. */
6459 if (maxlen > INT_MAX / TCHARS_PER_DCHAR)
6460 maxlen = INT_MAX / TCHARS_PER_DCHAR;
6461 maxlen = maxlen * TCHARS_PER_DCHAR;
6462 # define SNPRINTF_BUF(arg) \
6463 switch (prefix_count) \
6464 { \
6465 case 0: \
6466 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
6467 maxlen, buf, \
6468 arg, &count); \
6469 break; \
6470 case 1: \
6471 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
6472 maxlen, buf, \
6473 prefixes[0], arg, &count); \
6474 break; \
6475 case 2: \
6476 retcount = SNPRINTF ((TCHAR_T *) (result + length), \
6477 maxlen, buf, \
6478 prefixes[0], prefixes[1], arg, \
6479 &count); \
6480 break; \
6481 default: \
6482 abort (); \
6483 }
6484 #else
6485 # define SNPRINTF_BUF(arg) \
6486 switch (prefix_count) \
6487 { \
6488 case 0: \
6489 count = sprintf (tmp, buf, arg); \
6490 break; \
6491 case 1: \
6492 count = sprintf (tmp, buf, prefixes[0], arg); \
6493 break; \
6494 case 2: \
6495 count = sprintf (tmp, buf, prefixes[0], prefixes[1],\
6496 arg); \
6497 break; \
6498 default: \
6499 abort (); \
6500 }
6501 #endif
6502
6503 errno = 0;
6504 switch (type)
6505 {
6506 case TYPE_SCHAR:
6507 {
6508 int arg = a.arg[dp->arg_index].a.a_schar;
6509 SNPRINTF_BUF (arg);
6510 }
6511 break;
6512 case TYPE_UCHAR:
6513 {
6514 unsigned int arg = a.arg[dp->arg_index].a.a_uchar;
6515 SNPRINTF_BUF (arg);
6516 }
6517 break;
6518 case TYPE_SHORT:
6519 {
6520 int arg = a.arg[dp->arg_index].a.a_short;
6521 SNPRINTF_BUF (arg);
6522 }
6523 break;
6524 case TYPE_USHORT:
6525 {
6526 unsigned int arg = a.arg[dp->arg_index].a.a_ushort;
6527 SNPRINTF_BUF (arg);
6528 }
6529 break;
6530 case TYPE_INT:
6531 {
6532 int arg = a.arg[dp->arg_index].a.a_int;
6533 SNPRINTF_BUF (arg);
6534 }
6535 break;
6536 case TYPE_UINT:
6537 {
6538 unsigned int arg = a.arg[dp->arg_index].a.a_uint;
6539 SNPRINTF_BUF (arg);
6540 }
6541 break;
6542 case TYPE_LONGINT:
6543 {
6544 long int arg = a.arg[dp->arg_index].a.a_longint;
6545 SNPRINTF_BUF (arg);
6546 }
6547 break;
6548 case TYPE_ULONGINT:
6549 {
6550 unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint;
6551 SNPRINTF_BUF (arg);
6552 }
6553 break;
6554 case TYPE_LONGLONGINT:
6555 {
6556 long long int arg = a.arg[dp->arg_index].a.a_longlongint;
6557 SNPRINTF_BUF (arg);
6558 }
6559 break;
6560 case TYPE_ULONGLONGINT:
6561 {
6562 unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint;
6563 SNPRINTF_BUF (arg);
6564 }
6565 break;
6566 case TYPE_INT8_T:
6567 {
6568 int8_t arg = a.arg[dp->arg_index].a.a_int8_t;
6569 SNPRINTF_BUF (arg);
6570 }
6571 break;
6572 case TYPE_UINT8_T:
6573 {
6574 uint8_t arg = a.arg[dp->arg_index].a.a_uint8_t;
6575 SNPRINTF_BUF (arg);
6576 }
6577 break;
6578 case TYPE_INT16_T:
6579 {
6580 int16_t arg = a.arg[dp->arg_index].a.a_int16_t;
6581 SNPRINTF_BUF (arg);
6582 }
6583 break;
6584 case TYPE_UINT16_T:
6585 {
6586 uint16_t arg = a.arg[dp->arg_index].a.a_uint16_t;
6587 SNPRINTF_BUF (arg);
6588 }
6589 break;
6590 case TYPE_INT32_T:
6591 {
6592 int32_t arg = a.arg[dp->arg_index].a.a_int32_t;
6593 SNPRINTF_BUF (arg);
6594 }
6595 break;
6596 case TYPE_UINT32_T:
6597 {
6598 uint32_t arg = a.arg[dp->arg_index].a.a_uint32_t;
6599 SNPRINTF_BUF (arg);
6600 }
6601 break;
6602 case TYPE_INT64_T:
6603 {
6604 int64_t arg = a.arg[dp->arg_index].a.a_int64_t;
6605 SNPRINTF_BUF (arg);
6606 }
6607 break;
6608 case TYPE_UINT64_T:
6609 {
6610 uint64_t arg = a.arg[dp->arg_index].a.a_uint64_t;
6611 SNPRINTF_BUF (arg);
6612 }
6613 break;
6614 case TYPE_INT_FAST8_T:
6615 {
6616 int_fast8_t arg = a.arg[dp->arg_index].a.a_int_fast8_t;
6617 SNPRINTF_BUF (arg);
6618 }
6619 break;
6620 case TYPE_UINT_FAST8_T:
6621 {
6622 uint_fast8_t arg = a.arg[dp->arg_index].a.a_uint_fast8_t;
6623 SNPRINTF_BUF (arg);
6624 }
6625 break;
6626 case TYPE_INT_FAST16_T:
6627 {
6628 int_fast16_t arg = a.arg[dp->arg_index].a.a_int_fast16_t;
6629 SNPRINTF_BUF (arg);
6630 }
6631 break;
6632 case TYPE_UINT_FAST16_T:
6633 {
6634 uint_fast16_t arg = a.arg[dp->arg_index].a.a_uint_fast16_t;
6635 SNPRINTF_BUF (arg);
6636 }
6637 break;
6638 case TYPE_INT_FAST32_T:
6639 {
6640 int_fast32_t arg = a.arg[dp->arg_index].a.a_int_fast32_t;
6641 SNPRINTF_BUF (arg);
6642 }
6643 break;
6644 case TYPE_UINT_FAST32_T:
6645 {
6646 uint_fast32_t arg = a.arg[dp->arg_index].a.a_uint_fast32_t;
6647 SNPRINTF_BUF (arg);
6648 }
6649 break;
6650 case TYPE_INT_FAST64_T:
6651 {
6652 int_fast64_t arg = a.arg[dp->arg_index].a.a_int_fast64_t;
6653 SNPRINTF_BUF (arg);
6654 }
6655 break;
6656 case TYPE_UINT_FAST64_T:
6657 {
6658 uint_fast64_t arg = a.arg[dp->arg_index].a.a_uint_fast64_t;
6659 SNPRINTF_BUF (arg);
6660 }
6661 break;
6662 case TYPE_DOUBLE:
6663 {
6664 double arg = a.arg[dp->arg_index].a.a_double;
6665 SNPRINTF_BUF (arg);
6666 }
6667 break;
6668 case TYPE_LONGDOUBLE:
6669 {
6670 long double arg = a.arg[dp->arg_index].a.a_longdouble;
6671 SNPRINTF_BUF (arg);
6672 }
6673 break;
6674 case TYPE_CHAR:
6675 {
6676 int arg = a.arg[dp->arg_index].a.a_char;
6677 SNPRINTF_BUF (arg);
6678 }
6679 break;
6680 #if HAVE_WINT_T
6681 case TYPE_WIDE_CHAR:
6682 {
6683 wint_t arg = a.arg[dp->arg_index].a.a_wide_char;
6684 SNPRINTF_BUF (arg);
6685 }
6686 break;
6687 #endif
6688 case TYPE_STRING:
6689 {
6690 const char *arg = a.arg[dp->arg_index].a.a_string;
6691 SNPRINTF_BUF (arg);
6692 }
6693 break;
6694 case TYPE_WIDE_STRING:
6695 {
6696 const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string;
6697 SNPRINTF_BUF (arg);
6698 }
6699 break;
6700 case TYPE_POINTER:
6701 {
6702 void *arg = a.arg[dp->arg_index].a.a_pointer;
6703 SNPRINTF_BUF (arg);
6704 }
6705 break;
6706 default:
6707 abort ();
6708 }
6709
6710 #if USE_SNPRINTF
6711 /* Portability: Not all implementations of snprintf()
6712 are ISO C 99 compliant. Determine the number of
6713 bytes that snprintf() has produced or would have
6714 produced. */
6715 if (count >= 0)
6716 {
6717 /* Verify that snprintf() has NUL-terminated its
6718 result. */
6719 if ((unsigned int) count < maxlen
6720 && ((TCHAR_T *) (result + length)) [count] != '\0')
6721 abort ();
6722 /* Portability hack. */
6723 if (retcount > count)
6724 count = retcount;
6725 }
6726 else
6727 {
6728 /* snprintf() doesn't understand the '%n'
6729 directive. */
6730 if (fbp[1] != '\0')
6731 {
6732 /* Don't use the '%n' directive; instead, look
6733 at the snprintf() return value. */
6734 fbp[1] = '\0';
6735 continue;
6736 }
6737 else
6738 {
6739 /* Look at the snprintf() return value. */
6740 if (retcount < 0)
6741 {
6742 # if (WIDE_CHAR_VERSION && DCHAR_IS_TCHAR) || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF
6743 /* HP-UX 10.20 snprintf() is doubly deficient:
6744 It doesn't understand the '%n' directive,
6745 *and* it returns -1 (rather than the length
6746 that would have been required) when the
6747 buffer is too small.
6748 Likewise, in case of
6749 WIDE_CHAR_VERSION && DCHAR_IS_TCHAR, the
6750 functions snwprintf()/_snwprintf() (Windows)
6751 or swprintf() (Unix).
6752 But a failure at this point can also come
6753 from other reasons than a too small buffer,
6754 such as an invalid wide string argument to
6755 the %ls directive, or possibly an invalid
6756 floating-point argument. */
6757 size_t tmp_length =
6758 MAX_ROOM_NEEDED (&a, dp->arg_index,
6759 dp->conversion, type, flags,
6760 width,
6761 has_precision,
6762 precision, pad_ourselves);
6763
6764 if (maxlen < tmp_length)
6765 {
6766 /* Make more room. But try to do through
6767 this reallocation only once. */
6768 size_t bigger_need =
6769 xsum (length,
6770 xsum (tmp_length,
6771 TCHARS_PER_DCHAR - 1)
6772 / TCHARS_PER_DCHAR);
6773 /* And always grow proportionally.
6774 (There may be several arguments, each
6775 needing a little more room than the
6776 previous one.) */
6777 size_t bigger_need2 =
6778 xsum (xtimes (allocated, 2), 12);
6779 if (bigger_need < bigger_need2)
6780 bigger_need = bigger_need2;
6781 ENSURE_ALLOCATION (bigger_need);
6782 continue;
6783 }
6784 # endif
6785 }
6786 else
6787 {
6788 count = retcount;
6789 # if WIDE_CHAR_VERSION && defined __MINGW32__
6790 if (count == 0 && dp->conversion == 'c')
6791 /* snwprintf returned 0 instead of 1. But it
6792 wrote a null wide character. */
6793 count = 1;
6794 # endif
6795 }
6796 }
6797 }
6798 #endif
6799
6800 /* Attempt to handle failure. */
6801 if (count < 0)
6802 {
6803 /* SNPRINTF or sprintf failed. Use the errno that it
6804 has set, if any. */
6805 if (errno == 0)
6806 {
6807 if (dp->conversion == 'c' || dp->conversion == 's')
6808 errno = EILSEQ;
6809 else
6810 errno = EINVAL;
6811 }
6812
6813 goto fail_with_errno;
6814 }
6815
6816 #if USE_SNPRINTF
6817 /* Handle overflow of the allocated buffer.
6818 If such an overflow occurs, a C99 compliant snprintf()
6819 returns a count >= maxlen. However, a non-compliant
6820 snprintf() function returns only count = maxlen - 1. To
6821 cover both cases, test whether count >= maxlen - 1. */
6822 if ((unsigned int) count + 1 >= maxlen)
6823 {
6824 /* If maxlen already has attained its allowed maximum,
6825 allocating more memory will not increase maxlen.
6826 Instead of looping, bail out. */
6827 if (maxlen == INT_MAX / TCHARS_PER_DCHAR)
6828 goto overflow;
6829 else
6830 {
6831 /* Need at least (count + 1) * sizeof (TCHAR_T)
6832 bytes. (The +1 is for the trailing NUL.)
6833 But ask for (count + 2) * sizeof (TCHAR_T)
6834 bytes, so that in the next round, we likely get
6835 maxlen > (unsigned int) count + 1
6836 and so we don't get here again.
6837 And allocate proportionally, to avoid looping
6838 eternally if snprintf() reports a too small
6839 count. */
6840 size_t n =
6841 xmax (xsum (length,
6842 ((unsigned int) count + 2
6843 + TCHARS_PER_DCHAR - 1)
6844 / TCHARS_PER_DCHAR),
6845 xtimes (allocated, 2));
6846
6847 ENSURE_ALLOCATION (n);
6848 continue;
6849 }
6850 }
6851 #endif
6852
6853 #if NEED_PRINTF_FLAG_ALT_PRECISION_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
6854 if (prec_ourselves)
6855 {
6856 /* Handle the precision. */
6857 TCHAR_T *prec_ptr =
6858 # if USE_SNPRINTF
6859 (TCHAR_T *) (result + length);
6860 # else
6861 tmp;
6862 # endif
6863 size_t prefix_count;
6864 size_t move;
6865
6866 prefix_count = 0;
6867 /* Put the additional zeroes after the sign. */
6868 if (count >= 1
6869 && (*prec_ptr == '-' || *prec_ptr == '+'
6870 || *prec_ptr == ' '))
6871 prefix_count = 1;
6872 /* Put the additional zeroes after the 0x prefix if
6873 (flags & FLAG_ALT) || (dp->conversion == 'p'). */
6874 else if (count >= 2
6875 && prec_ptr[0] == '0'
6876 && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X'))
6877 prefix_count = 2;
6878
6879 move = count - prefix_count;
6880 if (precision > move)
6881 {
6882 /* Insert zeroes. */
6883 size_t insert = precision - move;
6884 TCHAR_T *prec_end;
6885
6886 # if USE_SNPRINTF
6887 size_t n =
6888 xsum (length,
6889 (count + insert + TCHARS_PER_DCHAR - 1)
6890 / TCHARS_PER_DCHAR);
6891 length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
6892 ENSURE_ALLOCATION (n);
6893 length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR;
6894 prec_ptr = (TCHAR_T *) (result + length);
6895 # endif
6896
6897 prec_end = prec_ptr + count;
6898 prec_ptr += prefix_count;
6899
6900 while (prec_end > prec_ptr)
6901 {
6902 prec_end--;
6903 prec_end[insert] = prec_end[0];
6904 }
6905
6906 prec_end += insert;
6907 do
6908 *--prec_end = '0';
6909 while (prec_end > prec_ptr);
6910
6911 count += insert;
6912 }
6913 # if NEED_PRINTF_FLAG_ALT_PRECISION_ZERO
6914 else if (precision == 0
6915 && move == 1
6916 && prec_ptr[prefix_count] == '0')
6917 {
6918 /* Replace the "0" result with an empty string. */
6919 count = prefix_count;
6920 }
6921 # endif
6922 }
6923 #endif
6924
6925 #if !USE_SNPRINTF
6926 if (count >= tmp_length)
6927 /* tmp_length was incorrectly calculated - fix the
6928 code above! */
6929 abort ();
6930 #endif
6931
6932 #if !DCHAR_IS_TCHAR
6933 /* Convert from TCHAR_T[] to DCHAR_T[]. */
6934 if (dp->conversion == 'c' || dp->conversion == 's'
6935 # if __GLIBC__ >= 2 && !defined __UCLIBC__
6936 || (flags & FLAG_LOCALIZED)
6937 # endif
6938 )
6939 {
6940 /* The result string is not guaranteed to be ASCII. */
6941 const TCHAR_T *tmpsrc;
6942 DCHAR_T *tmpdst;
6943 size_t tmpdst_len;
6944 /* This code assumes that TCHAR_T is 'char'. */
6945 static_assert (sizeof (TCHAR_T) == 1);
6946 # if USE_SNPRINTF
6947 tmpsrc = (TCHAR_T *) (result + length);
6948 # else
6949 tmpsrc = tmp;
6950 # endif
6951 # if WIDE_CHAR_VERSION
6952 /* Convert tmpsrc[0..count-1] to a freshly allocated
6953 wide character array. */
6954 mbstate_t state;
6955
6956 mbszero (&state);
6957 tmpdst_len = 0;
6958 {
6959 const TCHAR_T *src = tmpsrc;
6960 size_t srclen = count;
6961
6962 for (; srclen > 0; tmpdst_len++)
6963 {
6964 /* Parse the next multibyte character. */
6965 size_t ret = mbrtowc (NULL, src, srclen, &state);
6966 if (ret == (size_t)(-2) || ret == (size_t)(-1))
6967 goto fail_with_EILSEQ;
6968 if (ret == 0)
6969 ret = 1;
6970 src += ret;
6971 srclen -= ret;
6972 }
6973 }
6974
6975 tmpdst =
6976 (wchar_t *) malloc ((tmpdst_len + 1) * sizeof (wchar_t));
6977 if (tmpdst == NULL)
6978 goto out_of_memory;
6979
6980 mbszero (&state);
6981 {
6982 DCHAR_T *destptr = tmpdst;
6983 const TCHAR_T *src = tmpsrc;
6984 size_t srclen = count;
6985
6986 for (; srclen > 0; destptr++)
6987 {
6988 /* Parse the next multibyte character. */
6989 size_t ret = mbrtowc (destptr, src, srclen, &state);
6990 if (ret == (size_t)(-2) || ret == (size_t)(-1))
6991 /* Should already have been caught in the first
6992 loop, above. */
6993 abort ();
6994 if (ret == 0)
6995 ret = 1;
6996 src += ret;
6997 srclen -= ret;
6998 }
6999 }
7000 # else
7001 tmpdst =
7002 DCHAR_CONV_FROM_ENCODING (locale_charset (),
7003 iconveh_question_mark,
7004 tmpsrc, count,
7005 NULL,
7006 NULL, &tmpdst_len);
7007 if (tmpdst == NULL)
7008 goto fail_with_errno;
7009 # endif
7010 ENSURE_ALLOCATION_ELSE (xsum (length, tmpdst_len),
7011 { free (tmpdst); goto out_of_memory; });
7012 DCHAR_CPY (result + length, tmpdst, tmpdst_len);
7013 free (tmpdst);
7014 count = tmpdst_len;
7015 }
7016 else
7017 {
7018 /* The result string is ASCII.
7019 Simple 1:1 conversion. */
7020 # if USE_SNPRINTF
7021 /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a
7022 no-op conversion, in-place on the array starting
7023 at (result + length). */
7024 if (sizeof (DCHAR_T) != sizeof (TCHAR_T))
7025 # endif
7026 {
7027 const TCHAR_T *tmpsrc;
7028 DCHAR_T *tmpdst;
7029 size_t n;
7030
7031 # if USE_SNPRINTF
7032 if (result == resultbuf)
7033 {
7034 tmpsrc = (TCHAR_T *) (result + length);
7035 /* ENSURE_ALLOCATION will not move tmpsrc
7036 (because it's part of resultbuf). */
7037 ENSURE_ALLOCATION (xsum (length, count));
7038 }
7039 else
7040 {
7041 /* ENSURE_ALLOCATION will move the array
7042 (because it uses realloc(). */
7043 ENSURE_ALLOCATION (xsum (length, count));
7044 tmpsrc = (TCHAR_T *) (result + length);
7045 }
7046 # else
7047 tmpsrc = tmp;
7048 ENSURE_ALLOCATION (xsum (length, count));
7049 # endif
7050 tmpdst = result + length;
7051 /* Copy backwards, because of overlapping. */
7052 tmpsrc += count;
7053 tmpdst += count;
7054 for (n = count; n > 0; n--)
7055 *--tmpdst = *--tmpsrc;
7056 }
7057 }
7058 #endif
7059
7060 #if DCHAR_IS_TCHAR && !USE_SNPRINTF
7061 /* Make room for the result. */
7062 if (count > allocated - length)
7063 {
7064 /* Need at least count elements. But allocate
7065 proportionally. */
7066 size_t n =
7067 xmax (xsum (length, count), xtimes (allocated, 2));
7068
7069 ENSURE_ALLOCATION (n);
7070 }
7071 #endif
7072
7073 /* Here count <= allocated - length. */
7074
7075 /* Perform padding. */
7076 #if (WIDE_CHAR_VERSION && MUSL_LIBC) || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_FLAG_ALT_PRECISION_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
7077 if (pad_ourselves && has_width)
7078 {
7079 size_t w;
7080 # if ENABLE_UNISTDIO
7081 /* Outside POSIX, it's preferable to compare the width
7082 against the number of _characters_ of the converted
7083 value. */
7084 w = DCHAR_MBSNLEN (result + length, count);
7085 # else
7086 /* The width is compared against the number of _bytes_
7087 of the converted value, says POSIX. */
7088 w = count;
7089 # endif
7090 if (w < width)
7091 {
7092 size_t pad = width - w;
7093
7094 /* Make room for the result. */
7095 if (xsum (count, pad) > allocated - length)
7096 {
7097 /* Need at least count + pad elements. But
7098 allocate proportionally. */
7099 size_t n =
7100 xmax (xsum3 (length, count, pad),
7101 xtimes (allocated, 2));
7102
7103 # if USE_SNPRINTF
7104 length += count;
7105 ENSURE_ALLOCATION (n);
7106 length -= count;
7107 # else
7108 ENSURE_ALLOCATION (n);
7109 # endif
7110 }
7111 /* Here count + pad <= allocated - length. */
7112
7113 {
7114 # if !DCHAR_IS_TCHAR || USE_SNPRINTF
7115 DCHAR_T * const rp = result + length;
7116 # else
7117 DCHAR_T * const rp = tmp;
7118 # endif
7119 DCHAR_T *p = rp + count;
7120 DCHAR_T *end = p + pad;
7121 DCHAR_T *pad_ptr;
7122 # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO
7123 if (dp->conversion == 'c'
7124 || dp->conversion == 's')
7125 /* No zero-padding for string directives. */
7126 pad_ptr = NULL;
7127 else
7128 # endif
7129 {
7130 pad_ptr = (*rp == '-' ? rp + 1 : rp);
7131 /* No zero-padding of "inf" and "nan". */
7132 if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
7133 || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
7134 pad_ptr = NULL;
7135 else
7136 /* Do the zero-padding after the "0x" or
7137 "0b" prefix, not before. */
7138 if (p - rp >= 2
7139 && *rp == '0'
7140 && (((dp->conversion == 'a'
7141 || dp->conversion == 'x')
7142 && rp[1] == 'x')
7143 || ((dp->conversion == 'A'
7144 || dp->conversion == 'X')
7145 && rp[1] == 'X')
7146 || (dp->conversion == 'b'
7147 && rp[1] == 'b')
7148 || (dp->conversion == 'B'
7149 && rp[1] == 'B')))
7150 pad_ptr += 2;
7151 }
7152 /* The generated string now extends from rp to p,
7153 with the zero padding insertion point being at
7154 pad_ptr. */
7155
7156 count = count + pad; /* = end - rp */
7157
7158 if (flags & FLAG_LEFT)
7159 {
7160 /* Pad with spaces on the right. */
7161 for (; pad > 0; pad--)
7162 *p++ = ' ';
7163 }
7164 else if ((flags & FLAG_ZERO) && pad_ptr != NULL
7165 /* ISO C says: "For d, i, o, u, x, and X
7166 conversions, if a precision is
7167 specified, the 0 flag is ignored. */
7168 && !(has_precision
7169 && (dp->conversion == 'd'
7170 || dp->conversion == 'i'
7171 || dp->conversion == 'o'
7172 || dp->conversion == 'u'
7173 || dp->conversion == 'x'
7174 || dp->conversion == 'X'
7175 /* Although ISO C does not
7176 require it, treat 'b' and 'B'
7177 like 'x' and 'X'. */
7178 || dp->conversion == 'b'
7179 || dp->conversion == 'B')))
7180 {
7181 /* Pad with zeroes. */
7182 DCHAR_T *q = end;
7183
7184 while (p > pad_ptr)
7185 *--q = *--p;
7186 for (; pad > 0; pad--)
7187 *p++ = '0';
7188 }
7189 else
7190 {
7191 /* Pad with spaces on the left. */
7192 DCHAR_T *q = end;
7193
7194 while (p > rp)
7195 *--q = *--p;
7196 for (; pad > 0; pad--)
7197 *p++ = ' ';
7198 }
7199 }
7200 }
7201 }
7202 #endif
7203
7204 /* Here still count <= allocated - length. */
7205
7206 #if !DCHAR_IS_TCHAR || USE_SNPRINTF
7207 /* The snprintf() result did fit. */
7208 #else
7209 /* Append the sprintf() result. */
7210 memcpy (result + length, tmp, count * sizeof (DCHAR_T));
7211 #endif
7212 #if !USE_SNPRINTF
7213 if (tmp != tmpbuf)
7214 free (tmp);
7215 #endif
7216
7217 #if NEED_PRINTF_DIRECTIVE_F
7218 if (dp->conversion == 'F')
7219 {
7220 /* Convert the %f result to upper case for %F. */
7221 DCHAR_T *rp = result + length;
7222 size_t rc;
7223 for (rc = count; rc > 0; rc--, rp++)
7224 if (*rp >= 'a' && *rp <= 'z')
7225 *rp = *rp - 'a' + 'A';
7226 }
7227 #endif
7228
7229 length += count;
7230 break;
7231 }
7232 errno = orig_errno;
7233 #undef pad_ourselves
7234 #undef prec_ourselves
7235 }
7236 }
7237 }
7238
7239 /* Add the final NUL. */
7240 ENSURE_ALLOCATION (xsum (length, 1));
7241 result[length] = '\0';
7242
7243 if (result != resultbuf && length + 1 < allocated)
7244 {
7245 /* Shrink the allocated memory if possible. */
7246 DCHAR_T *memory;
7247
7248 memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
7249 if (memory != NULL)
7250 result = memory;
7251 }
7252
7253 if (buf_malloced != NULL)
7254 free (buf_malloced);
7255 CLEANUP ();
7256 *lengthp = length;
7257 /* Note that we can produce a big string of a length > INT_MAX. POSIX
7258 says that snprintf() fails with errno = EOVERFLOW in this case, but
7259 that's only because snprintf() returns an 'int'. This function does
7260 not have this limitation. */
7261 return result;
7262
7263 overflow:
7264 errno = EOVERFLOW;
7265 goto fail_with_errno;
7266
7267 out_of_memory:
7268 errno = ENOMEM;
7269 goto fail_with_errno;
7270
7271 #if ENABLE_UNISTDIO || (WIDE_CHAR_VERSION || !USE_SNPRINTF || (PTRDIFF_MAX > INT_MAX) || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || NEED_PRINTF_DIRECTIVE_LS || ENABLE_WCHAR_FALLBACK) || ((NEED_PRINTF_DIRECTIVE_LC || ENABLE_WCHAR_FALLBACK) && HAVE_WINT_T && !WIDE_CHAR_VERSION) || (NEED_WPRINTF_DIRECTIVE_C && WIDE_CHAR_VERSION)
7272 fail_with_EILSEQ:
7273 errno = EILSEQ;
7274 goto fail_with_errno;
7275 #endif
7276
7277 fail_with_errno:
7278 if (result != resultbuf)
7279 free (result);
7280 if (buf_malloced != NULL)
7281 free (buf_malloced);
7282 CLEANUP ();
7283 return NULL;
7284 }
7285
7286 out_of_memory_1:
7287 errno = ENOMEM;
7288 goto fail_1_with_errno;
7289
7290 fail_1_with_EINVAL:
7291 errno = EINVAL;
7292 goto fail_1_with_errno;
7293
7294 fail_1_with_errno:
7295 CLEANUP ();
7296 return NULL;
7297 }
7298
7299 #undef MAX_ROOM_NEEDED
7300 #undef TCHARS_PER_DCHAR
7301 #undef SNPRINTF
7302 #undef USE_SNPRINTF
7303 #undef DCHAR_SET
7304 #undef DCHAR_CPY
7305 #undef PRINTF_PARSE
7306 #undef DIRECTIVES
7307 #undef DIRECTIVE
7308 #undef DCHAR_IS_TCHAR
7309 #undef TCHAR_T
7310 #undef DCHAR_T
7311 #undef FCHAR_T
7312 #undef VASNPRINTF