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