Debian Codegraph @

lib/vasnprintf.c

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