Debian Codegraph @

gnulib-tests/vasnprintf.c

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