Debian Codegraph @

gnulib/lib/vasnprintf.c

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