Debian Codegraph @

gnu/vasnprintf.c

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