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