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